gs-json
Version:
gs-JSON is a domain agnostic unifying 3D file format for geometric and semantic modelling (hence the 'gs').
54 lines • 2.11 kB
JavaScript
import * as three from "three";
import * as threex from "../threex/threex";
import { Arr } from "../arr/arr";
import * as earcut from "./earcut";
// 3D to 2D ======================================================================================================
/**
* Function to transform a set of vertices in 3d space onto the xy plane. This function assumes that the vertices
* are co-planar. Returns a set of three Vectors that represent points on the xy plane.
*/
export function makeVertices2D(vertices) {
const points = threex.vectorsFromVertices(vertices);
const o = new three.Vector3();
for (const v of points) {
o.add(v);
}
o.divideScalar(points.length);
let vx;
let vz;
let got_vx = false;
for (let i = 0; i < vertices.length; i++) {
if (!got_vx) {
vx = threex.subVectors(points[i], o).normalize();
if (vx.lengthSq() !== 0) {
got_vx = true;
}
}
else {
vz = threex.crossVectors(vx, threex.subVectors(points[i], o).normalize()).normalize();
if (vz.lengthSq() !== 0) {
break;
}
}
if (i === vertices.length - 1) {
return null;
}
}
const vy = threex.crossVectors(vz, vx);
const m = threex.xformMatrix(o, vx, vy, vz);
const points_2d = points.map((v) => threex.multVectorMatrix(v, m));
// console.log(o, vx, vy, vz);
// console.log(points_2d);
return points_2d;
}
// Triangulation =================================================================================================
export function triangulate2D(vertices, verts_indexes) {
const points_2d = makeVertices2D(vertices);
if (points_2d === null) {
return [0, 1, 2].map((v) => verts_indexes[v]);
}
const flat_vert_xyzs = Arr.flatten(points_2d.map((v) => [v.x, v.y]));
const tri_indexes = earcut.Earcut.triangulate(flat_vert_xyzs);
return tri_indexes.map((v) => verts_indexes[v]);
}
//# sourceMappingURL=triangulate.js.map