webgl/src/client/objutils.ts

117 lines
2.6 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 {any} obj the obj file to push
* @return {any} the initiated buffers
*/
export function pushBuffersToScene(
context: any,
obj: any) {
return initBuffers(context.gl,
obj.positions, obj.indices, obj.normals, obj.uvs);
}
/**
* Pushes a new obj file to the gl buffer
* @param {any} context the program context
* @param {any} obj the obj file to push
*/
export function loadObjBuffers(
context: any,
obj: any) {
if (context.buffers != null) {
deleteBuffers(context.gl, context.buffers);
}
context.obj = {
positions: obj.positions,
indices: obj.indices,
normals: obj.normals,
uvs: obj.uvs,
};
context.buffers = initBuffers(context.gl,
obj.positions, obj.indices, obj.normals, obj.uvs);
}
/**
* Load a new obj file to the cache
* @param {string} data the obj file to push
* @return {any} the obj file loaded
*/
export function loadObj(
data: string) {
const [
positions,
normals,
uvs,
indices,
] = convert(data);
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];
}
}
const avgx = x / (positions.length / 3);
const avgy = y / (positions.length / 3);
const avgz = z / (positions.length / 3);
for (let i = 0; i < positions.length; i++) {
if (i % 3 == 0) {
positions[i] -= avgx;
} else if (i % 3 == 1) {
positions[i] -= avgy;
} else {
positions[i] -= avgz;
}
}
return {
positions: positions,
indices: indices,
normals: normals,
uvs: uvs,
range: Math.max(maxx - minx, maxy - miny, maxz - minz),
};
}