grid-apps-cmms/src/mode/laser/driver.js

611 lines
20 KiB
JavaScript
Raw Normal View History

2020-06-03 22:39:30 -04:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
2017-04-18 17:09:33 -04:00
"use strict";
(function() {
if (!self.kiri.driver) self.kiri.driver = { };
if (self.kiri.driver.LASER) return;
2020-06-03 22:39:30 -04:00
const KIRI = self.kiri,
2017-04-18 17:09:33 -04:00
BASE = self.base,
UTIL = BASE.util,
2020-03-12 19:23:09 -04:00
POLY = BASE.polygons,
2020-11-08 20:19:50 -05:00
FDM = KIRI.driver.FDM,
CAM = KIRI.driver.CAM,
LASER = KIRI.driver.LASER = {
2020-12-03 14:46:20 -05:00
init,
slice,
2020-11-08 20:19:50 -05:00
prepare,
export: exportLaser,
exportGCode,
exportSVG,
exportDXF
},
2017-04-18 17:09:33 -04:00
SLICER = KIRI.slicer,
newPoint = BASE.newPoint;
2020-12-03 14:46:20 -05:00
function init(kiri, api) {
api.event.on("settings.saved", (settings) => {
let UI = kiri.api.ui;
UI.knife.marker.style.display = UI.knifeOn.checked ? '' : 'none';
});
}
2017-04-18 17:09:33 -04:00
/**
* DRIVER SLICE CONTRACT
*
* @param {Object} settings
* @param {Widget} Widget
* @param {Function} onupdate (called with % complete and optional message)
* @param {Function} ondone (called when complete with an array of Slice objects)
*/
function slice(settings, widget, onupdate, ondone) {
2020-03-12 19:23:09 -04:00
let proc = settings.process;
2020-12-03 14:46:20 -05:00
let offset = proc.laserOffset;
2017-04-18 17:09:33 -04:00
if (proc.laserSliceHeight < 0) {
return ondone("invalid slice height");
2017-04-18 17:09:33 -04:00
}
2020-04-13 19:28:17 -04:00
SLICER.sliceWidget(widget, {
single: proc.laserSliceSingle,
height: proc.laserSliceHeight,
minHeight: proc.laserSliceHeight === 0 ? proc.laserSliceHeightMin : 0
2020-04-13 19:28:17 -04:00
}, function(slices) {
2017-04-18 17:09:33 -04:00
widget.slices = slices;
slices.forEach(function(slice, index) {
2020-12-03 14:46:20 -05:00
let tops = slice.tops.map(t => t.poly);
let offsets = slice.offset = offset ?
POLY.offset(tops, offset, {z: slice.z, miter: 2 / offset}) : tops;
slice.output().setLayer("layer", { line: 0x888800 }).addPolys(tops);
slice.output().setLayer("cut").addPolys(offsets);
2017-04-18 17:09:33 -04:00
onupdate(0.80 + (index/slices.length) * 0.20);
});
ondone();
2017-04-18 17:09:33 -04:00
}, function(update) {
onupdate(0.0 + update * 0.80)
});
};
2020-12-03 14:46:20 -05:00
function sliceEmitObjects(print, slice, groups, simple) {
2020-03-12 19:23:09 -04:00
let start = newPoint(0,0,0);
let process = print.settings.process;
let grouped = process.outputLaserGroup;
let group = [];
let zcolor = print.settings.process.outputLaserZColor;
2020-03-12 19:23:09 -04:00
group.thick = slice.thick;
2020-03-12 19:23:09 -04:00
function laserOut(poly, group) {
if (!poly) {
return;
}
2017-04-18 17:09:33 -04:00
if (Array.isArray(poly)) {
poly.forEach(function(pi) {
2020-03-12 19:23:09 -04:00
laserOut(pi, group);
2017-04-18 17:09:33 -04:00
});
} else {
2020-12-03 14:46:20 -05:00
let pathOpt = zcolor ? {extrude: slice.z, rate: slice.z} : {extrude: 1};
if (simple) pathOpt.simple = true;
if (poly.open) pathOpt.open = true;
print.polyPrintPath(poly, start, group, pathOpt);
2017-04-18 17:09:33 -04:00
}
}
2020-12-03 14:46:20 -05:00
let offset = slice.offset;
let inner = offset.map(poly => poly.inner || []).flat();
laserOut(offset, group);
laserOut(inner, group);
2020-11-08 20:19:50 -05:00
if (!grouped) {
groups.push(group);
group = [];
group.thick = slice.thick;
}
2019-05-23 16:52:55 -04:00
2020-03-12 19:23:09 -04:00
if (grouped) {
groups.push(group);
2019-05-23 16:52:55 -04:00
}
2017-04-18 17:09:33 -04:00
};
/**
* DRIVER PRINT CONTRACT
*
* @param {Object} print state object
* @param {Function} update incremental callback
*/
2020-11-08 20:19:50 -05:00
function prepare(widgets, settings, update) {
let device = settings.device,
2017-04-18 17:09:33 -04:00
process = settings.process,
2020-11-08 20:19:50 -05:00
print = self.worker.print = KIRI.newPrint(settings, widgets),
2020-12-03 14:46:20 -05:00
knifeOn = process.knifeOn,
knifeDepth = process.outputKnifeDepth,
knifePasses = process.outputKnifePasses,
knifeTipOff = process.outputKnifeTip,
2020-11-08 20:19:50 -05:00
output = print.output = [],
2017-04-18 17:09:33 -04:00
totalSlices = 0,
slices = 0;
2020-12-03 14:46:20 -05:00
function arc(center, s1, s2, out) {
let a1 = s1.angle;
let a2 = s2.angle;
let diff = s1.angleDiff(s2,true);
let step = 5;
let ticks = Math.abs(Math.floor(diff / step));
let dir = Math.sign(diff);
let off = (diff % step) / 2;
if (off == 0) {
ticks++;
} else {
out.push( center.projectOnSlope(s1, knifeTipOff) );
}
while (ticks-- > 0) {
out.push( center.projectOnSlope(BASE.newSlopeFromAngle(a1 + off), knifeTipOff) );
a1 += step * dir;
}
out.push( center.projectOnSlope(s2, knifeTipOff) );
}
// start to the "left" of the first point
function addKnifeRadii(poly) {
poly.setClockwise();
let oldpts = poly.points.slice();
// find leftpoint and make that the first point
let start = oldpts[0];
let startI = 0;
for (let i=1; i<oldpts.length; i++) {
let pt = oldpts[i];
if (pt.x < start.x || pt.y > start.y) {
start = pt;
startI = i;
}
}
if (startI > 0) {
oldpts = oldpts.slice(startI,oldpts.length).appendAll(oldpts.slice(0,startI));
}
let lastpt = oldpts[0].clone().move({x:-knifeTipOff,y:0,z:0});
let lastsl = lastpt.slopeTo(oldpts[0]).toUnit();
let newpts = [ lastpt, lastpt = oldpts[0] ];
let tmp;
for (let i=1; i<oldpts.length + 1; i++) {
let nextpt = oldpts[i % oldpts.length];
let nextsl = lastpt.slopeTo(nextpt).toUnit();
2020-12-03 19:51:14 -05:00
if (lastsl.angleDiff(nextsl) >= 10) {
if (lastpt.distTo2D(nextpt) >= knifeTipOff) {
arc(lastpt, lastsl, nextsl, newpts);
} else {
// todo handle short segments
// newpts.push(lastpt.projectOnSlope(lastsl, knifeTipOff) );
// newpts.push( lastpt.projectOnSlope(nextsl, knifeTipOff) );
}
2020-12-03 14:46:20 -05:00
}
newpts.push(nextpt);
lastsl = nextsl;
lastpt = nextpt;
}
newpts.push( tmp = lastpt.projectOnSlope(lastsl, knifeTipOff) );
newpts.push( tmp.clone().move({x:knifeTipOff, y:0, z: 0}) );
poly.open = true;
poly.points = newpts;
poly.length = newpts.length;
}
2017-04-18 17:09:33 -04:00
// find max layers (for updates)
widgets.forEach(function(widget) {
totalSlices += widget.slices.length;
});
// emit objects from each slice into output array
widgets.forEach(function(widget) {
2020-03-12 19:23:09 -04:00
// slice stack merging
if (process.outputLaserMerged) {
let merged = [];
widget.slices.forEach(function(slice) {
let polys = [];
2020-12-03 14:46:20 -05:00
slice.offsets.clone(true).forEach(p => p.flattenTo(polys));
2020-03-12 19:23:09 -04:00
polys.forEach(p => {
let match = false;
for (let i=0; i<merged.length; i++) {
let mp = merged[i];
if (p.isEquivalent(mp)) {
// increase weight
match = true;
mp.depth++;
}
}
if (!match) {
p.depth = 1;
merged.push(p);
}
});
update((slices++ / totalSlices) * 0.5, "prepare");
2020-03-12 19:23:09 -04:00
});
let start = newPoint(0,0,0);
let gather = [];
merged.forEach(poly => {
print.polyPrintPath(poly, start, gather, {
extrude: poly.depth,
rate: poly.depth * 10
});
});
output.push(gather);
} else {
2020-12-03 14:46:20 -05:00
if (knifeOn) {
widget.slices.forEach(slice => {
slice.offset.forEach(poly => {
addKnifeRadii(poly);
if (poly.inner) poly.inner.forEach(ip => {
addKnifeRadii(ip);
});
});
});
}
2020-03-12 19:23:09 -04:00
widget.slices.forEach(function(slice) {
2020-12-03 14:46:20 -05:00
sliceEmitObjects(print, slice, output, knifeOn);
update((slices++ / totalSlices) * 0.5, "prepare");
2020-03-12 19:23:09 -04:00
});
}
2017-04-18 17:09:33 -04:00
});
// compute tile width / height
output.forEach(function(layerout) {
2020-03-12 19:23:09 -04:00
let min = {w:Infinity, h:Infinity}, max = {w:-Infinity, h:-Infinity}, p;
2017-04-18 17:09:33 -04:00
layerout.forEach(function(out) {
p = out.point;
2017-11-01 07:43:42 -04:00
out.point = p.clone(); // b/c first/last point are often shared
2017-04-18 17:09:33 -04:00
min.w = Math.min(min.w, p.x);
max.w = Math.max(max.w, p.x);
min.h = Math.min(min.h, p.y);
max.h = Math.max(max.h, p.y);
});
layerout.w = max.w - min.w;
layerout.h = max.h - min.h;
2017-11-01 07:43:42 -04:00
// shift objects to top/left of w/h bounds
layerout.forEach(function(out) {
p = out.point;
p.x -= min.w;
p.y -= min.h;
});
2017-04-18 17:09:33 -04:00
});
// do object layout packing
2020-03-12 19:23:09 -04:00
let i, m, e,
2017-04-18 17:09:33 -04:00
MOTO = self.moto,
2020-10-14 17:18:14 -04:00
dw = device.bedWidth / 2,
dh = device.bedDepth / 2,
sort = !process.outputLaserLayer,
// sort objects by size when not using laser layer ordering
c = sort ? output.sort(MOTO.Sort) : output,
p = new MOTO.Pack(dw, dh, process.outputTileSpacing).fit(c, !sort);
2017-04-18 17:09:33 -04:00
2017-11-01 07:43:42 -04:00
// test different ratios until packed
2017-04-18 17:09:33 -04:00
while (!p.packed) {
2020-10-14 17:18:14 -04:00
dw *= 1.1;
dh *= 1.1;
p = new MOTO.Pack(dw, dh, process.outputTileSpacing).fit(c ,!sort);
2017-04-18 17:09:33 -04:00
}
for (i = 0; i < c.length; i++) {
m = c[i];
2018-03-25 19:21:07 -04:00
m.fit.x += m.w + p.pad;
m.fit.y += m.h + p.pad;
2017-04-18 17:09:33 -04:00
m.forEach(function(o, i) {
// because first point emitted twice (begin/end)
2017-11-01 07:43:42 -04:00
e = o.point;
2017-04-18 17:09:33 -04:00
e.x += p.max.w / 2 - m.fit.x;
e.y += p.max.h / 2 - m.fit.y;
2020-10-10 10:45:58 -04:00
// e.z = 0;
2017-04-18 17:09:33 -04:00
});
}
return print.render = FDM.prepareRender(output, (progress, layer) => {
update(0.5 + progress * 0.5, "render", layer);
2020-12-03 14:46:20 -05:00
}, { thin: true, z: 0, action: "cut", moves: process.knifeOn });
2017-04-18 17:09:33 -04:00
};
2020-11-08 20:19:50 -05:00
function exportLaser(print, online, ondone) {
ondone(print.output);
}
2017-04-18 17:09:33 -04:00
/**
*
*/
2020-11-08 20:19:50 -05:00
function exportElements(settings, output, onpre, onpoly, onpost, onpoint, onlayer) {
let process = settings.process,
zcolor = process.outputLaserZColor,
2017-04-18 17:09:33 -04:00
last,
point,
poly = [],
min = {x:0, y:0},
max = {x:0, y:0};
output.forEach(function(layer) {
layer.forEach(function(out) {
point = out.point;
if (process.outputInvertX) point.x = -point.x;
if (process.outputInvertY) point.y = -point.y;
min.x = Math.min(min.x, point.x);
max.x = Math.max(max.x, point.x);
min.y = Math.min(min.y, point.y);
max.y = Math.max(max.y, point.y);
});
});
2020-03-12 20:46:32 -04:00
2017-04-18 17:09:33 -04:00
if (!process.outputOriginCenter) {
2019-05-24 14:15:54 -04:00
// normalize against origin lower left
2017-04-18 17:09:33 -04:00
output.forEach(function(layer) {
layer.forEach(function(out) {
point = out.point;
point.x -= min.x;
point.y -= min.y;
});
});
max.x = max.x - min.x;
max.y = max.y - min.y;
min.x = 0;
min.y = 0;
2019-05-24 14:15:54 -04:00
} else {
// normalize against center of build area
2020-11-09 19:22:28 -05:00
let w = settings.device.bedWidth;
let h = settings.device.bedDepth;
2019-05-24 14:15:54 -04:00
output.forEach(function(layer) {
layer.forEach(function(out) {
point = out.point;
point.x += w/2;
point.y += h/2;
});
});
max.x = w;
max.y = h;
min.x = 0;
min.y = 0;
2017-04-18 17:09:33 -04:00
}
onpre(min, max, process.outputLaserPower, process.outputLaserSpeed);
output.forEach(function(layer, index) {
let thick = 0;
2020-03-12 19:23:09 -04:00
let color = 0;
layer.forEach(function(out, li) {
thick = out.thick;
2017-04-18 17:09:33 -04:00
point = out.point;
if (onlayer) {
onlayer(index, point.z, out.thick, output.length);
}
2017-04-18 17:09:33 -04:00
if (out.emit) {
2020-03-12 19:23:09 -04:00
color = out.emit;
if (last && poly.length === 0) {
poly.push(onpoint(last));
}
2017-04-18 17:09:33 -04:00
poly.push(onpoint(point));
} else if (poly.length > 0) {
onpoly(poly, color, thick);
2017-04-18 17:09:33 -04:00
poly = [];
}
last = point;
});
if (poly.length > 0) {
onpoly(poly, color, thick);
2017-04-18 17:09:33 -04:00
poly = [];
}
});
onpost();
};
/**
*
*/
2020-11-08 20:19:50 -05:00
function exportGCode(settings, data) {
let lines = [], dx = 0, dy = 0, z = 0, feedrate;
2020-11-08 20:19:50 -05:00
let dev = settings.device;
2020-12-03 14:46:20 -05:00
let proc = settings.process;
2020-05-05 20:45:09 -04:00
let space = dev.gcodeSpace ? ' ' : '';
let power = 255;
let laser_on = dev.gcodeLaserOn || [];
let laser_off = dev.gcodeLaserOff || [];
2020-12-03 14:46:20 -05:00
let knifeOn = proc.knifeOn;
let knifeDepth = proc.outputKnifeDepth;
let passes = knifeOn ? proc.outputKnifePasses : 1;
2017-04-18 17:09:33 -04:00
exportElements(
2020-11-08 20:19:50 -05:00
settings,
data,
2017-04-18 17:09:33 -04:00
function(min, max, power, speed) {
2020-03-12 19:23:09 -04:00
let width = (max.x - min.x),
2017-04-18 17:09:33 -04:00
height = (max.y - min.y);
2017-04-18 17:09:33 -04:00
dx = min.x;
dy = min.y;
feedrate = `${space}F${speed}`;
power = (256 * (power / 100)).toFixed(3);
(dev.gcodePre || []).forEach(line => {
lines.push(line);
});
2017-04-18 17:09:33 -04:00
},
function(poly, color, thick) {
2020-12-03 14:46:20 -05:00
if (knifeOn) {
lines.push(`; start new poly id=${poly.id} len=${poly.length}`);
}
2020-12-05 16:06:02 -05:00
for (let i=1; i<passes + 1; i++) {
2020-12-03 14:46:20 -05:00
poly.forEach(function(point, index) {
if (index === 0) {
if (knifeOn) {
// lift
lines.appendAll(['; drag-knife lift', `G0${space}Z5`]);
}
lines.push(`G0${space}${point}`);
if (knifeOn) {
// drop
2020-12-05 16:06:02 -05:00
lines.appendAll(['; drag-knife down', `G0${space}Z${-i * knifeDepth}`]);
2020-12-03 14:46:20 -05:00
}
} else if (index === 1) {
laser_on.forEach(line => {
line = line.replace('{power}', power);
line = line.replace('{color}', color);
line = line.replace('{thick}', thick);
line = line.replace('{z}', z);
lines.push(line);
});
lines.push(`G1${space}${point}${feedrate}`);
} else {
lines.push(`G1${space}${point}`);
}
});
laser_off.forEach(line => {
lines.push(line);
});
}
if (knifeOn) {
lines.appendAll([`G0${space}Z5`]);
}
2017-04-18 17:09:33 -04:00
},
function() {
(dev.gcodePost || []).forEach(line => {
lines.push(line);
});
2017-04-18 17:09:33 -04:00
},
function(point) {
z = point.z;
2020-05-05 20:45:09 -04:00
return `X${(point.x - dx).toFixed(3)}${space}Y${(point.y - dy).toFixed(3)}`;
},
function(layer, z, thick, layers) {
// ununsed
2017-04-18 17:09:33 -04:00
}
);
return lines.join('\n');
};
/**
*
*/
2020-11-08 20:19:50 -05:00
function exportSVG(settings, data, cut_color) {
let zcolor = settings.process.outputLaserZColor ? 1 : 0;
2020-10-10 10:45:58 -04:00
let lines = [], dx = 0, dy = 0, my, z = 0;
2020-03-12 19:23:09 -04:00
let colors = [
"black",
2020-03-12 19:23:09 -04:00
"purple",
"blue",
"red",
"orange",
"yellow",
"green",
"brown",
"gray"
2020-03-12 19:23:09 -04:00
];
2017-04-18 17:09:33 -04:00
exportElements(
2020-11-08 20:19:50 -05:00
settings,
data,
2017-04-18 17:09:33 -04:00
function(min, max) {
2020-03-12 19:23:09 -04:00
let width = (max.x - min.x),
2017-04-18 17:09:33 -04:00
height = (max.y - min.y);
dx = min.x;
dy = min.y;
my = max.y;
lines.push('<?xml version="1.0" standalone="no"?>');
lines.push('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">');
2020-03-12 19:23:09 -04:00
lines.push(`<svg width="${width}mm" height="${height}mm" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" version="1.1">`);
2017-04-18 17:09:33 -04:00
},
function(poly, color, thick) {
let cout = zcolor || colors[((color-1) % colors.length)];
let def = ["polyline"];
2020-10-14 15:30:18 -04:00
if (z !== undefined) def.push(`z="${z}"`);
if (thick !== undefined) def.push(`h="${thick}"`);
lines.push(`<${def.join(' ')} points="${poly.join(' ')}" fill="none" stroke="${cout}" stroke-width="0.1mm" />`);
2017-04-18 17:09:33 -04:00
},
function() {
lines.push("</svg>");
},
function(point) {
2020-10-10 10:45:58 -04:00
z = point.z;
2017-04-18 17:09:33 -04:00
return UTIL.round(point.x - dx, 3) + "," + UTIL.round(my - point.y - dy, 3);
},
function(layer, z, thick, layers) {
if (zcolor) {
zcolor = Math.round(((layer + 1) / layers) * 0xffffff).toString(16);
zcolor = `#${zcolor.padStart(6,0)}`;
}
2017-04-18 17:09:33 -04:00
}
);
return lines.join('\n');
};
/**
*
*/
2020-11-08 20:19:50 -05:00
function exportDXF(settings, data) {
2020-03-12 19:23:09 -04:00
let lines = [];
2017-04-18 17:09:33 -04:00
exportElements(
2020-11-08 20:19:50 -05:00
settings,
data,
2017-04-18 17:09:33 -04:00
function(min, max) {
lines.appendAll([
' 0',
'SECTION',
' 2',
'HEADER',
' 9',
'$ACADVER',
'1',
'AC1014',
' 0',
'ENDSEC',
' 0',
'SECTION',
' 2',
'ENTITIES',
]);
},
function(poly) {
lines.appendAll([
' 0',
'LWPOLYLINE',
'100', // subgroup required
'AcDbPolyline',
' 90', // poly vertices
poly.length,
' 70', // open
'0',
' 43', // constant width line
'0.0'
]);
poly.forEach(function(point) {
lines.appendAll([
' 10',
point.x,
' 20',
point.y
]);
});
lines.appendAll([
' 0',
'SEQEND',
]);
},
function() {
lines.appendAll([
' 0',
'ENDSEC',
' 0',
'EOF',
]);
},
function(point) {
return {x:point.x,y:point.y};
}
);
return lines.join('\n');
};
})();