checkpoint kiri module migration work

This commit is contained in:
Stewart Allen 2025-07-04 22:18:18 -04:00
commit 7d22cc1029
201 changed files with 41262 additions and 85 deletions

View file

@ -0,0 +1,310 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
// WORKER BACK END ANIMATION CODE for 2D
let stock, center, grid, gridX, gridY, rez;
let path, pathIndex, tool, tools, last, toolID = 1;
kiri.worker.animate_setup = function(data, send) {
const { settings } = data;
const { process } = settings;
const print = worker.print;
const density = parseInt(settings.controller.animesh) * 1000;
pathIndex = 0;
path = print.output.flat();
tools = settings.tools;
stock = settings.stock;
rez = 1/Math.sqrt(density/(stock.x * stock.y));
//destructure arcs into path points
path = path.map(o=>
o.arcPoints
? [
...o.arcPoints.map(point=>
({
...o,
point
})
),
o
]
: o
)
.flat();
const step = rez;
const stepsX = Math.floor(stock.x / step);
const stepsY = Math.floor(stock.y / step);
const { pos, ind, sab } = createGrid(stepsX, stepsY, stock, step, true);
const offset = {
x: process.camOriginCenter ? 0 : stock.x / 2,
y: process.camOriginCenter ? 0 : stock.y / 2,
z: process.camOriginTop ? -stock.z : 0
}
grid = pos;
gridX = stepsX;
gridY = stepsY;
tool = null;
last = null;
animating = false;
animateClear = false;
center = Object.assign({}, stock.center);
center.z -= stock.z / 2;
send.data({ mesh_add: { id: 0, ind, offset, sab } }, [ ]); // sab not transferrable
send.data({ mesh_move: { id: 0, pos: center } });
send.done();
};
kiri.worker.animate = function(data, send) {
renderPause = data.pause || renderPause;
renderSpeed = data.speed || 0;
if (animating) {
return send.done();
}
renderSteps = data.steps || 1;
renderDone = false;
animating = renderSpeed > 0;
renderPath(send);
};
kiri.worker.animate_cleanup = function(data, send) {
if (animating) {
animateClear = true;
}
};
function createGrid(stepsX, stepsY, size, step, stock) {
const gridPoints = stepsX * stepsY;
const sab = new SharedArrayBuffer(gridPoints * 3 * 4)
const pos = new Float32Array(sab);
const ind = [];
const ox = size.x / 2;
const oy = size.y / 2;
let ex = stepsX - 1;
let ey = stepsY - 1;
// initialize grid points
for (let x=0, ai=0; x<stepsX; x++) {
for (let y=0; y<stepsY; y++) {
let px = pos[ai++] = x * step - ox + step / 2;
let py = pos[ai++] = y * step - oy + step / 2;
pos[ai++] = stock && (x * y === 0 || x === ex || y === ey) ? 0 : size.z;
if (asPoints) {
continue;
}
if (asLines) {
if (y > 0) ind.appendAll([
(stepsY * x) + (y - 1),
(stepsY * x) + (y )
]);
if (x > 0) ind.appendAll([
(stepsY * (x - 1)) + y,
(stepsY * (x )) + y
]);
} else {
if (x > 0 && y > 0) {
let v0 = stepsY * (x - 1) + y - 1;
let v1 = stepsY * (x - 0) + y - 1;
let v2 = stepsY * (x - 0) + y;
let v3 = stepsY * (x - 1) + y;
ind.appendAll([
v0, v1, v2, v0, v2, v3
]);
}
}
}
}
return { pos, ind, sab };
}
let animateClear = false;
let animating = false;
let renderDist = 0;
let renderDone = false;
let renderPause = 10;
let renderSteps = 0;
let renderSpeed = 0;
let skipMove = null;
let toolUpdate;
let depth = 0;
// send latest tool position and progress bar
function renderUpdate(send) {
if (toolUpdate) {
send.data(toolUpdate);
}
send.data({ progress: pathIndex / path.length, id: 0, mesh_update: 1 });
}
function renderPath(send) {
if (renderDone) {
return;
}
if (renderSteps-- === 0) {
animating = false;
renderPath(send);
return;
}
if (animating === false || animateClear || renderSpeed === 0) {
renderUpdate(send);
renderDone = true;
animating = false;
animateClear = false;
send.done();
return;
}
let next = path[pathIndex];
while (next && next.type === 'laser') {
last = next;
next = path[++pathIndex];
}
if (!next) {
animating = false;
renderPath(send);
return;
}
pathIndex++;
const firstTool = !tool && next.tool;
const toolChange = !firstTool && (tool.getID() !== next.tool.getID());
if (firstTool || toolChange) {
// on real tool change, go to safe Z first
if (tool && last.point) {
let pos = last.point = {
x: last.point.x,
y: last.point.y,
z: stock.z
};
send.data({ mesh_move: { toolID, pos }});
}
updateTool(next.tool, send);
}
const id = toolID;
const rezstep = rez;
if (last) {
const lp = last.point, np = next.point;
last = next;
// dwell ops have no point
if (!np || !lp) {
return renderPath(send);
}
const dx = np.x - lp.x, dy = np.y - lp.y, dz = np.z - lp.z;
const dist = Math.sqrt(dx*dx + dy*dy + dz*dz);
renderDist += dist;
// skip moves that are less than grid resolution
if (renderDist < rezstep) {
renderPath(send);
return;
}
const md = Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz));
const st = Math.ceil(md / rezstep);
const mx = dx / st, my = dy / st, mz = dz / st;
const moves = [];
for (let i=0, x=lp.x, y=lp.y, z=lp.z; i<st; i++) {
moves.push({x,y,z});
x += mx;
y += my;
z += mz;
}
moves.push(next.point);
renderMoves(id, moves, send);
} else {
last = next;
if (tool) {
tool.pos = next.point;
toolUpdate = { mesh_move: { id, pos: next.point }};
}
renderPath(send);
}
}
function renderMoves(id, moves, send, seed = 0) {
for (let index = seed; index<moves.length; index++) {
const pos = moves[index];
if (!pos) {
throw `no pos @ ${index} of ${moves.length}`;
}
tool.pos = pos;
deformMesh(pos, send);
toolUpdate = { mesh_move: { id, pos }};
// pause renderer at specified offsets
if ((renderSpeed && renderDist >= renderSpeed) || (depth > 600)) {
renderDist = depth = 0;
renderUpdate(send);
setTimeout(() => {
renderMoves(id, moves, send, index);
}, renderPause);
return;
}
}
depth++;
renderPath(send);
}
// update stock mesh to reflect tool tip geometry at given XYZ position
function deformMesh(pos, send) {
const prof = tool.profile;
const { size, pix } = tool.profileDim;
const mid = Math.floor(pix / 2);
const rx = Math.floor((pos.x + stock.x / 2 - size / 2 - center.x) / rez);
const ry = Math.floor((pos.y + stock.y / 2 - size / 2 - center.y) / rez);
let upos = 0;
// deform mesh to lowest point on tool profile
for (let i=0, il=prof.length; i < il; ) {
const dx = mid + prof[i++];
const dy = mid + prof[i++];
const dz = prof[i++];
const gx = rx + dx;
const gy = ry + dy;
if (gx < 0|| gy < 0 || gx > gridX-1 || gy > gridY-1) {
continue;
}
const gi = gx * gridY + gy;
const iz = gi * 3 + 2;
const cz = grid[iz];
const tz = tool.pos.z - dz;
if (tz < cz) {
upos++;
grid[iz] = tz;
}
}
}
function updateTool(toolobj, send) {
if (tool) {
send.data({ mesh_del: toolID });
}
tool = new CAM.Tool({ tools }, toolobj.getID());
tool.generateProfile(rez);
const flen = tool.fluteLength() || 15;
const slen = tool.shaftLength() || 15;
// const frad = tool.fluteDiameter() / 2;
const prof = tool.profile;
const { size, pix } = tool.profileDim;
const { pos, ind, sab } = createGrid(pix, pix, {x:size, y:size, z:flen+slen}, rez);
const mid = Math.floor(pix/2);
// deform mesh to fit tool profile
for (let i=0, il=prof.length; i < il; ) {
const dx = mid + prof[i++];
const dy = mid + prof[i++];
const dz = prof[i++];
pos[(dx * pix + dy) * 3 + 2] = -dz;
}
send.data({ mesh_add: { id:++toolID, ind, sab }});
}

View file

@ -0,0 +1,309 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
// UI FRONT END ANIMATION CODE for 2D
import { api } from '../../kiri/api.js';
import { space } from '../../moto/space.js';
const { client } = api;
const asLines = false;
const asPoints = false;
let meshes = {},
button = {},
label = {},
unitScale = 1,
speedValues = [ 1, 2, 4, 8, 32 ],
speedPauses = [ 30, 20, 10, 5, 0 ],
speedNames = [ "1x", "2x", "4x", "8x", "!!" ],
speedMax = speedValues.length - 1,
speedIndex = 0,
speed,
color = 0,
material,
origin,
posOffset = { x:0, y:0, z:0 };
export function animate_clear(api) {
let { anim } = api.ui;
space.platform.showGridBelow(true);
client.animate_cleanup();
Object.keys(meshes).forEach(id => deleteMesh(id));
toggleStock(undefined,true,false);
api.uc.setVisible(anim.laba, false);
api.uc.setVisible(anim.vala, false);
}
export function animate(api, delay) {
let alert = api.alerts.show("building animation");
let settings = api.conf.get();
client.animate_setup(settings, data => {
checkMeshCommands(data);
if (!(data && data.mesh_add)) {
return;
}
let { anim } = api.ui;
Object.assign(button, {
replay: anim.replay,
play: anim.play,
step: anim.step,
pause: anim.pause,
speed: anim.speed,
trans: anim.trans,
model: anim.model,
shade: anim.shade
});
Object.assign(label, {
progress: anim.progress,
speed: anim.labspd,
x: anim.valx,
y: anim.valy,
z: anim.valz,
});
origin = settings.origin;
speedIndex = api.local.getInt('cam.anim.speed') || 0;
updateSpeed();
setTimeout(step, delay || 0);
button.replay.onclick = replay;
button.play.onclick = play;
button.step.onclick = step;
button.pause.onclick = pause;
button.speed.onclick = fast;
button.trans.onclick = toggleTrans;
button.model.onclick = toggleModel;
button.shade.onclick = toggleStock;
button.play.style.display = '';
button.pause.style.display = 'none';
api.event.emit('animate', 'CAM');
api.alerts.hide(alert);
space.platform.showGridBelow(false);
toggleTrans(0,api.local.getBoolean('cam.anim.trans', true));
toggleModel(0,api.local.getBoolean('cam.anim.model', false));
toggleStock(0,api.local.getBoolean('cam.anim.stock', false));
});
}
Object.assign(client, {
animate(data, ondone) {
client.send("animate", data, ondone);
},
animate_setup(settings, ondone) {
color = settings.controller.dark ? 0x48607B : 0x607FA4;
unitScale = settings.controller.units === 'in' ? 1/25.4 : 1;
let flatShading = true,
transparent = true,
opacity = 0.9,
side = THREE.DoubleSide;
material = new THREE.MeshPhongMaterial({
flatShading,
transparent,
opacity,
color,
side
});
add_red_neg_z(material);
client.send("animate_setup", {settings}, ondone);
},
animate_cleanup(data, ondone) {
client.send("animate_cleanup", data, ondone);
}
});
function meshAdd(id, ind, pos, sab) {
const geo = new THREE.BufferGeometry();
if (sab) {
// use array buffer shared with worker
pos = new Float32Array(sab);
}
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
if (ind.length) {
geo.setIndex(new THREE.BufferAttribute(new Uint32Array(ind), 1));
}
let mesh;
if (asPoints) {
const mat = new THREE.PointsMaterial({
transparent: true,
opacity: 0.75,
color: 0x888888,
size: 0.3
});
mesh = new THREE.Points(geo, mat);
} else if (asLines) {
const mat = new THREE.LineBasicMaterial({
transparent: true,
opacity: 0.75,
color
});
mesh = new THREE.LineSegments(geo, mat);
} else {
geo.computeVertexNormals();
mesh = new THREE.Mesh(geo, material);
mesh.renderOrder = -10;
}
space.world.add(mesh);
meshes[id] = mesh;
}
function meshUpdates(id) {
const mesh = meshes[id];
if (!mesh) {
return; // animate cancelled
}
mesh.geometry.attributes.position.needsUpdate = true;
space.update();
}
function deleteMesh(id) {
space.world.remove(meshes[id]);
delete meshes[id];
}
function toggleModel(ev,bool) {
api.local.toggle('cam.anim.model', bool);
api.widgets.all().forEach(w => w.toggleVisibility(bool));
}
function toggleStock(ev,bool,set) {
set !== false && api.local.toggle('cam.anim.stock', bool);
return api.event.emit('cam.stock.toggle', bool ?? undefined);
}
function toggleTrans(ev,bool) {
bool = api.local.toggle('cam.anim.trans', bool);
material.transparent = bool;
material.needsUpdate = true;
}
function step() {
updateSpeed();
client.animate({speed, steps: 1}, handleGridUpdate);
}
function play(opts) {
const { steps } = opts;
updateSpeed();
if (steps !== 1) {
button.play.style.display = 'none';
button.pause.style.display = '';
}
client.animate({
speed,
steps: steps || Infinity,
pause: speedPauses[speedIndex]
}, handleGridUpdate);
}
function fast(opts) {
const { steps } = opts;
updateSpeed(1);
button.play.style.display = 'none';
button.pause.style.display = '';
client.animate({
speed,
steps: steps || Infinity,
pause: speedPauses[speedIndex]
}, handleGridUpdate);
}
function pause() {
button.play.style.display = '';
button.pause.style.display = 'none';
client.animate({speed: 0}, handleGridUpdate);
}
function handleGridUpdate(data) {
checkMeshCommands(data);
if (data && data.progress) {
label.progress.value = (data.progress * 100).toFixed(1);
}
}
function updateSpeed(inc = 0) {
if (inc === Infinity) {
speedIndex = speedMax;
} else if (inc > 0) {
speedIndex = (speedIndex + inc) % speedValues.length;
}
api.local.set('cam.anim.speed', speedIndex);
speed = speedValues[speedIndex];
label.speed.value = speedNames[speedIndex];
}
function replay() {
animate_clear(api);
setTimeout(() => {
animate(api, 50);
}, 250);
}
function checkMeshCommands(data) {
if (!data) {
return;
}
if (data.mesh_add) {
const { id, ind, pos, offset, sab } = data.mesh_add;
meshAdd(id, ind, pos, sab);
space.refresh();
if (offset) {
posOffset = offset;
}
}
if (data.mesh_del) {
deleteMesh(data.mesh_del);
}
if (data.mesh_move) {
const { id, pos } = data.mesh_move;
const mesh = meshes[id];
if (mesh) {
mesh.position.x = pos.x;
mesh.position.y = pos.y;
mesh.position.z = pos.z;
space.update();
}
label.x.value = (pos.x - origin.x).toFixed(2);
label.y.value = (pos.y + origin.y).toFixed(2);
label.z.value = (pos.z - origin.z).toFixed(2);
}
if (data.mesh_update) {
meshUpdates(data.id);
}
}
// SHADER: tint points below z=0 with red
function add_red_neg_z(material) {
material.onBeforeCompile = (shader) => {
shader.vertexShader = shader.vertexShader.replace(
`#include <worldpos_vertex>`,
`
#include <worldpos_vertex>
vWorldPosition = vec3(transformed);
`
);
shader.vertexShader = `
varying vec3 vWorldPosition;
` + shader.vertexShader;
shader.fragmentShader = `
varying vec3 vWorldPosition;
` + shader.fragmentShader;
shader.fragmentShader = shader.fragmentShader.replace(
`#include <dithering_fragment>`,
`
#include <dithering_fragment>
if (vWorldPosition.z < 0.0) {
gl_FragColor.rgb += vec3(0.5, 0.0, 0.0); // Add red tint
}
`
);
};
return material;
}

View file

