-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
604 lines (529 loc) · 20 KB
/
Copy pathmain.js
File metadata and controls
604 lines (529 loc) · 20 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { SVGLoader } from 'three/addons/loaders/SVGLoader.js';
import { STLLoader } from 'three/addons/loaders/STLLoader.js';
import { STLExporter } from 'three/addons/exporters/STLExporter.js';
import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
const BASE_STL_PATH = 'Digital_keychain_plain_any.stl';
// Configuração base (1 unidade = 1mm para impressão 3D)
const NFC_SLOT_WIDTH = 25;
const NFC_SLOT_HEIGHT = 25;
const NFC_SLOT_DEPTH = 1.5;
const BORDER_HEIGHT = 2;
const KEYRING_HOLE_RADIUS = 3;
const LOGO_AREA_RADIUS = 18;
const TAB_WIDTH = 10;
const TAB_HEIGHT = 10;
class KeychainCreator {
constructor() {
this.container = document.getElementById('canvas-container');
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, 1, 1, 1000);
this.renderer = null;
this.controls = null;
this.keychainGroup = new THREE.Group();
this.logoMesh = null;
this.logoBottomMesh = null;
this.baseStlGeometry = null;
this.useStlBase = false;
this.params = {
diameter: 50,
thickness: 5,
rounding: 100,
colorBase: 0xffffff,
colorLogo: 0x000000,
logoDepth: 0.8,
logoSvg: null,
logoBottomSvg: null,
};
this.init();
}
async init() {
this.setupRenderer();
this.setupLights();
this.setupControls();
this.bindUI();
await this.loadBaseStl();
this.buildKeychain();
this.animate();
window.addEventListener('load', () => {
this.onResize();
this.forceRender();
});
}
setupRenderer() {
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
const w = Math.max(this.container.clientWidth, 400);
const h = Math.max(this.container.clientHeight, 300);
this.renderer.setSize(w, h);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.updateRendererTheme();
window.addEventListener('themechange', () => this.updateRendererTheme());
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.shadowMap.enabled = true;
this.container.appendChild(this.renderer.domElement);
this.camera.position.set(0, 0, 120);
this.camera.lookAt(0, 0, 0);
window.addEventListener('resize', () => this.onResize());
if (typeof ResizeObserver !== 'undefined') {
new ResizeObserver(() => this.onResize()).observe(this.container);
}
requestAnimationFrame(() => this.onResize());
}
setupLights() {
const ambient = new THREE.AmbientLight(0xffffff, 0.6);
this.scene.add(ambient);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(50, 80, 60);
dirLight.castShadow = true;
this.scene.add(dirLight);
const fillLight = new THREE.DirectionalLight(0x88ccff, 0.3);
fillLight.position.set(-40, 20, 40);
this.scene.add(fillLight);
}
setupControls() {
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.05;
this.controls.minDistance = 40;
this.controls.maxDistance = 200;
}
async loadBaseStl() {
try {
const loader = new STLLoader();
const geometry = await loader.loadAsync(BASE_STL_PATH);
geometry.computeVertexNormals();
geometry.computeBoundingBox();
this.baseStlGeometry = geometry;
this.useStlBase = true;
console.log('Base STL carregada:', BASE_STL_PATH);
} catch (err) {
console.warn('Base STL não encontrada, usando geometria procedural:', err.message);
this.baseStlGeometry = null;
this.useStlBase = false;
}
}
buildKeychain() {
this.scene.remove(this.keychainGroup);
this.keychainGroup = new THREE.Group();
const radius = this.params.diameter / 2;
if (this.useStlBase && this.baseStlGeometry) {
const geom = this.baseStlGeometry.clone();
geom.computeBoundingBox();
const box = geom.boundingBox;
const center = new THREE.Vector3();
const size = new THREE.Vector3();
box.getCenter(center);
box.getSize(size);
geom.translate(-center.x, -center.y, -center.z);
const maxDim = Math.max(size.x, size.y, 0.001);
const scale = (radius * 2) / maxDim;
geom.scale(scale, scale, scale);
geom.computeBoundingBox();
const stlHeight = geom.boundingBox.max.z - geom.boundingBox.min.z;
this.params.effectiveThickness = stlHeight;
geom.translate(0, 0, -geom.boundingBox.min.z);
geom.computeVertexNormals();
const bodyMaterial = new THREE.MeshPhongMaterial({
color: this.params.colorBase,
shininess: 35,
specular: 0x333333,
});
const bodyMesh = new THREE.Mesh(geom, bodyMaterial);
bodyMesh.castShadow = true;
bodyMesh.receiveShadow = true;
this.keychainGroup.add(bodyMesh);
} else {
this.params.effectiveThickness = this.params.thickness;
const baseGeometry = this.createBaseGeometry(radius);
const slotGeometry = this.createNFCSlotRecess(radius);
const borderGeometry = this.createBorderGeometry(radius);
const tabGeometry = this.createKeyringTab(radius);
const mergedBody = BufferGeometryUtils.mergeGeometries([
baseGeometry,
slotGeometry,
borderGeometry,
...(tabGeometry ? [tabGeometry] : []),
]);
if (mergedBody) {
mergedBody.computeVertexNormals();
const bodyMaterial = new THREE.MeshPhongMaterial({
color: this.params.colorBase,
shininess: 35,
specular: 0x333333,
});
const bodyMesh = new THREE.Mesh(mergedBody, bodyMaterial);
bodyMesh.castShadow = true;
bodyMesh.receiveShadow = true;
this.keychainGroup.add(bodyMesh);
}
}
if (this.params.logoSvg) {
this.addLogoMesh(true);
}
if (this.params.logoBottomSvg) {
this.addLogoMesh(false);
}
this.scene.add(this.keychainGroup);
}
createKeychainShape(radius, clockwise = false) {
const pct = this.params.rounding / 100;
const segments = 64;
if (pct >= 0.99) {
const shape = new THREE.Shape();
shape.absarc(0, 0, radius, 0, Math.PI * 2, clockwise);
return shape;
}
const R = radius;
const n = pct <= 0.01 ? 100 : 2 + 48 * (1 - pct);
const shape = new THREE.Shape();
for (let i = 0; i < segments; i++) {
const t = (clockwise ? 1 : -1) * (2 * Math.PI * i) / segments;
const ct = Math.cos(t);
const st = Math.sin(t);
const x = R * (ct >= 0 ? 1 : -1) * Math.pow(Math.abs(ct), 2 / n);
const y = R * (st >= 0 ? 1 : -1) * Math.pow(Math.abs(st), 2 / n);
if (i === 0) shape.moveTo(x, y);
else shape.lineTo(x, y);
}
shape.closePath();
return shape;
}
createBaseGeometry(radius) {
const innerRadius = radius - BORDER_HEIGHT;
const baseDepth = this.params.thickness / 2;
const shape = this.createKeychainShape(innerRadius);
const extrudeSettings = {
depth: baseDepth,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.computeVertexNormals();
return geometry;
}
createBorderGeometry(radius) {
const outerRadius = radius;
const innerRadius = radius - BORDER_HEIGHT;
const baseDepth = this.params.thickness / 2;
const borderHeight = Math.max(0.5, this.params.thickness / 2 - NFC_SLOT_DEPTH);
const outerShape = this.createKeychainShape(outerRadius);
const innerHole = this.createKeychainShape(innerRadius, true);
const innerPoints = innerHole.getPoints(64);
const holePath = new THREE.Path(innerPoints);
holePath.closePath();
outerShape.holes.push(holePath);
const extrudeSettings = {
depth: borderHeight,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(outerShape, extrudeSettings);
geometry.translate(0, 0, baseDepth + NFC_SLOT_DEPTH);
geometry.computeVertexNormals();
return geometry;
}
createNFCSlotRecess(radius) {
const innerRadius = radius - BORDER_HEIGHT;
const baseDepth = this.params.thickness / 2;
const maxSlotDim = Math.min(NFC_SLOT_WIDTH, innerRadius * 1.6);
const nfcW = Math.min((NFC_SLOT_WIDTH - 2) / 2, maxSlotDim / 2 - 1);
const nfcH = Math.min((NFC_SLOT_HEIGHT - 2) / 2, maxSlotDim / 2 - 1);
const shape = this.createKeychainShape(innerRadius);
const nfcHole = new THREE.Path();
nfcHole.moveTo(-nfcW, -nfcH);
nfcHole.lineTo(nfcW, -nfcH);
nfcHole.lineTo(nfcW, nfcH);
nfcHole.lineTo(-nfcW, nfcH);
nfcHole.closePath();
shape.holes.push(nfcHole);
const extrudeSettings = {
depth: NFC_SLOT_DEPTH,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.translate(0, 0, baseDepth);
geometry.computeVertexNormals();
return geometry;
}
createKeyringTab(radius) {
const innerRadius = radius - BORDER_HEIGHT;
const tabW = Math.min(TAB_WIDTH, innerRadius * 0.5);
const w = tabW / 2;
const h = TAB_HEIGHT;
const r = Math.min(2, w * 0.4, (h - 6) * 0.2);
const shape = new THREE.Shape();
shape.moveTo(-w + r, 0);
shape.lineTo(w - r, 0);
shape.absarc(w - r, r, r, -Math.PI / 2, 0, false);
shape.lineTo(w, h - r);
shape.absarc(w - r, h - r, r, 0, Math.PI / 2, false);
shape.lineTo(-w + r, h);
shape.absarc(-w + r, h - r, r, Math.PI / 2, Math.PI, false);
shape.lineTo(-w, r);
shape.absarc(-w + r, r, r, Math.PI, Math.PI * 3 / 2, false);
const hole = new THREE.Path();
hole.absarc(0, h - 4, KEYRING_HOLE_RADIUS, 0, Math.PI * 2, true);
shape.holes.push(hole);
const extrudeSettings = {
depth: this.params.thickness,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.translate(0, innerRadius - 0.5, 0);
geometry.computeVertexNormals();
return geometry;
}
addLogoMesh(isTop) {
const svgString = isTop ? this.params.logoSvg : this.params.logoBottomSvg;
if (!svgString) return;
try {
const normalizedSvg = this.normalizeSvgForLoader(svgString);
const loader = new SVGLoader();
const svgData = loader.parse(normalizedSvg);
const paths = svgData.paths;
if (paths.length === 0) {
console.warn('SVG sem elementos path encontrados');
return;
}
const group = new THREE.Group();
for (const path of paths) {
const shapes = SVGLoader.createShapes(path);
for (const shape of shapes) {
const extrudeSettings = {
depth: this.params.logoDepth,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
const material = new THREE.MeshPhongMaterial({
color: this.params.colorLogo,
side: THREE.DoubleSide,
});
const mesh = new THREE.Mesh(geometry, material);
group.add(mesh);
}
}
if (group.children.length === 0) {
const strokeGeometries = this.createStrokeGeometries(paths);
for (const geom of strokeGeometries) {
const material = new THREE.MeshPhongMaterial({
color: this.params.colorLogo,
side: THREE.DoubleSide,
});
group.add(new THREE.Mesh(geom, material));
}
}
if (group.children.length === 0) {
console.warn('SVG sem formas extraíveis. Use paths com fill.');
return;
}
const box = new THREE.Box3().setFromObject(group);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, 0.001);
const scale = (LOGO_AREA_RADIUS * 2) / maxDim;
group.children.forEach((child) => {
if (child.isMesh && child.geometry) {
child.geometry.translate(-center.x, -center.y, -center.z);
}
});
group.scale.set(scale, -scale, 1);
group.position.set(0, 0, 0);
const thickness = this.params.effectiveThickness ?? this.params.thickness;
const topSurfaceZ = thickness + this.params.logoDepth / 2 + 0.1;
const bottomSurfaceZ = -this.params.logoDepth / 2 - 0.1;
if (isTop) {
if (this.logoMesh) this.keychainGroup.remove(this.logoMesh);
group.position.z = topSurfaceZ;
this.logoMesh = group;
this.keychainGroup.add(group);
} else {
if (this.logoBottomMesh) this.keychainGroup.remove(this.logoBottomMesh);
group.position.z = bottomSurfaceZ;
group.rotation.x = Math.PI;
this.logoBottomMesh = group;
this.keychainGroup.add(group);
}
} catch (err) {
console.error('Erro ao processar SVG:', err);
alert('Erro ao processar o logo SVG. Use um arquivo com elementos <path> e fill.');
}
}
normalizeSvgForLoader(svgString) {
return svgString
.replace(/fill="none"/gi, 'fill="currentColor"')
.replace(/fill='none'/gi, "fill='currentColor'");
}
createStrokeGeometries(paths) {
const geometries = [];
try {
const style = SVGLoader.getStrokeStyle(2, '#000', 'round', 'round', 4);
for (const path of paths) {
const curvePath = path.path || path;
if (!curvePath || !curvePath.getPoints) continue;
const pts = curvePath.getPoints();
if (pts.length < 2) continue;
const points = pts.map((p) => new THREE.Vector2(p.x, p.y));
const strokeGeometry = SVGLoader.pointsToStroke(points, style);
if (strokeGeometry) geometries.push(strokeGeometry);
}
} catch (_) {}
return geometries;
}
async loadSvgFromFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = reject;
reader.readAsText(file);
});
}
syncParamsFromDOM() {
this.params.diameter = parseInt(document.getElementById('size-slider').value);
this.params.thickness = Math.max(5, Math.min(10, parseFloat(document.getElementById('thickness-input').value) || 5));
this.params.rounding = 100;
this.params.colorBase = this.hexToThree(document.getElementById('color-base').value);
this.params.colorLogo = this.hexToThree(document.getElementById('color-logo').value);
this.params.logoDepth = parseFloat(document.getElementById('logo-depth').value);
}
async setLogo(file, isTop) {
try {
const svgString = await this.loadSvgFromFile(file);
if (!svgString || !svgString.trim().startsWith('<')) {
throw new Error('Arquivo inválido. Use um arquivo SVG.');
}
this.syncParamsFromDOM();
if (isTop) {
this.params.logoSvg = svgString;
} else {
this.params.logoBottomSvg = svgString;
}
this.buildKeychain();
requestAnimationFrame(() => {
this.forceRender();
requestAnimationFrame(() => this.forceRender());
});
} catch (err) {
console.error('Erro ao carregar SVG:', err);
alert('Erro ao carregar o arquivo SVG. Verifique se é um SVG válido.');
}
}
clearLogo(isTop) {
if (isTop) {
this.params.logoSvg = null;
if (this.logoMesh) {
this.keychainGroup.remove(this.logoMesh);
this.logoMesh = null;
}
} else {
this.params.logoBottomSvg = null;
if (this.logoBottomMesh) {
this.keychainGroup.remove(this.logoBottomMesh);
this.logoBottomMesh = null;
}
}
document.getElementById(isTop ? 'logo-upload' : 'logo-bottom-upload').value = '';
requestAnimationFrame(() => this.renderer.render(this.scene, this.camera));
}
hexToThree(hex) {
return parseInt(hex.replace('#', ''), 16);
}
updateFromParams() {
this.syncParamsFromDOM();
this.buildKeychain();
requestAnimationFrame(() => this.renderer.render(this.scene, this.camera));
}
bindUI() {
document.getElementById('logo-upload').addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) this.setLogo(file, true);
});
document.getElementById('logo-bottom-upload').addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) this.setLogo(file, false);
});
document.getElementById('clear-logo').addEventListener('click', () => this.clearLogo(true));
document.getElementById('clear-logo-bottom').addEventListener('click', () => this.clearLogo(false));
document.getElementById('color-base').addEventListener('input', () => this.updateFromParams());
document.getElementById('color-logo').addEventListener('input', () => this.updateFromParams());
document.getElementById('size-slider').addEventListener('input', (e) => {
document.getElementById('size-value').textContent = e.target.value;
this.updateFromParams();
});
document.getElementById('thickness-input').addEventListener('input', () => this.updateFromParams());
document.getElementById('thickness-input').addEventListener('change', () => this.updateFromParams());
document.getElementById('logo-depth').addEventListener('input', (e) => {
document.getElementById('logo-depth-value').textContent = e.target.value;
this.updateFromParams();
});
document.getElementById('export-stl').addEventListener('click', () => this.exportSTL());
}
exportSTL() {
this.syncParamsFromDOM();
const totalHeight = this.params.effectiveThickness ?? this.params.thickness;
const pauseHeight = totalHeight / 2;
const exporter = new STLExporter();
const clone = this.keychainGroup.clone();
clone.traverse((child) => {
if (child.isMesh && child.geometry) {
child.geometry = child.geometry.clone();
}
});
const box = new THREE.Box3().setFromObject(clone);
const minZ = box.min.z;
if (minZ < 0) {
clone.traverse((child) => {
if (child.isMesh && child.geometry) {
child.geometry.translate(0, 0, -minZ);
}
});
}
const stlString = exporter.parse(clone, { binary: false });
const blob = new Blob([stlString], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'chaveiro-nfc.stl';
link.click();
URL.revokeObjectURL(url);
const pauseInstructions = `INSTRUÇÕES DE IMPRESSÃO - CHAVEIRO NFC
========================================
PAUSA OBRIGATÓRIA: Configure seu slicer para pausar em exatamente ${pauseHeight.toFixed(2)} mm de altura.
• No Cura: Extensions > Post Processing > Add a script > Pause at height
- Pause at: ${pauseHeight.toFixed(2)} mm
• No PrusaSlicer: Printer settings > Custom G-code
- Ou use "Pause print" no layer correspondente a ${pauseHeight.toFixed(2)} mm
Após a pausa: insira a etiqueta NFC no slot e retome a impressão.
`;
const txtBlob = new Blob([pauseInstructions], { type: 'text/plain' });
const txtUrl = URL.createObjectURL(txtBlob);
const txtLink = document.createElement('a');
txtLink.href = txtUrl;
txtLink.download = 'chaveiro-nfc-instrucoes.txt';
txtLink.click();
URL.revokeObjectURL(txtUrl);
alert(`Exportação concluída!\n\nPause a impressão em exatamente ${pauseHeight.toFixed(2)} mm (50% da altura) para inserir a tag NFC.\n\nUm arquivo de instruções também foi baixado.`);
}
updateRendererTheme() {
if (!this.renderer) return;
const theme = document.documentElement.getAttribute('data-theme') || 'dark';
this.renderer.setClearColor(theme === 'light' ? 0xe2e8f0 : 0x0c1220, 1);
}
onResize() {
const w = Math.max(this.container.clientWidth, 400);
const h = Math.max(this.container.clientHeight, 300);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
this.renderer.setSize(w, h);
this.forceRender();
}
forceRender() {
if (this.renderer && this.scene && this.camera) {
this.renderer.render(this.scene, this.camera);
}
}
animate() {
requestAnimationFrame(() => this.animate());
this.controls.update();
this.renderer.render(this.scene, this.camera);
}
}
new KeychainCreator();