Spaces:
Running
Running
fix(metrology): multi-target raycast on lateral walls/skirt, eliminate 1D ortho cursor trap, and guarantee instant click lock
f9a6ccd Download src/engine/threeCncScene.js from FuturoEPT/simuladorcnc: direct link, hf CLI and curl.
- Browser
- Download file 58.1 kB
-
https://huggingface.co/spaces/FuturoEPT/simuladorcnc/resolve/main/src/engine/threeCncScene.js
- Command line
-
hf download hf://spaces/FuturoEPT/simuladorcnc/src/engine/threeCncScene.js
-
curl -L -o threeCncScene.js https://huggingface.co/spaces/FuturoEPT/simuladorcnc/resolve/main/src/engine/threeCncScene.js
58.1 kB
import * as THREE from 'three';
import { GRID_SIZE, STOCK_WIDTH, STOCK_HEIGHT, STOCK_DEPTH } from '../constants/cncConfig.js';
import { TOOL_CATALOG } from '../constants/tools.js';
import { calculateCuttingPhysics } from './cuttingPhysics.js';
export class ThreeCncScene {
constructor(canvasElement, containerElement) {
this.canvas = canvasElement;
this.container = containerElement;
this.depthGrid = new Float32Array(GRID_SIZE * GRID_SIZE);
this.cameraSpherical = { radius: 175, theta: 0.55, phi: 1.05 };
this.cameraTarget = { x: 40, y: 4, z: -40 };
this.showTurretHead = true;
this.isInteracting = false;
this.prevMouse = { x: 0, y: 0 };
this.init();
}
init() {
const width = this.container.clientWidth || 800;
const height = this.container.clientHeight || 520;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x0c1322);
this.scene.fog = new THREE.FogExp2(0x0c1322, 0.0012);
this.camera = new THREE.PerspectiveCamera(45, width / height, 1, 1400);
this.updateCamera();
this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true, powerPreference: "high-performance" });
this.renderer.setSize(width, height);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.shadowMap.enabled = true;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.05;
// Mapa de reflexão de estúdio industrial (PMREMGenerator): confere reflexos e brilho metálico real a todas as superfícies
this.setupEnvironment();
// Iluminação balanceada de laboratório de usinagem
this.scene.add(new THREE.AmbientLight(0xffffff, 0.40));
this.scene.add(new THREE.HemisphereLight(0xe0f2fe, 0x0f172a, 0.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 1.30);
keyLight.position.set(110, 190, 120);
keyLight.castShadow = true;
this.scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xbae6fd, 0.65);
fillLight.position.set(-100, 120, -90);
this.scene.add(fillLight);
// Materiais PBR com aspecto industrial metálico realista
this.whitePaintMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.28, metalness: 0.25 });
this.darkIronMat = new THREE.MeshStandardMaterial({ color: 0x1e293b, roughness: 0.25, metalness: 0.82 });
this.chromeSteelMat = new THREE.MeshStandardMaterial({ color: 0xf8fafc, roughness: 0.08, metalness: 0.96 });
this.calviBlueMat = new THREE.MeshStandardMaterial({ color: 0x1d4ed8, roughness: 0.22, metalness: 0.40 });
this.buildMachineStructure();
this.buildWorkpieceStock();
this.buildOriginG54();
this.buildSpindleAndTool();
this.buildParticleSystems();
this.toolpathGroup = new THREE.Group();
this.scene.add(this.toolpathGroup);
this.buildCaliperVisuals();
this.attachEventListeners();
}
setupEnvironment() {
try {
const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
pmremGenerator.compileEquirectangularShader();
const envScene = new THREE.Scene();
envScene.background = new THREE.Color(0x0a101d);
// Softbox superior de teto (luz de oficina)
const ceilingSoftbox = new THREE.Mesh(
new THREE.PlaneGeometry(140, 140),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
ceilingSoftbox.position.set(0, 70, 0);
ceilingSoftbox.rotation.x = Math.PI / 2;
envScene.add(ceilingSoftbox);
// Luz frontal-esquerda quente de preenchimento
const keySoftbox = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshBasicMaterial({ color: 0xfef9c3 })
);
keySoftbox.position.set(70, 45, 70);
keySoftbox.lookAt(0, 0, 0);
envScene.add(keySoftbox);
// Luz de contorno azul metálico (reflexos de quina viva)
const rimSoftbox = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshBasicMaterial({ color: 0x38bdf8 })
);
rimSoftbox.position.set(-70, 35, -70);
rimSoftbox.lookAt(0, 0, 0);
envScene.add(rimSoftbox);
const envTex = pmremGenerator.fromScene(envScene, 0.04).texture;
this.scene.environment = envTex;
pmremGenerator.dispose();
} catch (e) {
console.warn("PMREM environment generation skipped:", e);
}
}
updateCamera() {
if (!this.camera) return;
this.camera.position.x = this.cameraTarget.x + this.cameraSpherical.radius * Math.sin(this.cameraSpherical.phi) * Math.sin(this.cameraSpherical.theta);
this.camera.position.y = this.cameraTarget.y + this.cameraSpherical.radius * Math.cos(this.cameraSpherical.phi);
this.camera.position.z = this.cameraTarget.z + this.cameraSpherical.radius * Math.sin(this.cameraSpherical.phi) * Math.cos(this.cameraSpherical.theta);
this.camera.lookAt(this.cameraTarget.x, this.cameraTarget.y, this.cameraTarget.z);
}
setPos(mesh, x, y, z) {
mesh.position.set(x, y, z);
return mesh;
}
buildMachineStructure() {
this.frame = new THREE.Group();
// Mesa, base, joelho e coluna
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(125, 45, 145), this.whitePaintMat), 40, -64, -55));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(135, 10, 130), this.whitePaintMat), 40, -37, -42));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(195, 9, 112), this.darkIronMat), 40, -28.5, -40));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(92, 195, 70), this.whitePaintMat), 40, 18, -138));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(62, 24, 135), this.whitePaintMat), 40, 106, -95));
// Morsa de fixação com mordentes em aço temperado retificado
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(106, 9, 116), new THREE.MeshStandardMaterial({ color: 0x0369a1, roughness: 0.35, metalness: 0.60 })), 40, -20, -40));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(96, 11, 10), new THREE.MeshStandardMaterial({ color: 0xf1f5f9, roughness: 0.12, metalness: 0.94 })), 40, -17.5, -85));
this.frame.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(96, 11, 10), new THREE.MeshStandardMaterial({ color: 0xf1f5f9, roughness: 0.12, metalness: 0.94 })), 40, -17.5, 5));
this.scene.add(this.frame);
}
buildWorkpieceStock() {
const stockGeo = new THREE.BufferGeometry();
const totalPts = GRID_SIZE * GRID_SIZE;
const positions = new Float32Array(totalPts * 3);
const colors = new Float32Array(totalPts * 3);
const normals = new Float32Array(totalPts * 3);
const indices = [];
for (let j = 0; j < GRID_SIZE - 1; j++) {
for (let i = 0; i < GRID_SIZE - 1; i++) {
const a = j * GRID_SIZE + i, b = a + 1, c = (j + 1) * GRID_SIZE + i, d = c + 1;
indices.push(a, b, c, b, d, c);
}
}
for (let k = 0; k < totalPts; k++) {
normals[k * 3] = 0;
normals[k * 3 + 1] = 1;
normals[k * 3 + 2] = 0;
}
stockGeo.setIndex(indices);
stockGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
stockGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
stockGeo.setAttribute('normal', new THREE.BufferAttribute(normals, 3));
// Bloco bruto de Alumínio 6061-T6 com propriedades PBR metálicas reais
// e sombreamento de rugosidade dinâmico baseado na cor do vértice (física de corte)
const stockMat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.26,
metalness: 0.88,
side: THREE.DoubleSide
});
stockMat.onBeforeCompile = (shader) => {
shader.vertexShader = shader.vertexShader.replace(
'#include <color_vertex>',
`#include <color_vertex>
#ifdef USE_COLOR
vCustomRoughness = clamp((1.0 - vColor.r) * 2.2, 0.05, 0.88);
#endif`
);
shader.vertexShader = 'varying float vCustomRoughness;\n' + shader.vertexShader;
shader.fragmentShader = 'varying float vCustomRoughness;\n' + shader.fragmentShader;
shader.fragmentShader = shader.fragmentShader.replace(
'#include <roughnessmap_fragment>',
`#include <roughnessmap_fragment>
#ifdef USE_COLOR
roughnessFactor = vCustomRoughness;
#endif`
);
};
this.stockMesh = new THREE.Mesh(stockGeo, stockMat);
this.scene.add(this.stockMesh);
// Paredes laterais (skirt)
const skirtGeo = new THREE.BufferGeometry();
const skirtPositions = new Float32Array((GRID_SIZE * 2) * 4 * 3);
const skirtIndices = [];
for (let w = 0; w < 4; w++) {
const base = w * (GRID_SIZE * 2);
for (let i = 0; i < GRID_SIZE - 1; i++) {
skirtIndices.push(
base + i * 2, base + i * 2 + 1, base + (i + 1) * 2,
base + (i + 1) * 2, base + i * 2 + 1, base + (i + 1) * 2 + 1
);
}
}
skirtGeo.setIndex(skirtIndices);
skirtGeo.setAttribute('position', new THREE.BufferAttribute(skirtPositions, 3));
this.skirtMesh = new THREE.Mesh(
skirtGeo,
new THREE.MeshStandardMaterial({ color: 0x94a3b8, roughness: 0.30, metalness: 0.85, side: THREE.DoubleSide })
);
this.scene.add(this.skirtMesh);
// Fundo da peça
this.bottomMesh = this.setPos(
new THREE.Mesh(new THREE.BoxGeometry(STOCK_WIDTH, 1, STOCK_HEIGHT), this.skirtMesh.material),
40, -STOCK_DEPTH - 0.5, -40
);
this.scene.add(this.bottomMesh);
this.resetStockMesh();
}
buildOriginG54() {
this.originGroup = new THREE.Group();
this.originGroup.position.set(0, 0.2, 0);
this.originGroup.add(new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), 16, 0xef4444, 4, 1.8)); // X
this.originGroup.add(new THREE.ArrowHelper(new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, 0, 0), 16, 0x22c55e, 4, 1.8)); // Y
this.originGroup.add(new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 0), 16, 0x3b82f6, 4, 1.8)); // Z
this.scene.add(this.originGroup);
}
buildSpindleAndTool() {
// Cabeçote Calvi
this.turretHeadGroup = new THREE.Group();
this.turretHeadGroup.add(this.setPos(new THREE.Mesh(new THREE.CylinderGeometry(11, 9.5, 22, 24), this.calviBlueMat), 0, 55, 0));
this.turretHeadGroup.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(30, 22, 54), this.calviBlueMat), 0, 77, -12));
this.turretHeadGroup.add(this.setPos(new THREE.Mesh(new THREE.BoxGeometry(16, 6.5, 1.5), new THREE.MeshBasicMaterial({ color: 0xdc2626 })), 0, 83, 15.2));
this.turretHeadGroup.add(this.setPos(new THREE.Mesh(new THREE.CylinderGeometry(11.5, 11.5, 28, 24), this.calviBlueMat), 0, 102, -24));
this.motorPulley = new THREE.Mesh(new THREE.BoxGeometry(14, 1.5, 4), new THREE.MeshBasicMaterial({ color: 0xfacc15 }));
this.motorPulley.position.set(0, 89, 0);
this.turretHeadGroup.add(this.motorPulley);
this.scene.add(this.turretHeadGroup);
// Mangote e cone ISO30 / pinça ER32
this.quillAssembly = new THREE.Group();
this.quillAssembly.add(this.setPos(new THREE.Mesh(new THREE.CylinderGeometry(6.8, 6.8, 34, 24), this.chromeSteelMat), 0, 42, 0));
this.rotatingHolderGroup = new THREE.Group();
this.rotatingHolderGroup.add(this.setPos(new THREE.Mesh(new THREE.CylinderGeometry(7.2, 5.5, 6, 24), this.darkIronMat), 0, 21, 0));
this.holderColletMesh = new THREE.Mesh(
new THREE.CylinderGeometry(5.8, 4.6, 5.5, 16),
new THREE.MeshStandardMaterial({ color: 0x1e293b, roughness: 0.24, metalness: 0.86 })
);
this.holderColletMesh.position.set(0, 15.2, 0);
this.rotatingHolderGroup.add(this.holderColletMesh);
const spinMarker = this.setPos(new THREE.Mesh(new THREE.BoxGeometry(14.8, 2.2, 2.2), new THREE.MeshBasicMaterial({ color: 0xf59e0b })), 0, 19.5, 0);
this.rotatingHolderGroup.add(spinMarker);
this.cutterGroup = new THREE.Group();
this.rotatingHolderGroup.add(this.cutterGroup);
this.quillAssembly.add(this.rotatingHolderGroup);
this.scene.add(this.quillAssembly);
this.rebuildEndmillGeometry(8, 0xf59e0b, "ENDMILL");
}
buildParticleSystems() {
const chipGeo = new THREE.BufferGeometry();
chipGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(65 * 3), 3));
this.chipsParticles = new THREE.Points(chipGeo, new THREE.PointsMaterial({ color: 0xfde047, size: 1.7 }));
this.chipsParticles.visible = false;
this.scene.add(this.chipsParticles);
const sparkGeo = new THREE.BufferGeometry();
sparkGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(85 * 3), 3));
this.crashSparks = new THREE.Points(sparkGeo, new THREE.PointsMaterial({ color: 0xff2200, size: 3.0 }));
this.crashSparks.visible = false;
this.scene.add(this.crashSparks);
}
buildCaliperVisuals() {
this.caliperGroup = new THREE.Group();
this.caliperGroup.visible = false;
this.scene.add(this.caliperGroup);
// Retículo / Sonda de Superfície (Cursor 3D que acompanha o mouse sobre a peça)
const probeGeo = new THREE.RingGeometry(0.8, 1.4, 24);
probeGeo.rotateX(-Math.PI / 2);
this.caliperProbeMesh = new THREE.Mesh(
probeGeo,
new THREE.MeshBasicMaterial({ color: 0x38bdf8, side: THREE.DoubleSide, transparent: true, opacity: 0.85 })
);
this.caliperProbeMesh.visible = false;
this.caliperGroup.add(this.caliperProbeMesh);
// Pino agulha da sonda
const probePin = new THREE.Mesh(
new THREE.CylinderGeometry(0.2, 0.2, 3.5, 12),
new THREE.MeshBasicMaterial({ color: 0x38bdf8 })
);
probePin.position.set(0, 1.75, 0);
this.caliperProbeMesh.add(probePin);
// Marcador Ponto A (Ciano)
this.caliperMarkerA = new THREE.Group();
const ringAGeo = new THREE.RingGeometry(1.0, 1.8, 24);
ringAGeo.rotateX(-Math.PI / 2);
const ringAMesh = new THREE.Mesh(ringAGeo, new THREE.MeshBasicMaterial({ color: 0x06b6d4, side: THREE.DoubleSide }));
const pinAMesh = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 4.0, 12), new THREE.MeshBasicMaterial({ color: 0x06b6d4 }));
pinAMesh.position.set(0, 2.0, 0);
const headAMesh = new THREE.Mesh(new THREE.SphereGeometry(0.85, 16, 16), new THREE.MeshBasicMaterial({ color: 0x22d3ee }));
headAMesh.position.set(0, 4.3, 0);
this.caliperMarkerA.add(ringAMesh);
this.caliperMarkerA.add(pinAMesh);
this.caliperMarkerA.add(headAMesh);
this.caliperMarkerA.visible = false;
this.caliperGroup.add(this.caliperMarkerA);
// Marcador Ponto B (Âmbar/Laranja)
this.caliperMarkerB = new THREE.Group();
const ringBGeo = new THREE.RingGeometry(1.0, 1.8, 24);
ringBGeo.rotateX(-Math.PI / 2);
const ringBMesh = new THREE.Mesh(ringBGeo, new THREE.MeshBasicMaterial({ color: 0xf59e0b, side: THREE.DoubleSide }));
const pinBMesh = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 4.0, 12), new THREE.MeshBasicMaterial({ color: 0xf59e0b }));
pinBMesh.position.set(0, 2.0, 0);
const headBMesh = new THREE.Mesh(new THREE.SphereGeometry(0.85, 16, 16), new THREE.MeshBasicMaterial({ color: 0xfbbf24 }));
headBMesh.position.set(0, 4.3, 0);
this.caliperMarkerB.add(ringBMesh);
this.caliperMarkerB.add(pinBMesh);
this.caliperMarkerB.add(headBMesh);
this.caliperMarkerB.visible = false;
this.caliperGroup.add(this.caliperMarkerB);
// Linha de Cota / Medição
const lineGeo = new THREE.BufferGeometry();
lineGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(6), 3));
this.caliperLine = new THREE.Line(lineGeo, new THREE.LineBasicMaterial({ color: 0x38bdf8, linewidth: 2 }));
this.caliperLine.visible = false;
this.caliperGroup.add(this.caliperLine);
// Linhas auxiliares de projeção (linhas de chamada CAD)
const extGeo = new THREE.BufferGeometry();
extGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(18), 3));
this.caliperExtLines = new THREE.LineSegments(extGeo, new THREE.LineBasicMaterial({ color: 0x94a3b8, transparent: true, opacity: 0.6 }));
this.caliperExtLines.visible = false;
this.caliperGroup.add(this.caliperExtLines);
this.isCaliperActive = false;
this.snapPoints = [
{ x: 0, y: 0, z: 0 },
{ x: 80, y: 0, z: 0 },
{ x: 80, y: 80, z: 0 },
{ x: 0, y: 80, z: 0 }
];
}
setCaliperContext(pointA, mode = 'free', isOrtho = true) {
this.caliperActivePointA = pointA;
this.caliperActiveMode = mode;
this.caliperActiveOrtho = isOrtho;
}
setCaliperActive(active, onPointClick = null, onHover = null) {
this.isCaliperActive = !!active;
if (this.caliperGroup) {
this.caliperGroup.visible = !!active;
}
this.onCaliperClick = onPointClick;
this.onCaliperHover = onHover;
if (!active) {
if (this.caliperProbeMesh) this.caliperProbeMesh.visible = false;
if (this.caliperMarkerA) this.caliperMarkerA.visible = false;
if (this.caliperMarkerB) this.caliperMarkerB.visible = false;
if (this.caliperLine) this.caliperLine.visible = false;
if (this.caliperExtLines) this.caliperExtLines.visible = false;
this.caliperActivePointA = null;
}
}
updateSnapPoints(commands) {
// Vértices físicos reais da peça bruta
const pts = [
{ x: 0, y: 0, z: 0 },
{ x: STOCK_WIDTH, y: 0, z: 0 },
{ x: STOCK_WIDTH, y: STOCK_HEIGHT, z: 0 },
{ x: 0, y: STOCK_HEIGHT, z: 0 },
{ x: 0, y: 0, z: -STOCK_DEPTH },
{ x: STOCK_WIDTH, y: 0, z: -STOCK_DEPTH },
{ x: STOCK_WIDTH, y: STOCK_HEIGHT, z: -STOCK_DEPTH },
{ x: 0, y: STOCK_HEIGHT, z: -STOCK_DEPTH },
{ x: 40, y: 40, z: 0 }
];
// Bordas e arestas analíticas reais das paredes usinadas
const wallEdges = [
// Arestas perimetrais do bloco bruto
{ type: 'line', p1: { x: 0, y: 0 }, p2: { x: STOCK_WIDTH, y: 0 }, zTop: 0.0, zBot: -STOCK_DEPTH },
{ type: 'line', p1: { x: STOCK_WIDTH, y: 0 }, p2: { x: STOCK_WIDTH, y: STOCK_HEIGHT }, zTop: 0.0, zBot: -STOCK_DEPTH },
{ type: 'line', p1: { x: STOCK_WIDTH, y: STOCK_HEIGHT }, p2: { x: 0, y: STOCK_HEIGHT }, zTop: 0.0, zBot: -STOCK_DEPTH },
{ type: 'line', p1: { x: 0, y: STOCK_HEIGHT }, p2: { x: 0, y: 0 }, zTop: 0.0, zBot: -STOCK_DEPTH }
];
const R = this.toolRadius || 4.0;
if (commands && commands.length) {
for (const cmd of commands) {
if (!cmd || cmd.type === 'EMPTY' || cmd.type === 'MISC' || cmd.type === 'M06') continue;
const f = cmd.from;
const t = cmd.to;
if (!f || !t || typeof t.x !== 'number' || typeof t.y !== 'number') continue;
const zCut = Math.min(f.z || 0, t.z || 0);
// Apenas movimentos de corte no material (Z < 0) geram paredes físicas usinadas
if (zCut < -0.05) {
if (cmd.type === 'G01') {
const dx = t.x - f.x;
const dy = t.y - f.y;
const L = Math.hypot(dx, dy);
if (L > 0.05) {
const nx = -dy / L;
const ny = dx / L;
// Linhas de parede esquerda e direita (onde o material foi cortado)
const wL1 = { x: f.x + nx * R, y: f.y + ny * R };
const wL2 = { x: t.x + nx * R, y: t.y + ny * R };
const wR1 = { x: f.x - nx * R, y: f.y - ny * R };
const wR2 = { x: t.x - nx * R, y: t.y - ny * R };
wallEdges.push({ type: 'line', p1: wL1, p2: wL2, zTop: 0.0, zBot: zCut });
wallEdges.push({ type: 'line', p1: wR1, p2: wR2, zTop: 0.0, zBot: zCut });
// Pontos de quina nas arestas reais das paredes
for (const wp of [wL1, wL2, wR1, wR2]) {
pts.push({ x: Number(wp.x.toFixed(2)), y: Number(wp.y.toFixed(2)), z: 0.0 });
pts.push({ x: Number(wp.x.toFixed(2)), y: Number(wp.y.toFixed(2)), z: Number(zCut.toFixed(2)) });
}
}
} else if (cmd.type === 'G02' || cmd.type === 'G03') {
const cx = f.x + (cmd.arcI || 0);
const cy = f.y + (cmd.arcJ || 0);
const rPath = Math.hypot(cmd.arcI || 0, cmd.arcJ || 0);
if (rPath > 0.05) {
const a1 = Math.atan2(f.y - cy, f.x - cx);
const a2 = Math.atan2(t.y - cy, t.x - cx);
const isCW = (cmd.type === 'G02');
const rInner = Math.max(0.5, rPath - R);
const rOuter = rPath + R;
wallEdges.push({
type: 'arc',
cx, cy,
radius: rInner,
a1, a2,
isCW,
zTop: 0.0,
zBot: zCut
});
wallEdges.push({
type: 'arc',
cx, cy,
radius: rOuter,
a1, a2,
isCW,
zTop: 0.0,
zBot: zCut
});
// Extremidades das arestas circulares
for (const rArc of [rInner, rOuter]) {
const pStart = { x: cx + rArc * Math.cos(a1), y: cy + rArc * Math.sin(a1) };
const pEnd = { x: cx + rArc * Math.cos(a2), y: cy + rArc * Math.sin(a2) };
pts.push({ x: Number(pStart.x.toFixed(2)), y: Number(pStart.y.toFixed(2)), z: 0.0 });
pts.push({ x: Number(pStart.x.toFixed(2)), y: Number(pStart.y.toFixed(2)), z: Number(zCut.toFixed(2)) });
pts.push({ x: Number(pEnd.x.toFixed(2)), y: Number(pEnd.y.toFixed(2)), z: 0.0 });
pts.push({ x: Number(pEnd.x.toFixed(2)), y: Number(pEnd.y.toFixed(2)), z: Number(zCut.toFixed(2)) });
}
}
}
}
}
}
this.snapPoints = pts;
this.wallEdges = wallEdges;
}
setCaliperMeasurement(pA, pB, mode = 'free', isOrtho = true) {
if (!this.caliperGroup) return;
this.caliperActivePointA = pA;
this.caliperActiveMode = mode;
this.caliperActiveOrtho = isOrtho;
if (!pA) {
if (this.caliperMarkerA) this.caliperMarkerA.visible = false;
if (this.caliperMarkerB) this.caliperMarkerB.visible = false;
if (this.caliperLine) this.caliperLine.visible = false;
if (this.caliperExtLines) this.caliperExtLines.visible = false;
return;
}
// Posiciona Marcador A (Three.js: x = pA.x, y = pA.z, z = -pA.y)
const wAx = pA.x, wAy = pA.z, wAz = -pA.y;
this.caliperMarkerA.position.set(wAx, wAy, wAz);
this.caliperMarkerA.visible = true;
if (!pB) {
if (this.caliperMarkerB) this.caliperMarkerB.visible = false;
if (this.caliperLine) this.caliperLine.visible = false;
if (this.caliperExtLines) this.caliperExtLines.visible = false;
return;
}
// Posiciona Marcador B
const wBx = pB.x, wBy = pB.z, wBz = -pB.y;
this.caliperMarkerB.position.set(wBx, wBy, wBz);
this.caliperMarkerB.visible = true;
// Linha de Medição principal
let l1 = new THREE.Vector3(wAx, wAy, wAz);
let l2 = new THREE.Vector3(wBx, wBy, wBz);
const extPos = this.caliperExtLines.geometry.attributes.position;
let extCount = 0;
if (mode === 'x') {
l2 = new THREE.Vector3(wBx, wAy, wAz);
extPos.setXYZ(0, wBx, wBy, wBz);
extPos.setXYZ(1, wBx, wAy, wAz);
extCount = 2;
} else if (mode === 'y') {
l2 = new THREE.Vector3(wAx, wAy, wBz);
extPos.setXYZ(0, wBx, wBy, wBz);
extPos.setXYZ(1, wAx, wAy, wBz);
extCount = 2;
} else if (mode === 'z' || mode === 'depth') {
l2 = new THREE.Vector3(wAx, wBy, wAz);
extPos.setXYZ(0, wBx, wBy, wBz);
extPos.setXYZ(1, wAx, wBy, wAz);
extCount = 2;
} else if (isOrtho) {
const dX = Math.abs(pB.x - pA.x);
const dY = Math.abs(pB.y - pA.y);
if (dX < 2.0 && dY > 0.5) {
l2 = new THREE.Vector3(wAx, wAy, wBz);
} else if (dY < 2.0 && dX > 0.5) {
l2 = new THREE.Vector3(wBx, wAy, wAz);
}
}
const lPos = this.caliperLine.geometry.attributes.position;
const yOffset = 0.25;
lPos.setXYZ(0, l1.x, l1.y + yOffset, l1.z);
lPos.setXYZ(1, l2.x, l2.y + yOffset, l2.z);
lPos.needsUpdate = true;
this.caliperLine.visible = true;
if (extCount > 0) {
extPos.needsUpdate = true;
this.caliperExtLines.visible = true;
} else {
this.caliperExtLines.visible = false;
}
}
raycastStock(clientX, clientY, activePointA = null, activeMode = null, isOrtho = null) {
if (!this.stockMesh || !this.container || !this.camera) return null;
const rect = this.canvas.getBoundingClientRect();
const mouseX = ((clientX - rect.left) / rect.width) * 2 - 1;
const mouseY = -((clientY - rect.top) / rect.height) * 2 + 1;
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera({ x: mouseX, y: mouseY }, this.camera);
// Alvos para intersecção: superfície superior, laterais verticais (skirt) e fundo
const targets = [this.stockMesh];
if (this.skirtMesh) targets.push(this.skirtMesh);
if (this.bottomMesh) targets.push(this.bottomMesh);
for (const m of targets) {
if (m && m.geometry && !m.geometry.boundingSphere) {
m.geometry.computeBoundingSphere();
}
}
let p = null;
const intersects = raycaster.intersectObjects(targets, false);
if (intersects && intersects.length > 0) {
p = intersects[0].point;
} else {
// Fallback 1: Caixa 3D do bloco bruto (intercepta as 4 paredes laterais e topos mesmo na margem)
const stockBox = new THREE.Box3(
new THREE.Vector3(-1.0, -STOCK_DEPTH - 1.0, -STOCK_HEIGHT - 1.0),
new THREE.Vector3(STOCK_WIDTH + 1.0, 1.0, 1.0)
);
const hitBox = new THREE.Vector3();
if (raycaster.ray.intersectBox(stockBox, hitBox)) {
p = hitBox;
} else {
// Fallback 2: Plano superior Z=0 expandido
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const hitOnPlane = new THREE.Vector3();
if (raycaster.ray.intersectPlane(plane, hitOnPlane)) {
if (hitOnPlane.x >= -4 && hitOnPlane.x <= STOCK_WIDTH + 4 &&
-hitOnPlane.z >= -4 && -hitOnPlane.z <= STOCK_HEIGHT + 4) {
p = hitOnPlane;
}
}
}
}
if (p) {
let wx = p.x;
let wy = -p.z;
let wz = p.y;
const pA = activePointA !== undefined && activePointA !== null ? activePointA : this.caliperActivePointA;
const mode = activeMode || this.caliperActiveMode || 'free';
const ortho = isOrtho !== undefined && isOrtho !== null ? isOrtho : (this.caliperActiveOrtho !== false);
// Limites físicos da peça
wx = Math.max(0, Math.min(STOCK_WIDTH, wx));
wy = Math.max(0, Math.min(STOCK_HEIGHT, wy));
wz = Math.min(0, Math.max(-STOCK_DEPTH, wz));
// Fixação magnética suave nas bordas das paredes usinadas e contornos da peça (raio de 2.5mm)
if (this.wallEdges && this.wallEdges.length > 0) {
let bestDist = 2.5;
let bestEdge = null;
let bestProj = null;
for (const edge of this.wallEdges) {
if (edge.type === 'line') {
const dx = edge.p2.x - edge.p1.x;
const dy = edge.p2.y - edge.p1.y;
const lenSq = dx * dx + dy * dy;
if (lenSq < 1e-5) continue;
let t = ((wx - edge.p1.x) * dx + (wy - edge.p1.y) * dy) / lenSq;
t = Math.max(0, Math.min(1, t));
const qx = edge.p1.x + t * dx;
const qy = edge.p1.y + t * dy;
const d = Math.hypot(wx - qx, wy - qy);
if (d < bestDist) {
bestDist = d;
bestEdge = edge;
bestProj = { x: qx, y: qy };
}
} else if (edge.type === 'arc') {
const dx = wx - edge.cx;
const dy = wy - edge.cy;
const distCenter = Math.hypot(dx, dy);
if (distCenter > 1e-4) {
const ang = Math.atan2(dy, dx);
let inArc = false;
const twoPi = Math.PI * 2;
if (edge.isCW) {
const da = ((edge.a1 - ang) % twoPi + twoPi) % twoPi;
const span = ((edge.a1 - edge.a2) % twoPi + twoPi) % twoPi;
inArc = (span < 1e-4) || (da <= span + 0.15);
} else {
const da = ((ang - edge.a1) % twoPi + twoPi) % twoPi;
const span = ((edge.a2 - edge.a1) % twoPi + twoPi) % twoPi;
inArc = (span < 1e-4) || (da <= span + 0.15);
}
if (inArc) {
const d = Math.abs(distCenter - edge.radius);
if (d < bestDist) {
bestDist = d;
bestEdge = edge;
bestProj = {
x: edge.cx + edge.radius * Math.cos(ang),
y: edge.cy + edge.radius * Math.sin(ang)
};
}
}
}
}
}
if (bestProj && bestEdge) {
wx = bestProj.x;
wy = bestProj.y;
if (wz > -1.5) {
wz = bestEdge.zTop !== undefined ? bestEdge.zTop : 0.0;
} else {
wz = bestEdge.zBot !== undefined ? bestEdge.zBot : -3.0;
}
}
}
// Snap magnético em quinas e vértices (raio de 1.5mm)
if (this.snapPoints && this.snapPoints.length > 0) {
for (const sp of this.snapPoints) {
if (Math.hypot(wx - sp.x, wy - sp.y) < 1.5) {
wx = sp.x;
wy = sp.y;
if (typeof sp.z === 'number' && Math.abs(wz - sp.z) < 1.5) {
wz = sp.z;
}
break;
}
}
}
// Snap suave de alinhamento ortogonal 90° (APENAS se o cursor estiver muito próximo da linha reta < 2.0mm)
// NUNCA bloqueia a liberdade de movimento do cursor para outros lados da peça
if (pA && ortho) {
if (Math.abs(wx - pA.x) < 2.0) {
wx = pA.x; // Suave trava em linha reta vertical
}
if (Math.abs(wy - pA.y) < 2.0) {
wy = pA.y; // Suave trava em linha reta horizontal
}
}
// Normalizações e encaixe de planos Z
if (Math.abs(wz - (-3.00)) < 0.35) wz = -3.00;
else if (Math.abs(wz) < 0.35) wz = 0.00;
if (Math.abs(wx) < 0.5) wx = 0.0;
if (Math.abs(wx - STOCK_WIDTH) < 0.5) wx = STOCK_WIDTH;
if (Math.abs(wy) < 0.5) wy = 0.0;
if (Math.abs(wy - STOCK_HEIGHT) < 0.5) wy = STOCK_HEIGHT;
return {
worldPoint: new THREE.Vector3(wx, wz, -wy),
workpiecePoint: {
x: Number(wx.toFixed(2)),
y: Number(wy.toFixed(2)),
z: Number(wz.toFixed(2))
}
};
}
return null;
}
rebuildEndmillGeometry(dia, coatingHex = 0xf59e0b, toolType = "ENDMILL") {
if (!this.cutterGroup) return;
while (this.cutterGroup.children.length > 0) {
this.cutterGroup.remove(this.cutterGroup.children[0]);
}
const r = Math.max(1, dia / 2);
this.toolRadius = r;
const shankMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, metalness: 0.96, roughness: 0.10 });
const coatMat = new THREE.MeshStandardMaterial({ color: coatingHex, metalness: 0.92, roughness: 0.16 });
const darkFluteMat = new THREE.MeshStandardMaterial({ color: 0x0f172a, metalness: 0.82, roughness: 0.28 });
const shank = new THREE.Mesh(new THREE.CylinderGeometry(Math.max(3, r * 0.95), r, 8, 24), shankMat);
shank.position.set(0, 14, 0);
this.cutterGroup.add(shank);
if (toolType === "DRILL") {
const tipHeight = Math.max(1.8, r * 1.15);
const coneGeo = new THREE.ConeGeometry(r, tipHeight, 24);
coneGeo.rotateX(Math.PI);
const coneMesh = new THREE.Mesh(coneGeo, coatMat);
coneMesh.position.set(0, tipHeight / 2, 0);
this.cutterGroup.add(coneMesh);
const bodyH = 12 - tipHeight;
const drillCore = new THREE.Mesh(new THREE.CylinderGeometry(r * 0.55, r * 0.55, bodyH, 20), darkFluteMat);
drillCore.position.set(0, tipHeight + bodyH / 2, 0);
this.cutterGroup.add(drillCore);
for (let s = 0; s < 12; s++) {
const bladeGroup = new THREE.Group();
bladeGroup.position.set(0, tipHeight + (s + 0.5) * (bodyH / 12), 0);
bladeGroup.rotation.y = (s / 12) * (Math.PI * 1.6);
bladeGroup.add(new THREE.Mesh(new THREE.BoxGeometry(dia, (bodyH / 12) * 1.15, r * 0.42), coatMat));
this.cutterGroup.add(bladeGroup);
}
} else {
const core = new THREE.Mesh(new THREE.CylinderGeometry(r * 0.68, r * 0.68, 12, 20), coatMat);
core.position.set(0, 6, 0);
this.cutterGroup.add(core);
const numSlices = 10, fluteHeight = 12, sliceH = fluteHeight / numSlices;
for (let s = 0; s < numSlices; s++) {
const bladeGroup = new THREE.Group();
bladeGroup.position.set(0, (s + 0.5) * sliceH, 0);
bladeGroup.rotation.y = (s / numSlices) * (Math.PI * 0.85);
bladeGroup.add(new THREE.Mesh(new THREE.BoxGeometry(dia, sliceH * 1.04, r * 0.48), coatMat));
bladeGroup.add(new THREE.Mesh(new THREE.BoxGeometry(r * 0.48, sliceH * 1.04, dia), coatMat));
bladeGroup.add(new THREE.Mesh(new THREE.CylinderGeometry(r * 0.97, r * 0.97, sliceH * 0.35, 16), darkFluteMat));
this.cutterGroup.add(bladeGroup);
}
// Centro morto não cortante
const deadCenter = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.38, r * 0.38, 0.25, 16),
new THREE.MeshBasicMaterial({ color: 0x0f172a })
);
deadCenter.position.set(0, 0.1, 0);
this.cutterGroup.add(deadCenter);
}
}
setToolWorldPos(x, y, z) {
if (this.quillAssembly) this.quillAssembly.position.set(x, z, -y);
if (this.turretHeadGroup) this.turretHeadGroup.position.set(x, 0, -y);
}
// ============================================================================
// MOTOR DE REMOÇÃO DE MATERIAL (Z-map / dexel vertical, padrão de simuladores 3 eixos)
//
// Por que havia "dentes" nas curvas: uma parede vertical (degrau de 3 mm) amostrada
// numa grade regular é um sinal com frequência infinita -> aliasing. Em paredes
// alinhadas aos eixos X/Y o erro não aparece; em arcos/diagonais a posição do degrau
// "pula" de célula em célula e vira serrilhado.
//
// Solução (anti-aliasing geométrico + triangulação adaptativa):
// 1. Perfil de parede limitado em banda: transição smoothstep com largura de
// 3 células, CENTRADA no raio exato da ferramenta (contorno sem desvio).
// 2. Distância analítica exata ao percurso (cápsula para G01, anel para G02/G03).
// 3. Triangulação adaptativa: cada quad escolhe a diagonal que acompanha a parede
// (menor diferença de altura), eliminando "aletas" em paredes diagonais.
// 4. Normais por Sobel 3x3 sobre a superfície já limitada em banda.
// 5. Upload parcial à GPU (addUpdateRange) só das linhas alteradas.
// ============================================================================
_initStockRefs() {
if (!this.stockMesh) return;
const geo = this.stockMesh.geometry;
this.cellDx = STOCK_WIDTH / (GRID_SIZE - 1);
this.cellDy = STOCK_HEIGHT / (GRID_SIZE - 1);
this.cellArea = this.cellDx * this.cellDy;
// Largura da banda de parede (1.5x célula = 0.30 mm): garante interpolação C1 suave e contínua
// sem degraus/serrilhados em qualquer direção (reta, diagonal ou curva) e com parede íngreme (~85°-88°)
this.wallBand = this.cellDx * 1.5;
this.stockPos = geo.attributes.position.array;
this.stockCol = geo.attributes.color.array;
this.stockNorm = geo.attributes.normal.array;
this.stockIdx = geo.index ? geo.index.array : null;
}
resetStockMesh() {
this.depthGrid.fill(0.0);
this.totalCutMm3 = 0;
const dx = STOCK_WIDTH / (GRID_SIZE - 1);
const dy = STOCK_HEIGHT / (GRID_SIZE - 1);
if (this.stockMesh) {
this._initStockRefs();
this.stockMesh.frustumCulled = false;
const geo = this.stockMesh.geometry;
const pos = geo.attributes.position;
const col = geo.attributes.color;
const norm = geo.attributes.normal;
for (let j = 0; j < GRID_SIZE; j++) {
for (let i = 0; i < GRID_SIZE; i++) {
const idx = j * GRID_SIZE + i;
pos.setXYZ(idx, i * dx, 0.0, -j * dy);
col.setXYZ(idx, 0.78, 0.82, 0.88);
if (norm) norm.setXYZ(idx, 0, 1, 0);
}
}
this._retriangulate(0, GRID_SIZE - 2, 0, GRID_SIZE - 2);
for (const attr of [pos, col, norm, geo.index]) {
if (!attr) continue;
if (attr.clearUpdateRanges) attr.clearUpdateRanges();
attr.needsUpdate = true;
}
}
if (this.skirtMesh) {
const sPos = this.skirtMesh.geometry.attributes.position;
let vIdx = 0;
for (let i = 0; i < GRID_SIZE; i++) { sPos.setXYZ(vIdx++, i * dx, 0, 0); sPos.setXYZ(vIdx++, i * dx, -STOCK_DEPTH, 0); }
for (let i = 0; i < GRID_SIZE; i++) { sPos.setXYZ(vIdx++, i * dx, 0, -STOCK_HEIGHT); sPos.setXYZ(vIdx++, i * dx, -STOCK_DEPTH, -STOCK_HEIGHT); }
for (let j = 0; j < GRID_SIZE; j++) { sPos.setY(vIdx++, 0, 0, -j * dy); sPos.setXYZ(vIdx++, 0, -STOCK_DEPTH, -j * dy); }
for (let j = 0; j < GRID_SIZE; j++) { sPos.setXYZ(vIdx++, STOCK_WIDTH, 0, -j * dy); sPos.setXYZ(vIdx++, STOCK_WIDTH, -STOCK_DEPTH, -j * dy); }
sPos.needsUpdate = true;
}
if (this.holderColletMesh) this.holderColletMesh.material.color.setHex(0x0f172a);
if (this.crashSparks) this.crashSparks.visible = false;
}
// Triangulação adaptativa: para cada quad escolhe a diagonal com menor salto de altura.
_retriangulate(qi0, qi1, qj0, qj1) {
const idxArr = this.stockIdx;
if (!idxArr) return;
const G = GRID_SIZE;
const h = this.depthGrid;
for (let j = qj0; j <= qj1; j++) {
for (let i = qi0; i <= qi1; i++) {
const a = j * G + i, b = a + 1, c = a + G, d = c + 1;
const o = (j * (G - 1) + i) * 6;
if (Math.abs(h[a] - h[d]) < Math.abs(h[b] - h[c]) - 1e-6) {
// diagonal a–d
idxArr[o] = a; idxArr[o + 1] = b; idxArr[o + 2] = d;
idxArr[o + 3] = a; idxArr[o + 4] = d; idxArr[o + 5] = c;
} else {
// diagonal b–c (padrão)
idxArr[o] = a; idxArr[o + 1] = b; idxArr[o + 2] = c;
idxArr[o + 3] = b; idxArr[o + 4] = d; idxArr[o + 5] = c;
}
}
}
}
// Normais contínuas C1 via filtro Sobel 3x3 no grid Z-map regular.
// Sem limiares artificiais ou descontinuidades discretas, garantindo sombreamento
// 100% liso, contínuo e sem dentes de serra ou espinhos em curvas e diagonais.
recomputeStockNormals(minI = 0, maxI = GRID_SIZE - 1, minJ = 0, maxJ = GRID_SIZE - 1) {
const n = this.stockNorm;
if (!n) return;
const G = GRID_SIZE;
const h = this.depthGrid;
const dx = this.cellDx, dy = this.cellDy;
const i0 = Math.max(0, minI), i1 = Math.min(G - 1, maxI);
const j0 = Math.max(0, minJ), j1 = Math.min(G - 1, maxJ);
for (let j = j0; j <= j1; j++) {
const jm = Math.max(0, j - 1), jp = Math.min(G - 1, j + 1);
const rm = jm * G, r0 = j * G, rp = jp * G;
for (let i = i0; i <= i1; i++) {
const im = Math.max(0, i - 1), ip = Math.min(G - 1, i + 1);
const z00 = h[rm + im], z10 = h[rm + i], z20 = h[rm + ip];
const z01 = h[r0 + im], z21 = h[r0 + ip];
const z02 = h[rp + im], z12 = h[rp + i], z22 = h[rp + ip];
const gx = ((z20 + 2 * z21 + z22) - (z00 + 2 * z01 + z02)) / (4 * Math.max(1, ip - im) * dx);
const gj = ((z02 + 2 * z12 + z22) - (z00 + 2 * z10 + z20)) / (4 * Math.max(1, jp - jm) * dy);
// Mundo Three.js: x = i*dx, y = h, z = -j*dy -> n = (-dh/dx, 1, dh/dj_dy)
const nx = -gx, ny = 1.0, nz = gj;
const inv = 1.0 / Math.hypot(nx, ny, nz);
const p = (r0 + i) * 3;
n[p] = nx * inv;
n[p + 1] = ny * inv;
n[p + 2] = nz * inv;
}
}
}
// Aplica o perfil suave calibrado de corte ao vértice. d = distância ao eixo da ferramenta.
// Mantém o piso de corte perfeitamente plano e uniforme, sem perturbações geométricas espúrias.
_applyProfile(idx, d, rIn, band, depth, cutRGB) {
let target = depth;
let s = 0;
if (d > rIn) {
const u = (d - rIn) / band;
if (u >= 1) return false;
s = u * u * (3 - 2 * u);
target = depth * (1 - s);
}
const cur = this.depthGrid[idx];
if (target >= cur - 1e-4) return false;
this.totalCutMm3 += (cur - target) * this.cellArea;
this.depthGrid[idx] = target;
const p = idx * 3;
this.stockPos[p + 1] = target;
const k = 1 - s;
this.stockCol[p] = 0.78 + (cutRGB[0] - 0.78) * k;
this.stockCol[p + 1] = 0.82 + (cutRGB[1] - 0.82) * k;
this.stockCol[p + 2] = 0.88 + (cutRGB[2] - 0.88) * k;
return true;
}
// Normais, triangulação, skirt e upload parcial da região modificada.
_commitRegion(minI, maxI, minJ, maxJ) {
const G = GRID_SIZE;
const geo = this.stockMesh.geometry;
this.recomputeStockNormals(minI - 1, maxI + 1, minJ - 1, maxJ + 1);
const qi0 = Math.max(0, minI - 1), qi1 = Math.min(G - 2, maxI);
const qj0 = Math.max(0, minJ - 1), qj1 = Math.min(G - 2, maxJ);
this._retriangulate(qi0, qi1, qj0, qj1);
const rj0 = Math.max(0, minJ - 1), rj1 = Math.min(G - 1, maxJ + 1);
const vStart = rj0 * G * 3, vCount = (rj1 - rj0 + 1) * G * 3;
for (const attr of [geo.attributes.position, geo.attributes.normal, geo.attributes.color]) {
if (attr.addUpdateRange) attr.addUpdateRange(vStart, vCount);
attr.needsUpdate = true;
}
if (geo.index) {
if (geo.index.addUpdateRange) geo.index.addUpdateRange(qj0 * (G - 1) * 6, (qj1 - qj0 + 1) * (G - 1) * 6);
geo.index.needsUpdate = true;
}
if (this.skirtMesh && (minI <= 0 || minJ <= 0 || maxI >= G - 1 || maxJ >= G - 1)) {
const sPos = this.skirtMesh.geometry.attributes.position;
let vIdx = 0;
for (let i = 0; i < G; i++) { sPos.setY(vIdx, this.depthGrid[i]); vIdx += 2; }
for (let i = 0; i < G; i++) { sPos.setY(vIdx, this.depthGrid[(G - 1) * G + i]); vIdx += 2; }
for (let j = 0; j < G; j++) { sPos.setY(vIdx, this.depthGrid[j * G]); vIdx += 2; }
for (let j = 0; j < G; j++) { sPos.setY(vIdx, this.depthGrid[j * G + (G - 1)]); vIdx += 2; }
sPos.needsUpdate = true;
}
}
// G00/G01: volume varrido = cápsula analítica suave e íngreme (~87.5°).
carveSegment(x1, y1, z1, x2, y2, z2, radius, cuttingInfo = null) {
if ((z1 >= 0 && z2 >= 0) || !this.stockMesh) return 0;
const G = GRID_SIZE;
const dx = this.cellDx, dy = this.cellDy;
const band = this.wallBand;
const rIn = radius - band * 0.5;
const rOut = radius + band * 0.5;
const rOutSq = rOut * rOut;
const minI = Math.max(0, Math.floor((Math.min(x1, x2) - rOut) / dx));
const maxI = Math.min(G - 1, Math.ceil((Math.max(x1, x2) + rOut) / dx));
const minJ = Math.max(0, Math.floor((Math.min(y1, y2) - rOut) / dy));
const maxJ = Math.min(G - 1, Math.ceil((Math.max(y1, y2) + rOut) / dy));
if (minI > maxI || minJ > maxJ) return this.totalCutMm3 / 1000;
const sx = x2 - x1, sy = y2 - y1;
const segLenSq = sx * sx + sy * sy;
const cutRGB = (cuttingInfo && cuttingInfo.colorRGB) ? cuttingInfo.colorRGB : [0.88, 0.92, 0.96];
let modified = false;
for (let j = minJ; j <= maxJ; j++) {
const vy = j * dy;
for (let i = minI; i <= maxI; i++) {
const vx = i * dx;
let t = 0;
if (segLenSq > 1e-9) {
t = ((vx - x1) * sx + (vy - y1) * sy) / segLenSq;
t = t < 0 ? 0 : (t > 1 ? 1 : t);
}
const ex = vx - (x1 + t * sx);
const ey = vy - (y1 + t * sy);
const distSq = ex * ex + ey * ey;
if (distSq > rOutSq) continue;
const zc = z1 + t * (z2 - z1);
if (zc >= 0) continue;
const depth = zc < -STOCK_DEPTH ? -STOCK_DEPTH : zc;
if (this._applyProfile(j * G + i, Math.sqrt(distSq), rIn, band, depth, cutRGB)) modified = true;
}
}
if (modified) this._commitRegion(minI, maxI, minJ, maxJ);
return this.totalCutMm3 / 1000; // cm³
}
carveStockAt(toolX, toolY, toolZ, radius, cuttingInfo = null) {
return this.carveSegment(toolX, toolY, toolZ, toolX, toolY, toolZ, radius, cuttingInfo);
}
// G02/G03: volume varrido = anel circular com continuidade C1 sem código de barras.
carveArc(cx, cy, rArc, a1, a2, isCW, z1, z2, radius, cuttingInfo = null) {
if ((z1 >= 0 && z2 >= 0) || !this.stockMesh) return 0;
if (rArc <= 0.001) {
return this.carveSegment(cx, cy, z1, cx, cy, z2, radius, cuttingInfo);
}
const G = GRID_SIZE;
const TWO_PI = Math.PI * 2;
const dx = this.cellDx, dy = this.cellDy;
const band = this.wallBand;
const rIn = radius - band * 0.5;
const rOut = radius + band * 0.5;
const rExt = rArc + rOut;
let sweep = isCW ? (a1 - a2) : (a2 - a1);
while (sweep < 0) sweep += TWO_PI;
while (sweep > TWO_PI) sweep -= TWO_PI;
if (sweep < 1e-9) {
const px = cx + rArc * Math.cos(a1), py = cy + rArc * Math.sin(a1);
return this.carveSegment(px, py, z1, px, py, z2, radius, cuttingInfo);
}
const p1x = cx + rArc * Math.cos(a1), p1y = cy + rArc * Math.sin(a1);
const p2x = cx + rArc * Math.cos(a2), p2y = cy + rArc * Math.sin(a2);
let minX = Math.min(p1x, p2x) - rOut, maxX = Math.max(p1x, p2x) + rOut;
let minY = Math.min(p1y, p2y) - rOut, maxY = Math.max(p1y, p2y) + rOut;
// Expande a caixa pelos pontos cardeais atravessados pelo arco
const cardinals = [0, Math.PI / 2, Math.PI, -Math.PI / 2];
for (let c = 0; c < 4; c++) {
let dd = isCW ? (a1 - cardinals[c]) : (cardinals[c] - a1);
dd = ((dd % TWO_PI) + TWO_PI) % TWO_PI;
if (dd <= sweep) {
if (c === 0) maxX = Math.max(maxX, cx + rExt);
if (c === 1) maxY = Math.max(maxY, cy + rExt);
if (c === 2) minX = Math.min(minX, cx - rExt);
if (c === 3) minY = Math.min(minY, cy - rExt);
}
}
const minI = Math.max(0, Math.floor(minX / dx));
const maxI = Math.min(G - 1, Math.ceil(maxX / dx));
const minJ = Math.max(0, Math.floor(minY / dy));
const maxJ = Math.min(G - 1, Math.ceil(maxY / dy));
if (minI > maxI || minJ > maxJ) return this.totalCutMm3 / 1000;
const cutRGB = (cuttingInfo && cuttingInfo.colorRGB) ? cuttingInfo.colorRGB : [0.88, 0.92, 0.96];
let modified = false;
for (let j = minJ; j <= maxJ; j++) {
const vy = j * dy;
const vdy = vy - cy;
for (let i = minI; i <= maxI; i++) {
const vx = i * dx;
const vdx = vx - cx;
let delta = isCW ? (a1 - Math.atan2(vdy, vdx)) : (Math.atan2(vdy, vdx) - a1);
delta = ((delta % TWO_PI) + TWO_PI) % TWO_PI;
let dist, tVal;
if (delta <= sweep) {
// Dentro do setor: distância radial exata ao arco
dist = Math.abs(Math.sqrt(vdx * vdx + vdy * vdy) - rArc);
tVal = delta / sweep;
} else {
// Fora do setor: distância ao extremo mais próximo
const d1 = Math.hypot(vx - p1x, vy - p1y);
const d2 = Math.hypot(vx - p2x, vy - p2y);
if (d1 <= d2) { dist = d1; tVal = 0; } else { dist = d2; tVal = 1; }
}
if (dist > rOut) continue;
const zc = z1 + tVal * (z2 - z1);
if (zc >= 0) continue;
const depth = zc < -STOCK_DEPTH ? -STOCK_DEPTH : zc;
if (this._applyProfile(j * G + i, dist, rIn, band, depth, cutRGB)) modified = true;
}
}
if (modified) this._commitRegion(minI, maxI, minJ, maxJ);
return this.totalCutMm3 / 1000;
}
getStockSurfaceZAt = (x, y) => {
const dx = STOCK_WIDTH / (GRID_SIZE - 1);
const dy = STOCK_HEIGHT / (GRID_SIZE - 1);
const i = Math.round(x / dx);
const j = Math.round(y / dy);
if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) return -STOCK_DEPTH;
return this.depthGrid[j * GRID_SIZE + i];
};
getHighestStockSurfaceInRadius = (tx, ty, rad) => {
const dx = STOCK_WIDTH / (GRID_SIZE - 1), dy = STOCK_HEIGHT / (GRID_SIZE - 1);
const checkRad = Math.max(0.6, rad * 0.72);
const minI = Math.max(0, Math.floor((tx - checkRad) / dx));
const maxI = Math.min(GRID_SIZE - 1, Math.ceil((tx + checkRad) / dx));
const minJ = Math.max(0, Math.floor((ty - checkRad) / dy));
const maxJ = Math.min(GRID_SIZE - 1, Math.ceil((ty + checkRad) / dy));
let highestZ = -STOCK_DEPTH;
const rSq = checkRad * checkRad;
for (let j = minJ; j <= maxJ; j++) {
for (let i = minI; i <= maxI; i++) {
const vx = i * dx, vy = j * dy;
if ((vx - tx) * (vx - tx) + (vy - ty) * (vy - ty) <= rSq) {
const zVal = this.depthGrid[j * GRID_SIZE + i];
if (zVal > highestZ) highestZ = zVal;
}
}
}
return highestZ;
};
rebuildToolpathVisual(commands, currentStepIndex) {
if (!this.toolpathGroup) return;
this.updateSnapPoints(commands);
while (this.toolpathGroup.children.length > 0) {
this.toolpathGroup.remove(this.toolpathGroup.children[0]);
}
commands.forEach((cmd, idx) => {
if (cmd.type === 'EMPTY' || cmd.type === 'MISC' || cmd.type === 'M06') return;
const pts = [];
if (cmd.type === 'G02' || cmd.type === 'G03') {
const cx = cmd.from.x + cmd.arcI, cy = cmd.from.y + cmd.arcJ;
const r = Math.hypot(cmd.arcI, cmd.arcJ);
const a1 = Math.atan2(cmd.from.y - cy, cmd.from.x - cx);
let a2 = Math.atan2(cmd.to.y - cy, cmd.to.x - cx);
if (cmd.type === 'G02' && a2 >= a1) a2 -= Math.PI * 2;
if (cmd.type === 'G03' && a2 <= a1) a2 += Math.PI * 2;
for (let s = 0; s <= 36; s++) {
const t = s / 36;
const a = a1 + (a2 - a1) * t;
const cz = cmd.from.z + (cmd.to.z - cmd.from.z) * t;
pts.push(new THREE.Vector3(cx + r * Math.cos(a), cz, -(cy + r * Math.sin(a))));
}
} else {
pts.push(new THREE.Vector3(cmd.from.x, cmd.from.z, -cmd.from.y));
pts.push(new THREE.Vector3(cmd.to.x, cmd.to.z, -cmd.to.y));
}
if (pts.length >= 2) {
const geo = new THREE.BufferGeometry().setFromPoints(pts);
let color = cmd.type === 'G00' ? 0xfacc15 : cmd.isCutting ? 0xef4444 : 0x10b981;
const mat = new THREE.LineBasicMaterial({
color,
opacity: idx < currentStepIndex ? 0.35 : 0.92,
transparent: true
});
this.toolpathGroup.add(new THREE.Line(geo, mat));
}
});
}
setViewPreset(viewKey) {
if (viewKey === 'iso') {
this.cameraSpherical.radius = 175;
this.cameraSpherical.theta = 0.55;
this.cameraSpherical.phi = 1.05;
this.cameraTarget.x = 40;
this.cameraTarget.y = 4;
this.cameraTarget.z = -40;
this.showTurretHead = true;
} else if (viewKey === 'closeup') {
this.cameraSpherical.radius = 95;
this.cameraSpherical.theta = 0.42;
this.cameraSpherical.phi = 1.12;
this.cameraTarget.x = 40;
this.cameraTarget.y = -2;
this.cameraTarget.z = -40;
this.showTurretHead = true;
} else if (viewKey === 'top') {
this.cameraSpherical.radius = 160;
this.cameraSpherical.theta = 0;
this.cameraSpherical.phi = 0.22; // Inclinação ~12.6° em relação ao zênite para visão CAD de topo perfeita
this.cameraTarget.x = 40;
this.cameraTarget.y = -2;
this.cameraTarget.z = -40;
this.showTurretHead = false;
} else if (viewKey === 'front') {
this.cameraSpherical.radius = 155;
this.cameraSpherical.theta = 0;
this.cameraSpherical.phi = Math.PI / 2.12;
this.cameraTarget.x = 40;
this.cameraTarget.y = 2;
this.cameraTarget.z = -40;
this.showTurretHead = true;
} else if (viewKey === 'side') {
this.cameraSpherical.radius = 155;
this.cameraSpherical.theta = -Math.PI / 2;
this.cameraSpherical.phi = Math.PI / 2.12;
this.cameraTarget.x = 40;
this.cameraTarget.y = 2;
this.cameraTarget.z = -40;
this.showTurretHead = true;
}
if (this.turretHeadGroup) this.turretHeadGroup.visible = this.showTurretHead;
if (this.quillAssembly) this.quillAssembly.visible = (viewKey !== 'top' && this.showTurretHead);
this.updateCamera();
}
toggleHeadVisibility() {
this.showTurretHead = !this.showTurretHead;
if (this.turretHeadGroup) this.turretHeadGroup.visible = this.showTurretHead;
if (this.quillAssembly) this.quillAssembly.visible = this.showTurretHead;
return this.showTurretHead;
}
showSparks(x, y, z) {
if (this.crashSparks) {
const sPos = this.crashSparks.geometry.attributes.position;
for (let i = 0; i < sPos.count; i++) {
sPos.setXYZ(i, x + (Math.random() - 0.5) * 16, Math.max(-24, z) + Math.random() * 12, -y + (Math.random() - 0.5) * 16);
}
sPos.needsUpdate = true;
this.crashSparks.visible = true;
}
}
showChips(x, y, z) {
if (this.chipsParticles) {
const pAttr = this.chipsParticles.geometry.attributes.position;
for (let i = 0; i < pAttr.count; i++) {
pAttr.setXYZ(i, x + (Math.random() - 0.5) * 10, z + Math.random() * 7, -y + (Math.random() - 0.5) * 10);
}
pAttr.needsUpdate = true;
this.chipsParticles.visible = true;
}
}
hideChips() {
if (this.chipsParticles) this.chipsParticles.visible = false;
}
render() {
if (this.renderer && this.scene && this.camera) {
this.renderer.render(this.scene, this.camera);
}
}
handleResize = () => {
if (!this.container || !this.renderer || !this.camera) return;
const w = this.container.clientWidth || 800;
const h = this.container.clientHeight || 520;
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
this.renderer.setSize(w, h);
};
attachEventListeners() {
this.onMouseDown = (e) => {
this.isInteracting = true;
this.prevMouse = { x: e.clientX, y: e.clientY };
this.mouseDownPos = { x: e.clientX, y: e.clientY };
this.mouseDownTime = performance.now();
this.hasDragged = false;
};
this.onMouseMove = (e) => {
const dx = e.clientX - this.prevMouse.x;
const dy = e.clientY - this.prevMouse.y;
this.prevMouse = { x: e.clientX, y: e.clientY };
const moveDist = this.mouseDownPos ? Math.hypot(e.clientX - this.mouseDownPos.x, e.clientY - this.mouseDownPos.y) : 0;
if (moveDist > 14) {
this.hasDragged = true;
}
if (this.isInteracting && (e.buttons === 1 || e.buttons === 2)) {
// No modo paquímetro com botão esquerdo, só gira a câmera se o usuário arrastar intencionalmente (> 14px)
const shouldRotateCamera = !this.isCaliperActive || e.buttons === 2 || moveDist > 14;
if (shouldRotateCamera) {
if (e.buttons === 1) {
this.cameraSpherical.theta -= dx * 0.008;
this.cameraSpherical.phi = Math.max(0.08, Math.min(Math.PI / 2 - 0.03, this.cameraSpherical.phi - dy * 0.008));
this.updateCamera();
} else if (e.buttons === 2) {
this.cameraTarget.x -= dx * 0.15;
this.cameraTarget.z += dy * 0.15;
this.updateCamera();
}
}
} else if (this.isCaliperActive && !this.isInteracting) {
// Hover sobre a peça no modo paquímetro com snap magnético
const hit = this.raycastStock(e.clientX, e.clientY);
if (hit) {
this.lastHoverHit = hit;
if (this.caliperProbeMesh) {
this.caliperProbeMesh.position.copy(hit.worldPoint);
this.caliperProbeMesh.visible = true;
}
if (this.onCaliperHover) {
this.onCaliperHover(hit.workpiecePoint);
}
}
// Se hit for null (mouse fora do stock ou sobre UI), preserva o último ponto para não zerar a leitura no HUD
}
};
this.onMouseUp = (e) => {
const moveDist = this.mouseDownPos ? Math.hypot(e.clientX - this.mouseDownPos.x, e.clientY - this.mouseDownPos.y) : 0;
// Clique legítimo no paquímetro: botão esquerdo solto com deslocamento menor que 16px (sem restrição arbitrária de tempo)
const isCaliperClick = this.isCaliperActive && e.button === 0 && moveDist < 16;
if (isCaliperClick) {
const hit = this.raycastStock(e.clientX, e.clientY) || this.lastHoverHit;
if (hit && this.onCaliperClick) {
this.onCaliperClick(hit.workpiecePoint);
}
}
this.isInteracting = false;
this.mouseDownPos = null;
};
this.onWheel = (e) => {
e.preventDefault();
this.cameraSpherical.radius = Math.max(35, Math.min(340, this.cameraSpherical.radius + e.deltaY * 0.1));
this.updateCamera();
};
this.canvas.addEventListener('mousedown', this.onMouseDown);
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('mouseup', this.onMouseUp);
this.canvas.addEventListener('wheel', this.onWheel, { passive: false });
window.addEventListener('resize', this.handleResize);
if (window.ResizeObserver) {
this.resizeObserver = new ResizeObserver(this.handleResize);
this.resizeObserver.observe(this.container);
}
}
dispose() {
if (this.canvas) {
this.canvas.removeEventListener('mousedown', this.onMouseDown);
this.canvas.removeEventListener('wheel', this.onWheel);
}
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('resize', this.handleResize);
if (this.resizeObserver) this.resizeObserver.disconnect();
if (this.renderer) this.renderer.dispose();
}
}
import * as THREE from 'three';
import { GRID_SIZE, STOCK_WIDTH, STOCK_HEIGHT, STOCK_DEPTH } from '../constants/cncConfig.js';
import { TOOL_CATALOG } from '../constants/tools.js';
import { calculateCuttingPhysics } from './cuttingPhysics.js';
export class ThreeCncScene {
constructor(canvasElement, containerElement) {
this.canvas = canvasElement;
this.container = containerElement;
this.depthGrid = new Float32Array(GRID_SIZE * GRID_SIZE);
this.cameraSpherical = { radius: 175, theta: 0.55, phi: 1.05 };
this.cameraTarget = { x: 40, y: 4, z: -40 };
this.showTurretHead = true;
this.isInteracting = false;
this.prevMouse = { x: 0, y: 0 };
this.init();
}
init() {
const width = this.container.clientWidth || 800;
const height = this.container.clientHeight || 520;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x0c1322);
this.scene.fog = new THREE.FogExp2(0x0c1322, 0.0012);
this.camera = new THREE.PerspectiveCamera(45, width / height, 1, 1400);
this.updateCamera();
this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true, powerPreference: "high-performance" });
this.renderer.setSize(width, height);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.shadowMap.enabled = true;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.05;
// Mapa de reflexão de estúdio industrial (PMREMGenerator): confere reflexos e brilho metálico real a todas as superfícies
this.setupEnvironment();
// Iluminação balanceada de laboratório de usinagem
this.scene.add(new THREE.AmbientLight(0xffffff, 0.40));
this.scene.add(new THREE.HemisphereLight(0xe0f2fe, 0x0f172a, 0.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 1.30);
keyLight.position.set(110, 190, 120);
keyLight.castShadow = true;
this.scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xbae6fd, 0.65);
fillLight.position.set(-100, 120, -90);
this.scene.add(fillLight);
// Materiais PBR com aspecto industrial metálico realista
this.whitePaintMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.28, metalness: 0.25 });
this.darkIronMat = new THREE.MeshStandardMaterial({ color: 0x1e293b, roughness: 0.25, metalness: 0.82 });
this.chromeSteelMat = new THREE.MeshStandardMaterial({ color: 0xf8fafc, roughness: 0.08, metalness: 0.96 });
this.calviBlueMat = new THREE.MeshStandardMaterial({ color: 0x1d4ed8, roughness: 0.22, metalness: 0.40 });
this.buildMachineStructure();
this.buildWorkpieceStock();
this.buildOriginG54();
this.buildSpindleAndTool();
this.buildParticleSystems();
this.toolpathGroup = new THREE.Group();
this.scene.add(this.toolpathGroup);
this.buildCaliperVisuals();
this.attachEventListeners();
}
setupEnvironment() {
try {
const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
pmremGenerator.compileEquirectangularShader();
const envScene = new THREE.Scene();
envScene.background = new THREE.Color(0x0a101d);
// Softbox superior de teto (luz de oficina)
const ceilingSoftbox = new THREE.Mesh(
new THREE.PlaneGeometry(140, 140),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
ceilingSoftbox.position.set(0, 70, 0);
ceilingSoftbox.rotation.x = Math.PI / 2;
envScene.add(ceilingSoftbox);
// Luz frontal-esquerda quente de preenchimento
const keySoftbox = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshBasicMaterial({ color: 0xfef9c3 })
);
keySoftbox.position.set(70, 45, 70);
keySoftbox.lookAt(0, 0, 0);
envScene.add(keySoftbox);