@ -0,0 +1,391 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
// WORKER BACK END ANIMATION CODE for 3D (indexed)
import { CSG } from '../../geo/csg.js';
let nextMeshID = 1;
let stock, center, rez;
let path, pathIndex, tool, tools, last;
let stockZ;
let stockIndexMsg = false;
let stockSlices;
let stockIndex;
let startTime;
let toolID = -1;
let toolMesh;
let toolRadius;
let toolUpdateMsg;
let animateClear = false;
let animating = false;
let moveDist = 0;
let renderDist = 0;
let renderDone = false;
let renderPause = 10;
let renderSteps = 0;
let renderSpeed = 0;
let indexCount = 0;
let updates = 0;
kiri.worker.animate_setup2 = function (data, send) {
const { settings } = data;
const { process } = settings;
const print = worker.print;
const density = parseInt(settings.controller.animesh) * 1000;
const isIndexed = process.camStockIndexed;
pathIndex = 0;
path = print.output.flat();
tools = settings.tools;
stock = settings.stock;
rez = 1 / Math.sqrt(density / (stock.x * stock.y));
tool = null;
last = null;
animating = false;
animateClear = false;
stockIndex = 0;
indexCount = 0;
startTime = 0;
updates = 0;
stockZ = isIndexed ? 0 : stock.z;
stockSlices = [];
const { x, y, z } = stock;
const sliceCount = parseInt(settings.controller.animesh || 2000) / 100;
const sliceWidth = stock.x / sliceCount;
for (let i = 0; i < sliceCount; i++) {
let xmin = -(x / 2) + (i * sliceWidth) + sliceWidth / 2;
let slice = new Stock(sliceWidth, y, z).translate(xmin, 0, 0);
stockSlices.push(slice);
slice.updateMesh([]);
slice.send(send);
// send({ mesh_move: { id: slice.id, pos: { x:0, y:0, z: stock.z/2} } });
}
send.done();
};
kiri.worker.animate2 = function (data, send) {
renderPause = data.pause || renderPause;
renderSpeed = data.speed || 0;
if (animating) {
return send.done();
}
renderSteps = data.steps || 1;
renderDone = false;
animating = renderSpeed > 0;
startTime = startTime || Date.now();
renderPath(send);
};
kiri.worker.animate_cleanup2 = function (data, send) {
if (animating) {
animateClear = true;
}
};
function renderPath(send) {
if (renderDone) {
return;
}
if (renderSteps-- === 0) {
animating = false;
renderPath(send);
return;
}
if (animating === false || animateClear || renderSpeed === 0) {
renderUpdate(send);
renderDone = true;
animating = false;
animateClear = false;
send.done();
return;
}
let next = path[pathIndex];
while (next && next.type === 'laser') {
last = next;
next = path[++pathIndex];
}
if (!next) {
console.log('animation completed in ', ((Date.now() - startTime) / 1000).round(2));
animating = false;
renderPath(send);
return;
}
pathIndex++;
// console.log(next.point.z);
if (next.tool && (!tool || tool.getID() !== next.tool.getID())) {
// on real tool change, go to safe Z first
if (tool && last.point) {
let pos = last.point = {
x: last.point.x,
y: last.point.y,
z: stock.z
};
toolMove(pos);
send.data(toolUpdateMsg);
}
toolUpdate(next.tool.getID(), send);
}
const id = toolID;
const rezstep = rez * 2;
if (last) {
const lp = last.point, np = next.point;
last = next;
// dwell ops have no point
if (!np || !lp) {
return renderPath(send);
}
let dx = np.x - lp.x,
dy = np.y - lp.y,
dz = np.z - lp.z,
da = Math.abs((np.a || 0) - (lp.a || 0)),
dr = (da / 360) * (2 * Math.PI * Math.max(np.z, lp.z)),
dist = Math.sqrt(dx * dx + dy * dy + dz * dz + dr * dr);
moveDist += dist;
// skip moves that are less than grid resolution
if (moveDist < rezstep) {
// console.log('skip', moveDist, rezstep, next);
renderPath(send);
return;
}
const md = Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz), dr);
const st = Math.ceil(md / rezstep);
const mx = dx / st, my = dy / st, mz = dz / st;
// const sd = Math.sqrt(mx*mx + my*my + mz*mz + dr*dr);
const sd = Math.sqrt(mx * mx + my * my + Math.min(1, mz * mz) + dr * dr);
const moves = [];
for (let i = 0, x = lp.x, y = lp.y, z = lp.z; i < st; i++) {
moves.push({ x, y, z, a: lp.a, md: sd, dx, dy, dz });
x += mx;
y += my;
z += mz;
}
moveDist = 0;
moves.push({ ...next.point, md: sd });
renderMoves(id, moves, send);
} else {
last = next;
if (tool) {
toolMove(next.point);
}
renderPath(send);
}
}
function renderMoves(id, moves, send, seed = 0) {
for (let index = seed; index < moves.length; index++) {
const pos = moves[index];
if (!pos) {
throw `no pos @ ${index} of ${moves.length}`;
}
const { dx, dy, dz } = pos;
toolMove(pos);
// console.log('renderMoves', {id, moves, seed});
let subs = 0;
if (dx || dy || dz < 0)
for (let slice of stockSlices) {
if (slice.bounds.intersectsBox(toolMesh.bounds)) {
slice.subtractTool(toolMesh);
subs++;
}
}
// console.log({ index, subs });
renderDist += pos.md;
// pause renderer at specified offsets
if (renderSpeed && renderDist >= renderSpeed) {
renderDist = 0;
renderUpdate(send);
setTimeout(() => {
renderMoves(id, moves, send, index + 1);
}, renderPause);
return;
}
}
renderPath(send);
}
// send latest tool position and progress bar
function renderUpdate(send) {
const updated = []
for (let slice of stockSlices) {
slice.updateMesh(updated);
}
for (let slice of updated) {
slice.send(send);
}
if (toolUpdateMsg) {
send.data(toolUpdateMsg);
}
if (stockIndexMsg) {
send.data({ stock_index: stockIndex });
for (let slice of stockSlices) {
send.data({ mesh_index: { id: slice.id, index: -stockIndex } });
}
stockIndexMsg = false;
}
send.data({ progress: pathIndex / path.length });
updates++;
}
// move tool mesh animation space, update client
function toolMove(pos) {
toolUpdateMsg = { mesh_move: { id: toolID, pos: { x: pos.x, y: pos.y, z: pos.z } } };
if (toolMesh.mesh) {
toolMesh.mesh.delete();
}
toolMesh.mesh = toolMesh.root.translate(pos.x, pos.y, pos.z);
if (pos.a !== undefined) {
let tmp = toolMesh.mesh.rotate([pos.a, 0, 0]);
toolMesh.mesh.delete();
toolMesh.mesh = tmp;
if (pos.a !== stockIndex) {
stockIndexMsg = true;
stockIndex = pos.a;
}
}
toolMesh.bounds = CSG.toBox3(toolMesh.mesh);
}
// delete old tool mesh, generate tool mesh, send to client
function toolUpdate(toolid, send) {
if (tool) {
send.data({ mesh_del: toolID });
}
tool = new CAM.Tool({ tools }, toolid);
const Instance = CSG.Instance();
const slen = tool.shaftLength() || 15;
const srad = tool.shaftDiameter() / 2;
const flen = tool.fluteLength() || 15;
const frad = toolRadius = tool.fluteDiameter() / 2;
const tlen = slen + flen; // total tool length
let { cylinder, sphere } = Instance.Manifold;
let mesh;
if (tool.isBallMill()) {
mesh = cylinder(tlen - frad * 2, frad, frad, 20, true)
.add(sphere(frad, 20).translate(0, 0, -(tlen - frad * 2) / 2))
.add(cylinder(slen, srad, srad, 20, true).translate(0, 0, flen / 2));
} else if (tool.isTaperMill()) {
const trad = Math.max(tool.tipDiameter() / 2, 0.001);
mesh = cylinder(slen, srad, srad, 20, true).translate(0, 0, slen / 2)
.add(cylinder(flen, trad, frad, 20, true).translate(0, 0, -flen / 2));
} else {
mesh = cylinder(tlen, frad, frad, 20, true)
.add(cylinder(slen, srad, srad, 20, true).translate(0, 0, flen / 2));
}
mesh = mesh.translate(0, 0, (tlen - stockZ) / 2);
const raw = mesh.getMesh();
const vertex = raw.vertProperties;
const index = raw.triVerts;
toolMesh = { root: mesh, index, vertex, bounds: CSG.toBox3(mesh) };
send.data({ mesh_add: { id: --toolID, ind: index, pos: vertex } });
}
class Stock {
constructor(x, y, z) {
this.id = nextMeshID++;
this.vbuf = undefined;
this.ibuf = undefined;
this.ilen = 0;
this.sends = 0;
this.newbuf = true;
this.subtracts = 0;
this.mesh = CSG.Instance().Manifold.cube([x, y, z], true);
}
send(send) {
const newbuf = this.newbuf;
const action = this.sends++ === 0 ? 'mesh_add' : 'mesh_update';
send.data({
[action]: {
id: this.id,
ind: newbuf ? this.ibuf : undefined,
pos: newbuf ? this.vbuf : undefined,
ilen: this.ilen,
plen: this.plen
}
});
this.newbuf = false;
this.sends++;
// console.log({ send: this.id, newbuf, action });
}
translate(x, y, z) {
// console.log({ translate: this.id, x, y, z });
const oldmesh = this.mesh;
this.mesh = this.mesh.translate(x, y, z);
this.bounds = CSG.toBox3(this.mesh);
oldmesh.delete();
return this;
}
updateMesh(updates) {
if (this.sends > 0 && this.subtracts === 0) {
return;
}
const subs = this.subtracts;
this.subtracts = 0;
let start = Date.now();
let mesh = this.mesh.getMesh();
this.sharedVertexBuffer(mesh.numVert * 3);
this.sharedIndexBuffer(mesh.numTri * 3);
this.vbuf.set(mesh.vertProperties);
this.ibuf.set(mesh.triVerts);
let sub = Date.now();
updates.push(this);
if (false) console.log({
update: this.id,
time: sub - start,
subs,
mssub: ((sub - start) / subs).round(3)
});
}
subtractTool(toolMesh) {
const oldmesh = this.mesh;
this.mesh = this.mesh.subtract(toolMesh.mesh);
oldmesh.delete();
this.subtracts++;
}
sharedVertexBuffer(size) {
const old = this.vbuf;
this.plen = size;
if (old && old.length >= size) {
// console.log({svb: this.id, reuse: size, old: old.length});
return old;
}
// let buf = new Float32Array(new SharedArrayBuffer(size * 4));
let buf = new Float32Array(new SharedArrayBuffer(size * 4 + 1024 * 1024));
// console.log({new_svb: this.id, size, buf});
this.newbuf = true;
return this.vbuf = buf;
}
sharedIndexBuffer(size) {
const old = this.ibuf;
this.ilen = size;
if (old && old.length >= size) {
// console.log({sib: this.id, reuse: size, old: old.length});
return old;
}
// let buf = new Uint32Array(new SharedArrayBuffer(size * 4));
let buf = new Uint32Array(new SharedArrayBuffer(size * 4 + 1024 * 1024));
// console.log({new_sib: this.id, size, buf});
this.newbuf = true;
return this.ibuf = buf;
}
}

View file

@ -0,0 +1,253 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
// UI FRONT END ANIMATION CODE for 3D (indexed)
import { api } from '../../kiri/api.js';
import { space } from '../../moto/space.js';
const { client } = api;
let meshes = {},
button = {},
label = {},
material,
speedPauses = [0, 0, 0, 0, 0],
speedValues = [1, 2, 4, 8, 32],
speedNames = ["1x", "2x", "4x", "8x", "!!"],
speedMax = speedValues.length - 1,
speedIndex = 0,
speed,
origin,
color = 0;
export function animate_clear2(api) {
let { anim } = api.ui;
client.animate_cleanup2();
Object.keys(meshes).forEach(id => deleteMesh(id));
api.widgets.setAxisIndex(0);
api.uc.setVisible(anim.laba, true);
api.uc.setVisible(anim.vala, true);
anim.vala.value = "0.0";
}
export function animate2(api, delay) {
let alert = api.alerts.show("building animation");
let settings = api.conf.get();
client.animate_setup2(settings, data => {
handleUpdate(data);
if (data) {
return;
}
let { anim } = api.ui;
Object.assign(button, {
replay: anim.replay,
play: anim.play,
step: anim.step,
pause: anim.pause,
speed: anim.speed,
trans: anim.trans,
model: anim.model,
shade: anim.shade
});
Object.assign(label, {
progress: anim.progress,
speed: anim.labspd,
x: anim.valx,
y: anim.valy,
z: anim.valz,
a: anim.vala
});
updateSpeed(0);
setTimeout(step, delay || 0);
toggleTrans(undefined, false);
origin = settings.origin;
button.replay.onclick = replay;
button.play.onclick = play;
button.step.onclick = step;
button.pause.onclick = pause;
button.speed.onclick = fast;
button.trans.onclick = toggleTrans;
button.model.onclick = toggleModel;
button.shade.onclick = toggleStock;
button.play.style.display = '';
button.pause.style.display = 'none';
api.event.emit('animate', 'CAM');
api.alerts.hide(alert);
});
}
Object.assign(client, {
animate2(data, ondone) {
client.send("animate2", data, ondone);
},
animate_setup2(settings, ondone) {
color = settings.controller.dark ? 0x888888 : 0;
material = new THREE.MeshMatcapMaterial({
flatShading: true,
transparent: false,
opacity: 0.9,
color: 0x888888,
side: THREE.DoubleSide
});
client.send("animate_setup2", { settings }, ondone);
},
animate_cleanup2(data, ondone) {
client.send("animate_cleanup2", data, ondone);
}
});
function meshAdd(id, ind, pos, ilen, plen) {
const geo = new THREE.BufferGeometry();
const pa = plen ? pos.subarray(0, plen * 3) : pos;
const ia = ilen ? ind.subarray(0, ilen) : ind;
geo.setAttribute('position', new THREE.BufferAttribute(pa, 3));
geo.setIndex(new THREE.BufferAttribute(ia, 1));
const mesh = new THREE.Mesh(geo, material);
mesh.pos = pos;
mesh.ind = ind;
space.world.add(mesh);
meshes[id] = mesh;
}
function meshUpdate(id, ind, pos, ilen, plen) {
const mesh = meshes[id];
if (!mesh) {
return; // animate cancelled
}
const geo = mesh.geometry;
mesh.pos = pos || mesh.pos;
mesh.ind = ind || mesh.ind;
geo.setAttribute('position', new THREE.BufferAttribute(mesh.pos.subarray(0, plen * 3), 3));
geo.setIndex(new THREE.BufferAttribute(mesh.ind.subarray(0, ilen), 1));
geo.attributes.position.needsUpdate = true;
geo.index.needsUpdate = true;
space.update();
}
function deleteMesh(id) {
space.world.remove(meshes[id]);
delete meshes[id];
}
function toggleModel(ev, bool) {
api.local.toggle('cam.anim.model', bool);
api.widgets.all().forEach(w => w.toggleVisibility(bool));
}
function toggleStock(ev, bool, set) {
set !== false && api.local.toggle('cam.anim.stock', bool);
return api.event.emit('cam.stock.toggle', bool ?? undefined);
}
function toggleTrans(ev, bool) {
bool = api.local.toggle('cam.anim.trans', bool);
material.transparent = bool;
material.needsUpdate = true;
}
function step() {
updateSpeed();
client.animate2({ speed, steps: 1 }, handleUpdate);
}
function play(opts) {
const { steps } = opts;
updateSpeed();
if (steps !== 1) {
button.play.style.display = 'none';
button.pause.style.display = '';
}
client.animate2({
speed,
steps: steps || Infinity,
pause: speedPauses[speedIndex]
}, handleUpdate);
}
function fast(opts) {
const { steps } = opts;
updateSpeed(1);
button.play.style.display = 'none';
button.pause.style.display = '';
client.animate2({
speed,
steps: steps || Infinity,
pause: speedPauses[speedIndex]
}, handleUpdate);
}
function pause() {
button.play.style.display = '';
button.pause.style.display = 'none';
client.animate2({ speed: 0 }, handleUpdate);
}
function handleUpdate(data) {
if (!data) {
return;
}
if (data.mesh_add) {
const { id, ind, pos, ilen, plen } = data.mesh_add;
meshAdd(id, ind, pos, ilen, plen);
space.refresh();
}
if (data.mesh_del) {
deleteMesh(data.mesh_del);
}
if (data.mesh_move) {
const { id, pos } = data.mesh_move;
const mesh = meshes[id];
if (mesh) {
mesh.position.x = pos.x;
mesh.position.y = pos.y;
mesh.position.z = pos.z;
space.refresh();
}
label.x.value = (pos.x - origin.x).toFixed(2);
label.y.value = (pos.y + origin.y).toFixed(2);
label.z.value = (pos.z - origin.z).toFixed(2);
}
if (data.stock_index !== undefined) {
api.widgets.setAxisIndex(data.stock_index);
label.a.value = -data.stock_index.toFixed(1);
}
if (data.mesh_index) {
const { id, index } = data.mesh_index;
const mesh = meshes[id];
if (mesh) {
mesh.rotation.x = (Math.PI / 180) * index;
space.refresh();
}
}
if (data.mesh_update) {
const { id, ind, pos, ilen, plen } = data.mesh_update;
meshUpdate(id, ind, pos, ilen, plen);
}
if (data && data.progress) {
label.progress.value = (data.progress * 100).toFixed(1);
}
}
function updateSpeed(inc = 0) {
if (inc === Infinity) {
speedIndex = speedMax;
} else if (inc > 0) {
speedIndex = (speedIndex + inc) % speedValues.length;
}
api.local.set('cam.anim.speed', speedIndex);
speed = speedValues[speedIndex];
label.speed.value = speedNames[speedIndex];
}
function replay() {
animate_clear2(api);
setTimeout(() => {
animate2(api, 50);
}, 250);
}

2305
src2/kiri-mode/cam/client.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,98 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { codec } from '../../kiri/codec.js';
import { cam_slice } from './slice.js';
import { cam_prepare } from './prepare.js';
import { cam_export } from './export.js';
function surface_prep(widget, index) {
if (!widget.tool) {
let tool = widget.tool = new mesh.tool();
let translate = index ? true : false;
tool.index(widget.getGeoVertices({ unroll: true, translate }));
}
};
function surface_find(widget, faces, radians) {
CAM.surface_prep(widget);
return widget.tool.findConnectedSurface(faces, radians || 0, 0.0);
};
function init(worker) {
worker.cam_surfaces = function(data, send) {
const { settings, index } = data;
const widgets = Object.values(worker.cache);
for (let widget of widgets) {
if (index) {
widget.setIndexed(true);
widget.setAxisIndex(-index);
} else {
widget.setIndexed(false);
widget.setAxisIndex(0);
}
CAM.surface_prep(widget, index);
}
send.done({});
};
worker.cam_surface_find = function(data, send) {
const { id, face, radians } = data;
const widget = worker.cache[id];
const faces = CAM.surface_find(widget, [face], radians);
send.done(faces);
}
worker.cam_traces = async function(data, send) {
const { settings, single } = data;
const widgets = Object.values(worker.cache);
const fresh = [];
for (let widget of widgets) {
if (await CAM.traces(settings, widget, single)) {
fresh.push(widget);
}
}
// const fresh = widgets.filter(widget => CAM.traces(settings, widget, single));
send.done(codec.encode(fresh.map(widget => { return {
id: widget.id,
traces: widget.traces,
} } )));
};
worker.cam_traces_clear = function(data, send) {
for (let widget of Object.values(worker.cache)) {
delete widget.traces;
delete widget.topo;
}
send.done({});
};
worker.cam_holes = async function(data, send) {
const { settings, indiv, rec } = data;
const widgets = Object.values(worker.cache);
const fresh = [];
for (let [i,widget] of widgets.entries() ) {
if (await CAM.holes(settings, widget, indiv, rec,
( prog, msg )=>{ send.data({progress: (i/widgets.length)+(prog/widgets.length),msg})}
)){
fresh.push(widget);
}
}
// const fresh = widgets.filter(widget => CAM.traces(settings, widget, single));
send.done(codec.encode(fresh.map(widget => { return {
id: widget.id,
holes: widget.drills,
shadowed:widget.shadowedDrills
} } )));
}
}
export const CAM = {
init,
surface_prep,
surface_find,
slice: cam_slice,
prepare: cam_prepare,
export: cam_export
};

View file

@ -0,0 +1,89 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { api } from '../../kiri/api.js';
import { codec } from '../../kiri/codec.js';
function surface_prep(index, ondone) {
api.client.sync();
const settings = api.conf.get();
api.client.send("cam_surfaces", { settings, index }, output => {
ondone(output);
});
};
function surface_show(widget) {
widget.selectFaces(Object.values(widget._surfaces).flat());
};
function surface_toggle(widget, face, radians, ondone) {
let surfaces = widget._surfaces = widget._surfaces || {};
for (let [root, faces] of Object.entries(surfaces)) {
if (faces.contains(face)) {
// delete this face group
delete surfaces[root];
surface_show(widget);
ondone(Object.keys(surfaces).map(v => parseInt(v)));
return;
}
}
api.client.send("cam_surface_find", { id: widget.id, face, radians }, faces => {
if (faces.length) {
surfaces[face] = faces;
surface_show(widget);
}
ondone(Object.keys(surfaces).map(v => parseInt(v)));
});
};
function surface_clear(widget) {
widget.selectFaces([]);
widget._surfaces = {};
};
function traces(ondone, single) {
api.client.sync();
const settings = api.conf.get();
const widgets = api.widgets.map();
api.client.send("cam_traces", { settings, single }, output => {
const ids = [];
codec.decode(output).forEach(rec => {
ids.push(rec.id);
widgets[rec.id].traces = rec.traces;
});
ondone(ids);
});
};
function traces_clear(ondone) {
api.client.send("cam_traces_clear", {}, () => {
// console.log({clear_traces: true});
});
};
function holes(indiv,rec,onProgress,onDone) {
api.client.sync();
const settings = api.conf.get();
return new Promise((res,rej)=>{
api.client.send("cam_holes", { settings, rec, indiv }, output => {
let out = codec.decode(output)
if(out.progress != undefined){
//if a progress message,
onProgress(out.progress,out.msg)
}else{
api.hide.alert(alert);
onDone(out);
res(out);
}
});
})
};
export const CAM = {
surface_prep,
surface_show,
surface_toggle,
surface_clear,
traces,
traces_clear,
holes
};

View file

