feat: rust stuff

This commit is contained in:
2024-03-10 17:18:07 +01:00
parent 1ce75369a1
commit bc7b972314
19 changed files with 797 additions and 257 deletions

View File

@@ -7,11 +7,9 @@
BufferGeometry,
MathUtils,
Vector3,
Mesh,
DoubleSide,
Color,
BufferGeometryLoader,
ConeGeometry
BufferGeometryLoader
} from 'three';
import { writable } from 'svelte/store';
import { onDestroy, onMount } from 'svelte';

35
src/lib/slicer/slicer.ts Normal file
View File

@@ -0,0 +1,35 @@
import {
BufferAttribute,
BufferGeometry,
BufferGeometryLoader,
InterleavedBufferAttribute,
Vector3
} from 'three';
import type { SliceArguments } from './worker-data';
import { MeshBVH } from 'three-mesh-bvh';
export class SlicerOptions {
readonly bedNormal: Vector3;
readonly maxNonPlanarAngle: number;
readonly tolerance: number;
readonly layerHeight: number;
readonly geometry: BufferGeometry;
readonly bvh: MeshBVH;
readonly positions: BufferAttribute | InterleavedBufferAttribute;
readonly normals: BufferAttribute | InterleavedBufferAttribute;
readonly index: BufferAttribute;
constructor(options: SliceArguments) {
this.bedNormal = new Vector3(...options.bedNormal);
this.maxNonPlanarAngle = options.maxNonPlanarAngle;
this.tolerance = options.tolerance;
this.layerHeight = options.layerHeight;
this.geometry = new BufferGeometryLoader().parse(options.stl);
this.bvh = new MeshBVH(this.geometry);
this.positions = this.geometry.getAttribute('position');
this.normals = this.geometry.getAttribute('normal');
this.index = this.geometry.index!;
}
}

View File

