75 lines
1.8 KiB
TypeScript
75 lines
1.8 KiB
TypeScript
// @ts-ignore
|
|
import {convert} from './objparser';
|
|
import {initBuffers, deleteBuffers} from './buffers';
|
|
|
|
/**
|
|
* Fetch an obj file
|
|
* @param {string} url the url to fetch the object from
|
|
* @return {string} the raw data of the obj file
|
|
*/
|
|
export async function fetchObj(url: string) {
|
|
const response = await fetch(url);
|
|
const data = await response.text();
|
|
return data;
|
|
}
|
|
|
|
/**
|
|
* Pushes a new obj file to the gl buffer
|
|
* @param {any} context the program context
|
|
* @param {string} data the obj file to push
|
|
* @param {boolean} firstCall is it first object updated ?
|
|
*/
|
|
export function updateObj(
|
|
context: any,
|
|
data: string,
|
|
firstCall: boolean = false) {
|
|
const [
|
|
positions,
|
|
normals,
|
|
uvs,
|
|
indices,
|
|
] = convert(data);
|
|
context.params.length = indices.length;
|
|
let x = 0;
|
|
let y = 0;
|
|
let z = 0;
|
|
let maxx = positions[0];
|
|
let maxy = positions[1];
|
|
let maxz = positions[2];
|
|
let minx = positions[0];
|
|
let miny = positions[1];
|
|
let minz = positions[2];
|
|
for (let i = 0; i < positions.length; i++) {
|
|
if (i % 3 == 0) {
|
|
if (positions[i] > maxx) {
|
|
maxx = positions[i];
|
|
} else if (positions[i] < minx) {
|
|
minx = positions[i];
|
|
}
|
|
x += positions[i];
|
|
} else if (i % 3 == 1) {
|
|
if (positions[i] > maxy) {
|
|
maxy = positions[i];
|
|
} else if (positions[i] < miny) {
|
|
miny = positions[i];
|
|
}
|
|
y += positions[i];
|
|
} else {
|
|
if (positions[i] > maxz) {
|
|
maxz = positions[i];
|
|
} else if (positions[i] < minz) {
|
|
minz = positions[i];
|
|
}
|
|
z += positions[i];
|
|
}
|
|
}
|
|
context.params.range = Math.max(maxx - minx, maxy - miny, maxz - minz);
|
|
context.params.avg.x = x / (positions.length / 3);
|
|
context.params.avg.y = y / (positions.length / 3);
|
|
context.params.avg.z = z / (positions.length / 3);
|
|
if (!firstCall) {
|
|
deleteBuffers(context.gl, context.buffers);
|
|
}
|
|
context.buffers = initBuffers(context.gl, positions, indices, normals, uvs);
|
|
}
|