@ -0,0 +1,518 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base } from '../../geo/base.js';
const { util } = base;
/**
* @returns {Array} gcode lines
*/
export function cam_export(print, online) {
const widget = print.widgets[0];
if (!widget) return;
console.log({ cam_export: print });
const { settings } = print;
const { device, tools } = settings;
let i,
time = 0,
lines = 0,
bytes = 0,
opnum = 0,
factor = 1,
output = [],
spindle = 0,
newSpindle = 0,
toolChanges = 0,
spindleMax = device.spindleMax,
origin = settings.origin || { x: 0, y: 0, z: 0 },
space = device.gcodeSpace ? ' ' : '',
isRML = device.gcodeFExt?.toLowerCase() === 'rml',
stripComments = device.gcodeStrip || false,
cmdToolChange = device.gcodeChange || [ "M6 T{tool}" ],
cmdSpindle = device.gcodeSpindle || [ "M3 S{speed}" ],
cmdDwell = device.gcodeDwell || [ "G4 P{time}" ],
axis = { X: 'X', Y: 'Y', Z: 'Z', A: 'A', F: 'F', R: 'R', I: 'I', J: 'J' },
dev = settings.device,
spro = settings.process,
maxZd = spro.camFastFeedZ,
maxXYd = spro.camFastFeed,
decimals = base.config.gcode_decimals || 3,
pos = { x:null, y:null, z:null, a:undefined, f:null, t:null, emit:null },
line,
cidx,
mode,
point,
points = 0,
lastGn = '',
rewrite_comments = false,
compact_output = false,
lasering = false,
laserOp,
stock = settings.stock || { },
ztOff = stock.z - widget.track.top,
bounds = widget.getBoundingBox(),
zmax = stock.z,
runbox = {
max: { x:-Infinity, y:-Infinity, z:-Infinity},
min: { x:Infinity, y:Infinity, z:Infinity}
},
offset = {
x: -origin.x,
y: origin.y,
z: spro.camOriginTop ? origin.z - zmax : origin.z
},
scale = {
x: 1,
y: 1,
z: 1
},
consts = {
box: runbox,
tool: 0,
tool_name: "unknown",
top: (offset ? dev.bedDepth : dev.bedDepth/2),
left: (offset ? 0 : -dev.bedWidth/2),
right: (offset ? dev.bedWidth : dev.bedWidth/2),
bottom: (offset ? 0 : -dev.bedDepth/2),
time_sec: 0,
time_ms: 0,
time: 0
};
function section(section) {
append();
online({ section });
}
function append(line) {
if (line) {
lines++;
bytes += line.length;
if (rewrite_comments) {
const spos = line.indexOf(';');
if (spos >= 0) {
const left = line.substring(0, spos);
const right = '(' + line.substring(spos)
.replace(/; /g,'')
.replace(/;/g,'') + ')';
line = [ left, right ].join('');
}
}
output.append(line);
}
if (!line || output.length > 1000) {
online(output.join("\r\n"));
output = [];
}
}
/**
* Take an array of lines and emit them after:
* - splitting a string into an array
* - stripping comments if !isRML and stripComments
* - applying constant replacements
* - applying Inch/Millimeter conversions if G20 or G21 are found
*
* @param {string|Array} array - an array of lines or a single string
* @param {Object} consts - a dictionary of constants to replace
*/
function filterEmit(array, consts) {
if (!array) {
return;
}
if (typeof(array) === 'string') {
array = array.split('\n');
}
for (i=0; i<array.length; i++) {
line = print.constReplace(array[i], consts);
if (!isRML && stripComments && (cidx = line.indexOf(";")) >= 0) {
line = line.substring(0, cidx).trim();
if (line.length === 0) continue;
}
if (line.indexOf('G20') === 0) {
factor = 1/25.4;
consts.top = (offset ? dev.bedDepth : dev.bedDepth/2) * factor;
consts.left = (offset ? 0 : -dev.bedWidth/2) * factor;
consts.right = (offset ? dev.bedWidth : dev.bedWidth/2) * factor;
consts.bottom = (offset ? 0 : -dev.bedDepth/2) * factor;
} else if (line.indexOf('G21') === 0) {
factor = 1;
}
append(line);
}
}
function add0(val, opt) {
let s = val.toString(),
d = s.indexOf(".");
if (d < 0 && decimals > 0) {
return opt ? s : s + '.0';
} else {
return val.toFixed(decimals);
}
}
/**
* Move to a point, applies post-processing including for laser/RML, and appends to output
* @param {Point} out.point - the point to move to
* @param {Tool} [out.tool] - the tool to move with
* @param {number} [out.speed] - the speed to move at (in mm/min)
* @param {number} [out.emit] - the emission state (0=off, 1=on)
* @param {boolean} [opt.newOp] - whether to force a new operation
* @param {number} [opt.dx] - the delta X change (if not given, uses out.point.x - pos.x)
* @param {number} [opt.dy] - the delta Y change (if not given, uses out.point.y - pos.y)
* @param {number} [opt.dz] - the delta Z change (if not given, uses out.point.z - pos.z)
* @param {number} [opt.time] - the time to move (in ms) (if not given, calculate from speed)
*/
function moveTo(out, opt = {}) {
let laser = out.type === 'laser';
let newpos = out.point;
// no point == dwell
// out.speed = time to dwell in ms
if (!newpos) {
time += out.speed / 60;
consts.time_sec = out.speed / 1000;
consts.time_ms = out.speed;
consts.time = consts.time_sec;
filterEmit(cmdDwell, consts);
return;
}
newpos.x = util.round(newpos.x, decimals);
newpos.y = util.round(newpos.y, decimals);
newpos.z = util.round(newpos.z, decimals);
// on tool change
let changeTool = !(out.tool && pos.t) || out.tool.getID() !== pos.t.getID();
if (changeTool) {
pos.t = out.tool;
consts.tool = pos.t.getNumber();
consts.tool_name = pos.t.getName();
if (!laserOp && (spro.camToolInit || toolChanges > 0)) {
filterEmit(cmdToolChange, { ...consts, spindle: newSpindle } );
}
toolChanges++;
}
// on spindle change (deferred from layer transition so it's post-toolchange)
if (spindleMax && newSpindle && (changeTool || newSpindle !== spindle || opt.newOp)) {
spindle = newSpindle;
if (!laserOp) {
if (spindle > 0) {
let speed = Math.abs(spindle);
filterEmit(cmdSpindle, { speed, spindle: speed, rpm: speed });
} else {
append("M4");
}
}
}
// enforce XY origin at start of print
if (points === 0 || changeTool) {
pos.x = pos.y = pos.z = 0;
}
// split first move to X,Y then Z for that new location
// safety to prevent tool crashing
if (points === 0 || changeTool) {
points++;
if (spro.camFirstZMax) {
moveTo({
// speed: Infinity,
tool: out.tool,
point: { x: pos.x, y: pos.y, z: newpos.z, a: newpos.a },
emit: 0,
}, {
dx: 0, dy: 0, dz: 1, time: 0
});
moveTo({
// speed: Infinity,
tool: out.tool,
point: { x: newpos.x, y: newpos.y, z: newpos.z, a: pos.a },
emit: 1,
}, {
dx: 1, dy: 1, dz: 0, time: 0
});
} else {
moveTo({
// speed: Infinity,
tool: out.tool,
point: { x: newpos.x, y: newpos.y, z: pos.z, a: pos.a },
emit: 0
}, {
dx: 1, dy: 1, dz: 0, time: 0
});
moveTo({
// speed: Infinity,
tool: out.tool,
point: { x: newpos.x, y: newpos.y, z: newpos.z, a: newpos.a },
emit: 1
}, {
dx: 0, dy: 0, dz: 1, time: 0
});
}
points--;
return;
}
let gn;
if ( out.emit >=0 && out.emit <= 3) gn = `G${out.emit}`;
let speed = out.speed,
arc = out.emit == 2 || out.emit == 3,
center = out.center,
nl = (compact_output && lastGn === gn) ? [] : [gn],
dx = opt.dx || newpos.x - pos.x,
dy = opt.dy || newpos.y - pos.y,
dz = opt.dz || newpos.z - pos.z,
da = newpos.a != pos.a,
maxf = dz ? maxZd : maxXYd,
feed = Math.min(speed || maxf, maxf),
dist = Math.sqrt(dx * dx + dy * dy + dz * dz),
newFeed = feed && feed !== pos.f;
// drop dup points (all deltas are 0)
if (!arc && !(dx || dy || dz || da)) {
return;
}
lastGn = gn;
if (dx || newpos.x !== pos.x) {
pos.x = newpos.x;
runbox.min.x = Math.min(runbox.min.x, pos.x);
runbox.max.x = Math.max(runbox.max.x, pos.x);
nl.append(space).append(axis.X).append(add0(consts.pos_x = pos.x * factor));
}
if (dy || newpos.y !== pos.y) {
pos.y = newpos.y;
runbox.min.y = Math.min(runbox.min.y, pos.y);
runbox.max.y = Math.max(runbox.max.y, pos.y);
nl.append(space).append(axis.Y).append(add0(consts.pos_y = pos.y * factor));
}
if (dz || newpos.z !== pos.z) {
pos.z = newpos.z;
runbox.min.z = Math.min(runbox.min.z, pos.z);
runbox.max.z = Math.max(runbox.max.z, pos.z);
nl.append(space).append(axis.Z).append(add0(consts.pos_z = pos.z * factor));
}
if (da) {
pos.a = newpos.a;
nl.append(space).append(axis.A).append(add0(consts.pos_a = pos.a * -factor));
}
if (newFeed) {
pos.f = feed;
nl.append(space).append(axis.F).append(add0(consts.feed = feed * factor, true));
}
if(arc){
nl.append(space).append(axis.I).append(add0(center.x * factor, true))
.append(space).append(axis.J).append(add0(center.y * factor, true));
}
// temp hack to support RML1 dialect from a file extensions trigger
if (isRML) {
if (speed) {
if (newFeed) {
append(`VS${feed};`);
}
nl = [ axis.Z, add0(pos.x * factor), ",", add0(pos.y * factor), ",", add0(pos.z * factor), ";" ];
} else {
nl = [ "PU", add0(pos.x * factor), ",", add0(pos.y * factor), ";" ];
}
}
if (!lasering && laser) {
// enable laser
filterEmit(laserOp.on, consts);
}
// if (laser && pos.emit !== out.emit) {
if (laser) {
nl.append(space).append(`S${add0(out.emit)}`);
}
if (laser) {
pos.emit = out.emit;
}
if (lasering && !laser) {
// disable laser
filterEmit(laserOp.off, consts);
}
// update lasering state
lasering = laser;
// update time calculation
time += opt.time >= 0 ? opt.time : (dist / (pos.f || 1000)) * 60;
consts.time = Math.round(time);
// if (comment && !stripComments) {
// nl.append(" ; ").append(comment);
// nl.append(" ; ").append(points);
// }
append(nl.join(''));
points++;
}
// look for SCALE header directive
let gcodePre = [];
for (let line of device.gcodePre) {
if (line.indexOf(';; SCALE ') === 0) {
try {
let map = JSON.parse(line.substring(9));
if (map.X) scale.x = map.X;
if (map.Y) scale.y = map.Y;
if (map.Z) scale.z = map.Z;
if (map.A) scale.a = map.A;
if (map.DEC !== undefined) decimals = parseInt(map.DEC);
console.log('export scaling applied', map);
} catch (e) {
console.log('malformed scale directive', line);
}
} else if (line.indexOf(';; REWRITE-COMMENTS-PARENS') === 0) {
rewrite_comments = true;
} else if (line.indexOf(';; DECIMALS') === 0) {
decimals = parseInt(line.split('=')[1].trim() || 3) || 3;
} else if (line.indexOf(';; COMPACT-OUTPUT') === 0) {
compact_output = true;
stripComments = true;
space = '';
} else if (line.indexOf(";; AXISMAP ") === 0) {
let axmap = JSON.parse(line.substring(11).trim());
for (let key in axmap) {
axis[key] = axmap[key];
}
} else {
gcodePre.push(line);
}
}
section('header');
if (!stripComments) {
append(`; Generated by Kiri:Moto ${kiri.version}`);
append(`; ${new Date().toString()}`);
filterEmit(["; Bed left:{left} right:{right} top:{top} bottom:{bottom}"], consts);
append(`; Stock X:${stock.x?.round(2)} Y:${stock.y?.round(2)} Z:${stock.z?.round(2)}`);
append(`; Target: ${settings.filter[settings.mode]}`);
append("; --- process ---");
for (let pk in spro) {
if (pk !== "ops" && pk !== "op2") {
append("; " + pk + " = " + spro[pk]);
}
}
}
// collect tool info to add to header
let toolz = {}, ctool;
const isOffset = offset && (offset.x || offset.y);
// remap points as necessary for origins, offsets, inversions
print.output.forEach(layer => {
if (!Array.isArray(layer)) {
return;
}
layer.forEach(out => {
if (out.gcode || out.type === 'lerp') {
return;
}
if (out.tool && out.tool !== ctool) {
ctool = out.tool;
toolz[out.tool] = ctool;
}
point = out.point;
if (!point || point.mod) return;
// ensure not point is modified twice
point.mod = 1;
if (isOffset) {
point.x += offset.x;
point.y += offset.y;
}
if (scale) {
point.x *= scale.x;
point.y *= scale.y;
point.z *= scale.z;
}
if (point.a && scale.a) {
point.a *= scale.a;
}
if (spro.outputInvertX) point.x = -point.x;
if (spro.outputInvertY) point.y = -point.y;
if (spro.camOriginTop) point.z = point.z - zmax;
});
});
if (!stripComments) {
// emit tools used in comments
append("; --- tools ---");
Object.keys(toolz).sort().forEach(tn => {
let { number, flute_diam, flute_len, metric } = toolz[tn].tool;
append(`; tool#=${number} flute=${flute_diam} len=${flute_len} unit=${metric ? 'metric' : 'imperial'}`);
});
}
// emit gcode preamble
filterEmit(gcodePre, consts);
// emit all points in layer/point order
for (let layerout of print.output) {
const newmode = layerout.mode;
if (newmode) {
if (newmode.type === 'laser on') {
laserOp = newmode;
} else if (newmode.type === 'laser off') {
laserOp = undefined;
// force tool change in case laser tool matches next tool
pos.t = undefined;
}
}
const firstOut = layerout[0];
const newOp = newmode && !newmode.silent && mode !== newmode;
if (newOp) {
if (mode && !stripComments) {
append("; ending " + mode.type + " op after " + Math.round(time) + " seconds");
}
mode = newmode;
if (mode) {
section(`op-${opnum++}-${mode.type}`);
}
if (!stripComments && mode) {
append("; starting " + mode.type + " op");
}
}
newSpindle = layerout.spindle;
// iterate over layer output records
layerout.forEach((out, ind) => {
if (out.type === 'lerp') {
// suppress display only lerp points
return;
}
if (out.gcode && Array.isArray(out.gcode)) {
filterEmit(out.gcode, consts);
} else {
moveTo(out, { newOp: ind === 0 ? newOp : false });
}
});
if (lasering && laserOp) {
// disable laser
filterEmit(laserOp.off, consts);
lasering = false;
}
}
if (mode && !stripComments) {
append("; ending " + mode.type + " op after " + Math.round(time) + " seconds");
}
// emit gcode post
section('footer');
filterEmit(device.gcodePost, consts);
// flush buffered gcode
append();
print.time = time;
print.lines = lines;
print.bytes = bytes + lines - 1;
print.bounds = runbox;
};

1954
src2/kiri-mode/cam/ops.js Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

739
src2/kiri-mode/cam/slice.js Normal file
View file