@@ -0,0 +1,159 @@
import { BufferGeometry, Float32BufferAttribute, Line3, Matrix4, Plane, Vector3 } from 'three';
import type { SlicerOptions } from '../slicer';
import type { HitPointInfo, MeshBVH } from 'three-mesh-bvh';
import { LayerType, type LayerMessage, type ProgressMessage } from '../worker-data';
type Withheld = Array<
{ type: LayerType.Line; geometry: number[] } | { type: LayerType.Surface; id: [number, MeshBVH] }
>[];
function deactivateSurface(this: Withheld, surface: MeshBVH, index: number) {
self.postMessage({
type: 'layer',
data: { type: LayerType.Surface, geometry: surface.geometry.toJSON() }
} satisfies LayerMessage);
for (const thing of this[index]) {
if (thing.type === LayerType.Line) {
if (thing.geometry.length === 0) continue;
const additionalGeometry = new BufferGeometry();
additionalGeometry.setAttribute('position', new Float32BufferAttribute(thing.geometry, 3));
self.postMessage({
type: 'layer',
data: { type: LayerType.Line, geometry: additionalGeometry.toJSON() }
});
} else if (thing.type === LayerType.Surface) {
deactivateSurface.call(this, thing.id[1], thing.id[0]);
}
}
delete this[index];
}
const line = new Line3();
function intersect(layerPlane: Plane, a: Vector3, b: Vector3, targetVector: Vector3) {
line.set(a, b);
return layerPlane.intersectLine(line, targetVector);
}
export function extractLayers(
options: SlicerOptions,
surfaces: MeshBVH[],
surfaceTriangles: boolean[]
) {
const targetVector1 = new Vector3();
const targetVector2 = new Vector3();
const targetVector3 = new Vector3();
const hit1: HitPointInfo = { point: new Vector3(), distance: 0, faceIndex: 0 };
const hit2: HitPointInfo = { point: new Vector3(), distance: 0, faceIndex: 0 };
const layerPlane = new Plane();
const activeNonPlanarSurfaces: [number, MeshBVH][] = [];
const consumedNonPlanarSurfaces = surfaces.map(() => false);
const withheld: Withheld = surfaces.map(() => [{ type: LayerType.Line, geometry: [] }]);
const blacklist = Array.from({ length: options.index.count / 3 }).map(() => false);
for (let layer = 0; layer < options.geometry.boundingBox!.max.z; layer += options.layerHeight) {
layerPlane.set(options.bedNormal, -layer);
const layerGeometry = new BufferGeometry();
const positions: number[] = [];
for (let i = 0; i < surfaces.length; i++) {
if (consumedNonPlanarSurfaces[i]) continue;
if (layer >= surfaces[i].geometry.boundingBox!.min.z) {
consumedNonPlanarSurfaces[i] = true;
activeNonPlanarSurfaces.push([i, surfaces[i]]);
}
}
deactivate: for (let i = 0; i < activeNonPlanarSurfaces.length; i++) {
const [index, surface] = activeNonPlanarSurfaces[i];
if (layer > surface.geometry.boundingBox!.max.z) {
activeNonPlanarSurfaces.splice(i, 1);
i--;
for (const [activeIndex, active] of activeNonPlanarSurfaces) {
if (activeIndex === index) continue;
const hit = active.closestPointToGeometry(surface.geometry, new Matrix4(), hit1, hit2);
if (
hit &&
hit1.point.z < hit2.point.z &&
Math.abs(Math.PI / 2 - hit1.point.clone().sub(hit2.point).angleTo(options.bedNormal)) >
options.maxNonPlanarAngle
) {
withheld[activeIndex].push({ type: LayerType.Surface, id: [index, surface] });
withheld[activeIndex].push({ type: LayerType.Line, geometry: [] });
continue deactivate;
}
}
deactivateSurface.call(withheld, surface, index);
}
withheld[index]?.push({ type: LayerType.Line, geometry: [] });
}
options.bvh.shapecast({
intersectsBounds(box, _isLeaf, _score, _depth, _nodeIndex) {
return layerPlane.intersectsBox(box);
},
intersectsTriangle(target, triangleIndex, _contained, _depth) {
if (surfaceTriangles[triangleIndex] || blacklist[triangleIndex]) return;
const targets = [target.a, target.b, target.c];
const items = [targetVector1, targetVector2, targetVector3];
let a: Vector3 | null = intersect(layerPlane, targets[0], targets[1], targetVector1);
let b: Vector3 | null = null;
for (let i = 0; i < 3; i++) {
const i1 = (i + 1) % 3;
a = b;
b = intersect(
layerPlane,
targets[i1],
targets[(i1 + 1) % 3],
i % 2 === 0 ? targetVector2 : targetVector1
);
if (!a || !b) continue;
for (let i = 0; i < activeNonPlanarSurfaces.length; i++) {
const [index, surface] = activeNonPlanarSurfaces[i];
const withheldLayer = withheld[index].at(-1)!;
if (withheldLayer.type === LayerType.Surface) throw new Error('Unexpected surface');
const h1 = surface.closestPointToPoint(a);
if (
h1 &&
h1.point.z < a.z &&
Math.abs(Math.PI / 2 - h1.point.clone().sub(a).angleTo(options.bedNormal)) >
options.maxNonPlanarAngle
) {
withheldLayer.geometry.push(a.x, a.y, a.z, b.x, b.y, b.z);
return;
}
const h2 = surface.closestPointToPoint(b);
if (
h2 &&
h2.point.z < b.z &&
Math.abs(Math.PI / 2 - h2.point.clone().sub(b).angleTo(options.bedNormal)) >
options.maxNonPlanarAngle
) {
withheldLayer.geometry.push(a.x, a.y, a.z, b.x, b.y, b.z);
return;
}
}
positions.push(a.x, a.y, a.z, b.x, b.y, b.z);
return;
}
}
});
layerGeometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
self.postMessage({
type: 'layer',
data: { type: LayerType.Line, geometry: layerGeometry.toJSON() }
} satisfies LayerMessage);
self.postMessage({
type: 'progress',
percent: layer / options.geometry.boundingBox!.max.z,
layer: Math.round(layer / options.layerHeight)
} satisfies ProgressMessage);
}
for (const [index, surface] of activeNonPlanarSurfaces) {
deactivateSurface.call(withheld, surface, index);
}
}

