fix poly2polyemit logic bug from easedown overriding previously found closest point

This commit is contained in:
Stewart Allen 2025-07-06 18:24:19 -04:00
commit 120175cd77
6 changed files with 291 additions and 293 deletions

View file

@ -31,16 +31,16 @@ export function cam_export(print, online) {
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}" ],
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 },
pos = { x: null, y: null, z: null, a: undefined, f: null, t: null, emit: null },
line,
cidx,
mode,
@ -51,18 +51,18 @@ export function cam_export(print, online) {
compact_output = false,
lasering = false,
laserOp,
stock = settings.stock || { },
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}
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
y: origin.y,
z: spro.camOriginTop ? origin.z - zmax : origin.z
},
scale = {
x: 1,
@ -73,10 +73,10 @@ export function cam_export(print, online) {
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),
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
@ -96,9 +96,9 @@ export function cam_export(print, online) {
if (spos >= 0) {
const left = line.substring(0, spos);
const right = '(' + line.substring(spos)
.replace(/; /g,'')
.replace(/;/g,'') + ')';
line = [ left, right ].join('');
.replace(/; /g, '')
.replace(/;/g, '') + ')';
line = [left, right].join('');
}
}
output.append(line);
@ -123,21 +123,21 @@ export function cam_export(print, online) {
if (!array) {
return;
}
if (typeof(array) === 'string') {
if (typeof (array) === 'string') {
array = array.split('\n');
}
for (i=0; i<array.length; i++) {
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;
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;
}
@ -193,7 +193,7 @@ export function cam_export(print, online) {
consts.tool = pos.t.getNumber();
consts.tool_name = pos.t.getName();
if (!laserOp && (spro.camToolInit || toolChanges > 0)) {
filterEmit(cmdToolChange, { ...consts, spindle: newSpindle } );
filterEmit(cmdToolChange, { ...consts, spindle: newSpindle });
}
toolChanges++;
}
@ -259,20 +259,20 @@ export function cam_export(print, online) {
return;
}
let gn;
if ( out.emit >=0 && out.emit <= 3) gn = `G${out.emit}`;
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;
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)) {
@ -285,7 +285,7 @@ export function cam_export(print, online) {
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));
nl.append(space).append(axis.X).append(add0(consts.pos_x = pos.x * factor));
}
if (dy || newpos.y !== pos.y) {
pos.y = newpos.y;
@ -307,9 +307,9 @@ export function cam_export(print, online) {
pos.f = feed;
nl.append(space).append(axis.F).append(add0(consts.feed = feed * factor, true));
}
if(arc){
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));
.append(space).append(axis.J).append(add0(center.y * factor, true));
}
// temp hack to support RML1 dialect from a file extensions trigger
@ -318,9 +318,9 @@ export function cam_export(print, online) {
if (newFeed) {
append(`VS${feed};`);
}
nl = [ axis.Z, add0(pos.x * factor), ",", add0(pos.y * factor), ",", add0(pos.z * factor), ";" ];
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), ";" ];
nl = ["PU", add0(pos.x * factor), ",", add0(pos.y * factor), ";"];
}
}

View file