@ -0,0 +1,739 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base, util } from '../../geo/base.js';
import { newLine } from '../../geo/line.js';
import { newPoint } from '../../geo/point.js';
import { newPolygon } from '../../geo/polygon.js';
import { polygons as POLY } from '../../geo/polygons.js';
import { setSliceTracker } from '../../kiri/slice.js';
import { ops as OPS } from './ops.js';
import { Tool } from './tool.js';
import { Slicer as cam_slicer } from './slicer.js';
/**
* DRIVER SLICE CONTRACT
*
* @param {Object} settings
* @param {Widget} widget
* @param {Function} output
*/
export async function cam_slice(settings, widget, onupdate, ondone) {
let proc = settings.process,
sliceAll = widget.slices = [],
camOps = widget.camops = [],
isIndexed = proc.camStockIndexed;
let stock, bounds, track,
camZTop, camZBottom, camZThru, wztop, ztOff, zbOff,
zBottom, zMin, zMax, zThru, zTop,
minToolDiam, maxToolDiam, dark, color, tabs, unsafe, units,
axisRotation, axisIndex,
part_size,
bottom_gap, bottom_part, bottom_stock, bottom_thru, bottom_z, bottom_cut,
top_stock, top_part, top_gap, top_z,
workarea;
console.log('CAM_SLICE', [...arguments]);
// allow recomputing later if widget or settings changes
const var_compute = () => {
let { camStockX, camStockY, camStockZ, camStockOffset } = proc;
bounds = widget.getBoundingBox();
stock = camStockOffset ? {
x: bounds.dim.x + camStockX,
y: bounds.dim.y + camStockY,
z: bounds.dim.z + camStockZ,
} : {
x: camStockX,
y: camStockY,
z: camStockZ
}
track = widget.track;
({ camZTop, camZBottom, camZThru } = proc);
wztop = track.top;
ztOff = isIndexed ? (stock.z - bounds.dim.z) / 2 : (stock.z - wztop);
zbOff = isIndexed ? (stock.z - bounds.dim.z) / 2 : (wztop - track.box.d);
zBottom = isIndexed ? camZBottom : camZBottom - zbOff;
zMin = isIndexed ? bounds.min.z : Math.max(bounds.min.z, zBottom);
zMax = bounds.max.z;
zThru = camZThru;
zTop = zMax + ztOff;
minToolDiam = Infinity;
maxToolDiam = -Infinity;
dark = !!settings.controller.dark;
color = dark ? 0xbbbbbb : 0;
tabs = widget.anno.tab;
unsafe = proc.camExpertFast;
units = settings.controller.units === 'in' ? 25.4 : 1;
axisRotation = axisIndex = undefined;
part_size = bounds.dim;
bottom_gap = zbOff;
bottom_part = 0;
bottom_stock = -bottom_gap;
bottom_thru = zThru;
bottom_z = isIndexed ? zBottom : Math.max(
(camZBottom ? bottom_stock + camZBottom : bottom_part) - bottom_thru,
(camZBottom ? bottom_stock + camZBottom : bottom_stock - bottom_thru)
);
bottom_cut = Math.max(bottom_z, -zThru);
top_stock = zTop;
top_part = zMax;
top_gap = ztOff;
top_z = camZTop ? bottom_stock + camZTop : top_stock;
workarea = util.round({
top_stock, top_part, top_gap, top_z,
bottom_stock, bottom_part, bottom_gap,
bottom_z, bottom_cut
}, 3);
return structuredClone(workarea);
};
// initial setup
var_compute();
if (tabs) {
// make tab polygons
tabs.forEach(tab => {
let zero = newPoint(0,0,0),
point = newPoint(tab.pos.x, tab.pos.y, tab.pos.z),
poly = newPolygon().centerRectangle(zero, tab.dim.x, tab.dim.y),
[ rx, ry, rz, rw ] = tab.rot,
m4 = new THREE.Matrix4().makeRotationFromQuaternion(
new THREE.Quaternion(rx, ry, rz, rw)
);
poly.points = poly.points
.map(p => new THREE.Vector3(p.x,p.y,p.z).applyMatrix4(m4))
.map(v => newPoint(v.x, v.y, v.z));
poly.move(point);
tab.poly = poly;
// tslice.output().setLayer("tabs", 0xff0000).addPoly(poly);
// sliceAll.push(tslice);
});
}
function error(msg) {
ondone(msg);
}
if (unsafe) {
console.log("disabling overhang safeties");
}
if (!proc.ops || proc.ops.length === 0) {
return error('no processes specified');
}
if (stock.x === 0 || stock.y === 0 || stock.z === 0) {
return error("one or more stock dimensions is zero<br>offset stock or set to non zero value");
}
if (stock.x && stock.y && stock.z && !isIndexed) {
if (stock.x + 0.00001 < bounds.max.x - bounds.min.x) {
return error('stock X too small for part. resize stock or use offset stock');
}
if (stock.y + 0.00001 < bounds.max.y - bounds.min.y) {
return error('stock Y too small for part. resize stock or use offset stock');
}
if (stock.z + 0.00001 < bounds.max.z - bounds.min.z) {
return error('stock Z too small for part. resize stock or use offset stock');
}
}
if (zMin >= bounds.max.z) {
return error(`invalid z bottom ${(zMin/units).round(3)} >= bounds z max ${(zMax/units).round(3)}`);
}
let mark = Date.now();
let opList = [];
let opSum = 0;
let opTot = 0;
let shadows = {};
let slicer;
let state = {
settings,
widget,
bounds,
tabs,
cutTabs,
cutPolys,
contourPolys,
healPolys,
shadowAt,
slicer,
addSlices,
isIndexed,
setAxisIndex,
updateToolDiams,
updateSlicer,
computeShadows,
zBottom,
zThru,
ztOff,
zMax,
zTop,
unsafe,
color,
dark,
ops: opList
};
let tracker = setSliceTracker({ rotation: 0 });
function updateSlicer() {
slicer = state.slicer = new cam_slicer(widget);
}
async function computeShadows() {
shadows = {};
await new OPS.shadow(state, { type: "shadow", silent: true }).slice(progress => {
// console.log('reshadow', progress.round(3));
});
}
function updateToolDiams(toolDiam) {
minToolDiam = Math.min(minToolDiam, toolDiam);
maxToolDiam = Math.max(maxToolDiam, toolDiam);
}
function shadowAt(z) {
let cached = shadows[z];
if (cached) {
return cached;
}
// find closest shadow above and use to speed up delta shadow gen
let minZabove;
let zover = Object.keys(shadows).map(v => parseFloat(v)).filter(v => v > z);
for (let zkey of zover) {
if (minZabove && zkey < minZabove) {
minZabove = zkey;
} else {
minZabove = zkey;
}
}
let shadow = shadowAt(widget, z, minZabove);
if (minZabove) {
// const merge = shadow.length;
// const plus = shadows[minZabove].length;
// const mark = Date.now();
shadow = POLY.union([...shadow, ...shadows[minZabove]], 0.001, true);
// console.log({merge, plus, equals: shadow.length, time: Date.now() - mark});
}
return shadows[z] = POLY.setZ(shadow, z);
}
function setAxisIndex(degrees = 0, absolute = true) {
axisIndex = absolute ? degrees : axisIndex + degrees;
axisRotation = (Math.PI / 180) * axisIndex;
widget.setAxisIndex(isIndexed ? -axisIndex : 0);
return isIndexed ? -axisIndex : 0;
}
function addPolyIndexing(poly, a) {
if (!poly) {
return;
}
if (Array.isArray(poly)) {
for (let p of poly) {
addPolyIndexing(p, a);
}
return;
}
for (let point of poly.points) {
point.a = a;
}
addPolyIndexing(poly.inner, a);
}
function addSlices(slices, addIndexing = isIndexed) {
if (!Array.isArray(slices)) {
slices = [ slices ];
}
sliceAll.appendAll(slices);
if (addIndexing && axisIndex !== undefined) {
// update slice cam lines to add axis indexing
for (let slice of slices.filter(s => s.camLines)) {
addPolyIndexing(slice.camLines, -axisIndex);
}
}
}
if (false) {
opList.push(new OPS.xray(state, { type: "xray" }));
}
let activeOps = proc.ops.filter(op => !op.disabled);
// silently preface op list with OpShadow
if (isIndexed) {
if (activeOps.length === 0 || activeOps[0].type !== 'index')
opList.push(new OPS.index(state, { type: "index", index: 0 }));
} else {
opList.push(new OPS.shadow(state, { type: "shadow", silent: true }));
}
// determing # of steps and step weighting for progress bar
for (let op of activeOps) {
if (op.type === '|') {
break;
}
let opfn = OPS[op.type];
if (opfn) {
let opin = new opfn(state, op);
opList.push(opin);
opTot += opin.weight();
}
}
// call slice() function on all ops in order
setAxisIndex();
updateSlicer();
for (let op of opList) {
let weight = op.weight();
// apply operation override vars
let workover = var_compute();
let valz = op.op;
if (valz.ov_topz) {
workover.top_z = isIndexed ? valz.ov_topz : bottom_stock + valz.ov_topz;
}
if (valz.ov_botz) {
workover.bottom_z = isIndexed ? valz.ov_botz : bottom_stock + valz.ov_botz;
workover.bottom_cut = Math.max(workover.bottom_z, -zThru);
}
// state.workarea = workover;
Object.assign(state, {
zBottom,
zThru,
ztOff,
zMax,
zTop,
workarea: workover
});
// console.log({
// op,
// workover,
// bounds: structuredClone(bounds),
// stock: structuredClone(stock)
// });
await op.slice((progress, message) => {
onupdate((opSum + (progress * weight)) / opTot, message || op.type());
});
// update tracker rotation for next slice output() visualization
tracker.rotation = isIndexed ? axisRotation : 0;
camOps.push(op);
opSum += weight;
}
setSliceTracker();
// reindex
sliceAll.forEach((slice, index) => slice.index = index);
// used in printSetup()
// used in CAM.prepare.getZClearPath()
// add tabs to terrain tops so moves avoid them
if (tabs) {
state.terrain.forEach(slab => {
tabs.forEach(tab => {
if (tab.pos.z + tab.dim.z/2 >= slab.z) {
let all = [...slab.tops, tab.poly];
slab.tops = POLY.union(all, 0, true);
// slab.slice.output()
// .setLayer("debug-tabs", {line: 0x880088, thin: true })
// .addPolys(POLY.setZ(slab.tops.clone(true), slab.z), { thin: true });
}
});
});
}
// add shadow perimeter to terrain to catch outside moves off part
let tabpoly = tabs ? tabs.map(tab => tab.poly) : [];
let allpoly = POLY.union([...state.shadow.base, ...tabpoly], 0, true);
let shadowOff = maxToolDiam < 0 ? allpoly :
POLY.offset(allpoly, [minToolDiam/2,maxToolDiam/2], { count: 2, flat: true, minArea: 0 });
state.terrain.forEach(level => level.tops.appendAll(shadowOff));
widget.terrain = state.skipTerrain ? null : state.terrain;
widget.minToolDiam = minToolDiam;
widget.maxToolDiam = maxToolDiam;
ondone();
};
export function addDogbones(poly, dist, reverse) {
if (Array.isArray(poly)) {
return poly.forEach(p => addDogbones(p, dist));
}
let open = poly.open;
let isCW = poly.isClockwise();
if (reverse || poly.parent) isCW = !isCW;
let oldpts = poly.points.slice();
let lastpt = oldpts[oldpts.length - 1];
let lastsl = lastpt.slopeTo(oldpts[0]).toUnit();
let length = oldpts.length + (open ? 0 : 1);
let newpts = [ ];
for (let i=0; i<length; i++) {
let nextpt = oldpts[i % oldpts.length];
let nextsl = lastpt.slopeTo(nextpt).toUnit();
let adiff = lastsl.angleDiff(nextsl, true);
let bdiff = ((adiff < 0 ? (180 - adiff) : (180 + adiff)) / 2) + 180;
if (!open || (i > 1 && i < length)) {
if (isCW && adiff > 45) {
let newa = base.newSlopeFromAngle(lastsl.angle + bdiff);
newpts.push(lastpt.projectOnSlope(newa, dist));
newpts.push(lastpt.clone());
} else if (!isCW && adiff < -45) {
let newa = base.newSlopeFromAngle(lastsl.angle - bdiff);
newpts.push(lastpt.projectOnSlope(newa, dist));
newpts.push(lastpt.clone());
}
}
lastsl = nextsl;
lastpt = nextpt;
if (i < oldpts.length) {
newpts.push(nextpt);
}
}
poly.points = newpts;
if (poly.inner) {
addDogbones(poly.inner, dist, true);
}
};
export async function traces(settings, widget, single) {
if (widget.traces) {
return false;
}
// --- points → line segments ---
let edges = new THREE.EdgesGeometry(widget.mesh.geometry, settings.controller.edgeangle ?? 20);
let array = edges.attributes.position.array;
let pcache = {};
let points = new Array(2);
let lines = new Array(points.length / 2);
for (let i=0, j=0, k=0, l=array.length; i<l; ) {
let ps = [ array[i++], array[i++], array[i++] ];
let key = ps.map(v => (v * 10000) | 0).join(',');
let point = pcache[key];
if (!point) {
point = newPoint(ps[0], ps[1], ps[2], key);
point.lines = [];
pcache[key] = point;
}
points[j++ % 2] = point;
if (j % 2 === 0) {
let [ p0, p1 ] = points;
let line = lines[k++] = newLine(p0, p1);
p0.lines.push(line);
p1.lines.push(line);
}
}
// --- segments → chains (bidirectional walk) ---
let chains = [];
{
const segs = lines.slice(); // shallow copy
segs.forEach(s => (s.visited = false));
function step(dirPoint, prevSeg, pushFront, chain) {
let curr = dirPoint;
let prev = prevSeg;
while (curr.lines.length === 2) { // stay inside the arc
const next = curr.lines.find(l => !l.visited && l !== prev);
if (!next) break; // should not happen
next.visited = true;
if (pushFront) chain.unshift(next); // prepend or append?
else chain.push(next);
curr = next.p1 === curr ? next.p2 : next.p1;
prev = next;
}
}
for (const seed of segs) {
if (seed.visited) continue;
seed.visited = true; // always include the seed
const chain = [seed];
// grow backwards from p1 (prepend)
step(seed.p1, seed, true, chain);
// grow forwards from p2 (append)
step(seed.p2, seed, false, chain);
chains.push(chain);
}
}
// --- chains → polylines ---
const polylines = [];
for (const chain of chains) {
const poly = newPolygon().setOpen();
// choose any node whose degree !== 2; if none, it’s a closed loop
let start = null;
for (const s of chain) {
if (s.p1.lines.length !== 2) { start = s.p1; break; }
if (s.p2.lines.length !== 2) { start = s.p2; break; }
}
if (!start) start = chain[0].p1; // closed loop
let curr = start, prevSeg = null;
poly.push(curr); // first point
while (true) {
const nextSeg = curr.lines.find(
l => l !== prevSeg && chain.includes(l)
);
if (!nextSeg) break; // open end reached
curr = nextSeg.p1 === curr ? nextSeg.p2 : nextSeg.p1;
poly.push(curr); // << push *before* test
if (curr === start) break; // loop closed
prevSeg = nextSeg;
}
polylines.push(poly);
}
widget.traces = polylines;
return true;
};
/**
* Generate a list of holes in the model based on the given diameter.
*
* @param {Object} settings - settings object
* @param {Object} widget - widget object
* @param {boolean} individual - if true, drill holes individually
* @param {Object} rec - DrillOp record
* @param {Function} onProgress - callback function to report progress
* @returns {Array} list of hole centers as objects with `x`, `y`, `z`, `depth`, and `selected` properties.
*/
export async function holes(settings, widget, individual, rec,onProgress) {
let {tool,mark,precision} = rec //TODO: display some visual difference if mark is selected
let toolDiam = new Tool(settings,tool).fluteDiameter()
let diam = individual ? 1 : toolDiam; // sets default diameter when select individual used
let proc = settings.process,
stock = settings.stock || {},
isIndexed = proc.camStockIndexed,
track = widget.track,
{ camZTop, camZBottom, camZThru } = proc,
// widget top z as defined by setTopz()
wztop = track.top,
// distance between top of part and top of stock
ztOff = isIndexed ? 0 : (stock.z - wztop),
// distance between bottom of part and bottom of stock
zbOff = isIndexed ? 0 : (wztop - track.box.d),
// defined z bottom offset by distance to stock bottom
// keeps the z bottom relative to the part when z align changes
zBottom = isIndexed ? camZBottom : camZBottom - zbOff;
let slicerOpts = {flatoff: 0.001}
let slicer = new cam_slicer(widget,slicerOpts);
let zFlats = Object.keys(slicer.zFlat).map(Number).map(z=>[z,z-0.002]).flat()
precision = Math.max( 0, precision )
let intervals = (precision == 0) ? [] : slicer.interval(
precision,
{
fit: false, off: -0.01, flats: true
}
)
let zees = [...zFlats,...intervals]
let indices = [...new Set(zees
.map(kv => parseFloat(kv).round(5))
.filter(z => z !== null)
)]
let centerDiff = diam * 0.1,
area = (diam/2) * (diam/2) * Math.PI,
circles = [],
slices = [];
function onEach(slice) {
slices.push(slice);
}
let opts = { each: onEach, progress: (num,total)=> onProgress(num/total*0.5,"slice") };
await slicer.slice(indices, opts);
let shadowedDrills = false;
// console.log("slices",slices)
for (let [i,slice] of slices.entries()) {
for(let top of slice.tops){
// console.log("slicing",slice.z,top)
slice.shadow = shadowAt(widget, slice.z, 0)
let inner = top.inner;
if (!inner) { //no holes
continue;
}
for (let poly of inner) {
if ( poly.points.length < 7 ) continue;
let center = poly.calcCircleCenter();
center.area = poly.area();
center.overlapping = [center]
center.depth = 0;
// console.log("center",center)
if ( poly.circularity() < 0.985 ){
// if not circular, don't add to holes
continue;
}
if (center.isInPolygon(slice.shadow)) {
// if shadowed, don't add, and inform client
shadowedDrills = true;
continue;
}
let overlap = false;
for (let [i,circle] of circles.entries()) {
let dist = circle.distTo2D(center)
// //if on the same xy point,
if (dist <= centerDiff ) {
// console.log("overlap",center,circle);
circle.overlapping.push(center);
// if overlapping, don't add and continue
overlap = true;
continue;
}
}
if (!overlap) circles.push(center);
}
}
onProgress(0.5+(i/slices.length*0.25),"recognize circles")
}
let drills = []
for (let [i,c] of circles.entries()) {
let overlapping = c.overlapping
let last = overlapping.shift();
while (overlapping.length) {
let circ = overlapping.shift();
let aveArea = (circ.area + last.area) / 2;
let areaDelta = Math.abs(circ.area -last.area)
if (areaDelta < aveArea * 0.05){ // if area delta less than 5% of average area
//keep top circle selected
last.depth = last.z - circ.z;
}else{ // if not the same area
//push and move on
drills.push(last);
last = circ;
}
}
if (last.depth != 0) drills.push(last) //add last circle
onProgress(0.75+(i/circles.length*0.25),"assemble holes")
}
drills.forEach( h=>{
if(rec.fromTop){
// set z top if selected
h.depth += wztop - h.z
h.z = wztop
}
delete h.overlapping //for encoding
h.diam = toolDiam // for mesh generation
h.selected = (!individual && Math.abs(h.area - area) <= area * 0.05 ); //for same size selection
})
// console.log("unfiltered circles",circles)
// console.log("drills",drills)
drills = drills.filter(drill => drill.depth > 0)
widget.shadowedDrills = shadowedDrills
widget.drills = drills;
return drills;
}
function cutTabs(tabs, offset, z, inter) {
tabs = tabs.filter(tab => z < tab.pos.z + tab.dim.z/2).map(tab => tab.off).flat();
return cutPolys(tabs, offset, z, false);
}
function cutPolys(polys, offset, z, inter) {
let noff = [];
offset.forEach(op => noff.appendAll( op.cut(POLY.union(polys, 0, true), inter) ));
return healPolys(noff);
}
function contourPolys(widget, polys) {
const raycaster = new THREE.Raycaster();
raycaster.ray.direction.set(0, 0, -1); // ray pointing down Z
for (let poly of polys) {
for (let point of poly.points) {
raycaster.ray.origin.set(point.x, point.y, 10000);
const intersects = raycaster.intersectObject(widget.mesh, false);
const firstHit = intersects[0] || null;
point.z = firstHit.point.z;
}
}
}
function healPolys(noff) {
for (let p of noff) {
if (p.appearsClosed()) {
p.points.pop();
p.setClosed();
}
}
if (noff.length > 1) {
let heal = 0;
// heal/rejoin open segments that share endpoints
outer: for(;; heal++) {
let ntmp = noff, tlen = ntmp.length;
for (let i=0; i<tlen; i++) {
let s1 = ntmp[i];
if (!s1) continue;
for (let j=i+1; j<tlen; j++) {
let s2 = ntmp[j];
if (!s2) continue;
// require polys at same Z to heal
if (Math.abs(s1.getZ() - s2.getZ()) > 0.01) {
continue;
}
if (!(s1.open && s2.open)) continue;
if (s1.last().isMergable2D(s2.first())) {
s1.addPoints(s2.points.slice(1));
ntmp[j] = null;
continue outer;
}
if (s2.last().isMergable2D(s1.first())) {
s2.addPoints(s1.points.slice(1));
ntmp[i] = null;
continue outer;
}
if (s1.first().isMergable2D(s2.first())) {
s1.reverse();
s1.addPoints(s2.points.slice(1));
ntmp[j] = null;
continue outer;
}
if (s1.last().isMergable2D(s2.last())) {
s2.reverse();
s1.addPoints(s2.points.slice(1));
ntmp[j] = null;
continue outer;
}
}
}
break;
}
if (heal > 0) {
// cull nulls
noff = noff.filter(o => o);
}
// close poly if head meets tail
for (let poly of noff) {
if (poly.open && poly.first().isMergable2D(poly.last())) {
poly.points.pop();
poly.open = false;
}
}
}
return noff;
}

View file