View File

@@ -0,0 +1,88 @@
import { Vector3, BufferGeometry } from 'three';
import { type SlicerOptions } from '../slicer';
import { ExtendedTriangle, MeshBVH } from 'three-mesh-bvh';
/**
* Extracts all continuous surfaces that can be printed at the specified angle.
*/
export function extractSurfaces(
options: SlicerOptions
): [surfaces: MeshBVH[], surfaceTriangles: boolean[]] {
const qualifyingTriangles = Array.from({ length: options.index.count / 3 }, () => false);
let qualifyingTrianglesCount = 0;
const triangle = new ExtendedTriangle();
const normal = new Vector3();
for (let i = 0; i < options.index.count / 3; i++) {
triangle.setFromAttributeAndIndices(
options.positions,
options.index.array[i * 3],
options.index.array[i * 3 + 1],
options.index.array[i * 3 + 2]
);
triangle.getNormal(normal);
const angle = normal.angleTo(options.bedNormal);
// TODO: bottom layers
if (angle < options.maxNonPlanarAngle) {
qualifyingTriangles[i] = true;
qualifyingTrianglesCount++;
}
}
const surfaceTriangles = [...qualifyingTriangles];
const surfaces: number[][] = [];
while (qualifyingTrianglesCount > 0) {
const faceIndex = qualifyingTriangles.findIndex((it) => it);
qualifyingTriangles[faceIndex] = false;
qualifyingTrianglesCount--;
const surface = [faceIndex];
let cursor = 0;
while (cursor < surface.length) {
triangle.setFromAttributeAndIndices(
options.positions,
options.index.array[surface[cursor] * 3],
options.index.array[surface[cursor] * 3 + 1],
options.index.array[surface[cursor] * 3 + 2]
);
options.bvh.shapecast({
intersectsBounds(box, _isLeaf, _score, _depth, _nodeIndex) {
return triangle.intersectsBox(box);
},
intersectsTriangle(target, triangleIndex, _contained, _depth) {
if (
qualifyingTriangles[triangleIndex] &&
target.distanceToTriangle(triangle) < options.tolerance
) {
qualifyingTriangles[triangleIndex] = false;
qualifyingTrianglesCount--;
surface.push(triangleIndex);
}
}
});
cursor++;
}
surfaces.push(surface);
}
return [
surfaces.map((surface) => {
const geometry = new BufferGeometry();
geometry.setAttribute('position', options.positions);
geometry.setAttribute('normal', options.normals);
const indices: number[] = Array.from({ length: surface.length * 3 });
for (let i = 0; i < surface.length; i++) {
const pos = surface[i] * 3;
indices[i * 3] = options.index.array[pos];
indices[i * 3 + 1] = options.index.array[pos + 1];
indices[i * 3 + 2] = options.index.array[pos + 2];
}
geometry.setIndex(indices);
const bvh = new MeshBVH(geometry);
geometry.boundsTree = bvh;
return bvh;
}),
surfaceTriangles
];
}

View File