@ -21,7 +21,7 @@ const { toRadians } = util
export async function cam_prepare(widall, settings, update) {
const widgets = widall.filter(w => !w.track.ignore && !w.meta.disabled);
const count = widgets.length;
const weight = 1/count;
const weight = 1 / count;
const print = self.kiri_worker.current.print = newPrint(settings, widgets);
print.output = [];
@ -35,11 +35,11 @@ export async function cam_prepare(widall, settings, update) {
const output = print.output.filter(level => Array.isArray(level));
if (render) // allows it to run from CLI
return render.path(
output,
(progress, layer) => {
update(0.75 + progress * 0.25, "render", layer);
}, {
return render.path(
output,
(progress, layer) => {
update(0.75 + progress * 0.25, "render", layer);
}, {
thin: true,
print: 0,
move: 0x557799,
@ -49,7 +49,7 @@ export async function cam_prepare(widall, settings, update) {
action: "milling",
maxspeed: settings.process.camFastFeed || 6000
}
);
);
};
export function prepEach(widget, settings, print, firstPoint, update) {
@ -193,13 +193,13 @@ export function prepEach(widget, settings, print, firstPoint, update) {
function emitDrills(polys) {
polys = polys.slice();
for (;;) {
for (; ;) {
let closestDist = Infinity,
closestI,
closest = null,
dist;
for (let i=0; i<polys.length; i++) {
for (let i = 0; i < polys.length; i++) {
if (!polys[i]) continue;
if ((dist = polys[i].first().distTo2D(printPoint)) < closestDist) {
closestDist = dist;
@ -222,7 +222,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
if (down <= 0) {
down = remain;
}
for (;;) {
for (; ;) {
if (remain > down * 2) {
points.push(point.clone());
point.z -= down;
@ -242,14 +242,14 @@ export function prepEach(widget, settings, print, firstPoint, update) {
}
}
camOut(point.clone().setZ(zmax));
points.forEach(function(point, index) {
points.forEach(function (point, index) {
camOut(point, 1);
if (index > 0 && index < points.length - 1) {
if (dwell) camDwell(dwell);
if (lift) camOut(point.clone().setZ(point.z + lift), 0);
}
})
camOut(point.clone().setZ(zmax),0);
camOut(point.clone().setZ(zmax), 0);
newLayer();
}
@ -290,9 +290,9 @@ export function prepEach(widget, settings, print, firstPoint, update) {
if (lasering.flat) {
point.z = (stock && stock.z ? stock.z : wztop) + lasering.flatz;
}
print.addOutput(layerOut, point, power, speed, tool, {type:'laser'});
print.addOutput(layerOut, point, power, speed, tool, { type: 'laser' });
} else {
print.addOutput(layerOut, point, emit, speed, tool, {type, center, arcPoints});
print.addOutput(layerOut, point, emit, speed, tool, { type, center, arcPoints });
}
lastPush = { point, emit, speed, tool };
return point;
@ -312,7 +312,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
* @param {Point} p - point to move
* @return {Point} new point with offset applied
*/
function applyWidgetMovement(p){
function applyWidgetMovement(p) {
return newPoint(
p.x + wmx,
p.y + wmy,
@ -329,8 +329,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
* @param {number} opts.moveLen typically = tool diameter used to trigger terrain detection
* @param {number} opts.factor speed scale factor
*/
function camOut(point, emit,opts) {
function camOut(point, emit, opts) {
// console.log({point, emit, opts})
let {
center = {},
@ -374,7 +373,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
emit,
rate,
tool,
{type:"lerp"},
{ type: "lerp" },
);
}
}
@ -401,7 +400,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
}
// convert short planar moves to cuts in some cases
if (!isRough&& !isArc && isMove && deltaXY <= moveLen && deltaZ <= 0 && !lasering ) {
if (!isRough && !isArc && isMove && deltaXY <= moveLen && deltaZ <= 0 && !lasering) {
let iscontour = tolerance > 0;
let isflat = absDeltaZ < 0.001;
// restrict this to contouring
@ -423,21 +422,21 @@ export function prepEach(widget, settings, print, firstPoint, update) {
} else if (isMove) {
// for longer moves, check the terrain to see if we need to go up and over
const bigXY = (deltaXY > moveLen && !lasering);
const bigZ = (deltaZ > toolDiam/2 && deltaXY > tolerance);
const bigZ = (deltaZ > toolDiam / 2 && deltaXY > tolerance);
const midZ = (tolerance && absDeltaZ >= tolerance) && !isContour;
if (bigXY || bigZ || midZ) {
let maxz = getZClearPath(
terrain,
lastPoint.x - wmx,
lastPoint.y - wmy,
point.x - wmx,
point.y - wmy,
Math.max(point.z, lastPoint.z),
zadd,
maxToolDiam/2,
zclear
),
terrain,
lastPoint.x - wmx,
lastPoint.y - wmy,
point.x - wmx,
point.y - wmy,
Math.max(point.z, lastPoint.z),
zadd,
maxToolDiam / 2,
zclear
),
maxZdelta = Math.max(maxz - point.z, maxz - lastPoint.z),
mustGoUp = maxZdelta >= tolerance,
clearz = maxz;
@ -471,7 +470,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
rate = Math.round(plungeRate + ((feedRate - plungeRate) * modifier));
cut = 1;
} else {
rate = 1 / Math.hypot(deltaXY / feedRate , absDeltaZ / plungeRate );
rate = 1 / Math.hypot(deltaXY / feedRate, absDeltaZ / plungeRate);
}
}
@ -534,8 +533,8 @@ export function prepEach(widget, settings, print, firstPoint, update) {
depthData.push(polys);
} else {
// if not depth first, output the polys in slice order
printPoint = poly2polyEmit(polys, printPoint, function(poly, index, count) {
poly.forEachPoint(function(point, pidx, points, offset) {
printPoint = poly2polyEmit(polys, printPoint, function (poly, index, count) {
poly.forEachPoint(function (point, pidx, points, offset) {
// scale speed of first cutting poly since it engages the full bit
camOut(point.clone(), offset !== 0, undefined, count === 1 ? engageFactor : 1);
}, poly.isClosed(), index);
@ -547,7 +546,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
// crucially returns true for -0 as well as other negative #s
function isNeg(v) {
return v < 0 || (v === 0 && 1/v === -Infinity);
return v < 0 || (v === 0 && 1 / v === -Infinity);
}
if (depthFirst) {
@ -571,7 +570,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
* 1. Travel from fromPoint to closest point on polygon, to rampZ above that that point,
* 2. ease-down starts, following the polygonal path, decreasing Z at a fixed slope until target Z is hit,
*/
function generateEaseDown(fn,poly, fromPoint, degrees = 45){
function generateEaseDown(fn, poly, fromPoint, degrees = 45) {
let index = poly.findClosestPointTo(fromPoint).index,
fromZ = fromPoint.z,
offset = 0,
@ -627,7 +626,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
index++;
}
return touch;
return touch;
}
// coming from a previous widget, use previous last point
@ -677,7 +676,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
};
let opSum = 0;
let opTot = widget.camops.map(op => op.weight()).reduce((a,v) => a + v);
let opTot = widget.camops.map(op => op.weight()).reduce((a, v) => a + v);
for (let op of widget.camops) {
setTolerance(0);
@ -729,95 +728,90 @@ export function prepEach(widget, settings, print, firstPoint, update) {
* @returns {Point} - the last point of the polygon
*/
function polyEmit(poly, index, count, fromPoint) {
let arcMax = Infinity, // no max arc radius
let arcQ = [],
arcMax = Infinity, // no max arc radius
lineTolerance = 0.001; // do not consider points under 0.001mm for arcs
fromPoint = fromPoint || printPoint;
let arcQ = [];
arcQ.angle = []
let closest = poly.findClosestPointTo(fromPoint);
let lastPoint = closest.point;
let startIndex = closest.index;
let lastPoint = fromPoint;
let startIndex = index;
// console.log({poly, index, count, fromPoint,startIndex})
// console.log({poly, index, count, fromPoint, startIndex})
// scale speed of first cutting poly since it engages the full bit
let scale = ((isRough || isPocket) && count === 1) ? engageFactor : 1;
if (easeDown && poly.isClosed()) { //if doing ease-down
let last = generateEaseDown((point,offset )=>{ //generate ease-down points
if(offset == 0) camOut(point.clone(), 0, {factor:engageFactor});
camOut(point.clone(), 1, {factor:scale}); // and pass them to camOut
// easeDown only allowed on closed polys (that we can continue around indefinitly)
if (easeDown && poly.isClosed()) {
let closest = poly.findClosestPointTo(fromPoint);
lastPoint = closest.point;
startIndex = closest.index;
let last = generateEaseDown((point, offset) => { // generate ease-down points
if (offset == 0) camOut(point.clone(), 0, { factor: engageFactor });
camOut(point.clone(), 1, { factor: scale }); // and pass them to camOut
}, poly, fromPoint, easeAngle);
lastPoint = poly.points[last];
startIndex = last;
}
}
// console.log(poly,poly.isClosed(),startIndex)
//A is first point of segment, B is last
poly.forEachSegment( ( pointA, pointB, indexA, indexB) => {
// A is first point of segment, B is last
poly.forEachSegment((pointA, pointB, indexA, indexB) => {
// if(offset == 0) console.log("forEachPoint",point,pidx,points)
// console.log({pointA, pointB, indexA, indexB,startIndex})
if(indexA == startIndex){
camOut(pointA.clone(), 0, {factor:engageFactor});
if (indexA == startIndex) {
camOut(pointA.clone(), 0, { factor: engageFactor });
// if first point, move to and call export function
quePush(pointA);
arcQ.push(pointA);
}
lastPoint = arcExport(pointB, pointA);
}, !poly.isClosed(), startIndex);
// console.log("at end of arcExport",structuredClone(arcQ));
if(arcQ.length > 3){
//if few points left, emit as lines
if (arcQ.length > 3) {
// if few points left, emit as lines
drainQ();
}
while (arcQ.length){
camOut(arcQ.shift(),1);
while (arcQ.length) {
camOut(arcQ.shift(), 1);
}
function quePush(point){
arcQ.push(point);
}
function arcExport(point,lastp){
let dist = lastp? point.distTo2D(lastp) : 0;
if (lastp) {
if (dist >lineTolerance && lastp) {
let rec = Object.assign(point,{dist});
function arcExport(point, lastp) {
let dist = lastp ? point.distTo2D(lastp) : 0;
if (lastp) {
if (dist > lineTolerance && lastp) {
let rec = Object.assign(point, { dist });
arcQ.push(rec);
// ondebug({arcQ});
if (arcQ.length > 2) {
let el = arcQ.length;
let e1 = arcQ[0]; // first in arcQ
let e2 = arcQ[Math.floor(el/2)]; // mid in arcQ
let e3 = arcQ[el-1]; // last in arcQ
let e4 = arcQ[el-2]; // second last in arcQ
let e5 = arcQ[el-3]; // third last in arcQ
let e2 = arcQ[Math.floor(el / 2)]; // mid in arcQ
let e3 = arcQ[el - 1]; // last in arcQ
let e4 = arcQ[el - 2]; // second last in arcQ
let e5 = arcQ[el - 3]; // third last in arcQ
let cc = util.center2d(e1, e2, e3, 1); // find center
let lr = util.center2d(e3, e4, e5, 1); // find local radius
let dc = 0;
let radFault = false;
if (lr) {
let angle = 2 * Math.asin(dist/(2*lr.r));
let angle = 2 * Math.asin(dist / (2 * lr.r));
radFault = Math.abs(angle) > arcRes; // enforce arcRes(olution)
} else {
radFault = true;
// console.log("too much angle")
radFault = true;
}
if (cc) {
if ([cc.x,cc.y,cc.z,cc.r].hasNaN()) {
if ([cc.x, cc.y, cc.z, cc.r].hasNaN()) {
// console.log({cc, e1, e2, e3});
}
if (arcQ.length === 3) {
arcQ.center = [ cc ];
arcQ.center = [cc];
arcQ.xSum = cc.x;
arcQ.ySum = cc.y;
arcQ.rSum = cc.r;
@ -825,39 +819,39 @@ export function prepEach(widget, settings, print, firstPoint, update) {
// check if first angles should have caused radFault
let a = toRadians(arcQ[0].slopeTo(cc).angle)
let b = toRadians(arcQ[1].slopeTo(cc).angle)
let angle = Math.abs(b-a)
let angle = Math.abs(b - a)
if( Math.abs(angle) > arcRes){
if (Math.abs(angle) > arcRes) {
// if so, remove first point
camOut(arcQ.shift(), 1)
radFault = true
}
} else {
// check center point delta
arcQ.xSum = arcQ.center.reduce( function (t, v) { return t + v.x }, 0 );
arcQ.ySum = arcQ.center.reduce( function (t, v) { return t + v.y }, 0 );
arcQ.rSum = arcQ.center.reduce( function (t, v) { return t + v.r }, 0 );
arcQ.xSum = arcQ.center.reduce(function (t, v) { return t + v.x }, 0);
arcQ.ySum = arcQ.center.reduce(function (t, v) { return t + v.y }, 0);
arcQ.rSum = arcQ.center.reduce(function (t, v) { return t + v.r }, 0);
let dx = cc.x - arcQ.xSum / arcQ.center.length;
let dy = cc.y - arcQ.ySum / arcQ.center.length;
dc = Math.hypot(dx, dy); // delta center distance
}
// if new point is off the arc
// if (deem || depm || desp || dc > arcTolerance || cc.r < arcMin || cc.r > arcMax || dist > cc.r) {
if ( dc * arcQ.center.length / arcQ.rSum > arcTolerance || dist > cc.r || cc.r > arcMax || radFault ) {
if (dc * arcQ.center.length / arcQ.rSum > arcTolerance || dist > cc.r || cc.r > arcMax || radFault) {
// let debug = [deem, depm, desp, dc * arcQ.center.length / arcQ.rSum > arcTolerance, dist > cc.r, cc.r > arcMax, radFault];
// console.log("point off the arc,",structuredClone(arcQ),);
if (arcQ.length === 4) {
// not enough points for an arc, drop first point and recalc center
camOut(arcQ.shift(),1);
camOut(arcQ.shift(), 1);
let tc = util.center2d(arcQ[0], arcQ[1], arcQ[2], 1);
// the new center is invalid as well. drop the first point
if (!tc) {
camOut(arcQ.shift(),1);
camOut(arcQ.shift(), 1);
} else {
arcQ.center = [ tc ];
let angle = 2 * Math.asin(arcQ[1].dist/(2*tc.r));
arcQ.center = [tc];
let angle = 2 * Math.asin(arcQ[1].dist / (2 * tc.r));
if (Math.abs(angle) > arcRes) { // enforce arcRes on initial angle
camOut(arcQ.shift(),1);
camOut(arcQ.shift(), 1);
}
}
} else {
@ -883,7 +877,6 @@ export function prepEach(widget, settings, print, firstPoint, update) {
}
} else {
// if first point, emit and set
camOut(point, 1);
// TODO disabling out of plane z moves until a better mechanism
// can be built that doesn't rely on computed zpos from layer heights...
@ -895,24 +888,24 @@ export function prepEach(widget, settings, print, firstPoint, update) {
}
function drainQ() {
let arcPreviewRes = 64
if (!arcTolerance) {
return;
}
if (arcQ.length > 4) {
// ondebug({arcQ});
let vec1 = new THREE.Vector2(arcQ[1].x - arcQ[0].x, arcQ[1].y - arcQ[0].y);
let vec2 = new THREE.Vector2(arcQ.center[0].x - arcQ[0].x, arcQ.center[0].y - arcQ[0].y);
let clockwise = vec1.cross(vec2) < 0
let gc = clockwise ? 2 :3
let clockwise = vec1.cross(vec2) < 0
let gc = clockwise ? 2 : 3
let from = arcQ[0];
let to = arcQ.peek();
let delta = from.distTo2D(to)
arcQ.xSum = arcQ.center.reduce( (t, v) => t + v.x , 0 );
arcQ.ySum = arcQ.center.reduce( (t, v) => t + v.y , 0 );
arcQ.rSum = arcQ.center.reduce( (t, v) => t + v.r , 0 );
arcQ.xSum = arcQ.center.reduce((t, v) => t + v.x, 0);
arcQ.ySum = arcQ.center.reduce((t, v) => t + v.y, 0);
arcQ.rSum = arcQ.center.reduce((t, v) => t + v.r, 0);
let cl = arcQ.center.length;
let center = newPoint(
arcQ.xSum / cl,
@ -920,32 +913,30 @@ export function prepEach(widget, settings, print, firstPoint, update) {
)
// console.log("draining")
if(arcQ.length == poly.points.length ){
if (arcQ.length == poly.points.length) {
//if is a circle
// generate circle
// console.log("circle",{from, to,center});
let arcPoints = arcToPath( from, from, arcPreviewRes,{ clockwise,center})
.map(applyWidgetMovement);
camOut(from,1);
camOut(from,gc,{ center:center.sub(from), clockwise, arcPoints});
let arcPoints = arcToPath(from, from, arcPreviewRes, { clockwise, center })
.map(applyWidgetMovement);
camOut(from, 1);
camOut(from, gc, { center: center.sub(from), clockwise, arcPoints });
// lastPoint = to.clone();
}else{
} else {
//if a non-circle arc
let arcPoints = arcToPath( from, to, arcPreviewRes,{ clockwise,center})
.map(applyWidgetMovement);
let arcPoints = arcToPath(from, to, arcPreviewRes, { clockwise, center })
.map(applyWidgetMovement);
// console.log("arc")
// first arc point
camOut(from,1);
camOut(from, 1);
// rest of arc to final point
camOut(to,gc,{ center:center.sub(from), clockwise, arcPoints});
camOut(to, gc, { center: center.sub(from), clockwise, arcPoints });
lastPoint = to.clone();
}
} else {
//if q too short, emit as lines
for (let rec of arcQ) {
camOut(rec,1);
camOut(rec, 1);
}
lastPoint = arcQ.peek().clone();
}
@ -953,7 +944,10 @@ export function prepEach(widget, settings, print, firstPoint, update) {
arcQ.center = undefined;
}
// newLayer();
if (depthFirst) {
newLayer();
}
return lastPoint;
}
@ -995,7 +989,7 @@ export function prepEach(widget, settings, print, firstPoint, update) {
function depthOutlinePath(start, depth, levels, radius, emitter, dir, ease) {
let bottm = depth < levels.length - 1 ? levels[levels.length - 1] : null;
let above = levels[depth-1];
let above = levels[depth - 1];
let level = levels[depth];
if (!level) {
return start;
@ -1061,7 +1055,7 @@ function getZClearPath(terrain, x1, y1, x2, y2, z, zadd, off, over) {
}
let maxz = z;
let check = [];
for (let i=0; i<terrain.length; i++) {
for (let i = 0; i < terrain.length; i++) {
let data = terrain[i];
check.push(data);
if (data.z + zadd < z) {
@ -1069,7 +1063,7 @@ function getZClearPath(terrain, x1, y1, x2, y2, z, zadd, off, over) {
}
}
check.reverse();
for (let i=0; i<check.length; i++) {
for (let i = 0; i < check.length; i++) {
let data = check[i];
let p1 = newPoint(x1, y1);
let p2 = newPoint(x2, y2);

View file

@ -93,15 +93,15 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
if (tabs) {
// make tab polygons
tabs.forEach(tab => {
let zero = newPoint(0,0,0),
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,
[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(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;
@ -141,7 +141,7 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
}
if (zMin >= bounds.max.z) {
return error(`invalid z bottom ${(zMin/units).round(3)} >= bounds z max ${(zMax/units).round(3)}`);
return error(`invalid z bottom ${(zMin / units).round(3)} >= bounds z max ${(zMax / units).round(3)}`);
}
let mark = Date.now();
@ -246,7 +246,7 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
function addSlices(slices, addIndexing = isIndexed) {
if (!Array.isArray(slices)) {
slices = [ slices ];
slices = [slices];
}
sliceAll.appendAll(slices);
if (addIndexing && axisIndex !== undefined) {
@ -266,7 +266,7 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
// 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 }));
opList.push(new OPS.index(state, { type: "index", index: 0 }));
} else {
opList.push(new OPS.shadow(state, { type: "shadow", silent: true }));
}
@ -333,7 +333,7 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
if (tabs) {
state.terrain.forEach(slab => {
tabs.forEach(tab => {
if (tab.pos.z + tab.dim.z/2 >= slab.z) {
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()
@ -348,7 +348,7 @@ export async function cam_slice(settings, widget, onupdate, ondone) {
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 });
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;
@ -369,8 +369,8 @@ export function addDogbones(poly, dist, reverse) {
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 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);
@ -409,8 +409,8 @@ export async function traces(settings, widget, single) {
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++] ];
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) {
@ -420,7 +420,7 @@ export async function traces(settings, widget, single) {
}
points[j++ % 2] = point;
if (j % 2 === 0) {
let [ p0, p1 ] = points;
let [p0, p1] = points;
let line = lines[k++] = newLine(p0, p1);
p0.lines.push(line);
p1.lines.push(line);
@ -513,10 +513,10 @@ export async function traces(settings, widget, single) {
* @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) {
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 { 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,
@ -535,37 +535,37 @@ export async function holes(settings, widget, individual, rec,onProgress) {
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()
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 )
precision = Math.max(0, precision)
let intervals = (precision == 0) ? [] : slicer.interval(
precision,
{
{
fit: false, off: -0.01, flats: true
}
)
let zees = [...zFlats,...intervals]
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,
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") };
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){
for (let [i, slice] of slices.entries()) {
for (let top of slice.tops) {
// console.log("slicing",slice.z,top)
slice.shadow = computeShadowAt(widget, slice.z, 0)
let inner = top.inner;
@ -573,13 +573,13 @@ export async function holes(settings, widget, individual, rec,onProgress) {
continue;
}
for (let poly of inner) {
if ( poly.points.length < 7 ) continue;
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 (poly.circularity() < 0.985) {
// if not circular, don't add to holes
continue;
}
@ -589,11 +589,11 @@ export async function holes(settings, widget, individual, rec,onProgress) {
continue;
}
let overlap = false;
for (let [i,circle] of circles.entries()) {
for (let [i, circle] of circles.entries()) {
let dist = circle.distTo2D(center)
// //if on the same xy point,
if (dist <= centerDiff ) {
if (dist <= centerDiff) {
// console.log("overlap",center,circle);
circle.overlapping.push(center);
// if overlapping, don't add and continue
@ -604,41 +604,41 @@ export async function holes(settings, widget, individual, rec,onProgress) {
if (!overlap) circles.push(center);
}
}
onProgress(0.5+(i/slices.length*0.25),"recognize circles")
onProgress(0.5 + (i / slices.length * 0.25), "recognize circles")
}
let drills = []
for (let [i,c] of circles.entries()) {
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;
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")
onProgress(0.75 + (i / circles.length * 0.25), "assemble holes")
}
drills.forEach( h=>{
if(rec.fromTop){
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
})
h.selected = (!individual && Math.abs(h.area - area) <= area * 0.05); //for same size selection
})
// console.log("unfiltered circles",circles)
// console.log("drills",drills)
@ -649,13 +649,13 @@ export async function holes(settings, widget, individual, rec,onProgress) {
}
function cutTabs(tabs, offset, z, inter) {
tabs = tabs.filter(tab => z < tab.pos.z + tab.dim.z/2).map(tab => tab.off).flat();
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) ));
offset.forEach(op => noff.appendAll(op.cut(POLY.union(polys, 0, true), inter)));
return healPolys(noff);
}
@ -682,12 +682,12 @@ function healPolys(noff) {
if (noff.length > 1) {
let heal = 0;
// heal/rejoin open segments that share endpoints
outer: for(;; heal++) {
outer: for (; ; heal++) {
let ntmp = noff, tlen = ntmp.length;
for (let i=0; i<tlen; i++) {
for (let i = 0; i < tlen; i++) {
let s1 = ntmp[i];
if (!s1) continue;
for (let j=i+1; j<tlen; j++) {
for (let j = i + 1; j < tlen; j++) {
let s2 = ntmp[j];
if (!s2) continue;
// require polys at same Z to heal
@ -743,13 +743,13 @@ export function computeShadowAt(widget, z, ztop) {
// cache faces with normals up
if (!widget.cache.shadow) {
const faces = [];
for (let i=0, ip=0; i<length; i += 3) {
for (let i = 0, ip = 0; i < length; i += 3) {
const a = new THREE.Vector3(geo[ip++], geo[ip++], geo[ip++]);
const b = new THREE.Vector3(geo[ip++], geo[ip++], geo[ip++]);
const c = new THREE.Vector3(geo[ip++], geo[ip++], geo[ip++]);
const n = THREE.computeFaceNormal(a,b,c);
const n = THREE.computeFaceNormal(a, b, c);
if (n.z > 0.001) {
faces.push(a,b,c);
faces.push(a, b, c);
// faces.push(newPoint(...a), newPoint(...b), newPoint(...c));
}
}
@ -758,7 +758,7 @@ export function computeShadowAt(widget, z, ztop) {
const found = [];
const faces = widget.cache.shadow;
const { checkOverUnderOn, intersectPoints } = cam_slicer;
for (let i=0; i<faces.length; ) {
for (let i = 0; i < faces.length;) {
const a = faces[i++];
const b = faces[i++];
const c = faces[i++];
@ -771,7 +771,7 @@ export function computeShadowAt(widget, z, ztop) {
// skip faces under threshold
continue;
} else if (a.z > z && b.z > z && c.z > z) {
found.push([a,b,c]);
found.push([a, b, c]);
} else {
// check faces straddling threshold
const where = { under: [], over: [], on: [] };
@ -789,7 +789,7 @@ export function computeShadowAt(widget, z, ztop) {
found.push([where.over[0], line[0], line[1]]);
}
} else {
console.log({msg: "invalid ips", line: line, where: where});
console.log({ msg: "invalid ips", line: line, where: where });
}
}
}
@ -797,9 +797,9 @@ export function computeShadowAt(widget, z, ztop) {
let polys = found.map(a => {
return newPolygon()
.add(a[0].x,a[0].y,a[0].z)
.add(a[1].x,a[1].y,a[1].z)
.add(a[2].x,a[2].y,a[2].z);
.add(a[0].x, a[0].y, a[0].z)
.add(a[1].x, a[1].y, a[1].z)
.add(a[2].x, a[2].y, a[2].z);
});
polys = POLY.union(polys, 0.001, true);

View file

@ -13,11 +13,11 @@ const { sliceConnect, sliceDedup } = slicer;
const { config } = base;
const timing = false;
const begin = function() {
const begin = function () {
if (timing) console.time(...arguments);
};
const end = function() {
const end = function () {
if (timing) console.timeEnd(...arguments);
};
@ -74,15 +74,15 @@ export class Slicer {
zList[z] = (zList[z] || 0) + 1;
}
let p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0);
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; ) {
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++]);
@ -100,7 +100,7 @@ export class Slicer {
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;
area = Math.abs(util.area2(p1, p2, p3)) / 2;
if (!zFlat[zkey]) {
zFlat[zkey] = area;
} else {
@ -155,7 +155,7 @@ export class Slicer {
// 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 => {
zs = zs.sort((a, b) => a - b).map(z => {
if (!flatoff) {
return z;
}
@ -183,13 +183,13 @@ export class Slicer {
b += step;
}
let p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0),
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; ) {
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++]);
@ -236,7 +236,7 @@ export class Slicer {
}
const data = (await Promise.all(promises)).flat();
data.sort((a,b) => b.z - a.z).forEach((rec, i) => {
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) {
@ -297,16 +297,16 @@ export class Slicer {
// const { points } = this,
const points = indices,
p1 = newPoint(0,0,0),
p2 = newPoint(0,0,0),
p3 = newPoint(0,0,0);
p1 = newPoint(0, 0, 0),
p2 = newPoint(0, 0, 0),
p3 = newPoint(0, 0, 0);
for (let index = 0; index < points.length; ) {
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: []};
let where = { under: [], over: [], on: [] };
checkOverUnderOn(p1, z, where);
checkOverUnderOn(p2, z, where);
checkOverUnderOn(p3, z, where);
@ -334,7 +334,7 @@ export class Slicer {
if (line.length === 2) {
lines.push(makeZLine(phash, line[0], line[1]));
} else {
console.log({msg: "invalid ips", line: line, where: where});
console.log({ msg: "invalid ips", line: line, where: where });
}
}
}
@ -344,7 +344,8 @@ export class Slicer {
lines = sliceDedup(lines, debug);
}
return lines.length ? { z,
return lines.length ? {
z,
lines: opt.lines !== false ? lines : undefined,
polys: links ? POLY.nest(sliceConnect(lines, opt, debug)) : undefined
} : null;
@ -367,12 +368,12 @@ export class Slicer {
step = (zmax - zmin) / count;
}
if (opt.down) {
for (let i=0; i<count; i++) {
for (let i = 0; i < count; i++) {
array.push(zmax);
zmax -= step;
}
} else {
for (let i=0; i<count; i++) {
for (let i = 0; i < count; i++) {
array.push(zmin);
zmin += step;
}
@ -392,13 +393,13 @@ export class Slicer {
}
});
// add over and under all flats by 'off'
array.appendAll(add).sort((a,b) => {
return opt.down ? b-a : a-b;
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]);
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)));
@ -471,7 +472,7 @@ function getCachedPoint(phash, p) {
function makeZLine(phash, p1, p2, coplanar, edge) {
p1 = getCachedPoint(phash, p1.clone());
p2 = getCachedPoint(phash, p2.clone());
let line = newOrderedLine(p1,p2);
let line = newOrderedLine(p1, p2);
line.coplanar = coplanar || false;
line.edge = edge || false;
return line;