@ -0,0 +1,510 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base, util } from '../../geo/base.js';
import { broker } from '../../moto/broker.js';
import { decode, decodePointArray, encode, encodePointArray } from '../../kiri/codec.js';
import { newLine, newOrderedLine } from '../../geo/line.js';
import { newPoint } from '../../geo/point.js';
import { newSlice } from '../../kiri/slice.js';
import { polygons as POLY } from '../../geo/polygons.js';
import { slicer } from '../../geo/slicer.js';
const { sliceConnect, sliceDedup } = slicer;
const { config } = base;
const timing = false;
const begin = function() {
if (timing) console.time(...arguments);
};
const end = function() {
if (timing) console.timeEnd(...arguments);
};
export class Slicer {
constructor(widget, options = { zlist: true, zline: true, lines: false }) {
this.minions = self.kiri_worker.minions;
this.options = {};
this.setOptions(options);
if (widget) {
this.setPoints(widget.getGeoVertices({ unroll: true, translate: true }));
this.computeFeatures();
}
}
get threaded() {
return this.options.threaded;
}
// zList = generate list of z vertices
// zline = generate list of z vertices with coplanar lines
// trace = find z coplanar trace lines
// flatoff = amount to offset z when slicing on detected flats
// each = call for each slice generated from an interval
setOptions(options) {
Object.assign(this.options, options || {});
return this.options;
}
setPoints(points) {
this.bounds = null;
this.points = points;
this.zFlat = {}; // accumulated flat area at z height
this.zLine = {}; // count of z coplanar lines
this.zList = {}; // count of z values for auto slicing
return this;
}
// gather z-index stats
// these are used for auto-slicing in laser
// and to flats detection in CAM mode
computeFeatures(options) {
begin('compute features');
const opt = this.setOptions(options);
const bounds = this.bounds = new THREE.Box3();
const points = this.points;
const zFlat = this.zFlat;
const zLine = this.zLine;
const zList = this.zList;
function countZ(z) {
z = z.round(5);
zList[z] = (zList[z] || 0) + 1;
}
let p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0);
// for (let i = 0, il = points.length; i < il; i++) {
// points[i] = points[i].round(5);
// }
for (let i = 0, il = points.length; i < il; ) {
p1.set(points[i++], points[i++], points[i++]);
p2.set(points[i++], points[i++], points[i++]);
p3.set(points[i++], points[i++], points[i++]);
// update bounds
bounds.expandByPoint(p1);
bounds.expandByPoint(p2);
bounds.expandByPoint(p3);
// count occurrences of z values for auto slicing
if (opt.zlist) {
countZ(p1.z);
countZ(p2.z);
countZ(p3.z);
}
// use co-flat and co-line detection to adjust slice Z
if (p1.z === p2.z && p2.z === p3.z) {
// detect zFlat faces to avoid slicing directly on them
let zkey = p1.z.toFixed(5),
area = Math.abs(util.area2(p1,p2,p3)) / 2;
if (!zFlat[zkey]) {
zFlat[zkey] = area;
} else {
zFlat[zkey] += area;
}
} else if (opt.zline) {
// detect zLine (curved region tops/bottoms)
// in cam used for ball and v mill tracing
if (p1.z === p2.z) {
let zkey = p1.z.toFixed(5);
let zval = zLine[zkey];
zLine[zkey] = (zval || 0) + 1;
}
if (p2.z === p3.z) {
let zkey = p2.z.toFixed(5);
let zval = zLine[zkey];
zLine[zkey] = (zval || 0) + 1;
}
if (p3.z === p1.z) {
let zkey = p3.z.toFixed(5);
let zval = zLine[zkey];
zLine[zkey] = (zval || 0) + 1;
}
}
}
end('compute features');
// console.log({ bounds, zFlat, zLine, zList });
return this;
}
/**
* Given an array of z-slice positions, generate a list of polygons
* representing the intersection of the mesh with the given z-slice
* positions.
*
* @param {number[]} zs - array of z-slice positions
* @param {Object} options - slicing parameters
* @param {number} [options.flatoff=0.01] - z offset when slicing on a flat surface
* @param {boolean} [options.progress=false] - callback with slice progress
* @param {function} [options.each] - callback with each slice result
* @returns {Promise<Object[]>} - list of slice objects with z and tops (polygons)
*/
async slice(zs, options) {
const opt = this.setOptions(options);
// slice through points at given Z and return polygons
if (!Array.isArray(zs)) {
throw "slice zs parameter must be ab array";
}
// sort Z and offset when on a flat
const flatoff = util.numOrDefault(opt.flatoff, 0.01);
zs = zs.sort((a,b) => a-b).map(z => {
if (!flatoff) {
return z;
}
const znorm = z.toFixed(5);
return this.zFlat[znorm] ? z + flatoff : z;
});
// compute buckets from z slice list
const { points } = this;
const plen = points.length;
const zlen = zs.length;
const ppz = plen / zlen;
const count = 25;//Math.ceil(ppz / 10000);
const step = Math.ceil(zlen / count);
const buckets = [];
// console.log({ points, zs, count, step });
for (let c = 0, b = 0; c < count; c++) {
if (b >= zlen) break;
buckets.push({
zs: zs.slice(b, b + step),
index: []
});
b += step;
}
let p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0),
ep = 0.001;
begin("create buckets");
for (let i = 0, il = points.length; i < il; ) {
p1.set(points[i++], points[i++], points[i++]);
p2.set(points[i++], points[i++], points[i++]);
p3.set(points[i++], points[i++], points[i++]);
let zmin = Math.min(p1.z, p2.z, p3.z);
let zmax = Math.max(p1.z, p2.z, p3.z);
for (let bucket of buckets) {
const { zs, index } = bucket;
const min = Math.min(...zs);
const max = Math.max(...zs);
if (zmin < min && zmax < min) {
if (Math.abs(zmin - min) > ep && Math.abs(zmax - min) > ep) {
continue;
}
}
if (zmin > max && zmax > max) {
if (Math.abs(zmin - max) > ep && Math.abs(zmax - max) > ep) {
continue;
}
}
index.push(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z);
}
}
end("create buckets");
// console.log({ zs, zlen, count, step, buckets, flatoff });
begin("slicing");
const { minions } = this;
const threaded = minions && minions.running;
const sliceFn = (threaded ? this.sliceBucketMinion : this.sliceBucket).bind(this);
const track = { count: 0, total: zs.length };
if (threaded) minions.broadcast("cam_slice_init", {});
const promises = []
for (let bucket of buckets) {
promises.push(sliceFn(bucket, { ...opt, minZ: this.bounds.min.z }, slice => {
track.count++;
if (opt.progress) {
opt.progress(track.count, track.total);
}
// console.log({ oneach: slice, ...track });
}));
}
const data = (await Promise.all(promises)).flat();
data.sort((a,b) => b.z - a.z).forEach((rec, i) => {
rec.tops = rec.polys;
rec.slice = newSlice(rec.z).addTops(rec.tops);
if (opt.each) {
opt.each(rec, i, data.length);
}
});
if (threaded) minions.broadcast("cam_slice_cleanup");
end("slicing");
return data;
}
async sliceBucketMinion(bucket, opt, oneach) {
const slices = (await new Promise(resolve => {
this.minions.queue({
cmd: "cam_slice",
opt: Object.clone(opt),
bucket,
}, resolve);
})).slices;
for (let slice of slices) {
slice.polys = decode(slice.polys);
if (slice.lines) {
slice.lines = decodePointArray(slice.lines)
.group(2)
.map(arr => {
return newLine(arr[0], arr[1])
});
}
oneach(slice);
}
// console.log(bucket, slices);
return slices;
}
async sliceBucket(bucket, opt, oneach) {
const { zs, index } = bucket;
const slices = [];
for (let z of zs) {
const slice = this.sliceZ(z, index, opt);
if (slice) {
slices.push(slice);
}
oneach(slice);
}
return slices;
}
sliceZ(z, indices, opt) {
let links = opt.links !== false,
dedup = opt.dedup !== false,
edges = opt.edges || false,
over = opt.over || z <= opt.minZ,
debug = opt.debug,
phash = {},
lines = [];
// const { points } = this,
const points = indices,
p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0);
for (let index = 0; index < points.length; ) {
p1.set(points[index++], points[index++], points[index++]);
p2.set(points[index++], points[index++], points[index++]);
p3.set(points[index++], points[index++], points[index++]);
let where = {under: [], over: [], on: []};
checkOverUnderOn(p1, z, where);
checkOverUnderOn(p2, z, where);
checkOverUnderOn(p3, z, where);
if (where.under.length === 3 || where.over.length === 3) {
// does not intersect (all 3 above or below)
} else if (where.on.length === 2) {
// one side of triangle is on the Z plane and 3rd is below
// drop lines with 3rd above because that leads to ambiguities
// with complex nested polygons on flat surface
if ((over && where.over.length === 1) || (!over && where.under.length === 1)) {
lines.push(makeZLine(phash, where.on[0], where.on[1], false, true));
}
} else if (where.on.length === 3) {
// triangle is coplanar with Z
// we drop these because this face is attached to 3 others
// that will satisfy the if above (line) with 2 points
} else if (where.under.length === 0 || where.over.length === 0) {
// does not intersect but one point is on the slice Z plane
} else if (!edges) {
// compute two point intersections and construct line
let line = intersectPoints(where.over, where.under, z);
if (line.length < 2 && where.on.length === 1) {
line.push(where.on[0].clone());
}
if (line.length === 2) {
lines.push(makeZLine(phash, line[0], line[1]));
} else {
console.log({msg: "invalid ips", line: line, where: where});
}
}
}
if (dedup) {
// console.log({ z, dedup: lines, points });
lines = sliceDedup(lines, debug);
}
return lines.length ? { z,
lines: opt.lines !== false ? lines : undefined,
polys: links ? POLY.nest(sliceConnect(lines, opt, debug)) : undefined
} : null;
}
interval(step, options) {
let opt = options || {},
bounds = this.bounds,
boff = opt.boff || opt.off || 0, // bottom offset
toff = opt.toff || opt.off || 0, // top offset
zmin = opt.min !== undefined ? opt.min : bounds.min.z + boff,
zmax = (opt.max || bounds.max.z) - toff,
steps = (zmax - zmin) / step,
rem = steps % 1 != 0 ? 0 : 1,
count = Math.floor(steps) + rem,
array = [];
if (opt.fit) {
count++;
step = (zmax - zmin) / count;
}
if (opt.down) {
for (let i=0; i<count; i++) {
array.push(zmax);
zmax -= step;
}
} else {
for (let i=0; i<count; i++) {
array.push(zmin);
zmin += step;
}
}
if (opt.fit) {
array.push(opt.down ? zmax : zmin);
}
if (opt.flats && opt.off) {
let add = [];
Object.keys(this.zFlat).forEach(z => {
z = parseFloat(z);
add.push(z + opt.off);
if (z > zmin) {
add.push(z - opt.off);
}
});
// add over and under all flats by 'off'
array.appendAll(add).sort((a,b) => {
return opt.down ? b-a : a-b;
});
}
// filter duplicate values
array = array.map(v => v.round(5)).filter((e,i,a) => i < 1 || a[i-1] !== a[i]);
// return array.map(v => Math.abs(parseFloat(v.toFixed(5))));
return array.map(v => parseFloat(v.toFixed(5)));
}
}
/**
* given a point, append to the correct
* 'where' objec tarray (on, over or under)
*
* @param {Point} p
* @param {number} z offset
* @param {Obejct} where
*/
function checkOverUnderOn(p, z, where) {
let delta = p.z - z;
if (Math.abs(delta) < config.precision_slice_z) { // on
where.on.push(p);
} else if (delta < 0) { // under
where.under.push(p);
} else { // over
where.over.push(p);
}
}
/**
* Given a point over and under a z offset, calculate
* and return the intersection point on that z plane
*
* @param {Point} over
* @param {Point} under
* @param {number} z offset
* @returns {Point} intersection point
*/
function intersectPoints(over, under, z) {
let ip = [];
for (let i = 0; i < over.length; i++) {
for (let j = 0; j < under.length; j++) {
ip.push(over[i].intersectZ(under[j], z));
}
}
return ip;
}
/**
* Ensure points are unique with a cache/key algorithm
*/
function getCachedPoint(phash, p) {
let cached = phash[p.key];
if (!cached) {
phash[p.key] = p;
return p;
}
return cached;
}
/**
* Given two points and hints about their edges,
* return a new Line object with points sorted
* lexicographically by key. This allows for future
* line de-duplication and joins.
*
* @param {Object} phash
* @param {Point} p1
* @param {Point} p2
* @param {boolean} [coplanar]
* @param {boolean} [edge]
* @returns {Line}
*/
function makeZLine(phash, p1, p2, coplanar, edge) {
p1 = getCachedPoint(phash, p1.clone());
p2 = getCachedPoint(phash, p2.clone());
let line = newOrderedLine(p1,p2);
line.coplanar = coplanar || false;
line.edge = edge || false;
return line;
}
Slicer.checkOverUnderOn = checkOverUnderOn;
Slicer.intersectPoints = intersectPoints;
broker.subscribe("minion.started", msg => {
const { funcs, cache, reply, log } = msg;
funcs.cam_slice_init = () => {
cache.slicer = new Slicer();
};
funcs.cam_slice_cleanup = () => {
delete cache.slicer;
};
funcs.cam_slice = (data, seq) => {
const { bucket, opt } = data;
// log({ slice: bucket, opt });
cache.slicer.sliceBucket(bucket, opt, slice => {
// console.log({ slice });
}).then(data => {
data.forEach(rec => {
rec.polys = encode(rec.polys);
if (rec.lines) {
const points = rec.lines.map(l => [l.p1, l.p2]).flat();
rec.lines = encodePointArray(points);
}
});
reply({ seq, slices: data });
});
};
});

View file

@ -0,0 +1,324 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base } from '../../../geo/base.js';
import { kiri } from '../../kiri.js';
import { config, newOrderedLine, newPoint } from '../../../geo/base.js';
const { base, kiri } = root;
const { config, newOrderedLine, newPoint } = base;
class Slicer {
static intersectPoints = intersectPoints;
static checkOverUnderOn = checkOverUnderOn;
static removeDuplicateLines = removeDuplicateLines;
constructor(index = 0) {
this.min = Infinity;
this.max = -Infinity;
this.index = index;
}
// position is a non-indexed 3js geometry position attribute array
// create Point array from optionally filtered Z range
setFromArray(position, options = {}) {
const min = options.min || -Infinity;
const max = options.max || Infinity;
const len = position.length;
const pts = this.points = [];
for (let i=0; i<len; ) {
const x0 = position[i++];
const y0 = position[i++];
const z0 = position[i++];
const x1 = position[i++];
const y1 = position[i++];
const z1 = position[i++];
const x2 = position[i++];
const y2 = position[i++];
const z2 = position[i++];
const minz = Math.min(z0, z1, z2);
const maxz = Math.max(z0, z1, z2);
if (maxz < min || minz > max) {
continue;
}
pts.push(
newPoint(x0, y0, z0),
newPoint(x1, y1, z1),
newPoint(x2, y2, z2)
);
this.min = options.min || Math.min(this.min, minz);
this.max = options.max || Math.max(this.max, maxz);
}
return this;
}
setFromPoints(points, options = {}) {
const pts = this.points = [];
const len = points.length;
const min = options.min || -Infinity;
const max = options.max || Infinity;
for (let i=0; i<len; ) {
const p0 = points[i++];
const p1 = points[i++];
const p2 = points[i++];
const minz = Math.min(p0.z, p1.z, p2.z);
const maxz = Math.max(p0.z, p1.z, p2.z);
if (maxz < min || minz > max) {
continue;
}
pts.push(p0, p1, p2);
this.min = options.min || Math.min(this.min, minz);
this.max = options.max || Math.max(this.max, maxz);
}
return this;
}
slice(interval = 1) {
const ret = [];
for (let z = this.min; z < this.max; z += interval) {
ret.push({ z, index: this.index++, lines: this.sliceZ(z) });
}
return ret;
}
sliceZ(z, options = {}) {
const points = this.points;
const zMin = this.min;
const zMax = this.max;
const phash = {};
const lines = [];
let { under, over, both } = options;
let p1, p2, p3;
// default to 'over' selection with 2 points on a line
if (!under && !both) over = true;
// iterate over matching buckets for this z offset
for (let i = 0; i < points.length; ) {
p1 = points[i++];
p2 = points[i++];
p3 = points[i++];
let where = {under: [], over: [], on: []};
checkOverUnderOn(p1, z, where);
checkOverUnderOn(p2, z, where);
checkOverUnderOn(p3, z, where);
if (where.under.length === 3 || where.over.length === 3) {
// does not intersect (all 3 above or below)
} else if (where.on.length === 2) {
// one side of triangle is on the Z plane and 3rd is below
// drop lines with 3rd above because that leads to ambiguities
// with complex nested polygons on flat surface
let add2 = both ||
(over && (where.over.length === 1 || z === zMax)) ||
(under && (where.under.length === 1 || z === zMin));
if (add2) {
lines.push(makeZLine(phash, where.on[0], where.on[1], false, true));
}
} else if (where.on.length === 3) {
// triangle is coplanar with Z
// we drop these because this face is attached to 3 others
// that will satisfy the if above (line) with 2 points
} else if (where.under.length === 0 || where.over.length === 0) {
// does not intersect but one point is on the slice Z plane
} else {
// compute two point intersections and construct line
let line = intersectPoints(where.over, where.under, z);
if (line.length < 2 && where.on.length === 1) {
line.push(where.on[0]);
}
if (line.length === 2) {
lines.push(makeZLine(phash, line[0], line[1]));
} else {
console.log({msg: "invalid ips", line: line, where: where});
}
}
}
if (lines.length == 0 && options.noEmpty) {
return;
}
return removeDuplicateLines(lines);
}
}
/**
* given a point, append to the correct
* 'where' objec tarray (on, over or under)
*
* @param {Point} p
* @param {number} z offset
* @param {Obejct} where
*/
function checkOverUnderOn(p, z, where) {
let delta = p.z - z;
if (Math.abs(delta) < config.precision_slice_z) { // on
where.on.push(p);
} else if (delta < 0) { // under
where.under.push(p);
} else { // over
where.over.push(p);
}
}
/**
* Given a point over and under a z offset, calculate
* and return the intersection point on that z plane
*
* @param {Point} over
* @param {Point} under
* @param {number} z offset
* @returns {Point} intersection point
*/
function intersectPoints(over, under, z) {
let ip = [];
for (let i = 0; i < over.length; i++) {
for (let j = 0; j < under.length; j++) {
ip.push(over[i].intersectZ(under[j], z));
}
}
return ip;
}
/**
* Ensure points are unique with a cache/key algorithm
*/
function getCachedPoint(phash, p) {
let cached = phash[p.key];
if (!cached) {
phash[p.key] = p;
return p;
}
return cached;
}
/**
* Given two points and hints about their edges,
* return a new Line object with points sorted
* lexicographically by key. This allows for future
* line de-duplication and joins.
*
* @param {Object} phash
* @param {Point} p1
* @param {Point} p2
* @param {boolean} [coplanar]
* @param {boolean} [edge]
* @returns {Line}
*/
function makeZLine(phash, p1, p2, coplanar, edge) {
p1 = getCachedPoint(phash, p1);
p2 = getCachedPoint(phash, p2);
let line = newOrderedLine(p1,p2);
line.coplanar = coplanar || false;
line.edge = edge || false;
return line;
}
/**
* eliminate duplicate lines and interior-only lines (coplanar)
*
* lines are sorted using lexicographic point keys such that
* they are comparable even if their points are reversed. hinting
* for deletion, co-planar and suspect shared edge is detectable at
* this time.
*
* @param {Line[]} lines
* @returns {Line[]}
*/
function removeDuplicateLines(lines, debug) {
let output = [],
tmplines = [],
points = [],
pmap = {};
function cachePoint(p) {
let cp = pmap[p.key];
if (cp) return cp;
points.push(p);
pmap[p.key] = p;
return p;
}
function addLinesToPoint(point, line) {
cachePoint(point);
if (!point.group) point.group = [ line ];
else point.group.push(line);
}
// mark duplicates for deletion preserving edges
lines.sort(function (l1, l2) {
if (l1.key === l2.key) {
l1.del = !l1.edge;
l2.del = !l2.edge;
if (debug && (l1.del || l2.del)) {
console.log('dup', l1, l2);
}
return 0;
}
return l1.key < l2.key ? -1 : 1;
});
// associate points with their lines, cull deleted
lines.forEach(function(line) {
if (!line.del) {
tmplines.push(line);
addLinesToPoint(line.p1, line);
addLinesToPoint(line.p2, line);
}
});
// merge collinear lines
points.forEach(function(point) {
if (point.group.length != 2) return;
let l1 = point.group[0],
l2 = point.group[1];
if (l1.isCollinear(l2)) {
l1.del = true;
l2.del = true;
// find new endpoints that are not shared point
let p1 = l1.p1 != point ? l1.p1 : l1.p2,
p2 = l2.p1 != point ? l2.p1 : l2.p2,
newline = base.newOrderedLine(p1,p2);
// remove deleted lines from associated points
p1.group.remove(l1);
p1.group.remove(l2);
p2.group.remove(l1);
p2.group.remove(l2);
// associate new line with points
p1.group.push(newline);
p2.group.push(newline);
// add new line to lines array
newline.edge = l1.edge || l2.edge;
tmplines.push(newline);
}
});
// mark duplicates for deletion
// but preserve one if it's an edge
tmplines.sort(function (l1, l2) {
if (l1.key === l2.key) {
l1.del = true;
l2.del = !l2.edge;
return 0;
}
return l1.key < l2.key ? -1 : 1;
});
// create new line array culling deleted
tmplines.forEach(function(line) {
if (!line.del) {
output.push(line);
line.p1.group = null;
line.p2.group = null;
}
});
return output;
}
kiri.topo_slicer = Slicer;
export { checkOverUnderOn, intersectPoints, getCachedPoint, makeZLine, removeDuplicateLines, cachePoint, addLinesToPoint, min, max, len, pts, i, x0, y0, z0, x1, y1, z1, x2, y2, z2, minz, maxz, p0, p1, p2, ret, z, points, zMin, zMax, phash, lines, where, add2, line, delta, ip, j, cached, output, cp, l1, Slicer };