@@ -0,0 +1,135 @@
import { Plane, Line3, Vector3 } from 'three';
import type { SlicerOptions } from '../slicer';
import { approxEquals } from '../util/equals';
/**
* A continuous 2d ring of points
*
* No matter how you slice, on a model without holes all points will
* form continous rings.
*/
export interface ShellRing {
/**
* The plane the ring is on
*/
plane: Plane;
/**
* Points of the ring
*/
points: Vector3[];
}
interface BaseSlice {
/**
* The plane the slice is on
*/
plane: Plane;
/**
* The lines of the slice (not sorted!)
*/
lines: Line3[];
}
const line = new Line3();
function intersect(layerPlane: Plane, a: Vector3, b: Vector3, targetVector: Vector3) {
line.set(a, b);
return layerPlane.intersectLine(line, targetVector);
}
/**
* Creates base slices from the geometry, excluding surfaces.
*
* The slicse are not sorted or separated into rings.
*/
function createBaseSlices(options: SlicerOptions, surfaceTriangles: boolean[]): BaseSlice[] {
const targetVector1 = new Vector3();
const targetVector2 = new Vector3();
const targetVector3 = new Vector3();
const baseSlices: BaseSlice[] = [];
for (let layer = 0; layer < options.geometry.boundingBox!.max.z; layer += options.layerHeight) {
const baseSlice: BaseSlice = {
plane: new Plane(options.bedNormal, -layer),
lines: []
};
options.bvh.shapecast({
intersectsBounds(box, _isLeaf, _score, _depth, _nodeIndex) {
return baseSlice.plane.intersectsBox(box);
},
intersectsTriangle(target, triangleIndex, _contained, _depth) {
if (surfaceTriangles[triangleIndex]) return;
const intersections = [
intersect(baseSlice.plane, target.a, target.b, targetVector1),
intersect(baseSlice.plane, target.b, target.c, targetVector2),
intersect(baseSlice.plane, target.c, target.a, targetVector3)
];
for (let i = 0; i < 3; i++) {
const a = intersections[i];
const b = intersections[(i + 1) % 3];
if (a === null || b === null) continue;
baseSlice.lines.push(new Line3(a.clone(), b.clone()));
return;
}
}
});
baseSlices.push(baseSlice);
}
return baseSlices;
}
/**
* Creates shell rings from the base slice
*
* Consumes the base slices
*/
function createShellRings(baseSlice: BaseSlice): ShellRing[] {
const shellRings: ShellRing[] = [];
let left: Vector3;
let right: Vector3;
while (baseSlice.lines.length > 0) {
const start = baseSlice.lines.pop()!;
const shellRing: ShellRing = {
plane: baseSlice.plane,
points: [start.start, start.end]
};
left = shellRing.points[0];
right = shellRing.points[1];
// This should use a linked list ideally, but whatever
while (!approxEquals(left, right)) {
for (let i = 0; i < baseSlice.lines.length; i++) {
const line = baseSlice.lines[i];
if (approxEquals(line.start, right)) {
shellRing.points.push(line.start, line.end);
right = line.end;
baseSlice.lines.splice(i, 1);
break;
} else if (approxEquals(line.end, right)) {
shellRing.points.push(line.end, line.start);
right = line.start;
baseSlice.lines.splice(i, 1);
break;
}
}
}
shellRings.push(shellRing);
}
return shellRings;
}
/**
* Creates standard slices from the geometry, excluding surfaces.
*/
export function slice(options: SlicerOptions, surfaceTriangles: boolean[]) {
const shellRings = createBaseSlices(options, surfaceTriangles).map(createShellRings);
}

View File

@@ -0,0 +1,10 @@
import type { Vector3 } from 'three';
/**
* Check if two vectors are approximately equal.
*/
export function approxEquals(a: Vector3, b: Vector3, epsilon = Number.EPSILON) {
return (
Math.abs(a.x - b.x) < epsilon && Math.abs(a.y - b.y) < epsilon && Math.abs(a.z - b.z) < epsilon
);
}

View File

