@polygonjs/polygonjs
Version:
node-based WebGL 3D engine https://polygonjs.com
53 lines (52 loc) • 1.99 kB
JavaScript
;
import { BufferGeometry, BufferAttribute, Matrix4, MathUtils } from "three";
import { ObjectType } from "../../../Constant";
import { BaseSopOperation } from "../../../../../engine/operations/sop/_Base";
import { csgMaterialMesh } from "../CsgConstant";
import { toCreasedNormals } from "three/examples/jsm/utils/BufferGeometryUtils";
export function geom3ToObject3D(csg, options) {
const geometry = geom3ToBufferGeometry(csg, options);
return BaseSopOperation.createObject(
geometry,
ObjectType.MESH,
csgMaterialMesh(options.meshesColor, options.wireframe)
);
}
export function geom3ToBufferGeometry(csg, options) {
const positions = [];
const indices = [];
const polygons = csg.polygons;
let currentIndex = 0;
const indexByPosition = /* @__PURE__ */ new Map();
for (const polygon of polygons) {
const polygonjsCount = polygon.vertices.length;
const polygonVertices = polygon.vertices;
for (const vertex of polygonVertices) {
const positionAsString = `${vertex[0]},${vertex[1]},${vertex[2]}`;
let index = indexByPosition.get(positionAsString);
if (index == null) {
index = currentIndex;
indexByPosition.set(positionAsString, index);
positions.push(vertex[0], vertex[1], vertex[2]);
currentIndex++;
}
vertex.index = index;
}
const first = polygonVertices[0].index;
for (let i = 2; i < polygonjsCount; i++) {
const second = polygon.vertices[i - 1].index;
const third = polygon.vertices[i].index;
indices.push(first, second, third);
}
}
const geo = new BufferGeometry();
geo.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
geo.setIndex(indices);
if (csg.transforms) {
const transforms = new Matrix4();
transforms.set(...csg.transforms).transpose();
geo.applyMatrix4(transforms);
}
geo.computeVertexNormals();
return toCreasedNormals(geo, MathUtils.degToRad(options.facetAngle));
}