208
src2/kiri-mode/cam/tool.js Normal file
View file

@ -0,0 +1,208 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
const HPI = Math.PI/2;
const RAD2DEG = 180/Math.PI;
class Tool {
constructor(settings, id, number) {
if (number >= 0) {
this.tool = settings.tools.filter(tool => tool.number == number)[0];
} else {
this.tool = settings.tools.filter(tool => tool.id == id)[0];
}
if (!this.tool) {
this.tool = Object.assign({}, settings.tools[0]);
this.tool.number = number >= 0 ? number : this.tool.number;
this.tool.id = id >= 0 ? id : this.tool.id;
}
}
getID() {
return this.tool.id;
}
getName() {
return this.tool.name;
}
getType() {
return this.tool.type;
}
getNumber() {
return this.tool.number;
}
isMetric() {
return this.tool.metric;
}
unitScale() {
return this.isMetric() ? 1 : 25.4;
}
fluteLength() {
return this.unitScale() * this.tool.flute_len;
}
fluteDiameter() {
return this.unitScale() * this.tool.flute_diam;
}
tipDiameter() {
return this.unitScale() * this.tool.taper_tip;
}
maxDiameter() {
return Math.max(this.fluteDiameter(), this.tipDiameter(), this.shaftDiameter());
}
traceOffset() {
return (this.hasTaper() ? this.tipDiameter() : this.fluteDiameter()) / 2;
}
contourOffset(step) {
const diam = Math.min(this.hasTaper() ? this.tipDiameter() : this.fluteDiameter());
return diam ? diam * step : step;
}
setTaperLengthFromAngle(angle) {
const rad = (this.flute_diam - this.taper_tip) / 2;
return this.flute_len = calcTaperLength(rad, angle);
}
getTaperAngle() {
return calcTaperAngle((this.flute_diam - this.taper_tip) / 2, this.flute_len);
}
shaftLength() {
return this.unitScale() * this.tool.shaft_len;
}
/**
* returns the length of the drill tip as a function of the flute diameter,
* given a 118 deg point angle. the result is in workspace units.
*
* @return {number} length of the drill tip.
*/
drillTipLength() {
const drillAngleRad = 140 * Math.PI / 180;
return 0.5 * this.fluteDiameter() * Math.sin(drillAngleRad);
}
shaftDiameter() {
return this.unitScale() * this.tool.shaft_diam;
}
isBallMill() {
return this.tool.type === "ballmill";
}
isTaperMill() {
return this.tool.type === "tapermill";
}
isDrill(){
return this.tool.type === "drill";
}
hasTaper() {
return this.isTaperMill();
}
/**
* generate tool profile with resolution number of pixels. the result is a
* Float32Array stored in `this.profile` and `this.profileDim` containing
* dimensions of the profile in pixels and shared array buffer size.
*
* @param {number} resolution - number of pixels for the tool profile
*
* @return {Tool} this
*/
generateProfile(resolution) {
// generate tool profile
let ball = this.isBallMill(),
taper = this.hasTaper(),
drill = this.isDrill(),
tip_diameter = this.tipDiameter(),
drill_tip_length = this.drillTipLength(),
shaft_offset = this.fluteLength(),
flute_diameter = this.fluteDiameter(),
shaft_diameter = Math.max(flute_diameter, this.shaftDiameter()),
max_diameter = Math.max(flute_diameter, shaft_diameter),
shaft_pix_float = max_diameter / resolution,
shaft_pix_int = Math.round(shaft_pix_float),
shaft_radius_pix_float = shaft_pix_float / 2,
flute_radius = flute_diameter / 2,
flute_pix_float = flute_diameter / resolution,
flute_radius_pix_float = flute_pix_float / 2,
tip_pix_float = tip_diameter / resolution,
tip_radius_pix_float = tip_pix_float / 2,
tip_max_radius_offset = flute_radius_pix_float - tip_radius_pix_float,
profile_pix_iter = shaft_pix_int + (1 - shaft_pix_int % 2),
toolCenter = (shaft_pix_int - (shaft_pix_int % 2)) / 2,
toolOffset = [],
larger_shaft = shaft_diameter - flute_diameter > 0.001,
rpixsq = flute_radius_pix_float * flute_radius_pix_float,
maxo = -Infinity;
// for each point in tool profile, check inside radius
for (let x = 0; x < profile_pix_iter; x++) {
for (let y = 0; y < profile_pix_iter; y++) {
let dx = x - toolCenter,
dy = y - toolCenter,
dist_from_center = Math.sqrt(dx * dx + dy * dy);
if (dist_from_center <= flute_radius_pix_float) { // if xy point inside flute radius
maxo = Math.max(maxo, dx, dy);
// flute offset points
let z_offset = 0;
if (ball) {
let rd = dist_from_center * dist_from_center;
z_offset = Math.sqrt(rpixsq - rd) * resolution - flute_radius;
// z_offset = (1 - Math.cos((dist_from_center / flute_radius_pix_float) * HPI)) * -flute_radius;
} else if (taper && dist_from_center >= tip_radius_pix_float) {// if tapered and not in the flat tip radius
z_offset = ((dist_from_center - tip_radius_pix_float) / tip_max_radius_offset) * -shaft_offset;
}else if(drill){
z_offset = -dist_from_center /45;
}
toolOffset.push(dx, dy, z_offset);
} else if (shaft_offset && larger_shaft && dist_from_center <= shaft_radius_pix_float) {
// shaft offset points
toolOffset.push(dx, dy, -shaft_offset);
}
}
}
// convert to shared array for use with minions
const profile = new Float32Array(new SharedArrayBuffer(toolOffset.length * 4));
profile.set(toolOffset);
this.profile = profile;
this.profileDim = {
size: shaft_diameter,
pix: profile_pix_iter + 2,
maxo
};
return this;
}
}
function calcTaperAngle(rad, len) {
return (Math.atan(rad / len) * RAD2DEG);
};
function calcTaperLength(rad, angle) {
return (rad / Math.tan(angle));
};
function getToolDiameter(settings, id) {
return new Tool(settings, id).fluteDiameter();
};
export {
Tool,
calcTaperAngle,
calcTaperLength,
getToolDiameter
};

354
src2/kiri-mode/cam/tools.js Normal file
View file

@ -0,0 +1,354 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { api } from '../kiri/api.js';
import { consts } from '../kiri/consts.js';
import { settings } from '../kiri/settings.js';
// Convert root destructuring to imports
import { kiri } from '../kiri.js';
const DEG2RAD = Math.PI / 180;
let { kiri } = root,
{ api, consts } = kiri,
{ uc, ui } = api,
{ MODES } = consts,
DOC = document,
selectedTool = null,
editTools = null,
maxTool = 0,
toolNames = ['endmill','ballmill','tapermill','drill'];
api.show.tools = showTools;
// extend API
Object.assign(api.tool, {
update: updateTool
});
function settings() {
return api.conf.get();
}
function renderTools() {
ui.toolSelect.innerHTML = '';
maxTool = 0;
editTools.forEach(function(tool, index) {
maxTool = Math.max(maxTool, tool.number);
tool.order = index;
let opt = DOC.createElement('option');
opt.appendChild(DOC.createTextNode(tool.name));
opt.onclick = function() { selectTool(tool) };
ui.toolSelect.appendChild(opt);
});
}
function selectTool(tool) {
selectedTool = tool;
ui.toolName.value = tool.name;
ui.toolNum.value = tool.number;
ui.toolFluteDiam.value = tool.flute_diam;
ui.toolFluteLen.value = tool.flute_len;
ui.toolShaftDiam.value = tool.shaft_diam;
ui.toolShaftLen.value = tool.shaft_len;
ui.toolTaperTip.value = tool.taper_tip || 0;
ui.toolMetric.checked = tool.metric;
ui.toolType.selectedIndex = toolNames.indexOf(tool.type);
if (tool === 'tapermill') {
ui.toolTaperAngle.value = kiri.driver.CAM.calcTaperAngle(
(tool.flute_diam - tool.taper_tip) / 2, tool.flute_len
).round(1);
} else if(tool === 'drill'){
ui.toolTaperAngle.value = 118;
} else {
ui.toolTaperAngle.value = 0;
}
renderTool(tool);
}
function otag(o) {
if (Array.isArray(o)) {
let out = []
o.forEach(oe => out.push(otag(oe)));
return out.join('');
}
let tags = [];
Object.keys(o).forEach(key => {
let val = o[key];
let att = [];
Object.keys(val).forEach(tk => {
let tv = val[tk];
att.push(`${tk.replace(/_/g,'-')}="${tv}"`);
});
tags.push(`<${key} ${att.join(' ')}></${key}>`);
});
return tags.join('');
}
function renderTool(tool) {
let type = selectedTool.type;
let taper = type=== 'tapermill'
let drill = type === 'drill'
const drillAngleRad = 140 * Math.PI / 180
ui.toolTaperAngle.disabled = taper ? undefined : 'true';
ui.toolTaperTip.disabled = taper ? undefined : 'true';
$('tool-view').innerHTML = '<svg id="tool-svg" width="100%" height="100%"></svg>';
setTimeout(() => {
let svg = $('tool-svg'),
pad = 10,
dim = { w: svg.clientWidth, h: svg.clientHeight },
max = { w: dim.w - pad * 2, h: dim.h - pad * 2},
off = { x: pad, y: pad },
isBall = type === "ballmill",
shaft_fill = "#cccccc",
flute_fill = "#dddddd",
stroke = "#777777",
stroke_width = 3,
stroke_thin = stroke_width / 2,
shaft = tool.shaft_len || 1,
flute = tool.flute_len || 1,
drillTip = drill ? 0.5 * tool.flute_diam * Math.sin(drillAngleRad) : 0,
total_len = shaft + flute+drillTip,
units = dim.h / total_len,
shaft_len = (shaft / total_len) * max.h,
flute_len = (flute / total_len) * max.h,
drill_tip_len = (drillTip / total_len) * max.h,
shaft_diam = tool.shaft_diam * units,
flute_diam = tool.flute_diam * units,
// total_wid = Math.max(flute_diam, shaft_diam),
shaft_off = (max.w - shaft_diam) / 2,
flute_off = (max.w - flute_diam) / 2,
taper_off = (max.w - (tool.taper_tip || 0) * units) / 2,
parts = [
// shaft rectangle
{ rect: {
x: off.x + shaft_off,
y: off.y,
width: max.w - shaft_off * 2,
height: shaft_len,
fill: shaft_fill,
stroke_width,
stroke
} }
];
if (taper) {
let yoff = off.y + shaft_len;
// let mid = dim.w / 2;
parts.push({path: {stroke_width, stroke, fill:flute_fill, d:[
`M ${off.x + flute_off} ${yoff}`,
`L ${off.x + taper_off} ${yoff + flute_len}`,
`L ${dim.w - off.x - taper_off} ${yoff + flute_len}`,
`L ${dim.w - off.x - flute_off} ${yoff}`,
`z`
].join('\n')}});
} else if(drill){
const x1 = off.x + flute_off,
y1 = off.y + shaft_len,
x2 = dim.w - off.x - flute_off,
y2 = y1 + flute_len,
xMid = dim.w / 2
parts.push({path: {stroke_width, stroke, fill:flute_fill, d:[
`M ${x1} ${y1}`, //move to top left
`L ${x1} ${y2}`, //line to bottom left
`L ${xMid} ${y2+drill_tip_len}`, //line to bottom mid point
`L ${x2} ${y2}`, //line to bottom right
`L ${x2} ${y1}`, //line to top right
`z`
].join('\n')}});
//add drill flute lines
parts.push({ line: {
x1, y1, x2, y2: (y1 + y2) / 2,
stroke, stroke_width: stroke_thin
} });
parts.push({ line: {
x1, y1: (y1 + y2) / 2, x2, y2,
stroke, stroke_width: stroke_thin
} });
} else {
let fl = isBall ? flute_len - flute_diam/2 : flute_len;
let x1 = off.x + flute_off;
let y1 = off.y + shaft_len;
let x2 = x1 + max.w - flute_off * 2;
let y2 = y1 + fl;
// flute rectangle
parts.push({ rect: {
x: off.x + flute_off,
y: off.y + shaft_len,
width: max.w - flute_off * 2,
height: fl,
fill: flute_fill,
stroke_width,
stroke,
} });
// hatch "fill" flute
parts.push({ line: { x1, y1, x2, y2, stroke, stroke_width: stroke_thin } });
parts.push({ line: {
x1: (x1 + x2) / 2, y1, x2, y2: (y1 + y2) / 2,
stroke, stroke_width: stroke_thin
} });
parts.push({ line: {
x1, y1: (y1 + y2) / 2, x2: (x1 + x2) / 2, y2,
stroke, stroke_width: stroke_thin
} });
}
if (isBall) {
let rad = (max.w - flute_off * 2) / 2;
let xend = dim.w - off.x - flute_off;
let yoff = off.y + shaft_len + flute_len + stroke_width/2 - flute_diam/2;
parts.push({path: {stroke_width, stroke, fill:flute_fill, d:[
`M ${off.x + flute_off} ${yoff}`,
`A ${rad} ${rad} 0 0 0 ${xend} ${yoff}`,
// `L ${off.x + flute_off} ${yoff}`
].join('\n')}})
}
svg.innerHTML = otag(parts);
}, 10);
}
function updateTool(ev) {
selectedTool.name = ui.toolName.value;
selectedTool.number = parseInt(ui.toolNum.value);
selectedTool.flute_diam = parseFloat(ui.toolFluteDiam.value);
selectedTool.flute_len = parseFloat(ui.toolFluteLen.value);
selectedTool.shaft_diam = parseFloat(ui.toolShaftDiam.value);
selectedTool.shaft_len = parseFloat(ui.toolShaftLen.value);
selectedTool.taper_tip = parseFloat(ui.toolTaperTip.value);
selectedTool.metric = ui.toolMetric.checked;
selectedTool.type = toolNames[ui.toolType.selectedIndex];
if (selectedTool.type === 'tapermill') {
const CAM = kiri.driver.CAM;
const rad = (selectedTool.flute_diam - selectedTool.taper_tip) / 2;
if (ev && ev.target === ui.toolTaperAngle) {
const angle = parseFloat(ev.target.value);
const len = CAM.calcTaperLength(rad, angle * DEG2RAD);
selectedTool.flute_len = len;
ui.toolTaperAngle.value = angle.round(1);
ui.toolFluteLen.value = selectedTool.flute_len.round(4);
} else {
ui.toolTaperAngle.value = CAM.calcTaperAngle(rad, selectedTool.flute_len).round(1);
}
} else {
ui.toolTaperAngle.value = 0;
}
renderTools();
ui.toolSelect.selectedIndex = selectedTool.order;
setToolChanged(true);
renderTool(selectedTool);
}
function setToolChanged(changed) {
editTools.changed = changed;
ui.toolsSave.disabled = !changed;
}
function showTools() {
if (api.mode.get_id() !== MODES.CAM) return;
api.settings.sync.get().then(_showTools);
}
function _showTools() {
let selectedIndex = null;
editTools = settings().tools.slice().sort((a,b) => {
return a.name > b.name ? 1 : -1;
});
setToolChanged(false);
ui.toolsClose.onclick = function() {
if (editTools.changed && !confirm("abandon changes?")) return;
api.dialog.hide();
};
ui.toolAdd.onclick = function() {
let metric = settings().controller.units === 'mm';
editTools.push(Object.assign({
id: Date.now(),
number: maxTool + 1,
name: "new tool",
type: "endmill",
taper_tip: 0,
metric
}, metric ? {
shaft_diam: 2,
shaft_len: 15,
flute_diam: 2,
flute_len: 20,
} : {
shaft_diam: 0.25,
shaft_len: 1.5,
flute_diam: 0.25,
flute_len: 2,
}));
setToolChanged(true);
renderTools();
ui.toolSelect.selectedIndex = editTools.length-1;
selectTool(editTools[editTools.length-1]);
};
ui.toolCopy.onclick = function() {
let clone = Object.assign({}, selectedTool);
let { name } = clone;
let split = name.split(' ');
let endv = parseInt(split.pop());
if (endv) {
name = split.join(' ') + ' ' + (endv + 1);
} else {
name = `${name} 2`;
}
clone.id = Date.now();
clone.number = maxTool + 1;
clone.name = name;
editTools.push(clone);
setToolChanged(true);
renderTools();
ui.toolSelect.selectedIndex = editTools.length-1;
selectTool(editTools[editTools.length-1]);
};
ui.toolDelete.onclick = function() {
editTools.remove(selectedTool);
setToolChanged(true);
renderTools();
};
ui.toolsSave.onclick = function() {
if (selectedTool) updateTool();
settings().tools = editTools.sort((a,b) => {
return a.name < b.name ? -1 : 1;
});
setToolChanged(false);
api.conf.save();
api.conf.update_fields();
api.event.settings();
api.settings.sync.put();
};
ui.toolsImport.onclick = (ev) => api.event.import(ev);
ui.toolsExport.onclick = () => {
uc.prompt("Export Tools Filename", "tools").then(name => {
if (!name) {
return;
}
const record = {
version: kiri.version,
tools: api.conf.get().tools,
time: Date.now()
};
api.util.download(api.util.b64enc(record), `${name}.km`);
});
};
renderTools();
if (editTools.length > 0) {
selectTool(editTools[0]);
ui.toolSelect.selectedIndex = 0;
} else {
ui.toolAdd.onclick();
}
api.dialog.show('tools');
ui.toolSelect.focus();
}
export { settings, renderTools, selectTool, otag, renderTool, updateTool, setToolChanged, showTools, DEG2RAD, opt, out, tags, att, tv, type, taper, drill, drillAngleRad, svg, yoff, mid, x1, fl, y1, x2, y2, rad, xend, CAM, angle, len, selectedIndex, metric, clone, split, endv, record };

894
src2/kiri-mode/cam/topo3.js Normal file
View file

