-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDSTLoader.js
455 lines (417 loc) · 13.6 KB
/
DSTLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//DST embroidery file loader for THREEJS by thrax. 1/15/24
/*
This is a loader/parser/renderer for the .dst embroidery machine file format.
It renders the stitches to textured geometry, and can optionally then render that to a rendertaret for
more efficient display..
Colors , geometry, and thread parameters can be changed on the fly...
a normalized drawRange is supported to display the stitches at different times in the process..
the loader takes an options parameter, and returns a container for the resulting mesh or line primitive
options:
quads:true | fals , // whether to generate quads or line primitives...
threadThickness:0 to Infinity.. defaults to 2
jumpThreadThickness:0 to Infinity.. defaults to 0.01
palette:['red','white','blue'] .. the colors to use for the thread color steps..
// ideally 1+ the number of thread color steps in the file..
// unsupplied entries are set to random colors...
the load method returns an object:
the object returned has:
mesh: the Mesh or Line primitive...
and then all the parameters in "options" which can be changed on the fly.
*/
import * as THREE from "three";
export default function DSTLoader() {
function decodeCoordinate(byte1, byte2, byte3) {
let cmd = byte1 | (byte2 << 8) | (byte3 << 16);
let x = 0,
y = 0,
jump,
cstop;
let bit = (bit) => cmd & (1 << bit);
if (bit(23)) y += 1;
if (bit(22)) y -= 1;
if (bit(21)) y += 9;
if (bit(20)) y -= 9;
if (bit(19)) x -= 9;
if (bit(18)) x += 9;
if (bit(17)) x -= 1;
if (bit(16)) x += 1;
if (bit(15)) y += 3;
if (bit(14)) y -= 3;
if (bit(13)) y += 27;
if (bit(12)) y -= 27;
if (bit(11)) x -= 27;
if (bit(10)) x += 27;
if (bit(9)) x -= 3;
if (bit(8)) x += 3;
if (bit(7)) jump = true;
if (bit(6)) cstop = true;
if (bit(5)) y += 81;
if (bit(4)) y -= 81;
if (bit(3)) x -= 81;
if (bit(2)) x += 81;
/*
//FROM THE SPEC:
23 Y += 1 add 0.1 mm to needle's Y current coordinate
22 Y -= 1 subtract 0.1 mm from the needle's current Y position
21 Y += 9
20 Y -= 9
19 X -= 9
18 X += 9
17 X -= 1
16 X += 1
15 Y += 3
14 Y -= 3
13 Y += 27
12 Y -= 27
11 X -= 27
10 X += 27
9 X -= 3
8 X += 3
7 Jump stitch (not a normal stitch)
6 Stop for colour change or end of pattern
5 Y += 81
4 Y -= 81, the end-of-pattern code sets both Y += 81 and Y -= 81 which cancel each other
3 X -= 81
2 X += 81
*/
return { x, y, jump, cstop };
}
async function loadBinaryData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const buffer = await response.arrayBuffer();
return buffer;
} catch (error) {
console.error("Failed to load binary data:", error);
}
}
let quads = true;
let threadThickness = 2;
let jumpThreadThickness = 0.1;
let palette = ["black", "white", "red", "gray", "yellow", "orange"];
let pidx = 0;
let v0 = new THREE.Vector3();
function parseDST(buffer) {
const dataView = new DataView(buffer);
const start = 512; // Starting byte
const indices = [];
const vertices = [];
const colors = [];
const normals = [];
const uvs = [];
let cx = 0;
let cy = 0;
let cr = 1,
cg = 1,
cb = 1;
let header = String.fromCharCode.apply(
String,
new Uint8Array(buffer, 0, 512)
);
let coff = header.indexOf("CO:");
let colorCount = 0;
if (coff > 0) colorCount = parseInt(header.slice(coff + 3, coff + 7));
let vcount = 0;
let wasJumpOrStop = false;
let pidx = 0;
let cpalette;
if (!palette) palette = [];
while (palette.length < colorCount + 1) {
cr = Math.random();
cg = Math.random();
cb = Math.random();
v0.set(cr, cg, cb).normalize();
palette.push("#" + new THREE.Color(v0.x, v0.y, v0.z).getHexString());
}
cpalette = [];
for (let i = 0; i < palette.length; i++) {
cpalette[i] = new THREE.Color(palette[i]);
let p = cpalette[pidx % cpalette.length];
cr = p.r;
cg = p.g;
cb = p.b;
}
for (let i = start; i < dataView.byteLength; i += 3) {
if (i >= dataView.byteLength - 3) break;
const byte1 = dataView.getUint8(i);
const byte2 = dataView.getUint8(i + 1);
const byte3 = dataView.getUint8(i + 2);
// Check for end of file sequence
if (byte1 === 0x00 && byte2 === 0x00 && byte3 === 0xf3) {
break;
}
const { x, y, cstop, jump } = decodeCoordinate(byte3, byte2, byte1);
let px = cx,
py = cy;
cx += x;
cy += y;
if (cstop) {
if (cpalette) {
//Get next step color
pidx++;
let p = cpalette[pidx % cpalette.length];
cr = p.r;
cg = p.g;
cb = p.b;
} else {
cr = Math.random();
cg = Math.random();
cb = Math.random();
v0.set(cr, cg, cb).normalize();
cr = v0.x;
cg = v0.y;
cb = v0.z;
}
}
if (quads) {
let dx = cx - px;
let dy = cy - py;
let dtx = -dy;
let dty = dx;
let llen = v0.set(dtx, dty, 0).length();
if (llen) v0.multiplyScalar(1 / llen);
let thickness = wasJumpOrStop ? jumpThreadThickness : threadThickness;
dtx = v0.x * thickness;
dty = v0.y * thickness;
//if (jump || cstop) vertices.push(Infinity, Infinity, Infinity);
//else
vertices.push(px + dtx, py + dty, 0);
vertices.push(px - dtx, py - dty, 0);
vertices.push(cx - dtx, cy - dty, 0);
vertices.push(cx + dtx, cy + dty, 0);
let vy = Math.random() * 0.5;
uvs.push(0, 0 + vy, 1, 0 + vy, 1, llen / 80 + vy, 0, llen / 80 + vy);
colors.push(cr, cg, cb);
colors.push(cr, cg, cb);
colors.push(cr, cg, cb);
colors.push(cr, cg, cb);
//normals.push(dtx, dty, .5, -dtx, -dty, .5, -dtx, -dty, .5, dtx, dty, .5);
normals.push(0, 0, 1, -0, -0, 1, -0, -0, 1, 0, 0, 1);
indices.push(
vcount,
vcount + 1,
vcount + 2,
vcount + 2,
vcount + 3,
vcount + 0
);
vcount += 4;
} else {
//lines
vertices.push(cx, cy, 0); // Z-coordinate is 0 as embroidery designs are 2D
colors.push(cr, cg, cb);
}
wasJumpOrStop = jump || cstop;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
uvs.length &&
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
normals.length &&
geometry.setAttribute(
"normal",
new THREE.Float32BufferAttribute(normals, 3)
);
indices.length && geometry.setIndex(indices);
return geometry;
}
this.loadAsync = async (url, options) =>
new Promise((resolve, reject) => this.load(url, resolve, options));
this.load = (url, resolve, opts = {}) => {
loadBinaryData(url).then((buffer) => {
quads = true;
threadThickness = 2;
jumpThreadThickness = 0.01;
palette = null;
let generate = () => {
if (opts.quads !== undefined) quads = opts.quads;
if (opts.threadThickness !== undefined)
threadThickness = opts.threadThickness;
if (opts.jumpThreadThickness !== undefined)
jumpThreadThickness = opts.jumpThreadThickness;
if (opts.palette !== undefined) palette = opts.palette;
opts.quads = quads;
opts.threadThickness = threadThickness;
opts.jumpThreadThickness = jumpThreadThickness;
opts.palette = palette;
const geometry = parseDST(buffer, opts);
opts.palette = palette;
let lines = quads
? new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: "white",
vertexColors: true,
side: THREE.DoubleSide,
depthTest: false,
metalness: 0.0,
roughness: 0.9,
normalScale: new THREE.Vector2(0.8, 0.8),
})
)
: new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: "white",
vertexColors: true,
})
);
lines.scale.set(0.01, 0.01, 0.01);
lines.updateMatrixWorld(true);
return lines;
};
let mesh = generate();
let params = {
mesh,
get quads() {
return opts.quads || false;
},
set quads(on) {
opts.quads = on == true;
params.meshNeedsUpdate = true;
},
get threadThickness() {
return opts.threadThickness;
},
set threadThickness(f) {
opts.threadThickness = parseFloat(f);
params.meshNeedsUpdate = true;
},
get jumpThreadThickness() {
return opts.jumpThreadThickness;
},
set jumpThreadThickness(f) {
opts.jumpThreadThickness = parseFloat(f);
params.meshNeedsUpdate = true;
},
get palette() {
return opts.palette;
},
set palette(arry) {
opts.palette = arry;
params.meshNeedsUpdate = true;
},
toTexture(renderer, scene, maxDim, padding = 10) {
if (!opts.map) {
let bounds = new THREE.Box3();
bounds.setFromObject(params.mesh);
let bsz = bounds.getSize(new THREE.Vector3());
let aspect = bsz.x / bsz.y;
let pad = bsz.x / maxDim + (padding * 2) / maxDim;
let szx = (bsz.x + pad) / 2;
let szy = (bsz.y + pad / aspect) / 2;
const camera = new THREE.OrthographicCamera(
-szx,
szx,
szy,
-szy,
1,
1000
);
params.mesh.localToWorld(camera.position.set(0, 0, 0));
camera.position.z += 500; // adjust as needed
camera.lookAt(params.mesh.position);
if (bsz.x > bsz.y) {
bsz.y = maxDim * (bsz.y / bsz.x);
bsz.x = maxDim;
} else {
bsz.x = maxDim * (bsz.x / bsz.y);
bsz.y = maxDim;
}
const renderTarget = new THREE.WebGLRenderTarget(
bsz.x | 0,
bsz.y | 0,
{
generateMipmaps: true,
minFilter: THREE.LinearMipmapLinearFilter,
magFilter: THREE.LinearFilter,
}
);
renderer.setRenderTarget(renderTarget);
let sv = scene.background;
scene.background = null;
renderer.setClearAlpha(0);
renderer.render(scene, camera);
const width = renderTarget.width;
const height = renderTarget.height;
const size = width * height * 4; // 4 components (RGBA) per pixel
const buffer = new Uint8Array(size);
// Read the pixels
renderer.readRenderTargetPixels(
renderTarget,
0,
0,
width,
height,
buffer
);
// Create a canvas to transfer the pixel data
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
// Create ImageData and put the render target pixels into it
const imageData = new ImageData(
new Uint8ClampedArray(buffer),
width,
height
);
context.putImageData(imageData, 0, 0);
params.canvas = canvas;
scene.background = sv;
renderer.setClearAlpha(1);
renderer.setRenderTarget(null);
return renderTarget.texture;
}
},
get normalMap() {},
};
let meshUpdateStarted = false;
let updateStarted = false;
mesh.onBeforeRender = function () {
if (params.drawRange !== undefined) {
let dr = params.mesh.geometry.index
? params.mesh.geometry.index.count
: params.mesh.geometry.attributes.position.count;
params.mesh.geometry.drawRange.count = (params.drawRange * dr) | 0;
}
if (params.meshNeedsUpdate) {
if (meshUpdateStarted) return;
meshUpdateStarted = true;
setTimeout(() => {
params.meshNeedsUpdate = false;
let newmesh = generate();
params.mesh.parent.add(newmesh);
params.mesh.geometry.dispose();
params.mesh.parent.remove(params.mesh);
newmesh.position.copy(params.mesh.position);
newmesh.scale.copy(params.mesh.scale);
newmesh.rotation.copy(params.mesh.rotation);
newmesh.material.map = mesh.material.map;
newmesh.material.normalMap = mesh.material.normalMap;
newmesh.onBeforeRender = params.mesh.onBeforeRender;
params.mesh = newmesh;
meshUpdateStarted = false;
}, 10);
} else if (params.needsUpdate) {
if (updateStarted) return;
updateStarted = true;
setTimeout(() => {
params.needsUpdate = false;
params.mesh.geometry.dispose();
params.mesh.geometry = generate().geometry;
updateStarted = false;
}, 10);
}
};
resolve(params);
});
};
}