@@ -16,237 +16,35 @@ import {
type ProgressMessage,
type WorkerEvent
} from './worker-data';
import init, { slice } from 'bampy';
addEventListener('message', (event: MessageEvent<WorkerEvent>) => {
addEventListener('message', async (event: MessageEvent<WorkerEvent>) => {
if (event.data.type === 'slice') {
slice(event.data.data);
const geometry = new BufferGeometryLoader().parse(event.data.data.stl);
if (geometry.index !== null) {
geometry.toNonIndexed();
}
await init();
slice(
geometry.attributes.position.array as Float32Array,
geometry.attributes.normal.array as Float32Array,
event.data.data.layerHeight
);
}
});
function slice({
async function todo({
stl,
bedNormal: bedNormalArray,
maxNonPlanarAngle,
tolerance,
layerHeight
}: SliceArguments) {
greet();
self.postMessage({ type: 'progress', percent: 0, layer: 0 } satisfies ProgressMessage);
const bedNormal = new Vector3(...bedNormalArray);
const geometry = new BufferGeometryLoader().parse(stl);
const bvh = new MeshBVH(geometry);
const positions = geometry.getAttribute('position');
const normals = geometry.getAttribute('normal');
const index = geometry.index!;
const qualifyingTriangles = Array.from({ length: index.count / 3 }, () => false);
let qualifyingTrianglesCount = 0;
const triangle = new ExtendedTriangle();
const normal = new Vector3();
for (let i = 0; i < index.count / 3; i++) {
triangle.setFromAttributeAndIndices(
positions,
index.array[i * 3],
index.array[i * 3 + 1],
index.array[i * 3 + 2]
);
triangle.getNormal(normal);
const angle = normal.angleTo(bedNormal);
// TODO: bottom layers
if (angle < maxNonPlanarAngle) {
qualifyingTriangles[i] = true;
qualifyingTrianglesCount++;
}
}
const includedTriangles = [...qualifyingTriangles];
const includedTrianglesCount = qualifyingTrianglesCount;
// TODO
const surfaces: number[][] = [];
while (qualifyingTrianglesCount > 0) {
const faceIndex = qualifyingTriangles.findIndex((it) => it);
qualifyingTriangles[faceIndex] = false;
qualifyingTrianglesCount--;
const surface = [faceIndex];
let cursor = 0;
while (cursor < surface.length) {
triangle.setFromAttributeAndIndices(
positions,
index.array[surface[cursor] * 3],
index.array[surface[cursor] * 3 + 1],
index.array[surface[cursor] * 3 + 2]
);
bvh.shapecast({
intersectsBounds(box, _isLeaf, _score, _depth, _nodeIndex) {
return triangle.intersectsBox(box);
},
intersectsTriangle(target, triangleIndex, _contained, _depth) {
if (
qualifyingTriangles[triangleIndex] &&
target.distanceToTriangle(triangle) < tolerance
) {
qualifyingTriangles[triangleIndex] = false;
qualifyingTrianglesCount--;
surface.push(triangleIndex);
}
}
});
cursor++;
}
surfaces.push(surface);
}
const nonPlanarSurfaces = surfaces.map((surface) => {
const geometry = new BufferGeometry();
geometry.setAttribute('position', positions);
geometry.setAttribute('normal', normals);
const indices: number[] = Array.from({ length: surface.length * 3 });
for (let i = 0; i < surface.length; i++) {
const pos = surface[i] * 3;
indices[i * 3] = index.array[pos];
indices[i * 3 + 1] = index.array[pos + 1];
indices[i * 3 + 2] = index.array[pos + 2];
}
geometry.setIndex(indices);
const bvh = new MeshBVH(geometry);
geometry.boundsTree = bvh;
return bvh;
});
const activeNonPlanarSurfaces: [number, MeshBVH][] = [];
const consumedNonPlanarSurfaces = nonPlanarSurfaces.map(() => false);
const withheld: Array<
| { type: LayerType.Line; geometry: number[] }
| { type: LayerType.Surface; id: [number, MeshBVH] }
>[] = nonPlanarSurfaces.map(() => [{ type: LayerType.Line, geometry: [] }]);
const blacklist = Array.from({ length: index.count / 3 }).map(() => false);
const line = new Line3();
const targetVector1 = new Vector3();
const targetVector2 = new Vector3();
const targetVector3 = new Vector3();
const hit1: HitPointInfo = { point: new Vector3(), distance: 0, faceIndex: 0 };
const hit2: HitPointInfo = { point: new Vector3(), distance: 0, faceIndex: 0 };
const layerPlane = new Plane();
function deactivateSurface(surface: MeshBVH, index: number) {
self.postMessage({
type: 'layer',
data: { type: LayerType.Surface, geometry: surface.geometry.toJSON() }
} satisfies LayerMessage);
for (const thing of withheld[index]) {
if (thing.type === LayerType.Line) {
if (thing.geometry.length === 0) continue;
const additionalGeometry = new BufferGeometry();
additionalGeometry.setAttribute('position', new Float32BufferAttribute(thing.geometry, 3));
self.postMessage({
type: 'layer',
data: { type: LayerType.Line, geometry: additionalGeometry.toJSON() }
});
} else if (thing.type === LayerType.Surface) {
deactivateSurface(thing.id[1], thing.id[0]);
}
}
delete withheld[index];
}
for (let layer = 0; layer < geometry.boundingBox!.max.z; layer += layerHeight) {
layerPlane.set(bedNormal, -layer);
const layerGeometry = new BufferGeometry();
const positions: number[] = [];
for (let i = 0; i < nonPlanarSurfaces.length; i++) {
if (consumedNonPlanarSurfaces[i]) continue;
if (layer >= nonPlanarSurfaces[i].geometry.boundingBox!.min.z) {
consumedNonPlanarSurfaces[i] = true;
activeNonPlanarSurfaces.push([i, nonPlanarSurfaces[i]]);
}
}
deactivate: for (let i = 0; i < activeNonPlanarSurfaces.length; i++) {
const [index, surface] = activeNonPlanarSurfaces[i];
if (layer > surface.geometry.boundingBox!.max.z) {
activeNonPlanarSurfaces.splice(i, 1);
i--;
for (const [activeIndex, active] of activeNonPlanarSurfaces) {
if (activeIndex === index) continue;
const hit = active.closestPointToGeometry(surface.geometry, new Matrix4(), hit1, hit2);
if (
hit &&
hit1.point.z < hit2.point.z &&
Math.abs(Math.PI / 2 - hit1.point.clone().sub(hit2.point).angleTo(bedNormal)) >
maxNonPlanarAngle
) {
withheld[activeIndex].push({ type: LayerType.Surface, id: [index, surface] });
withheld[activeIndex].push({ type: LayerType.Line, geometry: [] });
continue deactivate;
}
}
deactivateSurface(surface, index);
}
withheld[index]?.push({ type: LayerType.Line, geometry: [] });
}
bvh.shapecast({
intersectsBounds(box, _isLeaf, _score, _depth, _nodeIndex) {
return layerPlane.intersectsBox(box);
},
intersectsTriangle(target, triangleIndex, _contained, _depth) {
if (includedTriangles[triangleIndex] || blacklist[triangleIndex]) return;
function intersect(a: Vector3, b: Vector3, targetVector: Vector3) {
line.set(a, b);
return layerPlane.intersectLine(line, targetVector);
}
const a = intersect(target.a, target.b, targetVector1);
const b = intersect(target.b, target.c, targetVector2);
const c = intersect(target.c, target.a, targetVector3);
function add(a: Vector3, b: Vector3) {
for (let i = 0; i < activeNonPlanarSurfaces.length; i++) {
const [index, surface] = activeNonPlanarSurfaces[i];
const withheldLayer = withheld[index].at(-1)!;
if (withheldLayer.type === LayerType.Surface) throw new Error('Unexpected surface');
const h1 = surface.closestPointToPoint(a);
if (
h1 &&
h1.point.z < a.z &&
Math.abs(Math.PI / 2 - h1.point.clone().sub(a).angleTo(bedNormal)) > maxNonPlanarAngle
) {
withheldLayer.geometry.push(a.x, a.y, a.z, b.x, b.y, b.z);
return;
}
const h2 = surface.closestPointToPoint(b);
if (
h2 &&
h2.point.z < b.z &&
Math.abs(Math.PI / 2 - h2.point.clone().sub(b).angleTo(bedNormal)) > maxNonPlanarAngle
) {
withheldLayer.geometry.push(a.x, a.y, a.z, b.x, b.y, b.z);
return;
}
}
positions.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
if (a && b) {
add(a, b);
} else if (b && c) {
add(b, c);
} else if (c && a) {
add(c, a);
}
}
});
layerGeometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
self.postMessage({
type: 'layer',
data: { type: LayerType.Line, geometry: layerGeometry.toJSON() }
} satisfies LayerMessage);
self.postMessage({
type: 'progress',
percent: layer / geometry.boundingBox!.max.z,
layer: Math.round(layer / layerHeight)
} satisfies ProgressMessage);
}
for (const [index, surface] of activeNonPlanarSurfaces) {
deactivateSurface(surface, index);
}
self.postMessage({
type: 'progress',
layer: Math.round(geometry.boundingBox!.max.z / layerHeight)