@ -0,0 +1,894 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base } from '../../../geo/base.js';
import { kiri } from '../../kiri.js';
import { moto } from '../../../moto.js';
import { driver, newSlice } from '../../kiri.js';
import { CAM } from './driver.js';
import { polygons, newLine, newSlope, newPoint, newPolygon } from '../../../geo/base.js';
const { base, kiri, moto } = root;
const { driver, newSlice } = kiri;
const { CAM } = driver;
const { polygons, newLine, newSlope, newPoint, newPolygon } = base;
const PRO = CAM.process;
const POLY = polygons;
const RAD2DEG = 180 / Math.PI;
const DEG2RAD = Math.PI / 180;
class Topo {
constructor() { }
async generate(opt = {}) {
let { state, contour, onupdate, ondone } = opt;
let { widget, settings, tshadow, center, tabs, color } = opt.state;
let { controller, process } = settings,
animesh = parseInt(controller.animesh || 100) * 2500,
axis = contour.axis.toLowerCase(),
contourX = axis === "x",
contourY = axis === "y",
bounds = widget.getBoundingBox().clone(),
tolerance = contour.tolerance,
flatness = contour.flatness || (tolerance / 100),
shadow = tshadow,
minX = bounds.min.x,
maxX = bounds.max.x,
minY = bounds.min.y,
maxY = bounds.max.y,
zBottom = contour.bottom ? state.zBottom : 0,
zMin = Math.max(bounds.min.z, zBottom) + 0.0001,
boundsX = maxX - minX,
boundsY = maxY - minY,
inside = contour.inside,
density = 1 + (contour.reduction || 0),
resolution = tolerance ? tolerance : 1/Math.sqrt(animesh/(boundsX * boundsY)),
tool = new CAM.Tool(settings, contour.tool),
toolOffset = tool.generateProfile(resolution).profile,
toolDiameter = tool.fluteDiameter(),
toolStep = toolDiameter * contour.step, //tool.contourOffset(contour.step),
leave = contour.leave || 0,
maxangle = contour.angle,
curvesOnly = contour.curves,
bridge = contour.bridging || 0,
// R2A = 180 / Math.PI,
stepsX = Math.ceil(boundsX / resolution),
stepsY = Math.ceil(boundsY / resolution),
widtopo = widget.topo,
topoCache = widtopo
&& widtopo.resolution === resolution
&& widtopo.diameter === toolDiameter
? widtopo : undefined,
topo = widget.topo = topoCache || {
data: new Float32Array(new SharedArrayBuffer(stepsX * stepsY * 4)),
stepsX: stepsX,
stepsY: stepsY,
bounds: bounds,
diameter: toolDiameter,
resolution: resolution,
profile: toolOffset,
widget: widget,
raster: true,
slices: null
},
data = topo.data,
newslices = [],
tabsMax = tabs ? Math.max(...tabs.map(tab => tab.dim.z/2 + tab.pos.z)) : 0,
tabsOn = tabs,
tabHeight = Math.max(process.camTabsHeight + zBottom, tabsMax),
clipTab = tabsOn ? [] : null,
clipTo = inside ? shadow : POLY.expand(shadow, toolDiameter/2 + resolution * 3),
partOff = inside ? 0 : toolDiameter / 2 + resolution,
gridDelta = Math.floor(partOff / resolution),
debug = false,
debug_clips = debug && true,
debug_topo = debug && true,
debug_topo_lines = debug && true,
debug_topo_shells = debug && true,
time = Date.now;
if (tolerance === 0 && !topoCache) {
console.log(widget.id, 'topo auto tolerance', resolution.round(4));
}
// console.log({ resolution, flatness });
// used by Pocket -> Contour
this.tolerance = resolution;
if (tabs) {
clipTab.appendAll(tabs.map(tab => {
let ctab = POLY.expand([tab.poly], toolDiameter/2);
ctab.forEach(ct => ct.z = tab.dim.z/2 + tab.pos.z);
return ctab;
}).flat());
}
// debug clipTab and clipTo
if (debug_clips) {
const debug = newSlice(-1);
const output = debug.output();
// if (clipTab) output.setLayer("clip.tab", { line: 0xff0000 }).addPolys(clipTab);
if (clipTo) output.setLayer("clip.to", { line: 0x00dd00 }).addPolys(clipTo);
newslices.push(debug);
}
const probe = this.probe = new Probe({
profile: toolOffset,
data,
stepsX,
stepsY,
boundsX,
boundsY,
minX,
minY,
zMin
});
const { toolAtZ, toolAtXY, zAtXY } = probe;
this.toolAtZ = toolAtZ;
this.toolAtXY = toolAtXY;
this.zAtXY = zAtXY;
const trace = this.trace = new Trace(probe, {
curvesOnly,
maxangle,
flatness,
bridge,
contourX
});
if (topo.raster) {
const box = topo.box = new THREE.Box2();
const params = {
resolution,
curvesOnly,
flatness,
stepsY,
minY,
maxY,
zMin,
data,
box
};
onupdate(0, 1, "raster");
await this.raster(widget, params, (i, l, p) => {
onupdate(i / 2, l, p);
});
topo.raster = false;
}
await this.contour({
box: topo.box,
minX,
maxX,
minY,
maxY,
stepsX,
stepsY,
boundsX,
boundsY,
partOff,
gridDelta,
resolution,
toolStep,
contourX,
contourY,
density,
clipTo,
clipTab,
clipTabZ: clipTab ? clipTab.map(t => t.z) : undefined,
tabHeight,
newslices,
leave,
color
}, (i, l, p) => {
onupdate(l / 2 + i / 2, l, p);
});
ondone(newslices);
return this;
}
async raster(widget, params, onupdate) {
const { resolution } = params;
const { box } = params;
const { worker, minions } = kiri;
const vertices = widget.getGeoVertices({ unroll: true, translate: true }).toShared();
const range = { min: Infinity, max: -Infinity };
// swap XZ in shared array
for (let i=0,l=vertices.length; i<l; i += 3) {
const x = vertices[i];
const z = vertices[i + 2];
vertices[i] = z;
vertices[i + 2] = x;
range.min = Math.min(range.min, x);
range.max = Math.max(range.max, x);
}
const shards = Math.ceil(Math.min(25, vertices.length / 27000));
const step = (range.max - range.min) / shards;
let slices = [];
let index = 0;
let slice = { min: range.min, max: range.min + step, index };
for (let z = range.min; z < range.max; z += resolution) {
if (z > slice.max) {
slices.push(slice);
slice = { min: z, max: z + step, index };
}
index++;
}
slices.push(slice);
// console.log({ shards, range, step, slices });
let complete = 0;
// define sharded ranges
if (minions.running > 1) {
worker.putCache({ key: widget.id, data: vertices }, { done: data => {
// console.log({ put_cache_done: data });
}});
let promises = slices.map(slice => {
return new Promise(resolve => {
minions.queue({
cmd: "topo_raster",
id: widget.id,
params,
slice
}, data => {
resolve(data);
onupdate(++complete, slices.length, "raster");
});
});
});
// merge boxes for all rasters for contouring clipping
(await Promise.all(promises))
.map(rec => rec.box)
.map(box => new THREE.Box2(
new THREE.Vector2(box.min.x, box.min.y),
new THREE.Vector2(box.max.x, box.max.y)
))
.map(box2 => {
box.union(box2);
return box2;
});
worker.clearCache({}, { done: data => {
// console.log({ clear_cache_done: data });
}});
} else {
// iterate over shards, merge output
// const output = [];
for (let slice of slices) {
new kiri.topo_slicer(slice.index)
.setFromArray(vertices, slice)
.slice(resolution)
.map(rec => {
const slice = kiri.newSlice(rec.z);
slice.index = rec.index;
slice.lines = rec.lines;
for (let line of rec.lines) {
const { p1, p2 } = line;
if (!p1.swapped) { p1.swapXZ(); p1.swapped = true }
if (!p2.swapped) { p2.swapXZ(); p2.swapped = true }
}
raster_slice({
...params,
box,
lines: rec.lines,
gridx: rec.index
});
return slice;
});
onupdate(++complete, slices.length, "raster");
}
}
}
async contour(params, onupdate) {
const trace = this.trace;
const concurrent = kiri.minions.running;
const { minX, maxX, minY, maxY, boundsX, boundsY, stepsX, stepsY } = params;
const { gridDelta, resolution, density, partOff, toolStep, contourX, contourY } = params;
const { clipTo, clipTab, clipTabZ, tabHeight, newslices, color, leave } = params;
let stepsTaken = 0,
stepsTotal = 0;
if (contourX) {
stepsTotal += ((maxY - minY + partOff * 2) / toolStep) | 0;
}
if (contourY) {
stepsTotal += ((maxX - minX + partOff * 2) / toolStep) | 0;
}
if (stepsTotal === 0) {
return;
}
const box = params.box.clone().expandByVector(new THREE.Vector3(
partOff, partOff, 0
));
trace.init({
box,
leave,
clipTo,
clipTab,
clipTabZ,
tabHeight,
resolution,
concurrent,
density
});
let resolver;
let pcount = 0;
let slicesY = [];
let slicesX = [];
let promise = new Promise(resolve => {
resolver = () => {
// sort output slices (required for async)
slicesY.sort((a,b) => a.z - b.z);
slicesX.sort((a,b) => a.z - b.z);
newslices.appendAll(slicesY);
newslices.appendAll(slicesX);
resolve();
}
});
let inc = () => { pcount++ };
let dec = () => { if (--pcount === 0 && concurrent) resolver() };
if (contourY) {
onupdate(0, stepsTotal, "contour y");
// emit slice per X
for (let x = minX - partOff; x <= maxX + partOff; x += toolStep) {
if (x < box.min.x || x > box.max.x) continue;
const gridx = Math.round(((x - minX) / boundsX) * stepsX);
const gridy = -gridDelta;
inc();
trace.crossY({
from: minY - partOff,
to: maxY + partOff,
x,
gridx,
gridy
}, segments => {
if (segments.length > 0) {
let slice = newSlice(gridx);
slice.camLines = segments;
slice.output()
.setLayer("contour y", {face: color, line: color})
.addPolys(segments);
slicesY.push(slice);
}
onupdate(++stepsTaken, stepsTotal, "contour y");
dec();
});
}
}
if (contourX) {
// emit slice per Y
onupdate(0, stepsTotal, "contour x");
for (let y = minY - partOff; y <= maxY + partOff; y += toolStep) {
if (y < box.min.y || y > box.max.y) continue;
const gridy = Math.round(((y - minY) / boundsY) * stepsY);
const gridx = -gridDelta;
inc();
trace.crossX({
from: minX - partOff,
to: maxX + partOff,
y,
gridx,
gridy
}, segments => {
if (segments.length > 0) {
let slice = newSlice(gridy);
slice.camLines = segments;
slice.output()
.setLayer("contour x", {face: color, line: color})
.addPolys(segments);
slicesX.push(slice);
}
onupdate(++stepsTaken, stepsTotal, "contour x");
dec();
});
}
}
if (!concurrent) resolver();
await promise;
// const lines = newslices.map(s => (s.camLines || []).map(p => p.length));
// const points = lines.flat().reduce((a,b) => a+b);
// console.log({ lines, points });
trace.cleanup();
}
}
class Probe {
constructor(params) {
const { data, profile } = params;
const { stepsX, stepsY, boundsX, zMin, minX, minY } = params;
this.params = params;
// return the touching z given topo x,y and a tool profile
const toolAtZ = this.toolAtZ = function(x,y) {
let sx = stepsX,
sy = stepsY,
xl = sx - 1,
yl = sy - 1;
let gv, i = 0, mz = -Infinity;
while (i < profile.length) {
// tool profile point x, y, and z offsets
const tx = profile[i++] + x;
const ty = profile[i++] + y;
const tz = profile[i++];
if (tx < 0 || tx > xl || ty < 0 || ty > yl) {
// if outside max topo steps, use zMin
gv = zMin;
} else {
// lookup grid value @ tx, ty
gv = data[tx * sy + ty] || zMin;
}
// update the rest
mz = Math.max(tz + gv, mz);
}
return Math.max(mz, zMin);
}
// export z probe function
const rx = stepsX / boundsX;
const ry = stepsX / boundsX;
const toolAtXY = this.toolAtXY = function(px, py) {
px = Math.round(rx * (px - minX));
py = Math.round(ry * (py - minY));
return toolAtZ(px, py);
};
const zAtXY = this.zAtXY = function(px, py) {
let ix = Math.round(rx * (px - minX));
let iy = Math.round(ry * (py - minY));
return data[ix * stepsY + iy] || zMin;
};
}
}
class Trace {
constructor(probe, params) {
const { curvesOnly, maxangle, flatness, bridge, contourX, leave } = params;
this.params = params;
this.probe = probe;
let trace,
slice,
latent,
lastPP,
lastSlope;
const newslice = this.newslice = () => {
this.slice = slice = [];
}
const newtrace = this.newtrace = function() {
trace = newPolygon().setOpen();
}
const end_poly = this.end_poly = function(point) {
if (latent) {
trace.push(latent);
}
if (trace.length > 0) {
// add additional constraint on min perimeter()
if (trace.length > 1) {
slice.push(trace);
}
newtrace();
}
lastPP = undefined;
latent = undefined;
lastSlope = undefined;
if (point) {
trace.push(point);
lastPP = point;
}
}
const log = function(map) {
for (let key in map) {
const val = map[key];
if (typeof val === 'number') {
map[key] = val.round(4);
}
}
console.log(...arguments);
}
const push_point = this.push_point = function(x, y, z) {
const newP = newPoint(x, y, z);
const lastP = lastPP;//trace.last();
if (lastP) {
const dl = (x - lastP.x) || (y - lastP.y);
const dz = z - lastP.z;
const slope = Math.atan2(dz, dl);
if (curvesOnly && Math.abs(dz) < flatness) {
end_poly(newP);
} else if (lastSlope !== undefined && Math.abs(lastSlope - slope) < 0.001) {
latent = newP;
} else {
if (latent) {
trace.push(latent);
latent = undefined;
}
if (curvesOnly) {
const dv = contourX ? Math.abs(lastP.x - x) : Math.abs(lastP.y - y);
// const dz = lastPP.z - z;
const angle = Math.atan2( Math.abs(dz), dv) * RAD2DEG;
if (angle > maxangle) {
end_poly();
}
}
trace.push(newP);
}
lastSlope = slope;
} else {
trace.push(newP);
}
lastPP = newP;
}
const object = this.object = this;
this.inClip = function (clips, checkZ, point) {
for (let i=0; i<clips.length; i++) {
let poly = clips[i];
let zok = checkZ ? checkZ <= poly.z : true;
object.tabZ = poly.z;
if (zok && point.isInPolygon(poly)) {
return true;
}
}
return false;
}
}
init(params) {
this.cross = params;
const { minions } = kiri;
const { clipTab, clipTabZ } = params;
// because codec does not encode arbitrary fields
// in this case, z is appended to clip tabs in topo constructor
// we pass it as a side-channel and re-consitute here
if (clipTab)
for (let i=0, l=clipTab.length; i<l; i++) {
clipTab[i].z = clipTabZ[i];
}
if (minions && this.cross.concurrent) {
const { codec } = kiri;
minions.broadcast("trace_init", codec.encode({
probe: this.probe.params,
trace: this.params,
cross: params,
}));
}
}
cleanup() {
const { minions } = kiri;
if (minions && this.cross.concurrent) {
minions.broadcast("trace_cleanup");
}
}
crossY(params, then) {
const { minions } = kiri;
if (minions && this.cross.concurrent) {
minions.queue({
cmd: "trace_y",
params
}, data => {
then(kiri.codec.decode(data.slice));
});
} else {
this.crossY_sync(params, then);
}
}
crossX(params, then) {
const { minions } = kiri;
if (minions && this.cross.concurrent) {
minions.queue({
cmd: "trace_x",
params
}, data => {
then(kiri.codec.decode(data.slice));
});
} else {
this.crossX_sync(params, then);
}
}
crossY_sync(params, then) {
const { push_point, end_poly, newtrace, newslice, inClip } = this.object;
const { clipTab, tabHeight, clipTo, box, resolution, density, leave } = this.cross;
const { toolAtZ } = this.probe;
let { from, to, x, gridx, gridy } = params;
const step = resolution * density;
const checkr = newPoint(0,0);
newslice();
newtrace();
for (let y = from; y < to; y += step) {
if (y < box.min.y || y > box.max.y) {
gridy += density;
continue;
}
// find tool z at grid point
let tv = toolAtZ(gridx, gridy);
checkr.x = x;
checkr.y = y;
// when tabs are on and this point is inside the
// tab polygon, ensure z is at least tabHeight
if (clipTab && tv < tabHeight && inClip(clipTab, tv, checkr)) {
tv = this.tabZ;
}
// if the value is on the floor and inside the clip
// poly (usually shadow), end the segment
if (clipTo && !inClip(clipTo, undefined, checkr)) {
end_poly();
gridy += density;
continue;
}
push_point(x, y, tv + leave);
gridy += density;
}
end_poly();
then(this.slice);
}
crossX_sync(params, then) {
const { push_point, end_poly, newtrace, newslice, inClip } = this.object;
const { clipTab, tabHeight, clipTo, box, resolution, density, leave } = this.cross;
const { toolAtZ } = this.probe;
let { from, to, y, gridx, gridy } = params;
const step = resolution * density;
const checkr = newPoint(0,0);
newslice();
newtrace();
for (let x = from; x < to; x += step) {
if (x < box.min.x || x > box.max.x) {
gridx += density;
continue;
}
// find tool z at grid point
let tv = toolAtZ(gridx, gridy);
checkr.x = x;
checkr.y = y;
// when tabs are on and this point is inside the
// tab polygon, ensure z is at least tabHeight
if (clipTab && tv < tabHeight && inClip(clipTab, tv, checkr)) {
tv = this.tabZ;
}
// if the value is on the floor and inside the clip
// poly (usually shadow), end the segment
if (clipTo && !inClip(clipTo, undefined, checkr)) {
end_poly();
gridx += density;
continue;
}
push_point(x, y, tv + leave);
gridx += density;
}
end_poly();
then(this.slice);
}
}
function raster_slice(inputs) {
const { lines, data, box, resolution, curvesOnly } = inputs;
const { flatness, zMin, minY, maxY, stepsY, gridx } = inputs;
const { slice } = inputs;
let gridy,
gridi, // index
gridv, // value
i, il, j, x, y, tv;
// filter lines pairs to only surface "up-facing", "uncovered" lines
let points = [];
// emit an array of valid line-pairs
const len = lines.length;
outer: for (let i=0; i<len; i++) {
let l1 = lines[i], p1 = l1.p1, p2 = l1.p2;
// eliminate vertical
if (Math.abs(p1.y - p2.y) < flatness) continue;
// eliminate if both points below cutoff
if (p1.z < zMin && p2.z < zMin) continue;
// sort p1,p2 by y for comparison
if (p1.y > p2.y) { const tp = p1; p1 = p2; p2 = tp };
// eliminate if points "under" other lines
for (let j=0; j<len; j++) {
// skip self and adjacent
if (j >= i-1 && j <= i+1) continue;
let l2 = lines[j], p3 = l2.p1, p4 = l2.p2;
// sort p3,p4 by y for comparison
if (p3.y > p4.y) { const tp = p3; p3 = p4; p4 = tp };
// it's under the other line
if (Math.max(p1.z,p2.z) < Math.min(p3.z,p4.z)) {
// it's inside the other line, too, so skip
if (p1.y >= p3.y && p2.y <= p4.y) continue outer;
}
}
points.push(p1, p2);
box.expandByPoint(p1);
box.expandByPoint(p2);
}
gridy = 0;
// rasterize one x slice
for (y = minY; y < maxY && gridy < stepsY; y += resolution) {
gridi = gridx * stepsY + gridy;
gridv = data[gridi] || zMin;
// strategy using raw lines (faster slice, but more lines)
for (i=0, il=points.length; i<il; i += 2) {
const p1 = points[i], p2 = points[i+1];
// one endpoint above grid
const crossz = (p1.z > gridv || p2.z > gridv);
// segment crosses grid y
const spansy = (p1.y <= y && p2.y >= y);
if (crossz && spansy) {
// compute intersection of z ray up
// and segment at this grid point
const dy = p1.y - p2.y,
dz = p1.z - p2.z,
pct = (p1.y - y) / dy,
nz = p1.z - (dz * pct);
// save if point is greater than existing grid point
if (nz > gridv) {
gridv = data[gridi] = Math.max(nz, zMin);
if (slice) slice.output()
.setLayer("heights", {face: 0, line: 0})
.addLine(
newPoint(p1.x, y, 0),
newPoint(p1.x, y, gridv)
);
}
}
}
gridy++;
}
// remove flat lines when curvesOnly
if (curvesOnly) {
let nup = [];
for (let i=0, p=points, l=p.length; i<l; i += 2) {
const p1 = p[i];
const p2 = p[i+1];
if (Math.abs(p1.z - p2.z) >= flatness) {
nup.push(p1, p2);
}
}
points = nup;
}
return points;
};
CAM.Topo = async function(opt) {
return new Topo().generate(opt);
};
moto.broker.subscribe("minion.started", msg => {
const { funcs, cache, reply, log } = msg;
funcs.topo_raster = (data, seq) => {
const { id, slice, params } = data;
const { resolution } = params;
const vertices = cache[id];
const box = new THREE.Box2();
new kiri.topo_slicer(slice.index)
.setFromArray(vertices, slice)
.slice(resolution)
.forEach(rec => {
const { z, index, lines } = rec;
for (let line of lines) {
const { p1, p2 } = line;
if (!p1.swapped) { p1.swapXZ(); p1.swapped = true }
if (!p2.swapped) { p2.swapXZ(); p2.swapped = true }
}
raster_slice({
...params,
box,
lines,
gridx: index
});
});
// only pass back bounds of rasters to be merged
reply({ seq, box });
};
funcs.trace_init = data => {
const { cache } = self;
const { codec } = kiri;
data.cross.clipTo = codec.decode(data.cross.clipTo);
data.cross.clipTab = codec.decode(data.cross.clipTab);
const probe = new Probe(data.probe);
const trace = new Trace(probe, data.trace);
cache.trace = {
probe,
trace,
cross: data.cross
};
trace.init(data.cross);
};
funcs.trace_y = (data, seq) => {
const { cache } = self;
const { trace } = cache.trace;
trace.crossY_sync(data.params, slice => {
slice = kiri.codec.encode(slice);
reply({ seq, slice });
});
};
funcs.trace_x = (data, seq) => {
const { cache } = self;
const { trace } = cache.trace;
trace.crossX_sync(data.params, slice => {
slice = kiri.codec.encode(slice);
reply({ seq, slice });
});
};
funcs.trace_cleanup = () => {
delete cache.trace;
};
});
export { raster_slice, PRO, POLY, RAD2DEG, DEG2RAD, ctab, debug, output, probe, trace, box, params, vertices, range, i, x, z, shards, step, slices, index, slice, complete, promises, concurrent, stepsTaken, pcount, slicesY, slicesX, promise, inc, dec, gridx, gridy, y, lines, points, toolAtZ, sx, tx, ty, tz, rx, ry, toolAtXY, zAtXY, ix, iy, newslice, newtrace, end_poly, log, push_point, newP, lastP, dl, dz, slope, dv, angle, object, poly, zok, checkr, tv, len, l1, tp, j, l2, p1, crossz, spansy, dy, nup, p2, Topo };

