mson-three/src/three/mirror-helper.ts

39 lines
1.0 KiB
TypeScript

import { BufferGeometry, Matrix4 } from 'three';
import { Mirror3 } from '../mson/mson.type';
/**
* Utilities to mirror a THREE BufferGeometry in set axes.
*/
export class MirrorHelper {
static mirrorGeometry(axes: Mirror3, geometry: BufferGeometry) {
// No axes are mirrored, ignore
if (!axes.some((entry) => !!entry)) return;
// Invert geometry
const inversionMatrix = new Matrix4().makeScale(
axes[0] ? -1 : 1,
axes[1] ? -1 : 1,
axes[2] ? -1 : 1,
);
geometry.applyMatrix4(inversionMatrix);
// Reverse faces winding direction
MirrorHelper.reverseIndexBuffer(geometry);
// Recalculate normals to face correctly
geometry.computeVertexNormals();
}
static reverseIndexBuffer(geometry: BufferGeometry) {
if (!geometry.index) return;
const index = geometry.index.array;
for (let i = 0, il = index.length / 3; i < il; i++) {
let x = index[i * 3];
index[i * 3] = index[i * 3 + 2];
index[i * 3 + 2] = x;
}
geometry.index.needsUpdate = true;
}
}