534
src2/kiri-mode/cam/topo4.js Normal file
View file

@ -0,0 +1,534 @@
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
import { base } from '../geo/base.js';
import { line } from '../geo/line.js';
import { point } from '../geo/point.js';
import { polygon } from '../geo/polygon.js';
import { polygons } from '../geo/polygons.js';
import { broker } from '../moto/broker.js';
import { slice } from '../kiri/slice.js';
import { driver } from '../kiri-mode/cam/driver.js';
import { slicer2 } from '../kiri-mode/cam/slicer2.js';
const { base, kiri, moto } = root;
const { driver, newSlice } = kiri;
const { CAM } = driver;
const { polygons, newPoint, newPolygon, sliceConnect } = base;
const PRO = CAM.process;
const POLY = polygons;
const RAD2DEG = 180 / Math.PI;
const DEG2RAD = Math.PI / 180;
function scale(fn, factor = 1, base = 0) {
return (value, msg) => {
fn(base + value * factor, msg);
}
}
class Topo4 {
constructor() { }
async generate(opt = {}) {
let { state, op, onupdate, ondone } = opt;
let { widget, settings, tabs } = opt.state;
let { controller, process } = settings;
let axis = op.axis.toLowerCase(),
tool = new CAM.Tool(settings, op.tool),
bounds = widget.getBoundingBox().clone(),
density = parseInt(controller.animesh || 100) * 2500,
{ min, max } = bounds,
span = {
x: max.x - min.x,
y: max.y - min.y
},
contour = {
x: axis === "x",
y: axis === "y"
},
zMin = min.z + 0.0001,
tolerance = op.tolerance,
resolution = tolerance ? tolerance : 1 / Math.sqrt(density / (span.x * span.y)),
step = this.step = (tool.traceOffset() * 2) * op.step,
angle = this.angle = op.angle || 1;
if (tool.isTaperMill() && step === 0) {
step = this.step = op.step * tool.unitScale();
}
if (tolerance === 0) {
console.log(widget.id, 'topo4 auto tolerance', resolution.round(4));
}
this.zBottom = state.zBottom;
this.resolution = resolution;
this.vertices = widget.getGeoVertices({ unroll: true, translate: true });
this.tabverts = widget.getTabVertices();
this.tool = tool.generateProfile(resolution).profile;
this.maxo = tool.profileDim.maxo * resolution;
this.diam = tool.fluteDiameter();
this.zoff = widget.track.top || 0;
this.leave = op.leave || 0;
this.linear = op.linear || false;
this.lineColor = state.settings.controller.dark ? 0xffff00 : 0x555500;
onupdate(0, "lathe");
const range = this.range = { min: Infinity, max: -Infinity };
const slices = this.sliced = await this.slice(scale(onupdate, 0.25, 0));
for (let slice of slices) {
range.min = Math.min(range.min, slice.z);
range.max = Math.max(range.max, slice.z);
slice.output()
.setLayer("lathe", { line: 0x888888 })
.addPolys(slice.topPolys());
}
const lathe = await this.lathe(scale(onupdate, 0.75, 0.25));
onupdate(1, "lathe");
ondone(lathe);
// ondone([...slices, ...lathe]);
return this;
}
async slice(onupdate) {
const { vertices, resolution, tabverts, zoff } = this;
const range = this.range = { min: Infinity, max: -Infinity };
const box = this.box = new THREE.Box2();
// swap XZ in shared array
for (let i=0, l=vertices.length; i<l; i += 3) {
const x = vertices[i];
const z = vertices[i + 2] + zoff;
vertices[i] = z;
vertices[i + 2] = x;
range.min = Math.min(range.min, x);
range.max = Math.max(range.max, x);
}
// add tool radius to slice min/max range ot fully carve part
range.min -= this.diam / 2;
range.max += this.diam / 2;
// merge in tab vertices here so they don't affect slice range / dimensions
for (let i=0, l=tabverts.length; i<l; i += 3) {
const x = tabverts[i];
const z = tabverts[i + 2] + zoff;
tabverts[i] = z;
tabverts[i + 2] = x;
}
// re-create shared vertex array for workers
this.vertices = [].appendAll(vertices).appendAll(tabverts).toFloat32().toShared();
const shards = Math.ceil(Math.min(25, vertices.length / 27000));
const step = (range.max - range.min) / shards;
let index = 0;
let slices = this.slices = [];
let slice = { min: range.min, max: range.min + step, index };
for (let z = range.min; z < range.max; z += resolution) {
if (z > slice.max) {
slices.push(slice);
slice = { min: z, max: z + step, index };
}
index++;
}
slices.push(slice);
// console.log({ shards, range, step, slices });
if (kiri.minions.running > 1) {
return await this.sliceMinions(onupdate);
} else {
return await this.sliceWorker(onupdate);
}
}
async sliceWorker(onupdate) {
const { vertices, slices, resolution } = this;
const { codec } = kiri;
let output = [];
let complete = 0;
for (let slice of slices) {
const recs = new kiri.topo_slicer(slice.index)
.setFromArray(vertices, slice)
.slice(resolution)
.map(rec => {
const slice = kiri.newSlice(rec.z);
for (let line of rec.lines) {
const { p1, p2 } = line;
if (!p1.swapped) { p1.swapXZ(); p1.swapped = true }
if (!p2.swapped) { p2.swapXZ(); p2.swapped = true }
}
slice.index = rec.index;
slice.addTops(sliceConnect(rec.lines));
const points = codec.encodePointArray(rec.lines.map(l => [ l.p1, l.p2 ]).flat());
const shared = new Float32Array(new SharedArrayBuffer(points.length * 4));
shared.set(points);
slice.shared = shared;
return slice;
});
output.appendAll(recs);
onupdate(++complete /slices.length);
}
return output;
}
async sliceMinions(onupdate) {
const { codec } = kiri;
const { queue, putCache, clearCache } = this;
const { vertices, slices, resolution } = this;
putCache("vertices", vertices);
let complete = 0;
let promises = slices.map(slice => {
return queue("topo4_slice", {
resolution,
slice
}).then(data => {
onupdate(++complete / slices.length);
return data;
});
});
// merge boxes for all rasters for contouring clipping
const output = codec.decode(await Promise.all(promises))
.map(rec => rec.recs)
.flat()
.map(rec => newSlice(rec.z)
.addTops(rec.polys)
.setFields({ shared: rec.shared }))
.sort((a,b) => a.z - b.z);
clearCache();
return output;
}
async lathe(onupdate) {
if (kiri.minions.running > 1) {
return await this.latheMinions(onupdate);
} else {
return await this.latheWorker(onupdate);
}
}
lathePath(slices, tool) {
const { resolution, step, zBottom, maxo } = this;
const tlen = tool.length;
const slen = slices.length;
const sinc = Math.max(1, Math.ceil(step / resolution));
const heights = [];
// cull slice lines to only the ones in range (5x faster)
const oslices = [];
for (let slice of slices) {
const lines = slice.lines;
const plen = lines.length;
const rec = { z: slice.z, lines: [] };
for (let i = 0; i < plen; ) {
++i; // skip x which should match slice.z
let py0 = lines[i++];
const pz0 = lines[i++];
++i; // skip x which should match slice.z
let py1 = lines[i++];
const pz1 = lines[i++];
if ((py0 < -maxo && py1 < -maxo) || (py0 > maxo && py1 > maxo)) {
continue;
}
rec.lines.push(0, py0, pz0, 0, py1, pz1);
}
oslices.push(rec);
}
// iterate over all slices (real x = z)
// find max real z using z ray intersect from tool point to slice lines + offset
let lz = 0;
for (let si = 0; si < slen; si += sinc) {
const rx = oslices[si].z;
let mz = -Infinity;
// iterate over tool offsets
for (let ti = 0; ti < tlen; ) {
// tool offset in grid units from present x (si)
const xo = tool[ti++]; // x grid offset (slice)
const yo = tool[ti++] * resolution; // y grid offset (mult rez to get real y)
const zo = tool[ti++]; // real z delta offset
// get slice index corresponding with offset
const ts = si + xo;
// outside of slice array, skip
if (ts < 0 || ts >= slen - 1) {
continue;
}
const slice = oslices[ts];
const lines = slice.lines;
const plen = lines.length;
for (let i = 0; i < plen; ) {
++i; // skip x which should match slice.z
let py0 = lines[i++];
const pz0 = lines[i++];
++i; // skip x which should match slice.z
let py1 = lines[i++];
const pz1 = lines[i++];
if ((py0 <= yo && py1 >= yo) || (py1 <= yo && py0 >= yo)) {
const dz = pz1 - pz0;
const dy = Math.abs(py1 - py0);
if (dy === 0) continue;
const fr = Math.abs(yo - py0) / dy;
const lz = pz0 + dz * fr + zo;
// check z height
mz = Math.max(mz, lz);
}
}
if (mz === -Infinity && xo === 0 && yo === 0) {
// tool tip is off the model
continue;
}
}
if (mz === -Infinity) {
mz = zBottom; // Math.min(0, lz)
} else if (zBottom && mz < zBottom) {
mz = zBottom;
}
heights.push(rx, 0, lz = mz);
}
return heights;
}
async latheWorker(onupdate) {
const { sliced, tool, zoff, leave } = this;
const rota = this.angle * DEG2RAD;
const steps = (Math.PI * 2) / rota;
const axis = new THREE.Vector3(1, 0, 0);
const mrot = new THREE.Matrix4().makeRotationAxis(axis, rota);
const slices = sliced.map(s => { return { z: s.z, lines: s.shared } });
const paths = [];
const recs = [];
let angle = 0;
let count = 0;
// for each step angle, find Z spine heights, produce record
while (count++ < steps) {
const heights = this.lathePath(slices, tool, paths);
recs.push({ angle, heights, degrees: angle * RAD2DEG });
angle -= rota;
for (let lines of slices.map(s => s.lines)) {
rotatePoints(lines, mrot);
}
onupdate(count / steps);
}
count = recs[0].heights.length / 3;
while (count-- > 0) {
let slice = newSlice(count);
slice.camLines = [ newPolygon().setOpen() ];
paths.push(slice);
}
for (let rec of recs) {
const { degrees, heights } = rec;
[...heights].group(3).forEach((a,i) => {
// progress each path 360 degrees to prevent A rolling backwards
paths[i].camLines[0].push( newPoint(a[0], a[1], a[2] + leave).setA(degrees + i * -360) );
});
}
for (let slice of paths) {
const poly = slice.camLines[0];
if (!poly.length) {
console.log('empty', slice);
continue;
}
// repeat first point 360 degrees progressed
const repeat = poly.points[0];
slice.camLines[0].push(repeat.clone().setA(repeat.a - 360));
slice.output()
.setLayer("lathe", { line: this.lineColor })
.addPoly(poly.clone().applyRotations().move({ z: -zoff, x:0, y:0 }));
}
// console.log({ tool, slices, paths });
return paths;
}
async latheMinions(onupdate) {
const { sliced, tool, zoff, leave, maxo, zBottom, step, resolution, linear } = this;
const { putCache, clearCache, queue } = this;
const rota = this.angle * DEG2RAD;
const steps = (Math.PI * 2) / rota;
const slices = sliced.map(s => { return { z: s.z, lines: s.shared } });
const paths = [];
const recs = [];
putCache("lathe", {
maxo,
tool,
step,
slices,
zBottom,
resolution,
});
let done = 0;
let tangle = 0;
let count = 0;
let promises = [];
// for each step angle, find Z spine heights, produce record
while (count++ < steps) {
const angle = tangle;
let p = new Promise(resolve => {
queue("topo4_lathe", { angle }).then(data => {
// console.log({ angle, data });
recs.push({ angle, heights: data.heights, degrees: angle * RAD2DEG });
onupdate(++done / steps);
resolve();
});
});
// await p;
promises.push(p);
tangle -= rota;
}
await Promise.all(promises);
recs.sort((a, b) => { return b.angle - a.angle });
// let linear = true;
count = linear ? recs.length : recs[0].heights.length / 3;
while (count-- > 0) {
let slice = newSlice(count);
slice.camLines = [ newPolygon().setOpen() ];
paths.push(slice);
}
if (linear) {
recs.forEach((rec,i) => {
const { degrees, heights } = rec;
[...heights].group(3).forEach((a) => {
paths[i].camLines[0].push( newPoint(a[0], a[1], a[2] + leave).setA(degrees) );
});
if (i % 2 === 1) {
paths[i].camLines[0].reverse();
}
});
} else {
for (let rec of recs) {
const { degrees, heights } = rec;
[...heights].group(3).forEach((a,i) => {
// progress each path 360 degrees to prevent A rolling backwards
paths[i].camLines[0].push( newPoint(a[0], a[1], a[2] + leave).setA(degrees + i * -360) );
});
}
}
for (let slice of paths) {
const poly = slice.camLines[0];
if (!poly.length) {
console.log('empty', slice);
continue;
}
if (!linear) {
// repeat first point 360 degrees progressed
const repeat = poly.points[0];
slice.camLines[0].push(repeat.clone().setA(repeat.a - 360));
}
slice.output()
.setLayer("lathe", { line: this.lineColor })
.addPoly(poly.clone().applyRotations().move({ z: -zoff, x:0, y:0 }));
}
// console.log({ tool, slices, paths });
clearCache();
return paths;
}
putCache(key, data) {
kiri.worker.putCache({ key, data }, { done: data => { } });
}
clearCache() {
kiri.worker.clearCache({}, { done: data => { } });
}
queue(cmd, params) {
return new Promise(resolve => {
kiri.minions.queue({ cmd, ...params }, resolve);
});
}
}
function rotatePoints(lines, rot) {
new THREE.BufferAttribute(lines, 3).applyMatrix4(rot);
}
CAM.Topo4 = function(opt) {
return new Topo4().generate(opt);
};
moto.broker.subscribe("minion.started", msg => {
const { funcs, cache, reply, log } = msg;
const { codec } = kiri;
funcs.topo4_slice = (data, seq) => {
const { slice, resolution } = data;
const vertices = cache.vertices;
const recs = new kiri.topo_slicer(slice.index)
.setFromArray(vertices, slice)
.slice(resolution)
.map(rec => {
const { z, index, lines } = rec;
for (let line of lines) {
const { p1, p2 } = line;
if (!p1.swapped) { p1.swapXZ(); p1.swapped = true }
if (!p2.swapped) { p2.swapXZ(); p2.swapped = true }
}
const points = codec.encodePointArray(lines.map(l => [ l.p1, l.p2 ]).flat());
const shared = new Float32Array(new SharedArrayBuffer(points.length * 4));
shared.set(points);
return {
z, index, shared,
polys: codec.encode(sliceConnect(lines)),
};
});
// only pass back bounds of rasters to be merged
reply({ seq, recs });
};
funcs.topo4_lathe = (data, seq) => {
const { angle } = data;
const { slices, tool } = cache.lathe;
const axis = new THREE.Vector3(1, 0, 0);
const mrot = new THREE.Matrix4().makeRotationAxis(axis, -angle);
const stmp = slices.map(s => {
const lines = s.lines.slice();
rotatePoints(lines, mrot);
return { z: s.z, lines }
});
const topo4 = Object.assign(new Topo4(), cache.lathe);
const heights = topo4.lathePath(stmp, tool);
reply({ seq, heights });
}
});
export { scale, rotatePoints, PRO, POLY, RAD2DEG, DEG2RAD, axis, range, slices, lathe, box, i, x, z, shards, step, index, slice, output, complete, recs, points, shared, promises, tlen, slen, sinc, heights, oslices, lines, plen, rec, py0, pz0, py1, pz1, lz, si, rx, mz, ti, xo, yo, zo, ts, dz, dy, fr, rota, steps, mrot, paths, angle, count, poly, repeat, done, tangle, p, linear, vertices, stmp, topo4, Topo4 };