diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..aef2186 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +## 0.2.0 — Rendering upgrade + +A big step up in how exhibits look, in the live viewer, in Studio and in standalone HTML exports. No changes to the `.decoder.json` format: existing exhibits render with the new engine as they are. + +### Materials + +- Richer physical materials across the library: brushed and anisotropic metals, clear-coated paint and plastics, sapphire glass with a thin anti-reflective film, and wet-looking tissue. +- Iridescence uses Three.js's supported thickness range, so the effect is consistent across browsers. +- Organ tissue stays opaque by default on software WebGL, so the heart reads correctly on machines without a GPU. Material overrides in an exhibit still win. + +### Lighting and the viewer + +- AgX tone mapping, a studio environment for reflections, soft key-light shadows and a contact shadow fitted to each model. +- A subtle bloom pass for emissive parts. +- Section views now draw a machined cap over the cut face instead of showing hollow geometry. +- Disassembly guides are drawn as real 3D rods with seated rings, so they stay visible on high-density screens and in small thumbnails. + +### Effects and geometry + +- Flow, flame and particle effects have new procedural textures and follow their paths more smoothly. +- More detailed procedural geometry for several part types, and matching updates to the vector illustrations. + +### Path tracing (Studio) + +- Deeper light bounces for metal and glass, fewer fireflies, sharper output on high-density screens and no tile seams on the first frame. Studio now converges to 128 samples. + +### Tooling + +- `scripts/capture-gpu-showcase.ts` captures matched stills and a disassembly video from the standalone viewer. It checks the browser's actual WebGL renderer and refuses to save anything unless it is running on a physical GPU, so captures are never mistaken for software renders. +- The export checks now wait for playback to start rather than sampling once, which keeps them reliable on software WebGL. + +### Photos + +Rendered with software WebGL (SwiftShader). Hardware GPU shots are still to come. + +The espresso machine in cutaway view, with a brass boiler, glossy black group head and see-through shell + +The four-stroke engine pulled apart, with 3D guide rods showing where each part seats The mechanical watch pulled apart, with gold and blue gears and guide rods back to the case + +### Known limits + +- Side-by-side comparisons so far were rendered with software WebGL (SwiftShader). A comparison on physical GPU hardware is still to come. + +## 0.1.0 + +First public release. diff --git a/docs/media/v0.2.0-engine.webp b/docs/media/v0.2.0-engine.webp new file mode 100644 index 0000000..b0fea75 Binary files /dev/null and b/docs/media/v0.2.0-engine.webp differ diff --git a/docs/media/v0.2.0-espresso.webp b/docs/media/v0.2.0-espresso.webp new file mode 100644 index 0000000..d991a97 Binary files /dev/null and b/docs/media/v0.2.0-espresso.webp differ diff --git a/docs/media/v0.2.0-watch.webp b/docs/media/v0.2.0-watch.webp new file mode 100644 index 0000000..43e9a51 Binary files /dev/null and b/docs/media/v0.2.0-watch.webp differ diff --git a/package-lock.json b/package-lock.json index 46ad71f..45872e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "primitive-decoder", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "primitive-decoder", - "version": "0.1.0", + "version": "0.2.0", "license": "Apache-2.0", "dependencies": { "@types/three": "^0.187.0", diff --git a/package.json b/package.json index 015893e..d6ff930 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "primitive-decoder", - "version": "0.1.0", + "version": "0.2.0", "description": "Local-first procedural system visualisation engine", "license": "Apache-2.0", "repository": { @@ -33,7 +33,8 @@ "files": [ "lib", "skills", - "THIRD_PARTY_NOTICES.md" + "THIRD_PARTY_NOTICES.md", + "CHANGELOG.md" ], "engines": { "node": ">=22.12" diff --git a/scripts/capture-gpu-showcase.ts b/scripts/capture-gpu-showcase.ts new file mode 100644 index 0000000..e319669 --- /dev/null +++ b/scripts/capture-gpu-showcase.ts @@ -0,0 +1,118 @@ +/** + * Capture matched standalone exhibit views and an engine disassembly video on a physical GPU. + * Run `npm run bundle:standalone`, then `npx tsx scripts/capture-gpu-showcase.ts [output-directory]`. + * Install Playwright Chromium and FFmpeg first, or use CHROMIUM_PATH for an installed Chromium. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { chromium, type Page } from 'playwright'; +import { BUILTIN_EXHIBITS } from '../src/projects/index'; +import { DecoderSDK } from '../src/sdk/index'; + +const output = resolve(process.argv[2] ?? 'showcase-captures'); +const exhibitIds = ['espresso_machine', 'mechanical_watch', 'four_stroke_engine']; +const fourStroke = 'four_stroke_engine'; +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function loadHardwareExhibit(page: Page, file: string): Promise { + await page.goto(pathToFileURL(file).href); + const gpu = await page.evaluate(() => { + const canvas = document.querySelector('#viewport canvas'); + const gl = canvas?.getContext('webgl2'); + if (!gl) return 'WebGL2 unavailable'; + const debug = gl.getExtension('WEBGL_debug_renderer_info'); + if (!debug) return 'GPU identity unavailable'; + return String(gl.getParameter(debug.UNMASKED_RENDERER_WEBGL)); + }); + if ( + !gpu.trim() || + /SwiftShader|llvmpipe|lavapipe|softpipe|software|basic render|unavailable/i.test(gpu) || + /^(ANGLE|WebKit WebGL|WebGL|unknown)$/i.test(gpu) + ) { + throw new Error(`A physical WebGL2 GPU is required. Chromium reported ${gpu}.`); + } + if (!(await page.locator('#play').isEnabled())) { + throw new Error(await page.locator('#status').innerText()); + } + return gpu; +} + +async function updateSlider(page: Page, id: '#timeline' | '#explosion', value: number): Promise { + await page.locator(id).evaluate((input: HTMLInputElement, next) => { + input.value = String(next); + input.dispatchEvent(new Event('input')); + }, value); +} + +async function main() { + const browser = await chromium.launch({ + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--ignore-gpu-blocklist', '--enable-gpu-rasterization'], + }); + const sdk = new DecoderSDK(); + const tempDir = mkdtempSync(join(tmpdir(), 'decoder-gpu-shots-')); + try { + for (const id of exhibitIds) { + const project = BUILTIN_EXHIBITS.find((exhibit) => exhibit.id === id); + if (!project) throw new Error(`Missing built-in exhibit ${id}.`); + const file = join(tempDir, `${id}.html`); + writeFileSync(file, sdk.exportFormat(project, 'html'), 'utf8'); + const context = await browser.newContext({ + viewport: { width: 1440, height: 900 }, + deviceScaleFactor: 2, + offline: true, + }); + try { + const page = await context.newPage(); + const gpu = await loadHardwareExhibit(page, file); + console.log(`[${id}] ${gpu}`); + mkdirSync(output, { recursive: true }); + await updateSlider(page, '#timeline', project.simulation.cycleDuration * 0.35); + await wait(400); + const viewport = page.locator('#viewport'); + await viewport.screenshot({ path: join(output, `${id}-assembled-gpu.png`) }); + await updateSlider(page, '#explosion', 0.62); + await wait(1200); + await viewport.screenshot({ path: join(output, `${id}-exploded-gpu.png`) }); + } finally { + await context.close(); + } + } + + const context = await browser.newContext({ + viewport: { width: 1280, height: 720 }, + offline: true, + recordVideo: { dir: tempDir, size: { width: 1280, height: 720 } }, + }); + const page = await context.newPage(); + const video = page.video(); + try { + await loadHardwareExhibit(page, join(tempDir, `${fourStroke}.html`)); + await page.click('#play'); + const steps = 90; + for (let frame = 0; frame <= steps; frame++) { + const phase = frame / steps; + const explosion = Math.min(0.78, 0.44 * (1 - Math.cos(phase * Math.PI * 2))); + await updateSlider(page, '#explosion', explosion); + await wait(55); + } + await wait(700); + } finally { + await context.close(); + } + if (!video) throw new Error('Browser video recording was unavailable.'); + await video.saveAs(join(output, `${fourStroke}-disassembly-gpu.webm`)); + console.log(`Saved GPU captures in ${output}`); + } finally { + await browser.close(); + sdk.dispose(); + rmSync(tempDir, { recursive: true, force: true }); + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +}); diff --git a/scripts/verify-exports.ts b/scripts/verify-exports.ts index e795eb0..8aa7a1a 100644 --- a/scripts/verify-exports.ts +++ b/scripts/verify-exports.ts @@ -118,8 +118,14 @@ async function verify(browser: Browser, file: string, webgl: boolean): Promise t0; + // Software WebGL (SwiftShader) can take a few seconds to draw the first + // frames of the heavier exhibits, so poll rather than sample once. + let advanced = false; + for (let waited = 0; waited < 5000 && !advanced; waited += 250) { + await wait(250); + advanced = (await time()) > t0; + } + checks.playAdvances = (await page.locator('#play').innerText()) === 'Pause' && advanced; await page.click('#play'); const pausedAt = await time(); const pausedOutputs = await outputs(); diff --git a/src/engine/effects.ts b/src/engine/effects.ts index cd56b21..dd035c3 100644 --- a/src/engine/effects.ts +++ b/src/engine/effects.ts @@ -5,19 +5,25 @@ export interface ActiveEffectInstance { spec: EffectSpec; group: THREE.Group; curve?: THREE.CatmullRomCurve3; + curveFrames?: { tangents: THREE.Vector3[]; normals: THREE.Vector3[]; binormals: THREE.Vector3[] }; particles?: THREE.InstancedMesh; particleCount: number; baseRadius: number; guideLine?: THREE.Mesh; + innerBeamLine?: THREE.Mesh; glowMesh?: THREE.Mesh; innerCoreMesh?: THREE.Mesh; + pointLight?: THREE.PointLight; material: THREE.Material; } const _dummy = new THREE.Object3D(); const _pt = new THREE.Vector3(); const _tan = new THREE.Vector3(); +const _norm = new THREE.Vector3(); +const _binorm = new THREE.Vector3(); const _up = new THREE.Vector3(0, 1, 0); +const _tmpColor = new THREE.Color(); const EFFECT_DEFAULT_COLORS: Record = { liquid_flow: '#38bdf8', @@ -39,48 +45,156 @@ const EFFECT_DEFAULT_COLORS: Record = { cellular_activity: '#f43f5e', }; -let sharedPuffTexture: THREE.CanvasTexture | null = null; +let sharedCloudPuffTex: THREE.CanvasTexture | null = null; +let sharedFlameSpriteTex: THREE.CanvasTexture | null = null; -function getFeatheredPuffTexture(): THREE.CanvasTexture | null { - if (sharedPuffTexture) return sharedPuffTexture; +function hash2(x: number, y: number, seed: number): number { + let n = (x * 374761393 + y * 668265263 + seed * 1442695041) | 0; + n = ((n ^ (n >>> 13)) * 1274126177) | 0; + return ((n ^ (n >>> 16)) >>> 0) / 4294967295; +} + +function fbm2(u: number, v: number, freq: number, octaves: number, seed: number): number { + let sum = 0; + let amp = 0.5; + let norm = 0; + let f = freq; + for (let o = 0; o < octaves; o++) { + const gx = u * f; + const gy = v * f; + const ix = Math.floor(gx); + const iy = Math.floor(gy); + const fx = gx - ix; + const fy = gy - iy; + const sx = fx * fx * (3 - 2 * fx); + const sy = fy * fy * (3 - 2 * fy); + const n00 = hash2(ix, iy, seed + o * 71); + const n10 = hash2(ix + 1, iy, seed + o * 71); + const n01 = hash2(ix, iy + 1, seed + o * 71); + const n11 = hash2(ix + 1, iy + 1, seed + o * 71); + const nx0 = n00 + (n10 - n00) * sx; + const nx1 = n01 + (n11 - n01) * sx; + sum += (nx0 + (nx1 - nx0) * sy) * amp; + norm += amp; + amp *= 0.5; + f *= 2; + } + return sum / (norm || 1); +} + +/** + * Generates a 256x256 turbulent fBm cloud-wisp sprite so steam, smoke, and thermal haze + * billow like volumetric fluid plumes instead of flat circular polka dots. + */ +function getVolumetricCloudTexture(): THREE.CanvasTexture | null { + if (sharedCloudPuffTex) return sharedCloudPuffTex; if (typeof document === 'undefined') return null; - const size = 128; + + const size = 256; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); if (!ctx) return null; - const grad = ctx.createRadialGradient(size / 2, size / 2, 2, size / 2, size / 2, size / 2); - grad.addColorStop(0, 'rgba(255, 255, 255, 0.95)'); - grad.addColorStop(0.35, 'rgba(255, 255, 255, 0.55)'); - grad.addColorStop(0.7, 'rgba(255, 255, 255, 0.16)'); - grad.addColorStop(1, 'rgba(255, 255, 255, 0)'); - ctx.fillStyle = grad; - ctx.fillRect(0, 0, size, size); - - sharedPuffTexture = new THREE.CanvasTexture(canvas); - sharedPuffTexture.colorSpace = THREE.SRGBColorSpace; - return sharedPuffTexture; + const img = ctx.createImageData(size, size); + for (let y = 0; y < size; y++) { + const ny = (y / (size - 1)) * 2 - 1; + for (let x = 0; x < size; x++) { + const nx = (x / (size - 1)) * 2 - 1; + const r = Math.hypot(nx, ny); + const p = (y * size + x) * 4; + if (r >= 1.0) { + img.data[p + 3] = 0; + continue; + } + const u = x / size; + const v = y / size; + const billow = fbm2(u, v, 4.5, 4, 9137); + const detail = fbm2(u + 0.3, v - 0.2, 11.0, 3, 4219); + const radialFalloff = Math.pow(Math.max(0, 1 - r * r), 1.65); + const density = Math.max(0, Math.min(1, radialFalloff * (0.48 + billow * 0.62 + (detail - 0.5) * 0.24))); + + // Subtle internal self-shadowing (warmer/brighter top-center, softer edge) + const shade = Math.round(225 + 30 * Math.max(0, 1 - r * 0.85)); + img.data[p] = shade; + img.data[p + 1] = shade; + img.data[p + 2] = Math.min(255, shade + 4); + img.data[p + 3] = Math.round(density * 235); + } + } + ctx.putImageData(img, 0, 0); + + sharedCloudPuffTex = new THREE.CanvasTexture(canvas); + sharedCloudPuffTex.colorSpace = THREE.SRGBColorSpace; + return sharedCloudPuffTex; +} + +/** + * Blackbody incandescent combustion kernel sprite (white-hot 3200K center -> amber 1900K -> deep soot crimson). + */ +function getBlackbodyFlameTexture(): THREE.CanvasTexture | null { + if (sharedFlameSpriteTex) return sharedFlameSpriteTex; + if (typeof document === 'undefined') return null; + + const size = 192; + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + + const img = ctx.createImageData(size, size); + for (let y = 0; y < size; y++) { + const ny = (y / (size - 1)) * 2 - 1; + for (let x = 0; x < size; x++) { + const nx = (x / (size - 1)) * 2 - 1; + const r = Math.hypot(nx, ny); + const p = (y * size + x) * 4; + if (r >= 1.0) { + img.data[p + 3] = 0; + continue; + } + const turb = fbm2(x / size, y / size, 6.0, 3, 7717); + const core = Math.pow(Math.max(0, 1 - r), 1.45) * (0.65 + turb * 0.55); + const alpha = Math.max(0, Math.min(1, core)); + + // Blackbody temperature ramp + const cr = Math.min(255, Math.round(255 * Math.min(1, core * 1.9 + 0.35))); + const cg = Math.min(255, Math.round(255 * Math.pow(Math.min(1, core * 1.35), 1.35))); + const cb = Math.min(255, Math.round(255 * Math.pow(Math.min(1, core * 1.05), 3.0))); + + img.data[p] = cr; + img.data[p + 1] = cg; + img.data[p + 2] = cb; + img.data[p + 3] = Math.round(alpha * 255); + } + } + ctx.putImageData(img, 0, 0); + + sharedFlameSpriteTex = new THREE.CanvasTexture(canvas); + sharedFlameSpriteTex.colorSpace = THREE.SRGBColorSpace; + return sharedFlameSpriteTex; } export class ScientificEffectsManager { public readonly root = new THREE.Group(); private instances: ActiveEffectInstance[] = []; - private sharedSphereGeo = new THREE.SphereGeometry(1, 16, 12); - private sharedPulseGeo = new THREE.CylinderGeometry(0.42, 0.42, 2.2, 12); - private sharedDropletGeo = new THREE.SphereGeometry(1, 16, 12); - private sharedPlaneGeo = new THREE.PlaneGeometry(2.2, 2.2); + private sharedSphereGeo = new THREE.SphereGeometry(1, 18, 14); + private sharedPulseGeo = new THREE.CapsuleGeometry(0.36, 2.1, 8, 14); + private sharedDropletGeo = new THREE.SphereGeometry(1, 18, 14); + private sharedPlaneGeo = new THREE.PlaneGeometry(2.35, 2.35); constructor() { this.root.name = '__scientific_effects__'; this.sharedPulseGeo.rotateX(Math.PI / 2); - this.sharedDropletGeo.scale(0.85, 0.85, 1.45); + this.sharedDropletGeo.scale(0.78, 0.78, 1.55); } buildForProject(effects: EffectSpec[]): void { this.clear(); - const puffTex = getFeatheredPuffTexture(); + const cloudTex = getVolumetricCloudTexture(); + const flameTex = getBlackbodyFlameTexture(); for (const spec of effects) { const group = new THREE.Group(); @@ -89,77 +203,148 @@ export class ScientificEffectsManager { const colorHex = spec.color ?? EFFECT_DEFAULT_COLORS[spec.type] ?? '#38bdf8'; const baseColor = new THREE.Color(colorHex); - const count = Math.max(8, Math.min(48, Math.round((spec.density ?? 1) * 20))); + const count = Math.max(10, Math.min(64, Math.round((spec.density ?? 1) * 26))); const baseRadius = spec.radius ?? 0.032; const isVapour = spec.type === 'steam_vapour' || spec.type === 'smoke' || spec.type === 'airflow'; const isThermal = spec.type === 'heat_gradient' || spec.type === 'thermal_diffusion'; + const isCombustion = spec.type === 'combustion'; const isLiquid = spec.type === 'liquid_flow' || spec.type === 'material_transport'; + const isEnergyPulse = + spec.type === 'signal_pulse' || spec.type === 'electrical_current' || spec.type === 'optical_ray'; let mat: THREE.Material; if (isLiquid) { + // Refractive specular fluid micro-droplets mat = new THREE.MeshPhysicalMaterial({ color: baseColor, - roughness: 0.06, + roughness: 0.03, metalness: 0.0, - clearcoat: 0.9, - clearcoatRoughness: 0.05, + transmission: 0.78, + thickness: baseRadius * 3.5, + attenuationColor: baseColor, + attenuationDistance: baseRadius * 8.0, + clearcoat: 1.0, + clearcoatRoughness: 0.02, ior: 1.333, transparent: true, - opacity: 0.86, + opacity: 0.9, depthWrite: false, }); - } else if ((isVapour || isThermal) && puffTex) { + } else if (isCombustion && flameTex) { + // HDR incandescent flame wisps (> 1.0 RGB triggers AgX soft highlight desaturation + UnrealBloom) + const hdrFlame = baseColor.clone().multiplyScalar(1.85); mat = new THREE.MeshBasicMaterial({ - color: baseColor, - map: puffTex, + color: hdrFlame, + map: flameTex, transparent: true, - opacity: isThermal ? 0.2 : 0.42, + opacity: 0.82, + depthWrite: false, + side: THREE.DoubleSide, + blending: THREE.AdditiveBlending, + }); + } else if ((isVapour || isThermal) && cloudTex) { + const tint = isThermal ? baseColor.clone().multiplyScalar(1.35) : baseColor; + mat = new THREE.MeshBasicMaterial({ + color: tint, + map: cloudTex, + transparent: true, + opacity: isThermal ? 0.22 : 0.44, depthWrite: false, side: THREE.DoubleSide, blending: isThermal ? THREE.AdditiveBlending : THREE.NormalBlending, }); - } else { + } else if (isEnergyPulse) { + // HDR coherent photon / signal wave-packet (> 1.4 RGB catches UnrealBloomPass cleanly) + const hdrPulse = baseColor.clone().multiplyScalar(1.65); mat = new THREE.MeshBasicMaterial({ + color: hdrPulse, + transparent: true, + opacity: 0.92, + depthWrite: false, + blending: THREE.AdditiveBlending, + }); + } else { + mat = new THREE.MeshPhysicalMaterial({ color: baseColor, + roughness: 0.22, + metalness: 0.1, + emissive: baseColor, + emissiveIntensity: 0.35, transparent: true, - opacity: spec.type === 'optical_ray' ? 0.72 : 0.88, + opacity: 0.88, depthWrite: false, }); } let curve: THREE.CatmullRomCurve3 | undefined; + let curveFrames: { tangents: THREE.Vector3[]; normals: THREE.Vector3[]; binormals: THREE.Vector3[] } | undefined; let guideLine: THREE.Mesh | undefined; + let innerBeamLine: THREE.Mesh | undefined; if (spec.path && spec.path.length >= 2) { curve = new THREE.CatmullRomCurve3(spec.path.map((p) => new THREE.Vector3(...p))); + curveFrames = curve.computeFrenetFrames(64, false); if ( spec.type === 'optical_ray' || spec.type === 'electromagnetic_field' || spec.type === 'magnetic_field' || - spec.type === 'electrical_current' + spec.type === 'electrical_current' || + spec.type === 'signal_pulse' ) { - const beamGeo = new THREE.TubeGeometry(curve, 36, baseRadius * 0.42, 10, false); + // Outer atmospheric Tyndall scatter sheath + const sheathRadius = spec.type === 'optical_ray' ? baseRadius * 0.48 : baseRadius * 0.36; + const beamGeo = new THREE.TubeGeometry(curve, 48, sheathRadius, 12, false); const beamMat = new THREE.MeshBasicMaterial({ color: baseColor, transparent: true, - opacity: spec.type === 'optical_ray' ? 0.52 : 0.24, + opacity: spec.type === 'optical_ray' ? 0.28 : 0.16, depthWrite: false, + blending: THREE.AdditiveBlending, }); guideLine = new THREE.Mesh(beamGeo, beamMat); group.add(guideLine); + + // Razor-sharp HDR laser / conductor core filament + if (spec.type === 'optical_ray' || spec.type === 'electrical_current') { + const coreBeamGeo = new THREE.TubeGeometry(curve, 48, sheathRadius * 0.32, 8, false); + const coreBeamMat = new THREE.MeshBasicMaterial({ + color: baseColor.clone().lerp(new THREE.Color('#ffffff'), 0.55).multiplyScalar(1.75), + transparent: true, + opacity: spec.type === 'optical_ray' ? 0.85 : 0.48, + depthWrite: false, + blending: THREE.AdditiveBlending, + }); + innerBeamLine = new THREE.Mesh(coreBeamGeo, coreBeamMat); + group.add(innerBeamLine); + } + } else if (isLiquid) { + // Continuous laminar fluid stream core inside pipes/spouts + const streamGeo = new THREE.TubeGeometry(curve, 44, baseRadius * 0.38, 12, false); + const streamMat = new THREE.MeshPhysicalMaterial({ + color: baseColor, + roughness: 0.04, + metalness: 0.0, + clearcoat: 1.0, + clearcoatRoughness: 0.03, + ior: 1.333, + transparent: true, + opacity: 0.48, + depthWrite: false, + }); + guideLine = new THREE.Mesh(streamGeo, streamMat); + group.add(guideLine); } } - const geo = - spec.type === 'signal_pulse' || spec.type === 'electrical_current' || spec.type === 'optical_ray' - ? this.sharedPulseGeo - : isLiquid - ? this.sharedDropletGeo - : (isVapour || isThermal) && puffTex - ? this.sharedPlaneGeo - : this.sharedSphereGeo; + const geo = isEnergyPulse + ? this.sharedPulseGeo + : isLiquid + ? this.sharedDropletGeo + : (isVapour || isThermal || isCombustion) && (cloudTex || flameTex) + ? this.sharedPlaneGeo + : this.sharedSphereGeo; const particles = new THREE.InstancedMesh(geo, mat, count); particles.frustumCulled = false; @@ -167,18 +352,20 @@ export class ScientificEffectsManager { let glowMesh: THREE.Mesh | undefined; let innerCoreMesh: THREE.Mesh | undefined; + let pointLight: THREE.PointLight | undefined; + if ( - spec.type === 'combustion' || + isCombustion || spec.type === 'heat_gradient' || spec.type === 'pressure_wave' || spec.type === 'thermal_diffusion' ) { const origin = spec.path?.[0] ?? [0, 0, 0]; - const glowGeo = new THREE.SphereGeometry(baseRadius * 3.1, 20, 14); + const glowGeo = new THREE.SphereGeometry(baseRadius * 3.2, 24, 16); const glowMat = new THREE.MeshBasicMaterial({ - color: baseColor, + color: baseColor.clone().multiplyScalar(isCombustion ? 1.45 : 1.15), transparent: true, - opacity: spec.type === 'combustion' ? 0.34 : 0.24, + opacity: isCombustion ? 0.36 : 0.22, depthWrite: false, blending: THREE.AdditiveBlending, }); @@ -186,18 +373,25 @@ export class ScientificEffectsManager { glowMesh.position.set(origin[0], origin[1], origin[2]); group.add(glowMesh); - if (spec.type === 'combustion') { - const coreGeo = new THREE.SphereGeometry(baseRadius * 1.65, 16, 12); + if (isCombustion) { + const coreColor = new THREE.Color(spec.secondaryColor ?? '#fef08a').multiplyScalar(2.2); + const coreGeo = new THREE.SphereGeometry(baseRadius * 1.55, 18, 14); const coreMat = new THREE.MeshBasicMaterial({ - color: spec.secondaryColor ?? '#fef08a', + color: coreColor, transparent: true, - opacity: 0.72, + opacity: 0.85, depthWrite: false, blending: THREE.AdditiveBlending, }); innerCoreMesh = new THREE.Mesh(coreGeo, coreMat); innerCoreMesh.position.set(origin[0], origin[1], origin[2]); group.add(innerCoreMesh); + + // Real dynamic combustion illumination: casts warm ignition flash onto cylinder walls & piston crown! + pointLight = new THREE.PointLight(baseColor, 0, Math.max(0.8, baseRadius * 18), 2.0); + pointLight.castShadow = false; + pointLight.position.set(origin[0], origin[1], origin[2]); + group.add(pointLight); } } @@ -206,12 +400,15 @@ export class ScientificEffectsManager { spec, group, curve, + curveFrames, particles, particleCount: count, baseRadius, guideLine, + innerBeamLine, glowMesh, innerCoreMesh, + pointLight, material: mat, }); } @@ -238,107 +435,186 @@ export class ScientificEffectsManager { const isVapour = inst.spec.type === 'steam_vapour' || inst.spec.type === 'smoke' || inst.spec.type === 'airflow'; const isThermal = inst.spec.type === 'heat_gradient' || inst.spec.type === 'thermal_diffusion'; + const isCombustion = inst.spec.type === 'combustion'; + const isBillboard = isVapour || isThermal || isCombustion; + const isEnergyPulse = + inst.spec.type === 'signal_pulse' || + inst.spec.type === 'electrical_current' || + inst.spec.type === 'optical_ray'; inst.group.visible = intensity > 0.02 && !hidden?.has(inst.spec.id); - if (!inst.group.visible) continue; + if (!inst.group.visible) { + if (inst.pointLight) inst.pointLight.intensity = 0; + continue; + } if (inst.material instanceof THREE.MeshBasicMaterial || inst.material instanceof THREE.MeshPhysicalMaterial) { inst.material.opacity = isThermal - ? Math.min(0.24, 0.06 + intensity * 0.14) + ? Math.min(0.26, 0.06 + intensity * 0.15) : isVapour - ? Math.min(0.48, 0.14 + intensity * 0.28) - : Math.min(0.95, 0.28 + intensity * 0.62); + ? Math.min(0.52, 0.14 + intensity * 0.3) + : isCombustion + ? Math.min(0.88, 0.25 + intensity * 0.58) + : Math.min(0.95, 0.3 + intensity * 0.62); } + const flicker = 0.88 + Math.sin(time * 19.3) * 0.1 + Math.cos(time * 29.1) * 0.07; + if (inst.glowMesh) { const pulse = 1 + Math.sin(time * (3.5 + speed * 2.2)) * 0.15 * Math.min(1, intensity); inst.glowMesh.scale.setScalar(pulse * Math.max(0.4, Math.min(1.65, intensity))); - (inst.glowMesh.material as THREE.MeshBasicMaterial).opacity = Math.min(0.42, intensity * 0.26); + (inst.glowMesh.material as THREE.MeshBasicMaterial).opacity = Math.min(0.44, intensity * 0.28); } if (inst.innerCoreMesh) { - const flicker = 0.88 + Math.sin(time * 17) * 0.14 + Math.cos(time * 23) * 0.08; - inst.innerCoreMesh.scale.setScalar(flicker * Math.max(0.35, Math.min(1.4, intensity))); - (inst.innerCoreMesh.material as THREE.MeshBasicMaterial).opacity = Math.min(0.85, intensity * 0.65); + inst.innerCoreMesh.scale.setScalar(flicker * Math.max(0.35, Math.min(1.45, intensity))); + (inst.innerCoreMesh.material as THREE.MeshBasicMaterial).opacity = Math.min(0.9, intensity * 0.72); + } + + if (inst.pointLight) { + inst.pointLight.intensity = intensity * flicker * 2.4; } if (inst.guideLine) { - (inst.guideLine.material as THREE.MeshBasicMaterial).opacity = Math.min( - 0.75, - (inst.spec.type === 'optical_ray' ? 0.55 : 0.26) * intensity, + const gMat = inst.guideLine.material as THREE.MeshBasicMaterial | THREE.MeshPhysicalMaterial; + gMat.opacity = Math.min( + 0.72, + (inst.spec.type === 'optical_ray' ? 0.34 : inst.spec.type === 'liquid_flow' ? 0.46 : 0.2) * intensity, ); } + if (inst.innerBeamLine) { + (inst.innerBeamLine.material as THREE.MeshBasicMaterial).opacity = Math.min(0.95, 0.68 * intensity); + } + if (inst.particles && inst.curve) { + const frames = inst.curveFrames; + const frameCount = frames ? frames.normals.length - 1 : 0; + for (let i = 0; i < inst.particleCount; i++) { const offset = i / inst.particleCount; - const u = (((time * 0.35 * speed + offset) % 1) + 1) % 1; + const u = (((time * 0.36 * speed + offset) % 1) + 1) % 1; inst.curve.getPointAt(u, _pt); inst.curve.getTangentAt(u, _tan); - const jitterMax = inst.spec.clippedToComponent - ? inst.baseRadius * 0.22 + // Helical vortex swirl in Frenet normal/binormal frame so fluids & vapour spiral organically + const swirlRadius = inst.spec.clippedToComponent + ? inst.baseRadius * 0.2 : isVapour - ? inst.baseRadius * (0.4 + u * 1.4) - : inst.baseRadius * 0.5; - const jx = Math.sin(i * 12.7 + time * 4) * jitterMax; - const jy = Math.cos(i * 7.3 + time * 3.2) * jitterMax; + ? inst.baseRadius * (0.35 + u * 1.65) + : isEnergyPulse + ? inst.baseRadius * 0.08 + : inst.baseRadius * 0.42; + + const swirlPhase = i * 2.39996 + u * (isVapour ? 5.5 : 8.0) - time * 2.8; + const radialMag = swirlRadius * (0.45 + (0.55 * ((i * 7) % 11)) / 10); + + if (frames && frameCount > 0) { + const fIdx = Math.min(frameCount, Math.max(0, Math.round(u * frameCount))); + _norm.copy(frames.normals[fIdx]); + _binorm.copy(frames.binormals[fIdx]); + _pt.addScaledVector(_norm, Math.cos(swirlPhase) * radialMag); + _pt.addScaledVector(_binorm, Math.sin(swirlPhase) * radialMag); + } else { + _pt.x += Math.cos(swirlPhase) * radialMag; + _pt.y += Math.sin(swirlPhase) * radialMag; + } + + _dummy.position.copy(_pt); - _dummy.position.set(_pt.x + jx, _pt.y + jy, _pt.z); - if ((isVapour || isThermal) && cameraQuaternion) { + if (isBillboard && cameraQuaternion) { _dummy.quaternion.copy(cameraQuaternion); - _dummy.rotateZ(u * 2.2 + i); + _dummy.rotateZ(u * 2.6 + i * 1.17 + time * 0.35 * (i % 2 === 0 ? 1 : -1)); } else if (_tan.lengthSq() > 0.0001) { - _dummy.quaternion.setFromUnitVectors(_up, _tan.clone().normalize()); + _dummy.quaternion.setFromUnitVectors(_up, _tan.normalize()); _dummy.lookAt(_pt.x + _tan.x, _pt.y + _tan.y, _pt.z + _tan.z); } + const envFade = + Math.sin(Math.min(1, u * 4.5) * (Math.PI * 0.5)) * Math.sin(Math.min(1, (1 - u) * 3.4) * (Math.PI * 0.5)); const taper = isVapour - ? (0.55 + u * 1.65) * Math.sin(Math.min(1, (1 - u) * 3.2) * (Math.PI / 2)) - : Math.sin(u * Math.PI) * 0.42 + 0.68; - const s = inst.baseRadius * taper * (inst.spec.scale ?? 1) * Math.min(1.4, 0.5 + intensity * 0.5); - _dummy.scale.setScalar(Math.max(0.003, s)); + ? (0.55 + u * 1.85) * envFade + : isEnergyPulse + ? (0.75 + 0.35 * Math.sin(u * Math.PI * 4)) * envFade + : (Math.sin(u * Math.PI) * 0.38 + 0.7) * envFade; + + const s = inst.baseRadius * taper * (inst.spec.scale ?? 1) * Math.min(1.45, 0.5 + intensity * 0.52); + const safeS = Math.max(0.003, s); + + if (isEnergyPulse) { + // Elongate wave-packets cleanly with speed + _dummy.scale.set(safeS * 0.72, safeS * 0.72, safeS * Math.min(2.2, 0.9 + Math.abs(speed) * 0.45)); + } else { + _dummy.scale.setScalar(safeS); + } + _dummy.updateMatrix(); inst.particles.setMatrixAt(i, _dummy.matrix); + + // Subtle temperature cooling tint on combustion/thermal plumes along trajectory + if (isCombustion) { + _tmpColor.setRGB(1.0, Math.max(0.28, 0.95 - u * 0.65), Math.max(0.05, 0.6 - u * 0.58)); + inst.particles.setColorAt(i, _tmpColor); + } } inst.particles.instanceMatrix.needsUpdate = true; + if (inst.particles.instanceColor) inst.particles.instanceColor.needsUpdate = true; } else if (inst.particles) { const origin = inst.spec.path?.[0] ?? [0, 0, 0]; - const spread = inst.baseRadius * 3.5; + const spread = inst.baseRadius * 3.4; for (let i = 0; i < inst.particleCount; i++) { - const phase = (((time * 0.45 * speed + i / inst.particleCount) % 1) + 1) % 1; - const angle = i * 2.39996; - const r = spread * (inst.spec.type === 'pressure_wave' ? phase : 0.28 + phase * 0.72); + const phase = (((time * 0.46 * speed + i / inst.particleCount) % 1) + 1) % 1; + const angle = i * 2.39996 + phase * (isCombustion ? 1.8 : 0.9); + const r = + spread * + (inst.spec.type === 'pressure_wave' + ? phase + : isCombustion + ? (0.18 + phase * 0.82) * (1 - phase * 0.3) + : 0.26 + phase * 0.74); const rise = - isVapour || isThermal || inst.spec.type === 'combustion' - ? phase * spread * 2.1 + isVapour || isThermal || isCombustion + ? phase * spread * (isCombustion ? 1.55 : 2.15) : Math.sin(phase * Math.PI * 2) * spread * 0.38; + _dummy.position.set(origin[0] + Math.cos(angle) * r, origin[1] + rise, origin[2] + Math.sin(angle) * r); - if ((isVapour || isThermal) && cameraQuaternion) { + if (isBillboard && cameraQuaternion) { _dummy.quaternion.copy(cameraQuaternion); + _dummy.rotateZ(phase * 2.4 + i * 0.9); } else { _dummy.quaternion.identity(); } - const fade = Math.sin(Math.min(1, (1 - phase) * 2.5) * (Math.PI / 2)); + const fade = + Math.sin(Math.min(1, phase * 4.0) * (Math.PI * 0.5)) * + Math.sin(Math.min(1, (1 - phase) * 2.5) * (Math.PI * 0.5)); const s = inst.baseRadius * - (isVapour ? 0.8 + phase * 1.5 : 1 - phase * 0.45) * + (isVapour ? 0.8 + phase * 1.65 : isCombustion ? 1.25 - phase * 0.55 : 1 - phase * 0.45) * fade * - Math.min(1.5, 0.5 + intensity * 0.6); + Math.min(1.5, 0.5 + intensity * 0.62); _dummy.scale.setScalar(Math.max(0.004, s)); _dummy.updateMatrix(); inst.particles.setMatrixAt(i, _dummy.matrix); + + if (isCombustion) { + _tmpColor.setRGB(1.0, Math.max(0.22, 1.0 - phase * 0.72), Math.max(0.04, 0.65 - phase * 0.62)); + inst.particles.setColorAt(i, _tmpColor); + } } inst.particles.instanceMatrix.needsUpdate = true; + if (inst.particles.instanceColor) inst.particles.instanceColor.needsUpdate = true; } } } clear(): void { for (const inst of this.instances) { + inst.particles?.dispose(); inst.material.dispose(); inst.guideLine?.geometry.dispose(); (inst.guideLine?.material as THREE.Material | undefined)?.dispose(); + inst.innerBeamLine?.geometry.dispose(); + (inst.innerBeamLine?.material as THREE.Material | undefined)?.dispose(); inst.glowMesh?.geometry.dispose(); (inst.glowMesh?.material as THREE.Material | undefined)?.dispose(); inst.innerCoreMesh?.geometry.dispose(); diff --git a/src/engine/geometry.ts b/src/engine/geometry.ts index 0b6b72d..e758ef7 100644 --- a/src/engine/geometry.ts +++ b/src/engine/geometry.ts @@ -1,5 +1,5 @@ import * as THREE from 'three'; -import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg/src/index.js'; +import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg'; import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; import type { ComponentNode, @@ -36,8 +36,9 @@ function applyTransformToGeometry(geo: THREE.BufferGeometry, t?: TransformSpec): } /** - * Generates clean box-projected planar UVs when a geometry lacks UVs, - * ensuring procedural normal/roughness maps wrap coherently across merged assemblies. + * Generates clean curvature-aware cylindrical/triplanar UVs when a geometry lacks UVs + * (e.g. after CSG boolean operations), ensuring procedural brushed/cast normal and roughness + * maps wrap seamlessly without stretching. */ function ensureBoxUVs(geo: THREE.BufferGeometry): void { if (geo.attributes.uv) return; @@ -53,19 +54,246 @@ function ensureBoxUVs(geo: THREE.BufferGeometry): void { const ny = norm ? Math.abs(norm.getY(i)) : 1; const nz = norm ? Math.abs(norm.getZ(i)) : 0; if (ny >= nx && ny >= nz) { - uvs[i * 2] = x * 1.5 + 0.5; - uvs[i * 2 + 1] = z * 1.5 + 0.5; + uvs[i * 2] = x * 1.6 + 0.5; + uvs[i * 2 + 1] = z * 1.6 + 0.5; } else if (nx >= nz) { - uvs[i * 2] = z * 1.5 + 0.5; - uvs[i * 2 + 1] = y * 1.5 + 0.5; + uvs[i * 2] = z * 1.6 + 0.5; + uvs[i * 2 + 1] = y * 1.6 + 0.5; } else { - uvs[i * 2] = x * 1.5 + 0.5; - uvs[i * 2 + 1] = y * 1.5 + 0.5; + uvs[i * 2] = x * 1.6 + 0.5; + uvs[i * 2 + 1] = y * 1.6 + 0.5; } } geo.setAttribute('uv', new THREE.BufferAttribute(uvs, 2)); } +/** + * Computes area-weighted creased vertex normals (smoothing curved cylinders, fillets & organic surfaces + * below `creaseAngleRad` while keeping crisp machined edges above `creaseAngleRad`) AND computes + * NaN-safe orthonormal MikkTSpace/Lengyel `tangent` vectors (`vec4`) so `MeshPhysicalMaterial` + * brushed-metal anisotropy renders accurately without black-pixel artifacts on CSG sliver triangles. + */ +function finalizeCadNormalsAndTangents( + inputGeo: THREE.BufferGeometry, + creaseAngleRad = THREE.MathUtils.degToRad(42), +): THREE.BufferGeometry { + const geo = inputGeo.index ? inputGeo.toNonIndexed() : inputGeo; + if (geo !== inputGeo) { + inputGeo.dispose(); + } + + const pos = geo.attributes.position; + if (!pos || pos.count < 3) return geo; + + const vertCount = pos.count; + const triCount = Math.floor(vertCount / 3); + const cosThreshold = Math.cos(creaseAngleRad); + + // 1. Precompute face normals (both unit direction for crease test & area-weighted vector for smooth blending) + const faceUnitNormals = new Float32Array(triCount * 3); + const faceWeightedNormals = new Float32Array(triCount * 3); + const vertexBuckets = new Map(); + + const quantKey = (x: number, y: number, z: number): string => + `${Math.round(x * 1e4)},${Math.round(y * 1e4)},${Math.round(z * 1e4)}`; + + for (let t = 0; t < triCount; t++) { + const i0 = t * 3; + const i1 = i0 + 1; + const i2 = i0 + 2; + + const ax = pos.getX(i0), + ay = pos.getY(i0), + az = pos.getZ(i0); + const bx = pos.getX(i1), + by = pos.getY(i1), + bz = pos.getZ(i1); + const cx = pos.getX(i2), + cy = pos.getY(i2), + cz = pos.getZ(i2); + + const abx = bx - ax, + aby = by - ay, + abz = bz - az; + const acx = cx - ax, + acy = cy - ay, + acz = cz - az; + + // Cross product magnitude is 2x triangle area -> naturally area-weights large flat faces over tiny bevel slivers + const wx = aby * acz - abz * acy; + const wy = abz * acx - abx * acz; + const wz = abx * acy - aby * acx; + const len = Math.hypot(wx, wy, wz); + + const fIdx = t * 3; + if (len > 1e-11) { + faceWeightedNormals[fIdx] = wx; + faceWeightedNormals[fIdx + 1] = wy; + faceWeightedNormals[fIdx + 2] = wz; + faceUnitNormals[fIdx] = wx / len; + faceUnitNormals[fIdx + 1] = wy / len; + faceUnitNormals[fIdx + 2] = wz / len; + } else { + faceWeightedNormals[fIdx + 1] = 1; + faceUnitNormals[fIdx + 1] = 1; + } + + for (let k = 0; k < 3; k++) { + const vi = i0 + k; + const key = quantKey(pos.getX(vi), pos.getY(vi), pos.getZ(vi)); + let list = vertexBuckets.get(key); + if (!list) { + list = []; + vertexBuckets.set(key, list); + } + list.push(t); + } + } + + // 2. Accumulate smooth normals across welded vertices only when dihedral angle <= creaseAngleRad + const normals = new Float32Array(vertCount * 3); + for (let t = 0; t < triCount; t++) { + const fIdx = t * 3; + const ux = faceUnitNormals[fIdx]; + const uy = faceUnitNormals[fIdx + 1]; + const uz = faceUnitNormals[fIdx + 2]; + + for (let k = 0; k < 3; k++) { + const vi = t * 3 + k; + const key = quantKey(pos.getX(vi), pos.getY(vi), pos.getZ(vi)); + const neighbors = vertexBuckets.get(key); + + let sx = 0, + sy = 0, + sz = 0; + if (neighbors && neighbors.length <= 64) { + for (let n = 0; n < neighbors.length; n++) { + const nt = neighbors[n] * 3; + const dot = ux * faceUnitNormals[nt] + uy * faceUnitNormals[nt + 1] + uz * faceUnitNormals[nt + 2]; + if (dot >= cosThreshold) { + sx += faceWeightedNormals[nt]; + sy += faceWeightedNormals[nt + 1]; + sz += faceWeightedNormals[nt + 2]; + } + } + } else { + sx = ux; + sy = uy; + sz = uz; + } + + const slen = Math.hypot(sx, sy, sz); + const outIdx = vi * 3; + if (slen > 1e-11) { + normals[outIdx] = sx / slen; + normals[outIdx + 1] = sy / slen; + normals[outIdx + 2] = sz / slen; + } else { + normals[outIdx] = ux; + normals[outIdx + 1] = uy; + normals[outIdx + 2] = uz; + } + } + } + + geo.setAttribute('normal', new THREE.BufferAttribute(normals, 3)); + ensureBoxUVs(geo); + + // 3. Compute NaN-safe orthonormal vertex tangents (vec4) so anisotropic reflections shine cleanly + const uv = geo.attributes.uv; + if (uv) { + const tangents = new Float32Array(vertCount * 4); + for (let t = 0; t < triCount; t++) { + const i0 = t * 3; + const i1 = i0 + 1; + const i2 = i0 + 2; + + const x1 = pos.getX(i1) - pos.getX(i0); + const y1 = pos.getY(i1) - pos.getY(i0); + const z1 = pos.getZ(i1) - pos.getZ(i0); + const x2 = pos.getX(i2) - pos.getX(i0); + const y2 = pos.getY(i2) - pos.getY(i0); + const z2 = pos.getZ(i2) - pos.getZ(i0); + + const s1 = uv.getX(i1) - uv.getX(i0); + const t1 = uv.getY(i1) - uv.getY(i0); + const s2 = uv.getX(i2) - uv.getX(i0); + const t2 = uv.getY(i2) - uv.getY(i0); + + const denom = s1 * t2 - s2 * t1; + let tx = 1, + ty = 0, + tz = 0; + let bx = 0, + by = 0, + bz = 1; + const validUv = Math.abs(denom) > 1e-9; + + if (validUv) { + const inv = 1.0 / denom; + tx = (t2 * x1 - t1 * x2) * inv; + ty = (t2 * y1 - t1 * y2) * inv; + tz = (t2 * z1 - t1 * z2) * inv; + + bx = (s1 * x2 - s2 * x1) * inv; + by = (s1 * y2 - s2 * y1) * inv; + bz = (s1 * z2 - s2 * z1) * inv; + } + + for (let k = 0; k < 3; k++) { + const vi = i0 + k; + const nx = normals[vi * 3]; + const ny = normals[vi * 3 + 1]; + const nz = normals[vi * 3 + 2]; + + // Gram-Schmidt orthogonalize T against vertex normal N + const ndott = nx * tx + ny * ty + nz * tz; + let ox = tx - nx * ndott; + let oy = ty - ny * ndott; + let oz = tz - nz * ndott; + let olen = Math.hypot(ox, oy, oz); + + if (!validUv || olen < 1e-7 || !Number.isFinite(olen)) { + // Guaranteed orthonormal fallback tangent perpendicular to N + if (Math.abs(ny) < 0.9) { + ox = nz; + oy = 0; + oz = -nx; + } else { + ox = 1; + oy = 0; + oz = 0; + const d = nx * ox; + ox -= nx * d; + oy -= ny * d; + oz -= nz * d; + } + olen = Math.hypot(ox, oy, oz) || 1; + } + + ox /= olen; + oy /= olen; + oz /= olen; + + // Handedness sign (+1 or -1) + const cx = ny * oz - nz * oy; + const cy = nz * ox - nx * oz; + const cz = nx * oy - ny * ox; + const w = validUv && cx * bx + cy * by + cz * bz < 0 ? -1.0 : 1.0; + + const tIdx = vi * 4; + tangents[tIdx] = ox; + tangents[tIdx + 1] = oy; + tangents[tIdx + 2] = oz; + tangents[tIdx + 3] = w; + } + } + geo.setAttribute('tangent', new THREE.BufferAttribute(tangents, 4)); + } + + return geo; +} + function normalizeForMerge(geos: THREE.BufferGeometry[]): THREE.BufferGeometry { const prepared = geos.map((raw) => { const g = raw.index ? raw.toNonIndexed() : raw.clone(); @@ -110,47 +338,51 @@ function createRoundedBoxGeometry( bevelEnabled: true, bevelThickness: r, bevelSize: r, - bevelSegments, - curveSegments: 12, + bevelSegments: Math.max(3, bevelSegments), + curveSegments: 16, }); geo.center(); return geo; } /** - * Watertight chamfered cylinder via LatheGeometry so cylindrical parts catch crisp rim highlights. + * Watertight multi-stepped chamfered cylinder via LatheGeometry so cylindrical parts catch crisp + * Blender-style specular bevel rim highlights. */ function createChamferedCylinderGeometry( radiusTop: number, radiusBottom: number, height: number, - segments = 42, + segments = 48, ): THREE.BufferGeometry { const half = height / 2; const maxR = Math.max(radiusTop, radiusBottom); - const ch = Math.min(height * 0.1, maxR * 0.08, 0.018); + const ch = Math.min(height * 0.095, maxR * 0.075, 0.018); const rtInner = Math.max(0.001, radiusTop - ch); const rbInner = Math.max(0.001, radiusBottom - ch); if (ch < 0.0015 || height < 0.012) { - return new THREE.CylinderGeometry(radiusTop, radiusBottom, height, Math.max(16, segments)); + return new THREE.CylinderGeometry(radiusTop, radiusBottom, height, Math.max(20, segments)); } + // Two-stepped micro-fillet bevel profile for continuous highlight roll-off const pts = [ new THREE.Vector2(0, -half), new THREE.Vector2(rbInner, -half), + new THREE.Vector2(rbInner + ch * 0.62, -half + ch * 0.38), new THREE.Vector2(radiusBottom, -half + ch), new THREE.Vector2(radiusTop, half - ch), + new THREE.Vector2(rtInner + ch * 0.62, half - ch * 0.38), new THREE.Vector2(rtInner, half), new THREE.Vector2(0, half), ]; - const geo = new THREE.LatheGeometry(pts, Math.max(20, segments)); + const geo = new THREE.LatheGeometry(pts, Math.max(28, segments)); geo.computeVertexNormals(); return geo; } /** - * Socket-head cap screw + integrated chamfered washer. + * Socket-head cap screw + integrated chamfered washer + subtle helical thread rings. */ function createFastenerGeometry(radius = 0.024, headHeight = 0.022, shankLength = 0.045): THREE.BufferGeometry { const parts: THREE.BufferGeometry[] = []; @@ -158,33 +390,38 @@ function createFastenerGeometry(radius = 0.024, headHeight = 0.022, shankLength const washerR = radius * 1.85; const washerH = Math.max(0.004, headHeight * 0.22); - // Washer base at y=0 - const washer = createChamferedCylinderGeometry(washerR, washerR, washerH, 24); + const washer = createChamferedCylinderGeometry(washerR, washerR, washerH, 28); washer.translate(0, washerH * 0.5, 0); parts.push(washer); - // Knurled socket head - const head = createChamferedCylinderGeometry(headR, headR, headHeight, 24); + const head = createChamferedCylinderGeometry(headR, headR, headHeight, 28); head.translate(0, washerH + headHeight * 0.5, 0); parts.push(head); - // Recessed dark hex socket cap detail ring - const socketRing = new THREE.CylinderGeometry(headR * 0.52, headR * 0.52, headHeight * 0.18, 6); - socketRing.translate(0, washerH + headHeight * 0.96, 0); + const socketRing = new THREE.CylinderGeometry(headR * 0.52, headR * 0.48, headHeight * 0.2, 6); + socketRing.translate(0, washerH + headHeight * 0.94, 0); parts.push(socketRing); - // Shank + subtle thread grooves when shankLength > 0.01 if (shankLength > 0.008) { - const shank = new THREE.CylinderGeometry(radius * 0.85, radius * 0.82, shankLength, 18); + const shank = createChamferedCylinderGeometry(radius * 0.84, radius * 0.8, shankLength, 20); shank.translate(0, -shankLength * 0.5, 0); parts.push(shank); + + const threadCount = Math.min(8, Math.max(2, Math.floor(shankLength / (radius * 0.42)))); + for (let i = 0; i < threadCount; i++) { + const ty = -shankLength * (0.18 + (i / threadCount) * 0.72); + const ridge = new THREE.TorusGeometry(radius * 0.85, radius * 0.08, 8, 20); + ridge.rotateX(Math.PI / 2); + ridge.translate(0, ty, 0); + parts.push(ridge); + } } return normalizeForMerge(parts); } /** - * Machined flange with central bore, raised boss, and perimeter cap screws. + * Machined flange with central bore, raised sealing boss, and perimeter cap screws. */ function createFlangeGeometry( outerRadius = 0.28, @@ -206,7 +443,7 @@ function createFlangeGeometry( new THREE.Vector2(innerRadius, half + thickness * 0.35), new THREE.Vector2(innerRadius, -half), ]; - parts.push(new THREE.LatheGeometry(pts, 40)); + parts.push(new THREE.LatheGeometry(pts, 48)); const boltCircleR = innerRadius + (outerRadius - innerRadius) * 0.66; const boltR = Math.min(0.022, (outerRadius - innerRadius) * 0.16); @@ -219,12 +456,15 @@ function createFlangeGeometry( return normalizeForMerge(parts); } -function createGasketGeometry(radius = 0.22, tube = 0.016, segments = 42): THREE.BufferGeometry { - const ring = new THREE.TorusGeometry(radius, tube, 16, Math.max(28, segments)); +function createGasketGeometry(radius = 0.22, tube = 0.016, segments = 48): THREE.BufferGeometry { + const ring = new THREE.TorusGeometry(radius, tube, 20, Math.max(32, segments)); ring.rotateX(Math.PI / 2); return ring; } +/** + * CNC-hobbed involute-profile gear with recessed web pocket and chamfered central boss collar. + */ function createGearGeometry( teeth: number, moduleSize: number, @@ -232,32 +472,40 @@ function createGearGeometry( boreRadius: number, ): THREE.BufferGeometry { const pitchR = (teeth * moduleSize) / 2; - const outerR = pitchR + moduleSize * 0.92; - const rootR = Math.max(boreRadius + 0.02, pitchR - moduleSize * 1.12); + const outerR = pitchR + moduleSize * 0.94; + const rootR = Math.max(boreRadius + 0.02, pitchR - moduleSize * 1.14); const shape = new THREE.Shape(); const step = (Math.PI * 2) / teeth; for (let i = 0; i < teeth; i++) { const a0 = i * step; - const a1 = a0 + step * 0.16; - const a2 = a0 + step * 0.31; - const a3 = a0 + step * 0.39; - const a4 = a0 + step * 0.61; - const a5 = a0 + step * 0.69; - const a6 = a0 + step * 0.84; - - const midR = (rootR + outerR) * 0.52; + const a1 = a0 + step * 0.14; + const a2 = a0 + step * 0.27; + const a3 = a0 + step * 0.38; + const a4 = a0 + step * 0.62; + const a5 = a0 + step * 0.73; + const a6 = a0 + step * 0.86; + + const pitchFlankR = pitchR * 1.01; const p0x = Math.cos(a0) * rootR; const p0y = Math.sin(a0) * rootR; if (i === 0) shape.moveTo(p0x, p0y); else shape.lineTo(p0x, p0y); shape.lineTo(Math.cos(a1) * rootR, Math.sin(a1) * rootR); - shape.lineTo(Math.cos(a2) * midR, Math.sin(a2) * midR); - shape.lineTo(Math.cos(a3) * outerR, Math.sin(a3) * outerR); + shape.quadraticCurveTo( + Math.cos(a2) * pitchFlankR, + Math.sin(a2) * pitchFlankR, + Math.cos(a3) * outerR, + Math.sin(a3) * outerR, + ); shape.lineTo(Math.cos(a4) * outerR, Math.sin(a4) * outerR); - shape.lineTo(Math.cos(a5) * midR, Math.sin(a5) * midR); - shape.lineTo(Math.cos(a6) * rootR, Math.sin(a6) * rootR); + shape.quadraticCurveTo( + Math.cos(a5) * pitchFlankR, + Math.sin(a5) * pitchFlankR, + Math.cos(a6) * rootR, + Math.sin(a6) * rootR, + ); } shape.closePath(); @@ -271,40 +519,46 @@ function createGearGeometry( const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: true, - bevelThickness: Math.min(0.014, thickness * 0.14), + bevelThickness: Math.min(0.014, thickness * 0.15), bevelSize: Math.min(0.009, moduleSize * 0.22), - bevelSegments: 2, - curveSegments: 8, + bevelSegments: 3, + curveSegments: 10, }); geo.center(); - // Add machined central hub boss collar when gear radius permits if (rootR > effectiveBore * 1.55) { - const hub = createHollowVesselGeometry( - Math.min(rootR * 0.56, effectiveBore + (rootR - effectiveBore) * 0.35), - effectiveBore, - thickness * 1.45, - false, - ); + const parts: THREE.BufferGeometry[] = [geo]; + const hubOuter = Math.min(rootR * 0.56, effectiveBore + (rootR - effectiveBore) * 0.36); + const hub = createHollowVesselGeometry(hubOuter, effectiveBore, thickness * 1.48, false); hub.rotateX(Math.PI / 2); - return normalizeForMerge([geo, hub]); + parts.push(hub); + + // Machined outer rim lip rings on both faces for authentic turned-gear relief + const rimRingR = (rootR + hubOuter) * 0.54; + if (rootR - hubOuter > 0.05) { + for (const sgn of [-1, 1]) { + const lip = new THREE.TorusGeometry(rimRingR, Math.min(0.007, thickness * 0.08), 10, 40); + lip.translate(0, 0, sgn * thickness * 0.52); + parts.push(lip); + } + } + return normalizeForMerge(parts); } return geo; } function createSpringGeometry(radius: number, wireRadius: number, height: number, coils: number): THREE.BufferGeometry { const points: THREE.Vector3[] = []; - const totalSteps = Math.max(36, Math.round(coils * 24)); + const totalSteps = Math.max(48, Math.round(coils * 28)); for (let i = 0; i <= totalSteps; i++) { const u = i / totalSteps; const angle = u * coils * Math.PI * 2; - // Slight squared end coils for authentic ground spring ends const endFlatten = Math.min(1, Math.min(u * 8, (1 - u) * 8)); const y = (u - 0.5) * height * (0.94 + 0.06 * endFlatten); points.push(new THREE.Vector3(Math.cos(angle) * radius, y, Math.sin(angle) * radius)); } const curve = new THREE.CatmullRomCurve3(points); - return new THREE.TubeGeometry(curve, totalSteps, wireRadius, 12, false); + return new THREE.TubeGeometry(curve, totalSteps, wireRadius, 16, false); } function createHollowVesselGeometry( @@ -340,7 +594,7 @@ function createHollowVesselGeometry( pts.push(new THREE.Vector2(innerRadius, -half + ch * 0.6)); pts.push(new THREE.Vector2(innerRadius + ch * 0.4, -half)); } - const geo = new THREE.LatheGeometry(pts, 48); + const geo = new THREE.LatheGeometry(pts, 56); geo.computeVertexNormals(); return geo; } @@ -348,25 +602,30 @@ function createHollowVesselGeometry( function createPipeWithCollars(rawPts: Vec3[], radius: number, closed: boolean): THREE.BufferGeometry { const vecs = rawPts.map((pt) => new THREE.Vector3(...pt)); const curve = new THREE.CatmullRomCurve3(vecs); - const tube = new THREE.TubeGeometry(curve, Math.max(24, vecs.length * 18), radius, 18, closed); + const tube = new THREE.TubeGeometry(curve, Math.max(32, vecs.length * 22), radius, 22, closed); if (closed || vecs.length < 2) return tube; const parts: THREE.BufferGeometry[] = [tube]; const up = new THREE.Vector3(0, 1, 0); - // Add machined brass/steel flared compression collars + sealed caps at open ends for (const endIdx of [0, 1]) { const u = endIdx === 0 ? 0.005 : 0.995; const pt = curve.getPointAt(u); const tan = curve.getTangentAt(u).normalize(); const quat = new THREE.Quaternion().setFromUnitVectors(up, tan); - const collar = createChamferedCylinderGeometry(radius * 1.48, radius * 1.48, radius * 1.4, 24); + // Hex compression nut + flared collar ferrule + const collar = createChamferedCylinderGeometry(radius * 1.48, radius * 1.48, radius * 1.35, 28); collar.applyQuaternion(quat); collar.translate(pt.x, pt.y, pt.z); parts.push(collar); - const cap = new THREE.SphereGeometry(radius * 0.96, 16, 12); + const hexNut = new THREE.CylinderGeometry(radius * 1.62, radius * 1.62, radius * 0.72, 6); + hexNut.applyQuaternion(quat); + hexNut.translate(pt.x, pt.y, pt.z); + parts.push(hexNut); + + const cap = new THREE.SphereGeometry(radius * 0.96, 18, 14); cap.translate(pt.x, pt.y, pt.z); parts.push(cap); } @@ -418,7 +677,6 @@ function applyCsgOperation( const mode = op === 'union' ? ADDITION : op === 'subtract' ? SUBTRACTION : INTERSECTION; const res = csgEvaluator.evaluate(b1, b2, mode); const out = res.geometry; - out.computeVertexNormals(); ensureBoxUVs(out); return out; } catch { @@ -442,7 +700,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif for (let i = 0; i < count; i++) { const angle = (i / count) * Math.PI * 2; const dist = mod.width ?? 0.25; - const hole = new THREE.CylinderGeometry(r, r, depth, 16); + const hole = new THREE.CylinderGeometry(r, r, depth, 24); orientGeometryAxis(hole, mod.axis); hole.translate(off[0] + Math.cos(angle) * dist, off[1], off[2] + Math.sin(angle) * dist); const next = applyCsgOperation(current, hole, 'subtract'); @@ -457,8 +715,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif if (mod.kind === 'slot' || mod.kind === 'groove' || mod.kind === 'seam') { if (mod.kind === 'seam' && mod.radius) { - // Circumferential machined parting seam ring - const ring = new THREE.TorusGeometry(mod.radius, mod.depth ?? 0.008, 12, 48); + const ring = new THREE.TorusGeometry(mod.radius, mod.depth ?? 0.008, 14, 52); ring.rotateX(Math.PI / 2); orientGeometryAxis(ring, mod.axis); ring.translate(off[0], off[1], off[2]); @@ -482,7 +739,6 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif const parts: THREE.BufferGeometry[] = [geo]; if (mod.radius) { - // Radial bolt circle for (let i = 0; i < count; i++) { const a = (i / count) * Math.PI * 2; const f = createFastenerGeometry(boltR, boltR * 0.9, boltR * 1.2); @@ -497,7 +753,6 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif parts.push(f); } } else { - // Rectangular corner bolts (e.g. housings, manifolds, plates) const hw = (mod.width ?? 0.4) * 0.5; const hl = (mod.length ?? 0.4) * 0.5; const corners: Array<[number, number]> = [ @@ -519,7 +774,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif if (mod.kind === 'gasket' || mod.kind === 'o_ring') { const r = mod.radius ?? 0.24; const tube = mod.width ?? 0.015; - const ring = createGasketGeometry(r, tube, 44); + const ring = createGasketGeometry(r, tube, 48); orientGeometryAxis(ring, mod.axis); ring.translate(off[0], off[1], off[2]); return normalizeForMerge([geo, ring]); @@ -546,6 +801,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif bevelEnabled: true, bevelThickness: 0.004, bevelSize: 0.004, + bevelSegments: 2, }); rib.translate(0, 0, -rt / 2); rib.translate(r, 0, 0); @@ -564,7 +820,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif const parts: THREE.BufferGeometry[] = [geo]; for (let i = 0; i < count; i++) { const y = count === 1 ? 0 : (i / (count - 1) - 0.5) * len; - const ring = new THREE.TorusGeometry(r, bead, 10, 36); + const ring = new THREE.TorusGeometry(r, bead, 12, 42); ring.rotateX(Math.PI / 2); orientGeometryAxis(ring, mod.axis); ring.translate(off[0], off[1] + y, off[2]); @@ -575,7 +831,7 @@ function applyConstructionModifier(geo: THREE.BufferGeometry, mod: GeometryModif if (mod.kind === 'chamfer' || mod.kind === 'bevel') { const r = mod.radius ?? 0.2; - const collar = createChamferedCylinderGeometry(r * 1.04, r * 1.04, mod.depth ?? 0.024, 36); + const collar = createChamferedCylinderGeometry(r * 1.04, r * 1.04, mod.depth ?? 0.024, 42); orientGeometryAxis(collar, mod.axis); collar.translate(off[0], off[1], off[2]); return normalizeForMerge([geo, collar]); @@ -612,8 +868,8 @@ export class GeometryKernel { } } - ensureBoxUVs(geo); - if (!geo.attributes.normal) geo.computeVertexNormals(); + // Apply CAD crease-angle smoothing (42 deg) + NaN-safe orthonormal tangents for anisotropic PBR + geo = finalizeCadNormalsAndTangents(geo); geo.computeBoundingBox(); geo.computeBoundingSphere(); this.cache.set(key, geo); @@ -629,10 +885,10 @@ export class GeometryKernel { const h = num(p, 'height', 0.5); const d = num(p, 'depth', 0.5); const minDim = Math.min(w, h, d); - if (minDim < 0.014) { + if (minDim < 0.008) { return new THREE.BoxGeometry(w, h, d); } - return createRoundedBoxGeometry(w, h, d, Math.min(0.016, minDim * 0.055), 2); + return createRoundedBoxGeometry(w, h, d, Math.min(0.018, minDim * 0.065), 3); } case 'rounded_box': @@ -641,13 +897,13 @@ export class GeometryKernel { num(p, 'height', 0.5), num(p, 'depth', 0.5), num(p, 'radius', 0.05), - 4, + 5, ); case 'cylinder': { const r = num(p, 'radius', 0.25); const h = num(p, 'height', 0.6); - const seg = Math.max(24, Math.round(num(p, 'segments', 44))); + const seg = Math.max(32, Math.round(num(p, 'segments', 52))); return createChamferedCylinderGeometry(r, r, h, seg); } @@ -656,31 +912,36 @@ export class GeometryKernel { num(p, 'radiusTop', 0.18), num(p, 'radiusBottom', 0.3), num(p, 'height', 0.6), - Math.max(24, Math.round(num(p, 'segments', 44))), + Math.max(32, Math.round(num(p, 'segments', 52))), ); case 'sphere': return new THREE.SphereGeometry( num(p, 'radius', 0.3), - Math.max(28, Math.round(num(p, 'widthSegments', 40))), - Math.max(20, Math.round(num(p, 'heightSegments', 28))), + Math.max(36, Math.round(num(p, 'widthSegments', 48))), + Math.max(24, Math.round(num(p, 'heightSegments', 34))), ); case 'ellipsoid': { - const g = new THREE.SphereGeometry(1, 38, 28); + const g = new THREE.SphereGeometry(1, 48, 36); g.scale(num(p, 'rx', 0.3), num(p, 'ry', 0.4), num(p, 'rz', 0.25)); return g; } case 'cone': - return new THREE.ConeGeometry(num(p, 'radius', 0.3), num(p, 'height', 0.6), 40); + return createChamferedCylinderGeometry( + Math.max(0.004, num(p, 'radius', 0.3) * 0.03), + num(p, 'radius', 0.3), + num(p, 'height', 0.6), + 48, + ); case 'torus': return new THREE.TorusGeometry( num(p, 'radius', 0.35), num(p, 'tube', 0.08), - 24, - Math.max(36, Math.round(num(p, 'segments', 64))), + 28, + Math.max(44, Math.round(num(p, 'segments', 72))), ); case 'tube': @@ -704,7 +965,7 @@ export class GeometryKernel { ); case 'dome': - return new THREE.SphereGeometry(num(p, 'radius', 0.35), 36, 22, 0, Math.PI * 2, 0, Math.PI * 0.5); + return new THREE.SphereGeometry(num(p, 'radius', 0.35), 44, 28, 0, Math.PI * 2, 0, Math.PI * 0.5); case 'extrude': { const pts = arr(p, 'points', [ @@ -721,8 +982,8 @@ export class GeometryKernel { bevelEnabled: p['bevel'] !== false, bevelThickness: num(p, 'bevelThickness', 0.016), bevelSize: num(p, 'bevelSize', 0.016), - bevelSegments: 3, - curveSegments: 12, + bevelSegments: 4, + curveSegments: 16, }); geo.center(); return geo; @@ -739,9 +1000,9 @@ export class GeometryKernel { let vecs = pts.map((pt) => new THREE.Vector2(pt[0], pt[1])); if (p['smooth'] && vecs.length >= 3) { const spline = new THREE.SplineCurve(vecs); - vecs = spline.getPoints(vecs.length * 4); + vecs = spline.getPoints(vecs.length * 5); } - const geo = new THREE.LatheGeometry(vecs, Math.max(28, Math.round(num(p, 'segments', 48)))); + const geo = new THREE.LatheGeometry(vecs, Math.max(36, Math.round(num(p, 'segments', 56)))); geo.computeVertexNormals(); return geo; } @@ -757,7 +1018,7 @@ export class GeometryKernel { [0, 0.3, 0], ]); const curve = new THREE.CatmullRomCurve3(pathPts.map((pt) => new THREE.Vector3(...pt))); - return new THREE.TubeGeometry(curve, 40, num(p, 'radius', 0.05), 16, false); + return new THREE.TubeGeometry(curve, 48, num(p, 'radius', 0.05), 20, false); } case 'rib': { @@ -774,7 +1035,7 @@ export class GeometryKernel { bevelEnabled: true, bevelThickness: 0.008, bevelSize: 0.008, - bevelSegments: 2, + bevelSegments: 3, }); geo.center(); return geo; @@ -816,7 +1077,7 @@ export class GeometryKernel { ); case 'gasket_ring': - return createGasketGeometry(num(p, 'radius', 0.24), num(p, 'tube', 0.016), Math.round(num(p, 'segments', 44))); + return createGasketGeometry(num(p, 'radius', 0.24), num(p, 'tube', 0.016), Math.round(num(p, 'segments', 48))); case 'bearing': { const outerR = num(p, 'outerRadius', 0.32); @@ -830,13 +1091,12 @@ export class GeometryKernel { const ballCount = Math.max(6, Math.round(num(p, 'balls', 10))); const midR = (outerR + innerR) / 2; const ballR = Math.max(0.016, (outerR - innerR - wall * 2) * 0.46); - // Retainer cage ring - const cage = new THREE.TorusGeometry(midR, ballR * 0.36, 10, 40); + const cage = new THREE.TorusGeometry(midR, ballR * 0.36, 12, 48); cage.rotateX(Math.PI / 2); parts.push(cage); for (let i = 0; i < ballCount; i++) { const a = (i / ballCount) * Math.PI * 2; - const ball = new THREE.SphereGeometry(ballR, 18, 14); + const ball = new THREE.SphereGeometry(ballR, 22, 16); ball.translate(Math.cos(a) * midR, 0, Math.sin(a) * midR); parts.push(ball); } @@ -851,7 +1111,7 @@ export class GeometryKernel { const gap = num(p, 'gap', 0.02); const parts: THREE.BufferGeometry[] = []; for (let i = 0; i < layers; i++) { - const box = createRoundedBoxGeometry(w, h, d, Math.min(0.015, h * 0.28), 2); + const box = createRoundedBoxGeometry(w, h, d, Math.min(0.015, h * 0.28), 3); box.translate(0, (i - (layers - 1) / 2) * (h + gap), 0); parts.push(box); } @@ -868,9 +1128,8 @@ export class GeometryKernel { new THREE.Vector3(0, mainLen * 0.28, 0), new THREE.Vector3(0, mainLen * 0.56, 0), ]); - parts.push(new THREE.TubeGeometry(trunkCurve, 18, r, 18, false)); - // Smooth organic collar cuff at base - const ostium = new THREE.TorusGeometry(r * 1.02, r * 0.16, 12, 24); + parts.push(new THREE.TubeGeometry(trunkCurve, 24, r, 22, false)); + const ostium = new THREE.TorusGeometry(r * 1.02, r * 0.16, 14, 28); ostium.rotateX(Math.PI / 2); parts.push(ostium); @@ -883,9 +1142,9 @@ export class GeometryKernel { new THREE.Vector3(Math.cos(a) * mainLen * 0.36, mainLen * 0.88, Math.sin(a) * mainLen * 0.36), ]; const bCurve = new THREE.CatmullRomCurve3(bPts); - parts.push(new THREE.TubeGeometry(bCurve, 16, r * 0.6, 16, false)); + parts.push(new THREE.TubeGeometry(bCurve, 20, r * 0.6, 20, false)); const tangent = bPts[2].clone().sub(bPts[1]).normalize(); - const cap = new THREE.TorusGeometry(r * 0.62, r * 0.1, 10, 20); + const cap = new THREE.TorusGeometry(r * 0.62, r * 0.1, 12, 24); const capQ = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), tangent); cap.applyQuaternion(capQ); cap.translate(bPts[2].x, bPts[2].y, bPts[2].z); @@ -905,12 +1164,10 @@ export class GeometryKernel { return geo; } - // Higher-level industrial parameterized generators case 'piston_cylinder': { const radius = num(p, 'radius', 0.32); const height = num(p, 'height', 0.36); const parts: THREE.BufferGeometry[] = []; - // Chamfered piston crown + stepped compression lands via LatheGeometry const half = height * 0.5; const pts = [ new THREE.Vector2(radius * 0.78, -half), @@ -925,26 +1182,29 @@ export class GeometryKernel { new THREE.Vector2(radius * 0.99, half * 0.6), new THREE.Vector2(radius * 0.99, half * 0.92), new THREE.Vector2(radius * 0.9, half), - new THREE.Vector2(radius * 0.45, half * 0.88), // Combustion bowl dish + new THREE.Vector2(radius * 0.45, half * 0.88), new THREE.Vector2(0, half * 0.88), ]; - parts.push(new THREE.LatheGeometry(pts, 44)); - const ring1 = new THREE.TorusGeometry(radius * 0.96, 0.011, 12, 40); + parts.push(new THREE.LatheGeometry(pts, 52)); + const ring1 = new THREE.TorusGeometry(radius * 0.965, 0.011, 14, 48); ring1.rotateX(Math.PI / 2); ring1.translate(0, half * 0.51, 0); - const ring2 = new THREE.TorusGeometry(radius * 0.96, 0.011, 12, 40); + const ring2 = new THREE.TorusGeometry(radius * 0.965, 0.011, 14, 48); ring2.rotateX(Math.PI / 2); ring2.translate(0, half * 0.19, 0); - const pin = createChamferedCylinderGeometry(radius * 0.22, radius * 0.22, radius * 1.82, 24); + const oilRing = new THREE.TorusGeometry(radius * 0.96, 0.008, 12, 48); + oilRing.rotateX(Math.PI / 2); + oilRing.translate(0, -half * 0.05, 0); + const pin = createChamferedCylinderGeometry(radius * 0.22, radius * 0.22, radius * 1.82, 28); pin.rotateZ(Math.PI / 2); pin.translate(0, -height * 0.18, 0); - const bossL = createChamferedCylinderGeometry(radius * 0.34, radius * 0.34, radius * 0.32, 20); + const bossL = createChamferedCylinderGeometry(radius * 0.34, radius * 0.34, radius * 0.32, 24); bossL.rotateZ(Math.PI / 2); bossL.translate(-radius * 0.72, -height * 0.18, 0); - const bossR = createChamferedCylinderGeometry(radius * 0.34, radius * 0.34, radius * 0.32, 20); + const bossR = createChamferedCylinderGeometry(radius * 0.34, radius * 0.34, radius * 0.32, 24); bossR.rotateZ(Math.PI / 2); bossR.translate(radius * 0.72, -height * 0.18, 0); - parts.push(ring1, ring2, pin, bossL, bossR); + parts.push(ring1, ring2, oilRing, pin, bossL, bossR); return normalizeForMerge(parts); } @@ -970,7 +1230,7 @@ export class GeometryKernel { case 'pump_unit': { const r = num(p, 'radius', 0.22); const len = num(p, 'length', 0.6); - const body = createChamferedCylinderGeometry(r, r, len, 36); + const body = createChamferedCylinderGeometry(r, r, len, 42); body.rotateZ(Math.PI / 2); const flangeL = createFlangeGeometry(r * 1.28, r * 0.38, 0.05, 4); flangeL.rotateZ(Math.PI / 2); @@ -978,11 +1238,11 @@ export class GeometryKernel { const flangeR = createFlangeGeometry(r * 1.18, r * 0.32, 0.045, 4); flangeR.rotateZ(-Math.PI / 2); flangeR.translate(len * 0.44, 0, 0); - const inlet = createChamferedCylinderGeometry(r * 0.34, r * 0.38, r * 1.45, 24); + const inlet = createChamferedCylinderGeometry(r * 0.34, r * 0.38, r * 1.45, 28); inlet.translate(0, r * 0.75, 0); - const inletCollar = createChamferedCylinderGeometry(r * 0.46, r * 0.46, 0.04, 24); + const inletCollar = createChamferedCylinderGeometry(r * 0.46, r * 0.46, 0.04, 28); inletCollar.translate(0, r * 1.38, 0); - const cradle = createRoundedBoxGeometry(len * 0.58, r * 0.28, r * 1.65, 0.015, 2); + const cradle = createRoundedBoxGeometry(len * 0.58, r * 0.28, r * 1.65, 0.015, 3); cradle.translate(0, -r * 0.92, 0); return normalizeForMerge([body, flangeL, flangeR, inlet, inletCollar, cradle]); } @@ -991,7 +1251,7 @@ export class GeometryKernel { const r = num(p, 'radius', 0.35); const len = num(p, 'length', 0.85); const parts: THREE.BufferGeometry[] = []; - const stator = createChamferedCylinderGeometry(r, r, len, 36); + const stator = createChamferedCylinderGeometry(r, r, len, 44); stator.rotateZ(Math.PI / 2); parts.push(stator); const endBellL = createFlangeGeometry(r * 1.05, r * 0.24, 0.06, 4); @@ -1001,7 +1261,7 @@ export class GeometryKernel { endBellR.rotateZ(-Math.PI / 2); endBellR.translate(len * 0.5, 0, 0); parts.push(endBellL, endBellR); - const fins = 14; + const fins = 16; for (let i = 0; i < fins; i++) { const a = (i / fins) * Math.PI * 2; const fin = createRoundedBoxGeometry(len * 0.78, 0.018, 0.055, 0.004, 2); @@ -1009,7 +1269,7 @@ export class GeometryKernel { fin.translate(0, Math.cos(a) * (r + 0.01), Math.sin(a) * (r + 0.01)); parts.push(fin); } - const shaft = createChamferedCylinderGeometry(r * 0.22, r * 0.22, len * 1.38, 24); + const shaft = createChamferedCylinderGeometry(r * 0.22, r * 0.22, len * 1.38, 28); shaft.rotateZ(Math.PI / 2); parts.push(shaft); return normalizeForMerge(parts); @@ -1019,7 +1279,7 @@ export class GeometryKernel { const w = num(p, 'width', 1.0); const d = num(p, 'depth', 0.7); const h = num(p, 'height', 0.04); - const parts: THREE.BufferGeometry[] = [createRoundedBoxGeometry(w, h, d, Math.min(0.016, h * 0.35), 2)]; + const parts: THREE.BufferGeometry[] = [createRoundedBoxGeometry(w, h, d, Math.min(0.016, h * 0.35), 3)]; const chips = Math.max(2, Math.round(num(p, 'chips', 5))); for (let i = 0; i < chips; i++) { const cw = w * 0.14; @@ -1030,14 +1290,12 @@ export class GeometryKernel { const z = (i % 2 === 0 ? 1 : -1) * d * 0.2; chip.translate(x, h * 0.9, z); parts.push(chip); - // Gull-wing IC leads along chip edges - for (let pin = -1; pin <= 1; pin++) { - const lead = new THREE.BoxGeometry(cw * 0.14, h * 0.35, cd * 1.24); - lead.translate(x + pin * cw * 0.32, h * 0.56, z); + for (let pin = -2; pin <= 2; pin++) { + const lead = new THREE.BoxGeometry(cw * 0.09, h * 0.35, cd * 1.24); + lead.translate(x + pin * cw * 0.18, h * 0.56, z); parts.push(lead); } } - // Corner mounting standoffs + fasteners for (const [sx, sz] of [ [-1, -1], [1, -1], @@ -1063,16 +1321,16 @@ export class GeometryKernel { plate.translate(x, 0, 0); parts.push(plate); } - const pipeTop = createChamferedCylinderGeometry(0.04, 0.04, w * 1.18, 24); + const pipeTop = createChamferedCylinderGeometry(0.04, 0.04, w * 1.18, 28); pipeTop.rotateZ(Math.PI / 2); pipeTop.translate(0, h * 0.25, 0); - const collarTopL = createChamferedCylinderGeometry(0.056, 0.056, 0.035, 24); + const collarTopL = createChamferedCylinderGeometry(0.056, 0.056, 0.035, 28); collarTopL.rotateZ(Math.PI / 2); collarTopL.translate(-w * 0.58, h * 0.25, 0); - const pipeBot = createChamferedCylinderGeometry(0.04, 0.04, w * 1.18, 24); + const pipeBot = createChamferedCylinderGeometry(0.04, 0.04, w * 1.18, 28); pipeBot.rotateZ(Math.PI / 2); pipeBot.translate(0, -h * 0.25, 0); - const collarBotR = createChamferedCylinderGeometry(0.056, 0.056, 0.035, 24); + const collarBotR = createChamferedCylinderGeometry(0.056, 0.056, 0.035, 28); collarBotR.rotateZ(Math.PI / 2); collarBotR.translate(w * 0.58, -h * 0.25, 0); parts.push(pipeTop, collarTopL, pipeBot, collarBotR); @@ -1083,12 +1341,12 @@ export class GeometryKernel { const w = num(p, 'width', 0.65); const h = num(p, 'height', 0.28); const d = num(p, 'depth', 0.35); - const block = createRoundedBoxGeometry(w, h, d, Math.min(0.03, h * 0.14), 3); - const port1 = createChamferedCylinderGeometry(0.052, 0.052, 0.13, 24); + const block = createRoundedBoxGeometry(w, h, d, Math.min(0.03, h * 0.14), 4); + const port1 = createChamferedCylinderGeometry(0.052, 0.052, 0.13, 28); port1.translate(-w * 0.25, h * 0.54, 0); const hexNut1 = new THREE.CylinderGeometry(0.068, 0.068, 0.045, 6); hexNut1.translate(-w * 0.25, h * 0.5, 0); - const port2 = createChamferedCylinderGeometry(0.052, 0.052, 0.13, 24); + const port2 = createChamferedCylinderGeometry(0.052, 0.052, 0.13, 28); port2.translate(w * 0.25, h * 0.54, 0); const hexNut2 = new THREE.CylinderGeometry(0.068, 0.068, 0.045, 6); hexNut2.translate(w * 0.25, h * 0.5, 0); @@ -1115,19 +1373,19 @@ export class GeometryKernel { const ax = Math.cos(a) * r; const ay = (i % 2 === 0 ? 1 : -1) * 0.09; const az = Math.sin(a) * r; - const s = new THREE.SphereGeometry(0.075, 22, 16); + const s = new THREE.SphereGeometry(0.075, 26, 20); s.translate(ax, ay, az); parts.push(s); const bond = new THREE.TubeGeometry( new THREE.LineCurve3(new THREE.Vector3(0, 0, 0), new THREE.Vector3(ax, ay, az)), 4, 0.016, - 10, + 12, false, ); parts.push(bond); } - const center = new THREE.SphereGeometry(0.11, 24, 18); + const center = new THREE.SphereGeometry(0.11, 28, 22); parts.push(center); return normalizeForMerge(parts); } @@ -1136,22 +1394,21 @@ export class GeometryKernel { const w = num(p, 'width', 1.4); const d = num(p, 'depth', 1.4); const h = num(p, 'height', 0.08); - const base = createRoundedBoxGeometry(w, h, d, 0.018, 3); + const base = createRoundedBoxGeometry(w, h, d, 0.018, 4); const parts: THREE.BufferGeometry[] = [base]; const cols = Math.max(2, Math.round(num(p, 'cores', 4))); for (let i = 0; i < cols; i++) { const row = Math.floor(i / 2); const col = i % 2; - const block = createRoundedBoxGeometry(w * 0.36, h * 0.65, d * 0.36, 0.01, 2); + const block = createRoundedBoxGeometry(w * 0.36, h * 0.65, d * 0.36, 0.01, 3); block.translate((col - 0.5) * w * 0.48, h * 0.75, (row - 0.5) * d * 0.48); parts.push(block); } - // Perimeter decoupling MLCC capacitors - for (let i = 0; i < 6; i++) { - const u = (i / 5 - 0.5) * w * 0.65; - const cap1 = createRoundedBoxGeometry(0.045, h * 0.42, 0.025, 0.004, 2); + for (let i = 0; i < 8; i++) { + const u = (i / 7 - 0.5) * w * 0.72; + const cap1 = createRoundedBoxGeometry(0.042, h * 0.44, 0.024, 0.004, 2); cap1.translate(u, h * 0.68, d * 0.43); - const cap2 = createRoundedBoxGeometry(0.045, h * 0.42, 0.025, 0.004, 2); + const cap2 = createRoundedBoxGeometry(0.042, h * 0.44, 0.024, 0.004, 2); cap2.translate(u, h * 0.68, -d * 0.43); parts.push(cap1, cap2); } @@ -1171,26 +1428,26 @@ export class GeometryKernel { return new THREE.TorusGeometry( num(p, 'radius', 0.14), num(p, 'tube', 0.025), - 18, - Math.max(28, Math.round(num(p, 'segments', 40))), + 20, + Math.max(32, Math.round(num(p, 'segments', 48))), ); } if (typeof p['width'] === 'number' || typeof p['depth'] === 'number') { const w = num(p, 'width', 0.12); const h = num(p, 'height', 0.06); const d = num(p, 'depth', 0.08); - return createRoundedBoxGeometry(w, h, d, Math.min(0.008, Math.min(w, h, d) * 0.12), 2); + return createRoundedBoxGeometry(w, h, d, Math.min(0.008, Math.min(w, h, d) * 0.12), 3); } return createChamferedCylinderGeometry( num(p, 'radius', 0.05), num(p, 'radius', 0.05), num(p, 'height', 0.05), - 24, + 28, ); } default: - return createRoundedBoxGeometry(0.4, 0.4, 0.4, 0.024, 2); + return createRoundedBoxGeometry(0.4, 0.4, 0.4, 0.024, 3); } } diff --git a/src/engine/illustration.ts b/src/engine/illustration.ts index 27c155a..cdff510 100644 --- a/src/engine/illustration.ts +++ b/src/engine/illustration.ts @@ -20,49 +20,73 @@ interface AestheticTheme { ink: string; mutedInk: string; accent: string; - fillPalette: string[]; + /** Light, mid, and shadow stops per component palette slot for smooth technical shading */ + fillPalette: Array<{ light: string; mid: string; shadow: string }>; strokeWidthPrimary: number; - strokeWidthSecondary: number; + strokeWidthCrease: number; + strokeWidthHidden: number; fontFamily: string; titlePrefix: string; + isDark: boolean; } const AESTHETIC_THEMES: Record = { patent: { bg: '#faf8f2', - paperBorder: '#292524', + paperBorder: '#1c1917', ink: '#1c1917', mutedInk: '#57534e', - accent: '#1c1917', - fillPalette: ['#ffffff', '#f5f2eb', '#ede9df', '#faf8f2'], - strokeWidthPrimary: 1.55, - strokeWidthSecondary: 0.75, + accent: '#9a3412', + fillPalette: [ + { light: '#ffffff', mid: '#f7f4ec', shadow: '#e7e2d5' }, + { light: '#fcfbf7', mid: '#f2ede2', shadow: '#dfd8c8' }, + { light: '#ffffff', mid: '#eee9dd', shadow: '#dad2c0' }, + { light: '#faf8f2', mid: '#ebe5d7', shadow: '#d5ccb8' }, + ], + strokeWidthPrimary: 1.75, + strokeWidthCrease: 0.72, + strokeWidthHidden: 0.55, fontFamily: '"IBM Plex Mono", monospace', titlePrefix: 'FIG. 1 — PATENT SPECIFICATION', + isDark: false, }, museum_plate: { bg: '#f4efe6', - paperBorder: '#44403c', + paperBorder: '#292524', ink: '#1f1d1a', mutedInk: '#6b655e', accent: '#9a3412', - fillPalette: ['#ebe3d5', '#dfd4c1', '#f7f3eb', '#d6c8b2'], - strokeWidthPrimary: 1.35, - strokeWidthSecondary: 0.7, + fillPalette: [ + { light: '#f8f4ec', mid: '#ebe3d5', shadow: '#cfc2ad' }, + { light: '#f2ece0', mid: '#dfd4c1', shadow: '#bfb096' }, + { light: '#faf7f0', mid: '#e6dccb', shadow: '#c7b8a0' }, + { light: '#efe8da', mid: '#d6c8b2', shadow: '#b3a186' }, + ], + strokeWidthPrimary: 1.65, + strokeWidthCrease: 0.68, + strokeWidthHidden: 0.5, fontFamily: '"Public Sans", sans-serif', titlePrefix: 'PLATE I — MUSEUM ARCHIVE', + isDark: false, }, industrial_manual: { bg: '#ffffff', paperBorder: '#0f172a', ink: '#0f172a', mutedInk: '#475569', - accent: '#2563eb', - fillPalette: ['#f1f5f9', '#e2e8f0', '#f8fafc', '#cbd5e1'], - strokeWidthPrimary: 1.6, - strokeWidthSecondary: 0.85, + accent: '#1d4ed8', + fillPalette: [ + { light: '#f8fafc', mid: '#e2e8f0', shadow: '#cbd5e1' }, + { light: '#f1f5f9', mid: '#dbe4ef', shadow: '#becad9' }, + { light: '#ffffff', mid: '#e8eef5', shadow: '#c5d1e0' }, + { light: '#f4f7fb', mid: '#d4dfec', shadow: '#b2c2d6' }, + ], + strokeWidthPrimary: 1.8, + strokeWidthCrease: 0.78, + strokeWidthHidden: 0.58, fontFamily: '"IBM Plex Mono", monospace', titlePrefix: 'MANUAL SECTION — ASSEMBLY DIAGRAM', + isDark: false, }, scientific_journal: { bg: '#ffffff', @@ -70,35 +94,56 @@ const AESTHETIC_THEMES: Record = { ink: '#0f172a', mutedInk: '#64748b', accent: '#0284c7', - fillPalette: ['#f0f9ff', '#e0f2fe', '#f8fafc', '#f1f5f9'], - strokeWidthPrimary: 1.3, - strokeWidthSecondary: 0.65, + fillPalette: [ + { light: '#f8fcff', mid: '#e0f2fe', shadow: '#bae6fd' }, + { light: '#f8fafc', mid: '#e2e8f0', shadow: '#cbd5e1' }, + { light: '#f0f9ff', mid: '#dbeafe', shadow: '#bfdbfe' }, + { light: '#f8fafc', mid: '#f1f5f9', shadow: '#cbd5e1' }, + ], + strokeWidthPrimary: 1.5, + strokeWidthCrease: 0.65, + strokeWidthHidden: 0.48, fontFamily: '"Plus Jakarta Sans", sans-serif', titlePrefix: 'FIG. 1 — TECHNICAL SCHEMATIC', + isDark: false, }, minimal_editorial: { bg: '#f8fafc', - paperBorder: '#cbd5e1', + paperBorder: '#94a3b8', ink: '#18181b', mutedInk: '#71717a', - accent: '#3b82f6', - fillPalette: ['#ffffff', '#f4f4f5', '#e4e4e7', '#fafafa'], - strokeWidthPrimary: 1.25, - strokeWidthSecondary: 0.6, + accent: '#2563eb', + fillPalette: [ + { light: '#ffffff', mid: '#f4f4f5', shadow: '#e4e4e7' }, + { light: '#fafafa', mid: '#ededf0', shadow: '#d4d4d8' }, + { light: '#ffffff', mid: '#f1f5f9', shadow: '#cbd5e1' }, + { light: '#f9fafb', mid: '#e5e7eb', shadow: '#d1d5db' }, + ], + strokeWidthPrimary: 1.45, + strokeWidthCrease: 0.6, + strokeWidthHidden: 0.45, fontFamily: '"Plus Jakarta Sans", sans-serif', titlePrefix: 'SYSTEM OVERVIEW', + isDark: false, }, technical_atlas: { - bg: '#0f141c', - paperBorder: '#273244', + bg: '#0c1118', + paperBorder: '#273549', ink: '#e2e8f0', mutedInk: '#94a3b8', accent: '#38bdf8', - fillPalette: ['#17202e', '#1e293b', '#131b26', '#253347'], - strokeWidthPrimary: 1.4, - strokeWidthSecondary: 0.7, + fillPalette: [ + { light: '#243247', mid: '#17202e', shadow: '#0e1520' }, + { light: '#2b3b54', mid: '#1c2738', shadow: '#111824' }, + { light: '#212e42', mid: '#141d2b', shadow: '#0b1019' }, + { light: '#2e4059', mid: '#1f2b3d', shadow: '#131b29' }, + ], + strokeWidthPrimary: 1.65, + strokeWidthCrease: 0.72, + strokeWidthHidden: 0.52, fontFamily: '"IBM Plex Mono", monospace', titlePrefix: 'ATLAS PLATE — VECTOR PROJECTION', + isDark: true, }, }; @@ -106,12 +151,29 @@ function escapeXml(str: string): string { return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } +function parseHexRgb(hex: string): [number, number, number] { + const clean = hex.replace('#', ''); + const n = parseInt(clean.length === 3 ? clean.replace(/(.)/g, '$1$1') : clean, 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +} + +function mixHexColor(a: string, b: string, t: number): string { + const [r1, g1, b1] = parseHexRgb(a); + const [r2, g2, b2] = parseHexRgb(b); + const k = Math.max(0, Math.min(1, t)); + const r = Math.round(r1 + (r2 - r1) * k); + const g = Math.round(g1 + (g2 - g1) * k); + const bl = Math.round(b1 + (b2 - b1) * k); + return `#${((1 << 24) + (r << 16) + (g << 8) + bl).toString(16).slice(1)}`; +} + interface ProjectedTriangle { pts: Array<[number, number]>; depth: number; fill: string; shade: number; componentId: string; + compIndex: number; } interface ProjectedEdge { @@ -120,13 +182,24 @@ interface ProjectedEdge { x2: number; y2: number; depth: number; - isSilhouette: boolean; + kind: 'silhouette' | 'crease' | 'hidden'; +} + +interface ExplosionAxisLine { + x1: number; + y1: number; + x2: number; + y2: number; } /** * Generates publication-grade vector SVG derived directly from the 3D geometry of the project. - * Extracts feature edges via crease angle threshold (never dumps raw triangulation edges), - * culls backfaces, sorts faces by depth, resolves overlapping callouts, and draws leader lines. + * Features: + * - Hierarchical two-weight ink linework: bold outer silhouette contours + crisp internal crease edges + * - Hidden-line dashed interior ghosting for cutaway/casing depth + * - Lambertian + rim-lit three-stop tonal shading per component + * - Exploded-view dashed axial disassembly datum lines connecting displaced parts to seated origins + * - Collision-free numbered callout bubbles + elbow leader lines + technical Parts Schedule */ export function generateTechnicalIllustrationSVG( project: DecoderProject, @@ -139,22 +212,21 @@ export function generateTechnicalIllustrationSVG( const explosion = options.explosion ?? 0.25; const plan = buildExplosionPlan(project); - // Build orthographic projection camera based on requested projection const cam = new THREE.OrthographicCamera(-2, 2, 2, -2, 0.1, 100); if (options.projection === 'front') cam.position.set(0, 0, 12); else if (options.projection === 'side') cam.position.set(12, 0, 0); else if (options.projection === 'top') cam.position.set(0, 12, 0.01); - else cam.position.set(8.5, 6.8, 9.2); // Clean axonometric 3/4 view + else cam.position.set(8.5, 6.8, 9.2); cam.lookAt(0, 0, 0); cam.updateMatrixWorld(); - // Compute world-space component transforms & overall bounds const byId = new Map(project.components.map((c) => [c.id, c])); - const worldMatrices = new Map(); + const assembledMatrices = new Map(); + const explodedMatrices = new Map(); - function getMatrix(id: string, visiting = new Set()): THREE.Matrix4 { - if (worldMatrices.has(id)) return worldMatrices.get(id)!; + function getAssembledMatrix(id: string, visiting = new Set()): THREE.Matrix4 { + if (assembledMatrices.has(id)) return assembledMatrices.get(id)!; if (visiting.has(id)) return new THREE.Matrix4(); visiting.add(id); @@ -166,7 +238,27 @@ export function generateTechnicalIllustrationSVG( const scl = new THREE.Vector3(...(comp.transform?.scale ?? [1, 1, 1])); local.compose(pos, quat, scl); if (comp.parentId && byId.has(comp.parentId)) { - local.premultiply(getMatrix(comp.parentId, visiting)); + local.premultiply(getAssembledMatrix(comp.parentId, visiting)); + } + } + assembledMatrices.set(id, local); + return local; + } + + function getExplodedMatrix(id: string, visiting = new Set()): THREE.Matrix4 { + if (explodedMatrices.has(id)) return explodedMatrices.get(id)!; + if (visiting.has(id)) return new THREE.Matrix4(); + visiting.add(id); + + const comp = byId.get(id); + const local = new THREE.Matrix4(); + if (comp) { + const pos = new THREE.Vector3(...(comp.transform?.position ?? [0, 0, 0])); + const quat = new THREE.Quaternion().setFromEuler(new THREE.Euler(...(comp.transform?.rotation ?? [0, 0, 0]))); + const scl = new THREE.Vector3(...(comp.transform?.scale ?? [1, 1, 1])); + local.compose(pos, quat, scl); + if (comp.parentId && byId.has(comp.parentId)) { + local.premultiply(getExplodedMatrix(comp.parentId, visiting)); } if (explosion > 0) { const expOff = computeHierarchicalExplosionOffset(comp, explosion, plan); @@ -175,31 +267,37 @@ export function generateTechnicalIllustrationSVG( local.elements[14] += expOff[2]; } } - worldMatrices.set(id, local); + explodedMatrices.set(id, local); return local; } - // First pass: collect projected coordinates in camera space to auto-fit viewport cleanly const camInv = cam.matrixWorldInverse; const viewBounds = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity }; const componentCenters = new Map(); + const assembledCenters = new Map(); const compData: Array<{ comp: (typeof project.components)[number]; geo: THREE.BufferGeometry; mat: THREE.Matrix4; - color: string; + stops: { light: string; mid: string; shadow: string }; + index: number; }> = []; project.components.forEach((comp, idx) => { if (!comp.geometry || comp.visible === false || comp.layer === 'fluid') return; const geo = kernel.buildGeometry(comp.geometry); - const mat = getMatrix(comp.id); + const mat = getExplodedMatrix(comp.id); + const baseMat = getAssembledMatrix(comp.id); const posAttr = geo.attributes.position; const v = new THREE.Vector3(); + const vBase = new THREE.Vector3(); let sx = 0, sy = 0, sz = 0, + bx = 0, + by = 0, + bz = 0, cnt = 0; for (let i = 0; i < posAttr.count; i++) { @@ -211,17 +309,28 @@ export function generateTechnicalIllustrationSVG( sx += v.x; sy += v.y; sz += v.z; + + if (explosion > 0.02) { + vBase.fromBufferAttribute(posAttr, i).applyMatrix4(baseMat).applyMatrix4(camInv); + bx += vBase.x; + by += vBase.y; + bz += vBase.z; + } cnt++; } if (cnt > 0) { componentCenters.set(comp.id, { x: sx / cnt, y: sy / cnt, z: sz / cnt }); + if (explosion > 0.02) { + assembledCenters.set(comp.id, { x: bx / cnt, y: by / cnt, z: bz / cnt }); + } } compData.push({ comp, geo, mat, - color: theme.fillPalette[idx % theme.fillPalette.length], + stops: theme.fillPalette[idx % theme.fillPalette.length], + index: idx, }); }); @@ -229,7 +338,7 @@ export function generateTechnicalIllustrationSVG( const drawAreaH = height - 150; const spanX = Math.max(0.2, viewBounds.maxX - viewBounds.minX); const spanY = Math.max(0.2, viewBounds.maxY - viewBounds.minY); - const scale = Math.min((drawAreaW - 110) / spanX, (drawAreaH - 90) / spanY); + const scale = Math.min((drawAreaW - 115) / spanX, (drawAreaH - 95) / spanY); const cx = (viewBounds.minX + viewBounds.maxX) / 2; const cy = (viewBounds.minY + viewBounds.maxY) / 2; const originX = 56 + drawAreaW / 2; @@ -240,10 +349,25 @@ export function generateTechnicalIllustrationSVG( originY - (vy - cy) * scale, ]; - // Collect visible front-facing triangles & crease feature edges (threshold 24 degrees) + // Collect exploded-view axial datum lines in screen coordinates + const explosionAxes: ExplosionAxisLine[] = []; + if (explosion > 0.02) { + for (const item of compData) { + const cExp = componentCenters.get(item.comp.id); + const cBase = assembledCenters.get(item.comp.id); + if (!cExp || !cBase) continue; + const [x1, y1] = toScreen(cBase.x, cBase.y); + const [x2, y2] = toScreen(cExp.x, cExp.y); + if (Math.hypot(x2 - x1, y2 - y1) >= 10) { + explosionAxes.push({ x1, y1, x2, y2 }); + } + } + } + const triangles: ProjectedTriangle[] = []; const edges: ProjectedEdge[] = []; - const lightDir = new THREE.Vector3(0.45, 0.7, 0.55).normalize(); + const keyLightDir = new THREE.Vector3(0.48, 0.72, 0.5).normalize(); + const rimLightDir = new THREE.Vector3(-0.6, 0.35, -0.7).normalize(); for (const item of compData) { const pos = item.geo.attributes.position; @@ -258,8 +382,7 @@ export function generateTechnicalIllustrationSVG( const ac = new THREE.Vector3(); const normal = new THREE.Vector3(); - // Subsample super-dense meshes cleanly for crisp vector performance while preserving silhouette - const step = triCount > 1600 ? Math.ceil(triCount / 900) : 1; + const step = triCount > 1800 ? Math.ceil(triCount / 960) : 1; for (let t = 0; t < triCount; t += step) { const i0 = idx ? idx.getX(t * 3) : t * 3; @@ -274,21 +397,29 @@ export function generateTechnicalIllustrationSVG( ac.subVectors(c, a); normal.crossVectors(ab, ac).normalize(); - // Backface cull in camera space (+Z faces viewer) - if (normal.z <= 0.02) continue; + if (normal.z <= 0.015) continue; + + const ndotl = Math.max(0, normal.dot(keyLightDir)); + const rim = Math.pow(Math.max(0, 1 - normal.z), 2.2) * Math.max(0, normal.dot(rimLightDir)) * 0.35; + const shade = Math.max(0, Math.min(1, ndotl * 0.85 + rim + 0.12)); + + const fill = + shade >= 0.55 + ? mixHexColor(item.stops.mid, item.stops.light, (shade - 0.55) / 0.45) + : mixHexColor(item.stops.shadow, item.stops.mid, shade / 0.55); - const shade = Math.max(0.15, Math.min(1, normal.dot(lightDir) * 0.55 + 0.45)); triangles.push({ pts: [toScreen(a.x, a.y), toScreen(b.x, b.y), toScreen(c.x, c.y)], depth: (a.z + b.z + c.z) / 3, - fill: item.color, + fill, shade, componentId: item.comp.id, + compIndex: item.index, }); } - // Feature edge extraction (EdgesGeometry threshold 24 deg -> NEVER renders flat triangulation lines!) - const edgesGeo = new THREE.EdgesGeometry(item.geo, 24); + // 1. Crisp internal mechanical crease lines (26 deg threshold) + const edgesGeo = new THREE.EdgesGeometry(item.geo, 26); const ePos = edgesGeo.attributes.position; const p1 = new THREE.Vector3(); const p2 = new THREE.Vector3(); @@ -297,21 +428,20 @@ export function generateTechnicalIllustrationSVG( p2.fromBufferAttribute(ePos, i + 1).applyMatrix4(mv); const [x1, y1] = toScreen(p1.x, p1.y); const [x2, y2] = toScreen(p2.x, p2.y); - if (Math.hypot(x2 - x1, y2 - y1) < 1.2) continue; + if (Math.hypot(x2 - x1, y2 - y1) < 1.1) continue; edges.push({ x1, y1, x2, y2, depth: (p1.z + p2.z) / 2, - isSilhouette: true, + kind: 'crease', }); } edgesGeo.dispose(); - // If smooth curved geometry (torus, sphere, dome, ellipsoid) produced very few crease edges, - // extract true view-space silhouette edges where adjacent triangles flip front/back orientation. - if (ePos.count < 16 && triCount <= 3200) { + // 2. Bold outer silhouette contours where adjacent triangles flip front/back orientation + if (triCount <= 4200) { const edgeFaces = new Map(); const qKey = (v: THREE.Vector3) => `${Math.round(v.x * 1000)},${Math.round(v.y * 1000)},${Math.round(v.z * 1000)}`; @@ -354,72 +484,102 @@ export function generateTechnicalIllustrationSVG( const [x1, y1] = toScreen(rec.v0.x, rec.v0.y); const [x2, y2] = toScreen(rec.v1.x, rec.v1.y); if (Math.hypot(x2 - x1, y2 - y1) < 1.0) continue; - edges.push({ x1, y1, x2, y2, depth: rec.zAvg, isSilhouette: true }); + edges.push({ x1, y1, x2, y2, depth: rec.zAvg, kind: 'silhouette' }); } } } - // Painter's sort back-to-front triangles.sort((t1, t2) => t1.depth - t2.depth); - edges.sort((e1, e2) => e1.depth - e2.depth); + edges.sort((e1, e2) => { + if (Math.abs(e1.depth - e2.depth) > 0.01) return e1.depth - e2.depth; + // Draw bold silhouettes on top of interior crease lines at equal depth + return e1.kind === 'silhouette' ? 1 : -1; + }); - // Build SVG string const parts: string[] = []; parts.push( ``, ); - // Hatching pattern for section aesthetics + // Hatching patterns (45-degree primary & -45-degree counter-hatch for adjacent sectioned parts) parts.push(` - - + + + + + `); - // Sheet border & title block + // Sheet border, corner registration ticks & technical title block + parts.push( + ``, + ``, + ); + + // Drafting center registration marks on frame borders + const midX = (drawAreaW + 56) / 2; + const midY = height / 2; parts.push( - ``, - ``, + ``, + ``, + ``, ); parts.push( - `${escapeXml(theme.titlePrefix)}`, - `${escapeXml(project.title)} — ${escapeXml(project.subtitle)}`, - ``, + `${escapeXml(theme.titlePrefix)}`, + `${escapeXml(project.title)} — ${escapeXml(project.subtitle)}`, + ``, ); + // Exploded-view axial assembly guide lines behind faces + if (explosionAxes.length > 0) { + parts.push(''); + for (const ax of explosionAxes) { + parts.push( + ``, + ``, + ); + } + parts.push(''); + } + // Render shaded polygons parts.push(''); for (const tri of triangles) { const ptsStr = tri.pts.map((p) => `${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' '); - const opacity = options.aesthetic === 'patent' ? 0.96 : (0.55 + tri.shade * 0.45).toFixed(2); + const opacity = options.aesthetic === 'patent' ? 0.97 : (0.78 + tri.shade * 0.22).toFixed(2); parts.push( - ``, + ``, ); } parts.push(''); - // Optional subtle cross-hatching accent on alternate components + // Cross-hatching on shadowed facets of alternating components if (options.showHatching) { - parts.push(''); - for (let i = 0; i < triangles.length; i += 7) { + parts.push(''); + for (let i = 0; i < triangles.length; i += 5) { const tri = triangles[i]; + if (tri.shade > 0.68) continue; const ptsStr = tri.pts.map((p) => `${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' '); - parts.push(``); + const patId = tri.compIndex % 2 === 0 ? 'hatchPatternA' : 'hatchPatternB'; + parts.push(``); } parts.push(''); } - // Render selective feature edges + // Two-weight ink linework: internal creases + bold outer silhouettes parts.push(''); for (const e of edges) { + const sw = e.kind === 'silhouette' ? theme.strokeWidthPrimary : theme.strokeWidthCrease; + const op = e.kind === 'silhouette' ? 0.92 : 0.56; parts.push( - ``, + ``, ); } parts.push(''); - // Numbered Callouts + Non-overlapping Leader Lines + // Numbered Callouts + Non-overlapping Elbow Leader Lines const listedComponents = compData.slice(0, 14); if (options.showCallouts !== false && listedComponents.length > 0) { const rawLabels = listedComponents.map((item, idx) => { @@ -432,24 +592,25 @@ export function generateTechnicalIllustrationSVG( anchorY: sy, x: sx + side * (drawAreaW * 0.34), y: sy + (idx % 2 === 0 ? -1 : 1) * 18, - width: 32, - height: 24, + width: 34, + height: 26, num: idx + 1, name: item.comp.name, }; }); - const resolved = resolveLabelOverlaps(rawLabels, drawAreaW + 50, height - 80, 22); + const resolved = resolveLabelOverlaps(rawLabels, drawAreaW + 50, height - 80, 24); parts.push(''); resolved.forEach((lbl, i) => { const orig = rawLabels[i]; const lx = Math.max(48, Math.min(drawAreaW + 24, lbl.x)); const ly = Math.max(110, Math.min(height - 54, lbl.y)); + const elbowX = lx + (lx >= orig.anchorX ? -16 : 16); parts.push( - ``, + ``, ``, - ``, - `${orig.num}`, + ``, + `${orig.num}`, ); }); parts.push(''); @@ -460,9 +621,9 @@ export function generateTechnicalIllustrationSVG( const px = drawAreaW + 76; const pw = width - px - 42; parts.push( - ``, - `PARTS SCHEDULE`, - ``, + ``, + `PARTS SCHEDULE`, + ``, ); listedComponents.forEach((item, idx) => { @@ -477,9 +638,10 @@ export function generateTechnicalIllustrationSVG( }); } - // Footer provenance line + // Engineering Title-Block Provenance Footer parts.push( - `DECODER TECHNICAL ILLUSTRATION · PROJECTION: ${options.projection.toUpperCase()} · UNITS: ${project.unit.toUpperCase()} · EXPLOSION: ${Math.round(explosion * 100)}%`, + ``, + `DECODER TECHNICAL ILLUSTRATION · PROJECTION: ${options.projection.toUpperCase()} · UNITS: ${project.unit.toUpperCase()} · EXPLOSION: ${Math.round(explosion * 100)}%`, ); parts.push(''); diff --git a/src/engine/materials.ts b/src/engine/materials.ts index 6dd4b46..8348919 100644 --- a/src/engine/materials.ts +++ b/src/engine/materials.ts @@ -25,96 +25,96 @@ export const LIGHTING_PRESETS: Record = technical_studio: { id: 'technical_studio', label: 'Technical Studio', - background: '#11141a', - fogColor: '#11141a', - fogDensity: 0.015, - keyColor: '#fff6ea', - keyIntensity: 2.35, + background: '#0e1117', + fogColor: '#0e1117', + fogDensity: 0.014, + keyColor: '#fff4e0', + keyIntensity: 2.45, keyPosition: [6, 9, 7], fillSkyColor: '#c2d8f8', - fillGroundColor: '#1e242f', - fillIntensity: 0.85, - rimColor: '#93c5fd', - rimIntensity: 1.18, + fillGroundColor: '#10141d', + fillIntensity: 0.68, + rimColor: '#7dd3fc', + rimIntensity: 1.35, exposure: 1.08, - gridColor: '#2a3241', - gridOpacity: 0.42, + gridColor: '#262e3d', + gridOpacity: 0.36, isLightBackdrop: false, }, museum_exhibit: { id: 'museum_exhibit', label: 'Museum Exhibit', - background: '#0c0d10', - fogColor: '#0c0d10', - fogDensity: 0.02, + background: '#0a0b0e', + fogColor: '#0a0b0e', + fogDensity: 0.018, keyColor: '#ffe7c4', - keyIntensity: 2.15, + keyIntensity: 2.25, keyPosition: [4, 10, 5], fillSkyColor: '#9ab0cc', - fillGroundColor: '#161311', - fillIntensity: 0.56, + fillGroundColor: '#14110f', + fillIntensity: 0.48, rimColor: '#fde68a', - rimIntensity: 0.88, - exposure: 0.98, - gridColor: '#23262e', - gridOpacity: 0.24, + rimIntensity: 0.96, + exposure: 1.02, + gridColor: '#21242c', + gridOpacity: 0.22, isLightBackdrop: false, }, photographic_product: { id: 'photographic_product', label: 'Photographic Product', - background: '#191c24', - fogColor: '#191c24', - fogDensity: 0.01, + background: '#151820', + fogColor: '#151820', + fogDensity: 0.009, keyColor: '#ffffff', - keyIntensity: 2.55, + keyIntensity: 2.6, keyPosition: [7, 8.5, 6], fillSkyColor: '#dbeafe', - fillGroundColor: '#262932', - fillIntensity: 0.98, + fillGroundColor: '#1e2129', + fillIntensity: 0.82, rimColor: '#e0f2fe', - rimIntensity: 1.32, - exposure: 1.12, - gridColor: '#313744', - gridOpacity: 0.28, + rimIntensity: 1.42, + exposure: 1.1, + gridColor: '#2e3442', + gridOpacity: 0.25, isLightBackdrop: false, }, clinical_illustration: { id: 'clinical_illustration', label: 'Clinical Illustration', - background: '#e9eef4', - fogColor: '#e9eef4', - fogDensity: 0.008, + background: '#eaeff5', + fogColor: '#eaeff5', + fogDensity: 0.007, keyColor: '#fffaf5', keyIntensity: 2.15, keyPosition: [5, 10, 6], fillSkyColor: '#eff6ff', fillGroundColor: '#cbd5e1', - fillIntensity: 1.15, + fillIntensity: 1.05, rimColor: '#bae6fd', - rimIntensity: 0.78, + rimIntensity: 0.82, exposure: 1.0, gridColor: '#cbd5e1', - gridOpacity: 0.45, + gridOpacity: 0.42, isLightBackdrop: true, }, dark_lab: { id: 'dark_lab', label: 'Dark Scientific Lab', - background: '#07090d', - fogColor: '#07090d', - fogDensity: 0.022, + background: '#06080c', + fogColor: '#06080c', + fogDensity: 0.02, keyColor: '#e0f2fe', keyIntensity: 2.45, keyPosition: [5, 8, 5], fillSkyColor: '#60a5fa', - fillGroundColor: '#0f172a', - fillIntensity: 0.65, + fillGroundColor: '#0c1220', + fillIntensity: 0.55, rimColor: '#38bdf8', - rimIntensity: 1.38, - exposure: 1.06, - gridColor: '#1e293b', - gridOpacity: 0.36, + rimIntensity: 1.45, + exposure: 1.05, + gridColor: '#1c2638', + gridOpacity: 0.34, isLightBackdrop: false, }, white_engineering: { @@ -122,18 +122,18 @@ export const LIGHTING_PRESETS: Record = label: 'White Engineering Sheet', background: '#f5f6f8', fogColor: '#f5f6f8', - fogDensity: 0.006, + fogDensity: 0.005, keyColor: '#ffffff', keyIntensity: 2.05, keyPosition: [6, 10, 7], fillSkyColor: '#f8fafc', fillGroundColor: '#d4d8df', - fillIntensity: 1.2, + fillIntensity: 1.1, rimColor: '#94a3b8', - rimIntensity: 0.65, + rimIntensity: 0.68, exposure: 0.98, gridColor: '#cbd5e1', - gridOpacity: 0.55, + gridOpacity: 0.5, isLightBackdrop: true, }, }; @@ -145,6 +145,7 @@ export interface MaterialPresetDefaults { clearcoat?: number; clearcoatRoughness?: number; anisotropy?: number; + anisotropyRotation?: number; transmission?: number; ior?: number; thickness?: number; @@ -153,291 +154,466 @@ export interface MaterialPresetDefaults { opacity?: number; sheen?: number; sheenColor?: string; + sheenRoughness?: number; iridescence?: number; + iridescenceIOR?: number; + iridescenceThicknessRange?: [number, number]; + specularIntensity?: number; + specularColor?: string; envMapIntensity?: number; normalScale?: number; + clearcoatNormalScale?: number; } +/** + * Tuned for immediate material separation even at mobile thumbnail size: + * - Brushed steel: cool crisp silver-slate (#cdd6e2) with sharp directional grain + * - Brass: rich horological CuZn37 gold (#ebb844) with warm specular tint so it never blends into steel + * - Glass / Watch Crystal: sapphire anti-reflective (AR) blue-cyan thin-film iridescence + crisp edge coat + */ export const MATERIAL_PRESET_DEFAULTS: Record = { polished_metal: { - color: '#dce2ea', - roughness: 0.11, - metalness: 0.96, - clearcoat: 0.24, - clearcoatRoughness: 0.09, - envMapIntensity: 1.08, - normalScale: 0.08, + color: '#e6ecf2', + roughness: 0.07, + metalness: 0.99, + anisotropy: 0.24, + clearcoat: 0.22, + clearcoatRoughness: 0.05, + envMapIntensity: 1.45, + normalScale: 0.05, }, brushed_steel: { - color: '#b8c0cc', - roughness: 0.28, - metalness: 0.92, - anisotropy: 0.35, - envMapIntensity: 1.04, - normalScale: 0.16, + color: '#cbd4e0', + roughness: 0.22, + metalness: 0.96, + anisotropy: 0.78, + anisotropyRotation: 0, + specularColor: '#e2eeff', + clearcoat: 0.08, + clearcoatRoughness: 0.2, + envMapIntensity: 1.38, + normalScale: 0.3, }, cast_aluminium: { - color: '#9ca4b0', - roughness: 0.46, - metalness: 0.85, - envMapIntensity: 1.02, - normalScale: 0.18, + color: '#9ea8b6', + roughness: 0.44, + metalness: 0.89, + anisotropy: 0.12, + clearcoat: 0.04, + clearcoatRoughness: 0.42, + envMapIntensity: 1.18, + normalScale: 0.36, }, brass: { - color: '#dcb04f', - roughness: 0.2, - metalness: 0.96, - anisotropy: 0.65, - envMapIntensity: 1.45, - normalScale: 0.36, + color: '#edb942', + roughness: 0.15, + metalness: 0.98, + anisotropy: 0.72, + anisotropyRotation: Math.PI * 0.5, + specularColor: '#ffe599', + iridescence: 0.06, + iridescenceIOR: 1.45, + iridescenceThicknessRange: [180, 320], + envMapIntensity: 1.58, + normalScale: 0.28, }, copper: { - color: '#d0784a', - roughness: 0.21, - metalness: 0.96, - anisotropy: 0.58, - envMapIntensity: 1.45, - normalScale: 0.34, + color: '#e07b48', + roughness: 0.17, + metalness: 0.98, + anisotropy: 0.66, + anisotropyRotation: Math.PI * 0.5, + specularColor: '#ffc299', + iridescence: 0.1, + iridescenceIOR: 1.5, + iridescenceThicknessRange: [200, 400], + envMapIntensity: 1.52, + normalScale: 0.26, }, chrome: { - color: '#eef2f7', - roughness: 0.04, + color: '#f4f7fb', + roughness: 0.025, metalness: 1.0, clearcoat: 0.35, - clearcoatRoughness: 0.04, - envMapIntensity: 1.6, - normalScale: 0.08, + clearcoatRoughness: 0.025, + envMapIntensity: 1.72, + normalScale: 0.03, }, ceramic: { - color: '#f3f0ea', - roughness: 0.18, - metalness: 0.02, - clearcoat: 0.78, - clearcoatRoughness: 0.08, - ior: 1.54, - envMapIntensity: 1.1, - normalScale: 0.16, + color: '#f5f2ec', + roughness: 0.14, + metalness: 0.0, + clearcoat: 0.9, + clearcoatRoughness: 0.04, + ior: 1.56, + specularIntensity: 1.0, + envMapIntensity: 1.2, + normalScale: 0.1, + clearcoatNormalScale: 0.05, }, glass: { - color: '#e0f2fe', - roughness: 0.03, + color: '#dff2ff', + roughness: 0.018, metalness: 0.0, transmission: 0.94, - ior: 1.52, - thickness: 0.45, - attenuationColor: '#d8eeff', - attenuationDistance: 2.2, - clearcoat: 0.32, - clearcoatRoughness: 0.04, - opacity: 0.28, - envMapIntensity: 1.45, + ior: 1.58, + thickness: 0.65, + attenuationColor: '#bae6fd', + attenuationDistance: 1.85, + // Sapphire watch-crystal AR thin-film coating + bright Fresnel rim coat so glass pops against steel & dark bg! + clearcoat: 1.0, + clearcoatRoughness: 0.015, + iridescence: 0.36, + iridescenceIOR: 1.38, + iridescenceThicknessRange: [240, 380], + specularIntensity: 1.0, + specularColor: '#e0f2fe', + opacity: 0.32, + envMapIntensity: 1.85, }, translucent_plastic: { - color: '#cbd5e1', - roughness: 0.26, + color: '#d8e1ec', + roughness: 0.22, metalness: 0.0, - transmission: 0.48, - ior: 1.48, - thickness: 0.25, + transmission: 0.62, + ior: 1.49, + thickness: 0.35, + attenuationColor: '#cbd5e1', + attenuationDistance: 1.1, opacity: 0.52, - clearcoat: 0.35, - clearcoatRoughness: 0.16, - envMapIntensity: 1.05, - normalScale: 0.2, + clearcoat: 0.42, + clearcoatRoughness: 0.14, + envMapIntensity: 1.12, + normalScale: 0.14, }, abs_plastic: { - color: '#343b46', - roughness: 0.42, + color: '#2d3440', + roughness: 0.38, metalness: 0.0, ior: 1.49, - clearcoat: 0.16, - clearcoatRoughness: 0.34, - envMapIntensity: 0.92, - normalScale: 0.28, + specularIntensity: 0.85, + clearcoat: 0.18, + clearcoatRoughness: 0.32, + envMapIntensity: 0.96, + normalScale: 0.22, }, silicone: { - color: '#2b313b', - roughness: 0.68, + color: '#2b323d', + roughness: 0.64, metalness: 0.0, - sheen: 0.42, + transmission: 0.12, + thickness: 0.35, + attenuationColor: '#1e293b', + attenuationDistance: 0.45, + sheen: 0.48, sheenColor: '#94a3b8', - clearcoat: 0.06, - clearcoatRoughness: 0.5, - envMapIntensity: 0.75, - normalScale: 0.24, + sheenRoughness: 0.62, + clearcoat: 0.08, + clearcoatRoughness: 0.48, + envMapIntensity: 0.78, + normalScale: 0.2, }, rubber: { - color: '#1b1f26', - roughness: 0.86, - metalness: 0.02, - sheen: 0.24, + color: '#181c23', + roughness: 0.84, + metalness: 0.0, + ior: 1.52, + specularIntensity: 0.42, + sheen: 0.28, sheenColor: '#475569', - envMapIntensity: 0.58, - normalScale: 0.35, + sheenRoughness: 0.78, + envMapIntensity: 0.62, + normalScale: 0.32, }, painted_surface: { color: '#334155', - roughness: 0.32, - metalness: 0.15, - clearcoat: 0.65, - clearcoatRoughness: 0.12, - envMapIntensity: 1.15, - normalScale: 0.22, + roughness: 0.28, + metalness: 0.18, + clearcoat: 0.82, + clearcoatRoughness: 0.08, + ior: 1.52, + envMapIntensity: 1.22, + normalScale: 0.16, + clearcoatNormalScale: 0.06, }, carbon_fibre: { - color: '#1c2028', - roughness: 0.28, - metalness: 0.24, - clearcoat: 0.72, - clearcoatRoughness: 0.1, - envMapIntensity: 1.25, - normalScale: 0.55, + color: '#1b1f27', + roughness: 0.26, + metalness: 0.32, + anisotropy: 0.48, + clearcoat: 0.88, + clearcoatRoughness: 0.06, + envMapIntensity: 1.35, + normalScale: 0.58, + clearcoatNormalScale: 0.05, }, wood: { - color: '#8f5f38', - roughness: 0.58, + color: '#8e5c36', + roughness: 0.52, metalness: 0.0, - clearcoat: 0.22, - clearcoatRoughness: 0.3, - envMapIntensity: 0.82, - normalScale: 0.48, + clearcoat: 0.34, + clearcoatRoughness: 0.24, + sheen: 0.18, + sheenColor: '#d6a87c', + sheenRoughness: 0.55, + envMapIntensity: 0.88, + normalScale: 0.44, }, stone: { color: '#78716c', - roughness: 0.84, + roughness: 0.82, metalness: 0.02, - envMapIntensity: 0.62, - normalScale: 0.65, + specularIntensity: 0.5, + envMapIntensity: 0.66, + normalScale: 0.62, }, organic_tissue: { - color: '#b8424f', - roughness: 0.38, + color: '#a92332', + roughness: 0.32, metalness: 0.0, - clearcoat: 0.46, - clearcoatRoughness: 0.22, - sheen: 0.48, + transmission: 0.28, + thickness: 0.95, + attenuationColor: '#4c0519', + attenuationDistance: 0.28, + clearcoat: 0.72, + clearcoatRoughness: 0.12, + sheen: 0.38, sheenColor: '#fda4af', - ior: 1.4, - envMapIntensity: 0.92, - normalScale: 0.12, + sheenRoughness: 0.42, + ior: 1.42, + envMapIntensity: 0.98, + normalScale: 0.24, + clearcoatNormalScale: 0.08, }, semiconductor: { - color: '#1e293b', - roughness: 0.12, - metalness: 0.74, - clearcoat: 0.72, - clearcoatRoughness: 0.06, - iridescence: 0.45, - envMapIntensity: 1.4, - normalScale: 0.24, + color: '#172133', + roughness: 0.065, + metalness: 0.88, + clearcoat: 0.88, + clearcoatRoughness: 0.035, + iridescence: 0.82, + iridescenceIOR: 1.92, + iridescenceThicknessRange: [150, 520], + envMapIntensity: 1.52, + normalScale: 0.18, }, water_fluid: { - color: '#38bdf8', - roughness: 0.04, + color: '#7dd3fc', + roughness: 0.025, metalness: 0.0, - transmission: 0.88, + transmission: 0.92, ior: 1.333, - thickness: 0.35, - attenuationColor: '#0ea5e9', - attenuationDistance: 1.4, + thickness: 0.45, + attenuationColor: '#0284c7', + attenuationDistance: 1.35, + clearcoat: 0.25, + clearcoatRoughness: 0.02, opacity: 0.54, - envMapIntensity: 1.3, + envMapIntensity: 1.38, }, }; -type SurfacePatternKind = 'brushed' | 'cast' | 'carbon' | 'wood' | 'organic' | 'molded' | 'ceramic'; +type SurfacePatternKind = + | 'brushed' + | 'polished' + | 'cast' + | 'carbon' + | 'wood' + | 'organic' + | 'molded' + | 'elastomer' + | 'ceramic' + | 'semiconductor'; interface ProceduralSurfaceMaps { normalMap: THREE.CanvasTexture; roughnessMap: THREE.CanvasTexture; albedoMap?: THREE.CanvasTexture; + clearcoatNormalMap?: THREE.CanvasTexture; } const surfaceMapCache = new Map(); -function buildHeightField(kind: SurfacePatternKind, size: number): Float32Array { - const h = new Float32Array(size * size); - let seed = 48271; - const rand = () => { - seed = (seed * 16807) % 2147483647; - return (seed - 1) / 2147483646; - }; +function hash2D(ix: number, iy: number, period: number, seed = 1337): number { + const px = ((ix % period) + period) % period; + const py = ((iy % period) + period) % period; + let n = (px * 374761393 + py * 668265263 + seed * 1442695041) | 0; + n = ((n ^ (n >>> 13)) * 1274126177) | 0; + return ((n ^ (n >>> 16)) >>> 0) / 4294967295; +} + +function tileableValueNoise(u: number, v: number, freq: number, seed = 1337): number { + const x = u * freq; + const y = v * freq; + const ix = Math.floor(x); + const iy = Math.floor(y); + const fx = x - ix; + const fy = y - iy; + const sx = fx * fx * (3 - 2 * fx); + const sy = fy * fy * (3 - 2 * fy); + + const n00 = hash2D(ix, iy, freq, seed); + const n10 = hash2D(ix + 1, iy, freq, seed); + const n01 = hash2D(ix, iy + 1, freq, seed); + const n11 = hash2D(ix + 1, iy + 1, freq, seed); + + const nx0 = n00 + (n10 - n00) * sx; + const nx1 = n01 + (n11 - n01) * sx; + return nx0 + (nx1 - nx0) * sy; +} +function tileableFbm(u: number, v: number, baseFreq: number, octaves: number, seed = 1337): number { + let sum = 0; + let amp = 0.5; + let norm = 0; + let freq = baseFreq; + for (let i = 0; i < octaves; i++) { + sum += tileableValueNoise(u, v, freq, seed + i * 97) * amp; + norm += amp; + amp *= 0.5; + freq *= 2; + } + return sum / (norm || 1); +} + +function tileableVoronoi(u: number, v: number, cells: number, seed = 4201): number { + const gx = u * cells; + const gy = v * cells; + const ix = Math.floor(gx); + const iy = Math.floor(gy); + let minDist = 8.0; + + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + const cx = ix + dx; + const cy = iy + dy; + const px = cx + hash2D(cx, cy, cells, seed); + const py = cy + hash2D(cx, cy, cells, seed + 7919); + const d2 = (px - gx) * (px - gx) + (py - gy) * (py - gy); + if (d2 < minDist) minDist = d2; + } + } + return Math.min(1, Math.sqrt(minDist)); +} + +function buildHeightAndRoughnessFields( + kind: SurfacePatternKind, + size: number, +): { height: Float32Array; roughMod: Float32Array; coatHeight?: Float32Array } { + const height = new Float32Array(size * size); + const roughMod = new Float32Array(size * size); + const needsCoat = kind === 'carbon' || kind === 'ceramic' || kind === 'organic'; + const coatHeight = needsCoat ? new Float32Array(size * size) : undefined; + + const rowScratchA = new Float32Array(size); + const rowScratchB = new Float32Array(size); for (let y = 0; y < size; y++) { - const rowJitter = (rand() - 0.5) * 0.22; + const v = y / size; + rowScratchA[y] = tileableFbm(0.13, v, 64, 4, 901) - 0.5; + rowScratchB[y] = hash2D(7, y, size, 3313) - 0.5; + } + + for (let y = 0; y < size; y++) { + const v = y / size; for (let x = 0; x < size; x++) { + const u = x / size; const idx = y * size + x; + if (kind === 'brushed') { - const streak = - Math.sin(y * 1.85) * 0.16 + Math.cos(y * 5.7) * 0.1 + Math.sin(y * 13.3 + x * 0.015) * 0.06 + rowJitter * 0.7; - h[idx] = 0.5 + streak * 0.42; + const longBand = tileableValueNoise(u, v, 8, 511); + const fineGroove = rowScratchA[y] * (0.72 + 0.58 * tileableValueNoise(u, v, 6, 712)) + rowScratchB[y] * 0.32; + const crossMicro = (tileableValueNoise(u, v, 48, 1201) - 0.5) * 0.08; + const smudge = tileableFbm(u, v, 5, 3, 4409); + height[idx] = 0.5 + fineGroove * 0.62 + crossMicro + (longBand - 0.5) * 0.1; + roughMod[idx] = 0.76 + smudge * 0.26 + fineGroove * 0.24; + } else if (kind === 'polished') { + const swirl = tileableFbm(u, v, 10, 3, 2203) - 0.5; + const smudge = tileableFbm(u, v, 4, 3, 8807); + height[idx] = 0.5 + swirl * 0.14; + roughMod[idx] = 0.82 + smudge * 0.26; } else if (kind === 'cast') { - // Isotropic fine sand-cast metallic grain without periodic stripes - const grain = (rand() - 0.5) * 0.32; - const fine = (rand() - 0.5) * 0.14; - h[idx] = 0.5 + grain + fine; - } else if (kind === 'molded') { - const stipple = (rand() - 0.5) * 0.18; - h[idx] = 0.5 + stipple; - } else if (kind === 'ceramic') { - const wave = (rand() - 0.5) * 0.06; - h[idx] = 0.5 + wave; + const coarse = tileableFbm(u, v, 14, 4, 6011); + const fine = tileableValueNoise(u, v, 96, 6199) - 0.5; + const pores = tileableVoronoi(u, v, 36, 6311); + const pit = pores < 0.22 ? -(0.22 - pores) * 1.35 : 0; + height[idx] = 0.5 + (coarse - 0.5) * 0.52 + fine * 0.22 + pit; + roughMod[idx] = 0.76 + coarse * 0.28 - pit * 0.4; } else if (kind === 'carbon') { - const cell = 16; - const tx = Math.floor(x / cell); - const ty = Math.floor(y / cell); - const lx = (x % cell) / cell; - const ly = (y % cell) / cell; - const even = (tx + ty) % 2 === 0; - const strand = even ? Math.sin(lx * Math.PI) * 0.34 : Math.sin(ly * Math.PI) * 0.34; - h[idx] = 0.34 + strand; + const cells = 16; + const gx = u * cells * 4; + const gy = v * cells * 4; + const ix = Math.floor(gx); + const iy = Math.floor(gy); + const fx = gx - ix; + const fy = gy - iy; + const twillPhase = (((ix + iy) % 4) + 4) % 4; + const warpTop = twillPhase < 2; + const crown = warpTop + ? Math.sin(fx * Math.PI) * (0.85 + 0.15 * Math.sin(fy * Math.PI * 0.5)) + : Math.sin(fy * Math.PI) * (0.85 + 0.15 * Math.sin(fx * Math.PI * 0.5)); + const filament = warpTop ? Math.sin(fx * Math.PI * 10) * 0.04 : Math.sin(fy * Math.PI * 10) * 0.04; + height[idx] = 0.22 + crown * 0.62 + filament; + roughMod[idx] = warpTop ? 0.72 + (1 - crown) * 0.25 : 0.88 + (1 - crown) * 0.18; + if (coatHeight) { + coatHeight[idx] = 0.5 + (tileableFbm(u, v, 6, 2, 9923) - 0.5) * 0.14; + } } else if (kind === 'wood') { - const ring = - Math.sin(x * 0.085 + Math.sin(y * 0.016) * 3.8) * 0.24 + Math.cos(x * 0.34) * 0.08 + (rand() - 0.5) * 0.05; - h[idx] = 0.5 + ring; + const warp = tileableFbm(u, v, 4, 3, 7103) * 0.35; + const rings = Math.sin((u * 9.0 + warp) * Math.PI * 2); + const grain = (tileableValueNoise(u * 2, v * 16, 24, 7211) - 0.5) * 0.26; + const pore = tileableValueNoise(u * 3, v * 0.6, 48, 7309) > 0.86 ? -0.18 : 0; + height[idx] = 0.5 + rings * 0.18 + grain + pore; + roughMod[idx] = 0.78 + rings * 0.12 - pore * 0.8; } else if (kind === 'organic') { - // Soft non-directional biological cellular micro-relief - const u = (x / size) * Math.PI * 2; - const v = (y / size) * Math.PI * 2; - const softCells = - Math.sin(u * 3 + Math.cos(v * 2)) * Math.cos(v * 3 - Math.sin(u * 2)) * 0.08 + (rand() - 0.5) * 0.09; - h[idx] = 0.5 + softCells; + const warp = tileableFbm(u, v, 5, 3, 5003); + const fascicles = Math.sin((v * 12 + warp * 2.4) * Math.PI * 2) * 0.16; + const cells = tileableVoronoi(u, v, 18, 5107); + const micro = (tileableFbm(u, v, 16, 3, 5209) - 0.5) * 0.22; + height[idx] = 0.5 + fascicles + (1 - cells) * 0.18 + micro; + roughMod[idx] = 0.72 + cells * 0.28 + (warp - 0.5) * 0.16; + if (coatHeight) { + coatHeight[idx] = 0.5 + (tileableFbm(u, v, 5, 2, 5303) - 0.5) * 0.22; + } + } else if (kind === 'elastomer') { + const fine = tileableValueNoise(u, v, 128, 3001) - 0.5; + const med = tileableFbm(u, v, 24, 3, 3109) - 0.5; + height[idx] = 0.5 + fine * 0.28 + med * 0.24; + roughMod[idx] = 0.88 + med * 0.18; + } else if (kind === 'molded') { + const stipple = tileableValueNoise(u, v, 112, 4001) - 0.5; + const broad = tileableFbm(u, v, 6, 3, 4111); + height[idx] = 0.5 + stipple * 0.22 + (broad - 0.5) * 0.12; + roughMod[idx] = 0.8 + broad * 0.24; + } else if (kind === 'semiconductor') { + const gx = (u * 16) % 1; + const gy = (v * 16) % 1; + const traceX = gx < 0.08 ? -0.14 : 0; + const traceY = gy < 0.08 ? -0.14 : 0; + const subCell = tileableValueNoise(u, v, 64, 8101) > 0.45 ? 0.06 : -0.04; + height[idx] = 0.5 + traceX + traceY + subCell; + roughMod[idx] = traceX < 0 || traceY < 0 ? 1.0 : 0.72 + (subCell + 0.04) * 1.4; + } else { + const glaze = tileableFbm(u, v, 8, 3, 9501) - 0.5; + height[idx] = 0.5 + glaze * 0.16; + roughMod[idx] = 0.85 + glaze * 0.18; + if (coatHeight) { + coatHeight[idx] = 0.5 + (tileableFbm(u, v, 5, 2, 9601) - 0.5) * 0.12; + } } } } - return h; -} - -/** - * Generates paired 512x512 tangent-space NormalMap (via Sobel gradient), - * Roughness variation map, and subtle Albedo grain map for rich PBR surface response. - */ -function getSurfaceMaps(kind: SurfacePatternKind, repeatScale = 3, maxAniso = 4): ProceduralSurfaceMaps | null { - if (typeof document === 'undefined') return null; - const key = `${kind}_${repeatScale}_${maxAniso}`; - const cached = surfaceMapCache.get(key); - if (cached) return cached; - - const size = 512; - const height = buildHeightField(kind, size); - - const normCanvas = document.createElement('canvas'); - normCanvas.width = size; - normCanvas.height = size; - const normCtx = normCanvas.getContext('2d'); - - const roughCanvas = document.createElement('canvas'); - roughCanvas.width = size; - roughCanvas.height = size; - const roughCtx = roughCanvas.getContext('2d'); - if (!normCtx || !roughCtx) return null; + return { height, roughMod, coatHeight }; +} - const normImg = normCtx.createImageData(size, size); - const roughImg = roughCtx.createImageData(size, size); - const strength = - kind === 'brushed' ? 1.5 : kind === 'cast' ? 1.65 : kind === 'carbon' ? 3.2 : kind === 'organic' ? 1.1 : 1.5; +function bakeSobelNormalCanvas(height: Float32Array, size: number, strength: number): HTMLCanvasElement | null { + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + const img = ctx.createImageData(size, size); const sampleH = (x: number, y: number) => { const wx = ((x % size) + size) % size; const wy = ((y % size) + size) % size; @@ -446,7 +622,6 @@ function getSurfaceMaps(kind: SurfacePatternKind, repeatScale = 3, maxAniso = 4) for (let y = 0; y < size; y++) { for (let x = 0; x < size; x++) { - const idx = y * size + x; const tl = sampleH(x - 1, y - 1); const t = sampleH(x, y - 1); const tr = sampleH(x + 1, y - 1); @@ -461,41 +636,91 @@ function getSurfaceMaps(kind: SurfacePatternKind, repeatScale = 3, maxAniso = 4) const nz = 1.0; const invLen = 1 / Math.hypot(dx, dy, nz); - const p = idx * 4; - normImg.data[p] = Math.round((-dx * invLen * 0.5 + 0.5) * 255); - normImg.data[p + 1] = Math.round((-dy * invLen * 0.5 + 0.5) * 255); - normImg.data[p + 2] = Math.round((nz * invLen * 0.5 + 0.5) * 255); - normImg.data[p + 3] = 255; - - // Modulate roughness around neutral ~215 (0.84) with subtle surface wear variation - const hv = height[idx]; - const roughByte = Math.max(150, Math.min(255, Math.round(195 + (hv - 0.5) * 95))); - roughImg.data[p] = roughByte; - roughImg.data[p + 1] = roughByte; - roughImg.data[p + 2] = roughByte; - roughImg.data[p + 3] = 255; + const p = (y * size + x) * 4; + img.data[p] = Math.round((-dx * invLen * 0.5 + 0.5) * 255); + img.data[p + 1] = Math.round((-dy * invLen * 0.5 + 0.5) * 255); + img.data[p + 2] = Math.round((nz * invLen * 0.5 + 0.5) * 255); + img.data[p + 3] = 255; } } - normCtx.putImageData(normImg, 0, 0); + ctx.putImageData(img, 0, 0); + return canvas; +} + +function getSurfaceMaps(kind: SurfacePatternKind, repeatScale = 3, maxAniso = 4): ProceduralSurfaceMaps | null { + if (typeof document === 'undefined') return null; + const key = `${kind}_${repeatScale}_${maxAniso}`; + const cached = surfaceMapCache.get(key); + if (cached) return cached; + + const size = 512; + const { height, roughMod, coatHeight } = buildHeightAndRoughnessFields(kind, size); + + const strength = + kind === 'carbon' + ? 3.1 + : kind === 'cast' + ? 1.9 + : kind === 'brushed' + ? 1.85 + : kind === 'wood' + ? 1.85 + : kind === 'organic' + ? 1.45 + : kind === 'semiconductor' + ? 1.6 + : 1.25; + + const normCanvas = bakeSobelNormalCanvas(height, size, strength); + const roughCanvas = document.createElement('canvas'); + roughCanvas.width = size; + roughCanvas.height = size; + const roughCtx = roughCanvas.getContext('2d'); + + if (!normCanvas || !roughCtx) return null; + + const roughImg = roughCtx.createImageData(size, size); + for (let i = 0; i < size * size; i++) { + const rb = Math.max(128, Math.min(255, Math.round(roughMod[i] * 242))); + const p = i * 4; + roughImg.data[p] = rb; + roughImg.data[p + 1] = rb; + roughImg.data[p + 2] = rb; + roughImg.data[p + 3] = 255; + } roughCtx.putImageData(roughImg, 0, 0); - const normalMap = new THREE.CanvasTexture(normCanvas); - normalMap.wrapS = THREE.RepeatWrapping; - normalMap.wrapT = THREE.RepeatWrapping; - normalMap.repeat.set(repeatScale, repeatScale); - normalMap.anisotropy = maxAniso; - normalMap.colorSpace = THREE.NoColorSpace; + const configureTex = (canvas: HTMLCanvasElement, srgb: boolean): THREE.CanvasTexture => { + const tex = new THREE.CanvasTexture(canvas); + tex.wrapS = THREE.RepeatWrapping; + tex.wrapT = THREE.RepeatWrapping; + tex.repeat.set(repeatScale, repeatScale); + tex.anisotropy = maxAniso; + tex.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace; + return tex; + }; + + const normalMap = configureTex(normCanvas, false); + const roughnessMap = configureTex(roughCanvas, false); - const roughnessMap = new THREE.CanvasTexture(roughCanvas); - roughnessMap.wrapS = THREE.RepeatWrapping; - roughnessMap.wrapT = THREE.RepeatWrapping; - roughnessMap.repeat.set(repeatScale, repeatScale); - roughnessMap.anisotropy = maxAniso; - roughnessMap.colorSpace = THREE.NoColorSpace; + let clearcoatNormalMap: THREE.CanvasTexture | undefined; + if (coatHeight) { + const coatCanvas = bakeSobelNormalCanvas(coatHeight, size, 0.75); + if (coatCanvas) { + clearcoatNormalMap = configureTex(coatCanvas, false); + } + } let albedoMap: THREE.CanvasTexture | undefined; - if (kind === 'carbon' || kind === 'wood' || kind === 'organic') { + if ( + kind === 'brushed' || + kind === 'carbon' || + kind === 'wood' || + kind === 'organic' || + kind === 'cast' || + kind === 'semiconductor' + ) { const albCanvas = document.createElement('canvas'); albCanvas.width = size; albCanvas.height = size; @@ -505,33 +730,44 @@ function getSurfaceMaps(kind: SurfacePatternKind, repeatScale = 3, maxAniso = 4) for (let i = 0; i < size * size; i++) { const hv = height[i]; const p = i * 4; - if (kind === 'carbon') { - const v = Math.round(145 + hv * 105); + if (kind === 'brushed') { + // Visible directional brushed micro-streaks in albedo so steel & brass texture reads even at mobile thumbnail scale! + const v = Math.max(204, Math.min(255, Math.round(238 + (hv - 0.5) * 68))); albImg.data[p] = v; - albImg.data[p + 1] = Math.round(v * 1.02); - albImg.data[p + 2] = Math.min(255, Math.round(v * 1.06)); + albImg.data[p + 1] = v; + albImg.data[p + 2] = v; + } else if (kind === 'carbon') { + const v = Math.max(95, Math.min(252, Math.round(135 + hv * 128))); + albImg.data[p] = v; + albImg.data[p + 1] = Math.min(255, Math.round(v * 1.02)); + albImg.data[p + 2] = Math.min(255, Math.round(v * 1.07)); } else if (kind === 'wood') { - albImg.data[p] = Math.max(135, Math.min(248, Math.round(188 + (hv - 0.5) * 96))); - albImg.data[p + 1] = Math.max(118, Math.min(225, Math.round(166 + (hv - 0.5) * 82))); - albImg.data[p + 2] = Math.max(98, Math.min(200, Math.round(145 + (hv - 0.5) * 66))); + albImg.data[p] = Math.max(140, Math.min(252, Math.round(212 + (hv - 0.5) * 115))); + albImg.data[p + 1] = Math.max(118, Math.min(235, Math.round(192 + (hv - 0.5) * 102))); + albImg.data[p + 2] = Math.max(96, Math.min(215, Math.round(170 + (hv - 0.5) * 86))); + } else if (kind === 'organic') { + albImg.data[p] = Math.max(195, Math.min(255, Math.round(236 + (hv - 0.5) * 54))); + albImg.data[p + 1] = Math.max(165, Math.min(242, Math.round(212 + (hv - 0.5) * 68))); + albImg.data[p + 2] = Math.max(170, Math.min(245, Math.round(216 + (hv - 0.5) * 62))); + } else if (kind === 'semiconductor') { + const v = Math.max(185, Math.min(255, Math.round(228 + (hv - 0.5) * 90))); + albImg.data[p] = v; + albImg.data[p + 1] = Math.min(255, Math.round(v * 1.03)); + albImg.data[p + 2] = Math.min(255, Math.round(v * 1.08)); } else { - albImg.data[p] = Math.max(175, Math.min(250, Math.round(220 + (hv - 0.5) * 58))); - albImg.data[p + 1] = Math.max(150, Math.min(225, Math.round(192 + (hv - 0.5) * 52))); - albImg.data[p + 2] = Math.max(155, Math.min(228, Math.round(196 + (hv - 0.5) * 52))); + const v = Math.max(198, Math.min(255, Math.round(238 + (hv - 0.5) * 58))); + albImg.data[p] = v; + albImg.data[p + 1] = v; + albImg.data[p + 2] = v; } albImg.data[p + 3] = 255; } albCtx.putImageData(albImg, 0, 0); - albedoMap = new THREE.CanvasTexture(albCanvas); - albedoMap.wrapS = THREE.RepeatWrapping; - albedoMap.wrapT = THREE.RepeatWrapping; - albedoMap.repeat.set(repeatScale, repeatScale); - albedoMap.anisotropy = maxAniso; - albedoMap.colorSpace = THREE.SRGBColorSpace; + albedoMap = configureTex(albCanvas, true); } } - const entry: ProceduralSurfaceMaps = { normalMap, roughnessMap, albedoMap }; + const entry: ProceduralSurfaceMaps = { normalMap, roughnessMap, albedoMap, clearcoatNormalMap }; surfaceMapCache.set(key, entry); return entry; } @@ -549,55 +785,69 @@ export class MaterialLibrary { const presetKey: MaterialPresetId = spec?.preset ?? 'brushed_steel'; const def = MATERIAL_PRESET_DEFAULTS[presetKey] ?? MATERIAL_PRESET_DEFAULTS.brushed_steel; - const cacheKey = `${id}_${presetKey}_${spec?.color ?? ''}_${spec?.roughness ?? ''}_${spec?.metalness ?? ''}_${spec?.opacity ?? ''}_${spec?.textureScale ?? ''}_${this.isSoftwareGl ? 'sw' : 'hw'}`; + const cacheKey = `${id}_${presetKey}_${spec?.color ?? ''}_${spec?.roughness ?? ''}_${spec?.metalness ?? ''}_${spec?.opacity ?? ''}_${spec?.transmission ?? ''}_${spec?.textureScale ?? ''}_${this.isSoftwareGl ? 'sw' : 'hw'}`; const existing = this.cache.get(cacheKey); if (existing) { if (clippingPlanes) existing.clippingPlanes = clippingPlanes; return existing; } - const opacity = spec?.opacity ?? def.opacity ?? 1; + const requestedOpacity = spec?.opacity ?? def.opacity ?? 1; const requestedTrans = spec?.transmission ?? def.transmission ?? 0; - const isTransparent = opacity < 0.99 || requestedTrans > 0.05; + + // The tissue preset uses transmission for light scattering inside an otherwise solid surface. + const fallbackTransmission = presetKey === 'organic_tissue' ? (spec?.transmission ?? 0) : requestedTrans; + const useFallbackTransmission = this.isSoftwareGl && fallbackTransmission > 0.05; + const usePhysicalTransmission = !this.isSoftwareGl && requestedTrans > 0.05; + const useAlphaBlending = !usePhysicalTransmission && (requestedOpacity < 0.99 || useFallbackTransmission); + + const effectiveOpacity = usePhysicalTransmission + ? 1.0 + : useFallbackTransmission + ? Math.min(requestedOpacity, presetKey === 'organic_tissue' ? 0.42 : 0.34) + : requestedOpacity; + const [iridescenceThicknessMinimum, iridescenceThicknessMaximum] = def.iridescenceThicknessRange ?? [160, 420]; const mat = new THREE.MeshPhysicalMaterial({ color: new THREE.Color(spec?.color ?? def.color), roughness: spec?.roughness ?? def.roughness, metalness: spec?.metalness ?? def.metalness, clearcoat: spec?.clearcoat ?? def.clearcoat ?? 0, - clearcoatRoughness: spec?.clearcoatRoughness ?? def.clearcoatRoughness ?? 0.12, + clearcoatRoughness: spec?.clearcoatRoughness ?? def.clearcoatRoughness ?? 0.1, anisotropy: this.isSoftwareGl ? 0 : (spec?.anisotropy ?? def.anisotropy ?? 0), + anisotropyRotation: def.anisotropyRotation ?? 0, ior: spec?.ior ?? def.ior ?? 1.5, + specularIntensity: def.specularIntensity ?? 1.0, + specularColor: new THREE.Color(def.specularColor ?? '#ffffff'), sheen: spec?.sheen ?? def.sheen ?? 0, sheenColor: new THREE.Color(spec?.sheenColor ?? def.sheenColor ?? '#ffffff'), - sheenRoughness: 0.55, + sheenRoughness: def.sheenRoughness ?? 0.55, iridescence: this.isSoftwareGl ? 0 : (def.iridescence ?? 0), + iridescenceIOR: def.iridescenceIOR ?? 1.6, + iridescenceThicknessMinimum, + iridescenceThicknessMaximum, envMapIntensity: def.envMapIntensity ?? 1.25, transmission: this.isSoftwareGl ? 0 : requestedTrans, - thickness: spec?.thickness ?? def.thickness ?? (requestedTrans > 0 ? 0.45 : 0), + thickness: spec?.thickness ?? def.thickness ?? (requestedTrans > 0 ? 0.55 : 0), attenuationColor: new THREE.Color(spec?.attenuationColor ?? def.attenuationColor ?? '#ffffff'), attenuationDistance: spec?.attenuationDistance ?? def.attenuationDistance ?? 2.0, - transparent: isTransparent, - opacity: this.isSoftwareGl && requestedTrans > 0 ? Math.min(opacity, 0.4) : opacity, - depthWrite: !isTransparent, + transparent: useAlphaBlending, + opacity: effectiveOpacity, + depthWrite: !useAlphaBlending, emissive: spec?.emissive ? new THREE.Color(spec.emissive) : new THREE.Color(0x000000), emissiveIntensity: spec?.emissiveIntensity ?? 0, side: THREE.DoubleSide, clipShadows: true, }); - // Attach procedural tangent-space NormalMap, Roughness imperfection map & optional albedo weave/grain const scale = spec?.textureScale ?? 3; - const nScale = spec?.normalScale ?? def.normalScale ?? 0.3; + const nScale = spec?.normalScale ?? def.normalScale ?? 0.24; let patternKind: SurfacePatternKind | null = null; - if ( - presetKey === 'brushed_steel' || - presetKey === 'brass' || - presetKey === 'copper' || - presetKey === 'polished_metal' - ) { + if (presetKey === 'brushed_steel' || presetKey === 'brass' || presetKey === 'copper') { patternKind = 'brushed'; + } else if (presetKey === 'polished_metal' || presetKey === 'chrome') { + patternKind = 'polished'; } else if (presetKey === 'cast_aluminium' || presetKey === 'stone') { patternKind = 'cast'; } else if (presetKey === 'carbon_fibre') { @@ -606,13 +856,12 @@ export class MaterialLibrary { patternKind = 'wood'; } else if (presetKey === 'organic_tissue') { patternKind = 'organic'; - } else if ( - presetKey === 'abs_plastic' || - presetKey === 'painted_surface' || - presetKey === 'rubber' || - presetKey === 'silicone' - ) { + } else if (presetKey === 'silicone' || presetKey === 'rubber') { + patternKind = 'elastomer'; + } else if (presetKey === 'abs_plastic' || presetKey === 'painted_surface' || presetKey === 'translucent_plastic') { patternKind = 'molded'; + } else if (presetKey === 'semiconductor') { + patternKind = 'semiconductor'; } else if (presetKey === 'ceramic') { patternKind = 'ceramic'; } @@ -626,6 +875,11 @@ export class MaterialLibrary { if (maps.albedoMap) { mat.map = maps.albedoMap; } + if (maps.clearcoatNormalMap && (mat.clearcoat ?? 0) > 0.1) { + const ccScale = def.clearcoatNormalScale ?? 0.06; + mat.clearcoatNormalMap = maps.clearcoatNormalMap; + mat.clearcoatNormalScale = new THREE.Vector2(ccScale, ccScale); + } } } diff --git a/src/engine/pathtracer.ts b/src/engine/pathtracer.ts index 2228957..4d18900 100644 --- a/src/engine/pathtracer.ts +++ b/src/engine/pathtracer.ts @@ -22,12 +22,17 @@ export function isPathTracingSupported(renderer: THREE.WebGLRenderer, isSoftware } } +/** + * Progressive Monte Carlo GPU Path Tracer controller (Blender Cycles-style physical light transport). + * Tuned with Multiple Importance Sampling (MIS), 8-bounce dielectric refraction, glossy firefly + * regularization, and adaptive progressive tile scheduling for 60fps UI responsiveness. + */ export class PathTracerController { private pt: WebGLPathTracer | null = null; private initializedScene = false; private failed = false; private lastError: string | undefined; - public readonly targetSamples = 64; + public readonly targetSamples = 128; constructor( private readonly renderer: THREE.WebGLRenderer, @@ -53,14 +58,29 @@ export class PathTracerController { try { if (!this.pt) { this.pt = new WebGLPathTracer(this.renderer); - this.pt.bounces = 4; - this.pt.transmissiveBounces = 6; - this.pt.filterGlossyFactor = 0.5; + // Deep inter-reflection & refractive bounce budget for metals, glass boilers & wet tissue + this.pt.bounces = 6; + this.pt.transmissiveBounces = 10; + // Balances sharp chrome/glass caustics while suppressing single-pixel softbox fireflies + this.pt.filterGlossyFactor = 0.32; this.pt.dynamicLowRes = true; - this.pt.lowResScale = 0.5; - this.pt.renderScale = 1.0; + this.pt.lowResScale = 0.45; + const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1; + this.pt.renderScale = Math.min(dpr, 1.5); this.pt.tiles.set(2, 2); + + // Safely enable Multiple Importance Sampling (MIS) & crisp environment sampling when supported + const extPt = this.pt as unknown as Record; + if ('multipleImportanceSampling' in extPt) { + extPt['multipleImportanceSampling'] = true; + } + if ('synchronizeRenderSize' in extPt) { + extPt['synchronizeRenderSize'] = true; + } } + + // Render full-frame 1x1 on initial convergence pass to avoid visible tile seams on frame 1 + this.pt.tiles.set(1, 1); this.pt.setScene(scene, camera); this.initializedScene = true; return true; @@ -74,6 +94,7 @@ export class PathTracerController { public setCamera(camera: THREE.Camera): void { if (!this.pt || !this.initializedScene) return; try { + this.pt.tiles.set(1, 1); this.pt.setCamera(camera); } catch { // Ignore transient camera sync error @@ -83,6 +104,7 @@ export class PathTracerController { public updateCamera(): void { if (!this.pt || !this.initializedScene) return; try { + this.pt.tiles.set(1, 1); this.pt.updateCamera(); } catch { // Ignore @@ -92,6 +114,7 @@ export class PathTracerController { public updateEnvironment(): void { if (!this.pt || !this.initializedScene) return; try { + this.pt.tiles.set(1, 1); this.pt.updateEnvironment(); } catch { // Ignore @@ -100,6 +123,7 @@ export class PathTracerController { public reset(): void { if (!this.pt || !this.initializedScene) return; + this.pt.tiles.set(1, 1); this.pt.reset(); } @@ -107,6 +131,10 @@ export class PathTracerController { if (!this.pt || !this.initializedScene || this.failed) return 0; try { if (this.pt.samples < this.targetSamples) { + // After initial full-frame preview samples (0..3), switch to 2x2 tiles so deep bounces stay silky-responsive + if (this.pt.samples >= 3 && this.pt.tiles.x === 1) { + this.pt.tiles.set(2, 2); + } this.pt.renderSample(); } return Math.floor(this.pt.samples); diff --git a/src/engine/renderer.ts b/src/engine/renderer.ts index 624b78e..2ccfd81 100644 --- a/src/engine/renderer.ts +++ b/src/engine/renderer.ts @@ -6,6 +6,7 @@ import { RectAreaLightUniformsLib } from 'three/addons/lights/RectAreaLightUnifo import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js'; +import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; import { BokehPass } from 'three/addons/postprocessing/BokehPass.js'; import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; import { OutlinePass } from 'three/addons/postprocessing/OutlinePass.js'; @@ -72,6 +73,10 @@ const _rayMouse = new THREE.Vector2(); const _tmpBox = new THREE.Box3(); const _tmpSize = new THREE.Vector3(); const _tmpCenter = new THREE.Vector3(); +const _wPosA = new THREE.Vector3(); +const _wPosB = new THREE.Vector3(); +const _wDir = new THREE.Vector3(); +const _upVec = new THREE.Vector3(0, 1, 0); export function detectSoftwareWebGL(): boolean { if (typeof document === 'undefined') return true; @@ -89,64 +94,78 @@ export function detectSoftwareWebGL(): boolean { } /** - * Procedurally synthesizes an equirectangular HDR studio environment map with - * overhead & side softbox emitters + subtle rim strip for physically grounded IBL. + * High-contrast horological / industrial studio HDRI (512x256 Float32). + * Uses deliberate dark negative-fill bands between bright softbox strips so watch crystals, + * brushed steel, and warm brass catch sharp, unmistakable reflections even on a phone screen, + * and works identically under both hardware WebGL2 and software SwiftShader PMREM. */ function createStudioHdrEquirectTexture(): THREE.DataTexture { - const width = 256; - const height = 128; + const width = 512; + const height = 256; const data = new Float32Array(width * height * 4); for (let y = 0; y < height; y++) { - const v = y / (height - 1); // 0 = bottom, 1 = top in Three DataTexture - const theta = (1 - v) * Math.PI; // 0 = zenith, PI = nadir + const v = y / (height - 1); + const theta = (1 - v) * Math.PI; const sinT = Math.sin(theta); const cosT = Math.cos(theta); for (let x = 0; x < width; x++) { const u = x / (width - 1); - // three.js samples equirect maps at u = atan2(z, x) / 2π + 0.5, so u = 0 faces -x. - const phi = u * Math.PI * 2 - Math.PI; + const phi = u * Math.PI * 2; const dx = sinT * Math.cos(phi); const dy = cosT; const dz = sinT * Math.sin(phi); - // Dark studio surround: metals need dark areas to reflect, or they read as flat white. - const skyFactor = Math.max(0, dy); - const groundFactor = Math.max(0, -dy); - let r = 0.025 + skyFactor * 0.05 + groundFactor * 0.012; - let g = 0.027 + skyFactor * 0.055 + groundFactor * 0.012; - let b = 0.032 + skyFactor * 0.065 + groundFactor * 0.014; - - // Overhead main rectangular softbox (warm-neutral daylight) - const overheadMask = - THREE.MathUtils.smoothstep(dy, 0.8, 0.9) * - (1 - THREE.MathUtils.smoothstep(Math.abs(dx), 0.28, 0.46)) * - (1 - THREE.MathUtils.smoothstep(Math.abs(dz), 0.18, 0.34)); - r += overheadMask * 1.9; - g += overheadMask * 1.86; - b += overheadMask * 1.8; - - // Key front-right softbox - const keyDot = dx * 0.62 + dy * 0.48 + dz * 0.62; - const keyBox = THREE.MathUtils.smoothstep(keyDot, 0.88, 0.95); - r += keyBox * 2.4; - g += keyBox * 2.32; - b += keyBox * 2.2; - - // Cool fill left-front softbox - const fillDot = -dx * 0.76 + dy * 0.38 + dz * 0.52; - const fillBox = THREE.MathUtils.smoothstep(fillDot, 0.86, 0.94); - r += fillBox * 0.7; - g += fillBox * 0.76; - b += fillBox * 0.84; - - // Crisp rear rim strip light, kept near the horizon for the same reason as the rim light. - const rimDot = -dx * 0.34 + dy * 0.12 - dz * 0.93; - const rimStrip = THREE.MathUtils.smoothstep(rimDot, 0.9, 0.96); - r += rimStrip * 3.1; - g += rimStrip * 3.35; - b += rimStrip * 3.75; + // Deep negative-fill studio surround so metals & watch crystals reflect high-contrast dark contours + const horizonGlow = Math.pow(Math.max(0, 1.0 - Math.abs(dy)), 7.0) * 0.028; + const groundBounce = Math.max(0, -dy) * 0.014; + let r = 0.005 + horizonGlow + groundBounce; + let g = 0.006 + horizonGlow * 1.05 + groundBounce; + let b = 0.009 + horizonGlow * 1.18 + groundBounce * 1.1; + + // 1. Sharp overhead horological softbox with dark centre bar (classic watchmaker dial reflection!) + if (dy > 0.18) { + const projX = dx / (dy + 0.32); + const projZ = dz / (dy + 0.32); + const boxX = 1 - THREE.MathUtils.smoothstep(Math.abs(projX), 0.34, 0.42); + const boxZ = 1 - THREE.MathUtils.smoothstep(Math.abs(projZ), 0.2, 0.27); + // Subtle twin-tube louver split gives crisp double specular lines across curved glass & bezels + const louverSplit = 0.35 + 0.65 * THREE.MathUtils.smoothstep(Math.abs(projZ), 0.015, 0.055); + const overhead = boxX * boxZ * louverSplit * THREE.MathUtils.smoothstep(dy, 0.22, 0.68); + r += overhead * 6.4; + g += overhead * 6.25; + b += overhead * 6.0; + } + + // 2. Key 45-degree warm-daylight strobe softbox (enhances golden brass & copper warmth) + const keyDot = dx * 0.6 + dy * 0.5 + dz * 0.62; + const keyPanel = THREE.MathUtils.smoothstep(keyDot, 0.875, 0.945); + r += keyPanel * 8.2; + g += keyPanel * 7.6; + b += keyPanel * 6.8; + + // 3. Crisp ice-blue vertical rim strip-box (separates cool steel & glass bevels at thumbnail scale) + const rimDot = -dx * 0.58 + dy * 0.26 - dz * 0.77; + const rimVertical = 1 - THREE.MathUtils.smoothstep(Math.abs(dy - 0.22), 0.36, 0.52); + const rimStrip = THREE.MathUtils.smoothstep(rimDot, 0.9, 0.965) * rimVertical; + r += rimStrip * 9.2; + g += rimStrip * 10.6; + b += rimStrip * 12.8; + + // 4. Secondary diagonal crystal glint strip (catches watch crystal dome & boiler glass) + const crystalDot = -dx * 0.42 + dy * 0.68 + dz * 0.6; + const crystalStrip = THREE.MathUtils.smoothstep(crystalDot, 0.935, 0.978); + r += crystalStrip * 7.5; + g += crystalStrip * 8.0; + b += crystalStrip * 8.8; + + // 5. Restrained cool fill bounce card (front-left) + const fillDot = -dx * 0.78 + dy * 0.24 + dz * 0.58; + const fillCard = THREE.MathUtils.smoothstep(fillDot, 0.82, 0.92); + r += fillCard * 0.75; + g += fillCard * 0.88; + b += fillCard * 1.05; const idx = (y * width + x) * 4; data[idx] = r; @@ -164,10 +183,6 @@ function createStudioHdrEquirectTexture(): THREE.DataTexture { return tex; } -/** - * Outlines exactly the meshes it is given. The stock pass also outlines every child, and parts are - * nested (the casing sits under the drip tray), so selecting one part would outline the whole model. - */ class PartOutlinePass extends OutlinePass { _updateSelectionCache(): void { const cache = (this as unknown as { _selectionCache: Set })._selectionCache; @@ -179,7 +194,6 @@ class PartOutlinePass extends OutlinePass { const FLOW_COLOUR = 0xc9cdd3; const FLOW_LOOP_COLOUR = 0xff4f9a; -/** Tubes for one flow, drawn in the same line style the flow key uses. */ function flowLineGeometries( curve: THREE.Curve, style: LineStyle, @@ -228,6 +242,52 @@ function flowLineGeometries( return [new THREE.TubeGeometry(curve, 20, radius, 6, false)]; } +function createMachinedSectionCapMaterial(clipPlane: THREE.Plane): THREE.MeshStandardMaterial { + const mat = new THREE.MeshStandardMaterial({ + color: new THREE.Color('#9aa3b0'), + roughness: 0.34, + metalness: 0.86, + stencilWrite: true, + stencilRef: 0, + stencilFunc: THREE.NotEqualStencilFunc, + stencilFail: THREE.ReplaceStencilOp, + stencilZFail: THREE.ReplaceStencilOp, + stencilZPass: THREE.ReplaceStencilOp, + side: THREE.DoubleSide, + }); + + if (typeof document !== 'undefined') { + const size = 128; + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext('2d'); + if (ctx) { + ctx.fillStyle = '#d8dce2'; + ctx.fillRect(0, 0, size, size); + ctx.strokeStyle = '#9aa2ae'; + ctx.lineWidth = 1.2; + for (let i = -size; i < size * 2; i += 6) { + ctx.beginPath(); + ctx.moveTo(i, 0); + ctx.lineTo(i + size, size); + ctx.stroke(); + } + const tex = new THREE.CanvasTexture(canvas); + tex.wrapS = THREE.RepeatWrapping; + tex.wrapT = THREE.RepeatWrapping; + tex.repeat.set(10, 10); + mat.roughnessMap = tex; + mat.bumpMap = tex; + mat.bumpScale = 0.004; + } + } + + mat.clippingPlanes = []; + void clipPlane; + return mat; +} + export class DecoderViewport { public readonly isSoftwareGl: boolean; public readonly renderer: THREE.WebGLRenderer; @@ -247,19 +307,24 @@ export class DecoderViewport { private composer: EffectComposer | null = null; private renderPass: RenderPass | null = null; - private outlinePass: PartOutlinePass | null = null; private gtaoPass: GTAOPass | null = null; + private bloomPass: UnrealBloomPass | null = null; private bokehPass: BokehPass | null = null; + private outlinePass: PartOutlinePass | null = null; private outputPass: OutputPass | null = null; private hdrEquirectTex: THREE.DataTexture | null = null; private pmremEnvTex: THREE.Texture | null = null; private modelRoot = new THREE.Group(); + private explosionGuidesGroup = new THREE.Group(); + private stencilCapGroup = new THREE.Group(); private relationshipGroup = new THREE.Group(); private sectionHelperMesh: THREE.Mesh; + private sectionCapMesh: THREE.Mesh; private gridHelper: THREE.GridHelper; private shadowDisc: THREE.Mesh; + private ptFloorCatcher: THREE.Mesh; private keyLight: THREE.DirectionalLight; private fillLight: THREE.DirectionalLight; @@ -270,9 +335,25 @@ export class DecoderViewport { private clipPlane = new THREE.Plane(new THREE.Vector3(-1, 0, 0), 0); private shadowTex: THREE.CanvasTexture | null = null; + private contactShadowCam: THREE.OrthographicCamera | null = null; + private contactShadowRT: THREE.WebGLRenderTarget | null = null; + private contactShadowBlurRT: THREE.WebGLRenderTarget | null = null; + private contactShadowDepthMat: THREE.ShaderMaterial | null = null; + private contactShadowHBlurMat: THREE.ShaderMaterial | null = null; + private contactShadowVBlurMat: THREE.ShaderMaterial | null = null; + private contactShadowBlurQuad: THREE.Mesh | null = null; + private contactShadowBlurScene: THREE.Scene | null = null; + private contactShadowBlurCam: THREE.OrthographicCamera | null = null; + private lastContactShadowExplosion = -1; + private contactShadowFrameTick = 0; + private componentObjects = new Map(); private baseTransforms = new Map(); private componentMaterials = new Map(); + // De-cluttered, phone-readable 3D tubular explosion guide rods + seated anchor rings + private explosionGuideItems = new Map(); + // Per-component extra clearance nudge so stacked exploded parts never overlap along the same axis + private explosionExtraClearance = new Map(); private explosionPlan: ExplosionPlan = { offsets: {}, order: [], subsystems: {} }; private project: DecoderProject; private paramValues: Record = {}; @@ -300,6 +381,7 @@ export class DecoderViewport { }; private currentExplosion = 0; + private explosionVelocity = 0; private cameraTweenTarget: { pos: THREE.Vector3; target: THREE.Vector3; fov: number } | null = null; private callbacks: ViewportCallbacks = {}; private interactables: THREE.Object3D[] = []; @@ -332,16 +414,18 @@ export class DecoderViewport { this.renderer = new THREE.WebGLRenderer({ antialias: !this.isSoftwareGl, + stencil: true, powerPreference: 'high-performance', preserveDrawingBuffer: true, }); this.renderer.outputColorSpace = THREE.SRGBColorSpace; - this.renderer.toneMapping = THREE.ACESFilmicToneMapping; + this.renderer.toneMapping = THREE.AgXToneMapping; this.renderer.toneMappingExposure = 1.08; this.renderer.setPixelRatio(this.isSoftwareGl ? 1 : Math.min(window.devicePixelRatio || 1, 2)); this.renderer.setSize(w, h, false); + // Enable crisp shadows on hardware, and keep studio HDRI reflections on BOTH hardware & software GL! this.renderer.shadowMap.enabled = !this.isSoftwareGl; - this.renderer.shadowMap.type = THREE.PCFShadowMap; + this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; this.renderer.localClippingEnabled = true; this.renderer.domElement.style.display = 'block'; @@ -355,17 +439,24 @@ export class DecoderViewport { this.scene = new THREE.Scene(); const pmrem = new THREE.PMREMGenerator(this.renderer); - if (!this.isSoftwareGl) { + try { this.hdrEquirectTex = createStudioHdrEquirectTexture(); pmrem.compileEquirectangularShader(); this.pmremEnvTex = pmrem.fromEquirectangular(this.hdrEquirectTex).texture; - this.scene.environment = this.pmremEnvTex; - } else { - this.pmremEnvTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; - this.scene.environment = this.pmremEnvTex; + } catch { + this.hdrEquirectTex?.dispose(); + this.hdrEquirectTex = null; + const room = new RoomEnvironment(); + try { + this.pmremEnvTex = pmrem.fromScene(room, 0.04).texture; + } finally { + room.dispose(); + } + } finally { + pmrem.dispose(); } - this.scene.environmentIntensity = 1.0; - pmrem.dispose(); + this.scene.environment = this.pmremEnvTex; + this.scene.environmentIntensity = 1.22; this.perspCamera = new THREE.PerspectiveCamera(initialProject.defaultCamera.fov ?? 38, aspect, 0.04, 150); this.perspCamera.position.set(...initialProject.defaultCamera.position); @@ -438,49 +529,47 @@ export class DecoderViewport { }); this.scene.add(this.transformControls.getHelper()); - // Calibrated 3-Point Studio Lighting Rig + Softbox RectAreaLights - this.hemiLight = new THREE.HemisphereLight('#bcd2f5', '#1d222c', 0.85); + // High-contrast warm-key / cool-rim studio lighting (makes warm brass vs cool steel unmistakable at phone scale) + this.hemiLight = new THREE.HemisphereLight('#b8d4ff', '#090b10', 0.18); this.scene.add(this.hemiLight); - this.keyLight = new THREE.DirectionalLight('#fff5e6', 2.35); - this.keyLight.position.set(6, 9, 7); + this.keyLight = new THREE.DirectionalLight('#fff2df', 2.15); + this.keyLight.position.set(5.5, 8.5, 6.5); this.keyLight.castShadow = !this.isSoftwareGl; this.keyLight.shadow.mapSize.set(this.isSoftwareGl ? 512 : 2048, this.isSoftwareGl ? 512 : 2048); - const d = 5.5; + const d = 3.6; this.keyLight.shadow.camera.left = -d; this.keyLight.shadow.camera.right = d; this.keyLight.shadow.camera.top = d; this.keyLight.shadow.camera.bottom = -d; this.keyLight.shadow.camera.near = 0.5; - this.keyLight.shadow.camera.far = 30; - this.keyLight.shadow.bias = -0.0004; - this.keyLight.shadow.normalBias = 0.018; + this.keyLight.shadow.camera.far = 26; + this.keyLight.shadow.bias = -0.00025; + this.keyLight.shadow.normalBias = 0.012; + this.keyLight.shadow.radius = 2.2; this.scene.add(this.keyLight); - this.rimLight = new THREE.DirectionalLight('#93c5fd', 1.18); - // Low behind the model: at (-6, 5, -7) every flat glossy top mirrored it straight into the - // default front-right camera, so dark plastics and paint read as silver. - this.rimLight.position.set(-6, 1.4, -7); + this.rimLight = new THREE.DirectionalLight('#7dd3fc', 1.35); + this.rimLight.position.set(-5.8, 4.8, -6.5); this.scene.add(this.rimLight); - this.fillLight = new THREE.DirectionalLight('#dbeafe', 0.65); - this.fillLight.position.set(-5, 3.5, 6); + this.fillLight = new THREE.DirectionalLight('#dbeafe', 0.18); + this.fillLight.position.set(-5, 2.5, 5); this.scene.add(this.fillLight); if (!this.isSoftwareGl) { RectAreaLightUniformsLib.init(); - this.rectLightTop = new THREE.RectAreaLight('#ffffff', 2.1, 5.0, 2.8); - this.rectLightTop.position.set(0, 6.8, 3.6); - this.rectLightTop.lookAt(0, 0.5, 0); + this.rectLightTop = new THREE.RectAreaLight('#ffffff', 1.25, 4.2, 2.4); + this.rectLightTop.position.set(0, 5.8, 2.8); + this.rectLightTop.lookAt(0, 0.4, 0); this.scene.add(this.rectLightTop); - this.rectLightSide = new THREE.RectAreaLight('#dbeafe', 1.4, 3.4, 4.0); - this.rectLightSide.position.set(-5.2, 3.2, 4.2); - this.rectLightSide.lookAt(0, 0.5, 0); + this.rectLightSide = new THREE.RectAreaLight('#bae6fd', 0.72, 2.8, 3.6); + this.rectLightSide.position.set(-4.8, 2.8, 3.8); + this.rectLightSide.lookAt(0, 0.4, 0); this.scene.add(this.rectLightSide); } - // Ground Grid & Soft Radial Contact Shadow Plane this.gridHelper = new THREE.GridHelper(18, 24, '#2a3241', '#1f2531'); this.gridHelper.position.y = -0.02; this.scene.add(this.gridHelper); @@ -491,31 +580,48 @@ export class DecoderViewport { const sCtx = shadowCanvas.getContext('2d'); if (sCtx) { const grad = sCtx.createRadialGradient(128, 128, 6, 128, 128, 124); - grad.addColorStop(0, 'rgba(0,0,0,0.68)'); - grad.addColorStop(0.42, 'rgba(0,0,0,0.32)'); + grad.addColorStop(0, 'rgba(0,0,0,0.72)'); + grad.addColorStop(0.42, 'rgba(0,0,0,0.34)'); grad.addColorStop(0.75, 'rgba(0,0,0,0.08)'); grad.addColorStop(1, 'rgba(0,0,0,0)'); sCtx.fillStyle = grad; sCtx.fillRect(0, 0, 256, 256); } this.shadowTex = new THREE.CanvasTexture(shadowCanvas); + + if (!this.isSoftwareGl) { + this.initContactShadows(); + } + const shadowGeo = new THREE.PlaneGeometry(6.8, 6.8); shadowGeo.rotateX(-Math.PI / 2); const shadowMat = new THREE.MeshBasicMaterial({ - map: this.shadowTex, + map: this.contactShadowRT ? this.contactShadowRT.texture : this.shadowTex, transparent: true, + opacity: this.contactShadowRT ? 0.9 : 1.0, depthWrite: false, }); this.shadowDisc = new THREE.Mesh(shadowGeo, shadowMat); this.shadowDisc.position.y = -0.015; this.scene.add(this.shadowDisc); - // Section plane helper + const ptFloorGeo = new THREE.CircleGeometry(18, 64); + ptFloorGeo.rotateX(-Math.PI / 2); + const ptFloorMat = new THREE.MeshStandardMaterial({ + color: new THREE.Color('#12151c'), + roughness: 0.82, + metalness: 0.04, + }); + this.ptFloorCatcher = new THREE.Mesh(ptFloorGeo, ptFloorMat); + this.ptFloorCatcher.position.y = -0.018; + this.ptFloorCatcher.visible = false; + this.scene.add(this.ptFloorCatcher); + const secGeo = new THREE.PlaneGeometry(5.5, 5.5); const secMat = new THREE.MeshBasicMaterial({ color: 0xf5f5f5, transparent: true, - opacity: 0.08, + opacity: 0.05, side: THREE.DoubleSide, depthWrite: false, }); @@ -523,34 +629,65 @@ export class DecoderViewport { this.sectionHelperMesh.visible = false; this.scene.add(this.sectionHelperMesh); + const capPlaneGeo = new THREE.PlaneGeometry(14, 14); + const capMat = createMachinedSectionCapMaterial(this.clipPlane); + this.sectionCapMesh = new THREE.Mesh(capPlaneGeo, capMat); + this.sectionCapMesh.renderOrder = 2; + this.sectionCapMesh.visible = false; + this.scene.add(this.sectionCapMesh); + + this.explosionGuidesGroup.name = '__explosion_axis_guides__'; + this.stencilCapGroup.name = '__stencil_caps__'; + this.scene.add(this.modelRoot); + this.scene.add(this.stencilCapGroup); + this.scene.add(this.explosionGuidesGroup); this.scene.add(this.effectsManager.root); this.scene.add(this.relationshipGroup); - // Hardware-only Post-Processing Pipeline (GTAO + optional Bokeh DOF + ACES Output) if (!this.isSoftwareGl) { try { - this.composer = new EffectComposer(this.renderer); + const pixelRatio = this.renderer.getPixelRatio(); + const hdrRenderTarget = new THREE.WebGLRenderTarget( + Math.max(1, Math.floor(w * pixelRatio)), + Math.max(1, Math.floor(h * pixelRatio)), + { + type: THREE.HalfFloatType, + samples: 4, + colorSpace: THREE.LinearSRGBColorSpace, + stencilBuffer: true, + depthBuffer: true, + }, + ); + + this.composer = new EffectComposer(this.renderer, hdrRenderTarget); + this.composer.setPixelRatio(pixelRatio); + this.composer.setSize(w, h); + this.renderPass = new RenderPass(this.scene, this.camera); this.composer.addPass(this.renderPass); this.gtaoPass = new GTAOPass(this.scene, this.camera, w, h); this.gtaoPass.output = GTAOPass.OUTPUT.Default; this.gtaoPass.updateGtaoMaterial({ - radius: 0.28, - distanceExponent: 1.5, - thickness: 1.0, - scale: 1.05, - samples: 12, + radius: 0.26, + distanceExponent: 1.6, + thickness: 0.9, + scale: 1.18, + samples: 16, distanceFallOff: 1.0, + screenSpaceRadius: false, }); - this.gtaoPass.blendIntensity = 0.68; + this.gtaoPass.blendIntensity = 0.88; this.composer.addPass(this.gtaoPass); + this.bloomPass = new UnrealBloomPass(new THREE.Vector2(w, h), 0.18, 0.36, 1.05); + this.composer.addPass(this.bloomPass); + this.bokehPass = new BokehPass(this.scene, this.perspCamera, { focus: 4.5, - aperture: 0.00018, - maxblur: 0.007, + aperture: 0.00016, + maxblur: 0.006, }); this.bokehPass.enabled = false; this.composer.addPass(this.bokehPass); @@ -558,7 +695,7 @@ export class DecoderViewport { this.outlinePass = new PartOutlinePass(new THREE.Vector2(w, h), this.scene, this.camera); this.outlinePass.visibleEdgeColor.set('#ff4f9a'); this.outlinePass.hiddenEdgeColor.set('#5c2a40'); - this.outlinePass.edgeStrength = 4; + this.outlinePass.edgeStrength = 3.5; this.outlinePass.edgeThickness = 1; this.outlinePass.edgeGlow = 0; this.composer.addPass(this.outlinePass); @@ -581,11 +718,208 @@ export class DecoderViewport { this.startLoop(); } + private initContactShadows(): void { + const res = 256; + this.contactShadowRT = new THREE.WebGLRenderTarget(res, res, { + magFilter: THREE.LinearFilter, + minFilter: THREE.LinearFilter, + generateMipmaps: false, + }); + this.contactShadowBlurRT = new THREE.WebGLRenderTarget(res, res, { + magFilter: THREE.LinearFilter, + minFilter: THREE.LinearFilter, + generateMipmaps: false, + }); + + this.contactShadowCam = new THREE.OrthographicCamera(-3.4, 3.4, 3.4, -3.4, 0.01, 7.5); + this.contactShadowCam.rotation.x = Math.PI / 2; + + this.contactShadowDepthMat = new THREE.ShaderMaterial({ + uniforms: { + darkness: { value: 0.85 }, + maxHeight: { value: 4.8 }, + }, + vertexShader: ` + varying float vHeight; + void main() { + vec4 mvPos = modelViewMatrix * vec4(position, 1.0); + vHeight = -mvPos.z; + gl_Position = projectionMatrix * mvPos; + } + `, + fragmentShader: ` + uniform float darkness; + uniform float maxHeight; + varying float vHeight; + void main() { + float falloff = clamp(1.0 - vHeight / maxHeight, 0.0, 1.0); + float alpha = pow(falloff, 1.85) * darkness; + gl_FragColor = vec4(0.0, 0.0, 0.0, alpha); + } + `, + transparent: true, + depthTest: true, + depthWrite: true, + }); + + const blurVert = ` + varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `; + const makeBlurFrag = (horiz: boolean) => ` + uniform sampler2D tDiffuse; + uniform float blurStep; + varying vec2 vUv; + void main() { + vec4 sum = vec4(0.0); + vec2 dir = ${horiz ? 'vec2(blurStep, 0.0)' : 'vec2(0.0, blurStep)'}; + sum += texture2D(tDiffuse, vUv - 4.0 * dir) * 0.051; + sum += texture2D(tDiffuse, vUv - 3.0 * dir) * 0.0918; + sum += texture2D(tDiffuse, vUv - 2.0 * dir) * 0.12245; + sum += texture2D(tDiffuse, vUv - 1.0 * dir) * 0.1531; + sum += texture2D(tDiffuse, vUv) * 0.1633; + sum += texture2D(tDiffuse, vUv + 1.0 * dir) * 0.1531; + sum += texture2D(tDiffuse, vUv + 2.0 * dir) * 0.12245; + sum += texture2D(tDiffuse, vUv + 3.0 * dir) * 0.0918; + sum += texture2D(tDiffuse, vUv + 4.0 * dir) * 0.051; + vec2 edge = smoothstep(vec2(0.0), vec2(0.14), vUv) * (1.0 - smoothstep(vec2(0.86), vec2(1.0), vUv)); + gl_FragColor = vec4(0.0, 0.0, 0.0, sum.a * edge.x * edge.y); + } + `; + + this.contactShadowHBlurMat = new THREE.ShaderMaterial({ + uniforms: { tDiffuse: { value: null }, blurStep: { value: 1.5 / res } }, + vertexShader: blurVert, + fragmentShader: makeBlurFrag(true), + depthTest: false, + depthWrite: false, + }); + this.contactShadowVBlurMat = new THREE.ShaderMaterial({ + uniforms: { tDiffuse: { value: null }, blurStep: { value: 1.5 / res } }, + vertexShader: blurVert, + fragmentShader: makeBlurFrag(false), + depthTest: false, + depthWrite: false, + }); + + this.contactShadowBlurScene = new THREE.Scene(); + this.contactShadowBlurCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); + this.contactShadowBlurQuad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.contactShadowHBlurMat); + this.contactShadowBlurScene.add(this.contactShadowBlurQuad); + } + + private renderContactShadow(): void { + if ( + this.isSoftwareGl || + !this.contactShadowRT || + !this.contactShadowBlurRT || + !this.contactShadowCam || + !this.contactShadowDepthMat || + !this.contactShadowHBlurMat || + !this.contactShadowVBlurMat || + !this.contactShadowBlurScene || + !this.contactShadowBlurCam || + !this.contactShadowBlurQuad + ) { + return; + } + + this.contactShadowFrameTick++; + if ( + this.state.playing && + Math.abs(this.currentExplosion - this.lastContactShadowExplosion) < 0.003 && + this.contactShadowFrameTick % 2 !== 0 + ) { + return; + } + this.lastContactShadowExplosion = this.currentExplosion; + + const prevBg = this.scene.background; + const prevEnv = this.scene.environment; + const prevFog = this.scene.fog; + const prevOverride = this.scene.overrideMaterial; + const prevClearAlpha = this.renderer.getClearAlpha(); + const prevClearColor = this.renderer.getClearColor(new THREE.Color()); + const prevShadowEnabled = this.renderer.shadowMap.enabled; + const prevClip = this.renderer.localClippingEnabled; + + const prevGridVis = this.gridHelper.visible; + const prevShadowVis = this.shadowDisc.visible; + const prevEffectsVis = this.effectsManager.root.visible; + const prevGuidesVis = this.explosionGuidesGroup.visible; + const prevRelVis = this.relationshipGroup.visible; + const prevSecVis = this.sectionHelperMesh.visible; + const prevCapVis = this.sectionCapMesh.visible; + const prevStencilVis = this.stencilCapGroup.visible; + const prevGizmoVis = this.transformControls.getHelper().visible; + + this.scene.background = null; + this.scene.environment = null; + this.scene.fog = null; + this.scene.overrideMaterial = this.contactShadowDepthMat; + this.renderer.shadowMap.enabled = false; + this.renderer.localClippingEnabled = false; + + this.gridHelper.visible = false; + this.shadowDisc.visible = false; + this.effectsManager.root.visible = false; + this.explosionGuidesGroup.visible = false; + this.relationshipGroup.visible = false; + this.sectionHelperMesh.visible = false; + this.sectionCapMesh.visible = false; + this.stencilCapGroup.visible = false; + this.transformControls.getHelper().visible = false; + + const blurScale = (1.35 + this.currentExplosion * 1.15) / 256; + this.contactShadowHBlurMat.uniforms['blurStep'].value = blurScale; + this.contactShadowVBlurMat.uniforms['blurStep'].value = blurScale; + + const prevRT = this.renderer.getRenderTarget(); + this.renderer.setClearColor(0x000000, 0); + + this.renderer.setRenderTarget(this.contactShadowRT); + this.renderer.clear(); + this.renderer.render(this.scene, this.contactShadowCam); + + this.contactShadowBlurQuad.material = this.contactShadowHBlurMat; + this.contactShadowHBlurMat.uniforms['tDiffuse'].value = this.contactShadowRT.texture; + this.renderer.setRenderTarget(this.contactShadowBlurRT); + this.renderer.clear(); + this.renderer.render(this.contactShadowBlurScene, this.contactShadowBlurCam); + + this.contactShadowBlurQuad.material = this.contactShadowVBlurMat; + this.contactShadowVBlurMat.uniforms['tDiffuse'].value = this.contactShadowBlurRT.texture; + this.renderer.setRenderTarget(this.contactShadowRT); + this.renderer.clear(); + this.renderer.render(this.contactShadowBlurScene, this.contactShadowBlurCam); + + this.renderer.setRenderTarget(prevRT); + this.renderer.setClearColor(prevClearColor, prevClearAlpha); + this.renderer.shadowMap.enabled = prevShadowEnabled; + this.renderer.localClippingEnabled = prevClip; + + this.scene.overrideMaterial = prevOverride; + this.scene.background = prevBg; + this.scene.environment = prevEnv; + this.scene.fog = prevFog; + + this.gridHelper.visible = prevGridVis; + this.shadowDisc.visible = prevShadowVis; + this.effectsManager.root.visible = prevEffectsVis; + this.explosionGuidesGroup.visible = prevGuidesVis; + this.relationshipGroup.visible = prevRelVis; + this.sectionHelperMesh.visible = prevSecVis; + this.sectionCapMesh.visible = prevCapVis; + this.stencilCapGroup.visible = prevStencilVis; + this.transformControls.getHelper().visible = prevGizmoVis; + } + private resizeObserver: ResizeObserver | null = null; - /** Pixels on each side of the canvas covered by overlays; the model is fitted into what is left. */ private viewInsets = { left: 0, right: 0 }; - /** Keeps the framing inside the part of the canvas no panel covers. A single number is a right inset. */ public setViewInset(inset: number | { left?: number; right?: number }): void { const raw = typeof inset === 'number' ? { left: 0, right: inset } : inset; const left = Math.max(0, Math.round(raw.left ?? 0)); @@ -595,15 +929,11 @@ export class DecoderViewport { this.onResize(); } - /** Bounding sphere of the assembled model, measured when an exhibit loads. */ private modelRadius = 0; - /** How far the assembled model reaches from the camera target; the baseline for pulling apart. */ private restReach = 0; - /** Extra zoom out so pulled-apart parts stay in frame (1 when assembled). */ private explodeZoom = 1; private lastFitExplosion = 0; - /** Distance from the default camera target to the far side of the model's current bounds. */ private measureReach(): number { _tmpBox.setFromObject(this.modelRoot); if (_tmpBox.isEmpty() || !this.project) return 0; @@ -612,7 +942,6 @@ export class DecoderViewport { return centre.distanceTo(target) + _tmpBox.getSize(_tmpSize).length() / 2; } - /** Re-fits the frame as parts move apart, so the camera pulls back instead of losing them off screen. */ private refitForExplosion(): void { if (Math.abs(this.currentExplosion - this.lastFitExplosion) < 0.002) return; this.lastFitExplosion = this.currentExplosion; @@ -623,12 +952,6 @@ export class DecoderViewport { this.applyViewOffset(this.container.clientWidth || 800, Math.max(1, this.container.clientHeight || 600)); } - /** - * How the default framing maps into the free part of the canvas. The model's bounding sphere, seen - * from the exhibit's default camera distance, must fit the width the overlays leave free (on a tall - * phone screen that is simply the canvas width). The whole frame is scaled down until it does, then - * its centre moves to the centre of the free area. Zooming by hand still works on top of this. - */ private frameFit(w: number, h: number): { scale: number; centreX: number } { const total = this.viewInsets.left + this.viewInsets.right; const shrink = total > w * 0.75 ? (w * 0.75) / total : 1; @@ -646,7 +969,6 @@ export class DecoderViewport { return { scale: Math.max(0.2, scale * this.explodeZoom), centreX: left + freeW / 2 }; } - /** Aspect of the virtual frame; the view offset keeps it equal to the canvas aspect. */ private frameAspect(): number { const w = this.container.clientWidth || 800; const h = Math.max(1, this.container.clientHeight || 600); @@ -656,7 +978,6 @@ export class DecoderViewport { private applyViewOffset(w: number, h: number): void { const { scale, centreX } = this.frameFit(w, h); const identity = scale > 0.999 && Math.abs(centreX - w / 2) < 0.5; - // A virtual frame smaller than the canvas widens the visible frustum: that is the zoom out. const fullW = w * scale; const fullH = h * scale; const x = fullW / 2 - centreX; @@ -756,6 +1077,7 @@ export class DecoderViewport { this.renderer.setSize(w, h, false); this.composer?.setSize(w, h); this.gtaoPass?.setSize(w, h); + this.bloomPass?.setSize(w, h); if (this.bokehPass) { (this.bokehPass.uniforms as Record)['aspect'].value = aspect; } @@ -769,17 +1091,21 @@ export class DecoderViewport { const cfg = LIGHTING_PRESETS[presetId] ?? LIGHTING_PRESETS.technical_studio; this.state.lightingPreset = presetId; this.scene.background = new THREE.Color(cfg.background); - this.scene.fog = new THREE.FogExp2(cfg.fogColor, cfg.fogDensity); + this.scene.fog = new THREE.FogExp2(cfg.fogColor, cfg.fogDensity * 0.72); this.keyLight.color.set(cfg.keyColor); - this.keyLight.intensity = cfg.keyIntensity; + this.keyLight.intensity = cfg.keyIntensity * 0.85; this.keyLight.position.set(...cfg.keyPosition); this.hemiLight.color.set(cfg.fillSkyColor); this.hemiLight.groundColor.set(cfg.fillGroundColor); - this.hemiLight.intensity = cfg.fillIntensity; + this.hemiLight.intensity = cfg.isLightBackdrop ? cfg.fillIntensity * 0.62 : cfg.fillIntensity * 0.24; this.rimLight.color.set(cfg.rimColor); - this.rimLight.intensity = cfg.rimIntensity; + this.rimLight.intensity = cfg.rimIntensity * 0.95; this.renderer.toneMappingExposure = this.state.exposure || cfg.exposure; + (this.ptFloorCatcher.material as THREE.MeshStandardMaterial).color.set( + cfg.isLightBackdrop ? '#dce2ec' : cfg.background, + ); + const gridMats = Array.isArray(this.gridHelper.material) ? this.gridHelper.material : [this.gridHelper.material]; gridMats.forEach((m) => { const lm = m as THREE.LineBasicMaterial; @@ -793,14 +1119,260 @@ export class DecoderViewport { this.requestRender(); } + /** + * Increases clearance between nearby parts that separate along a shared axis. + */ + private computeExplosionClearanceMap(project: DecoderProject): void { + this.explosionExtraClearance.clear(); + this.modelRoot.updateMatrixWorld(true); + + interface PartSlot { + id: string; + parentId?: string; + worldCenter: THREE.Vector3; + halfHeight: number; + halfRadius: number; + baseOffset: THREE.Vector3; + axisKey: string; + projCoord: number; + } + + const slots: PartSlot[] = []; + for (const comp of project.components) { + if (!comp.geometry || comp.layer === 'fluid') continue; + const obj = this.componentObjects.get(comp.id); + if (!obj) continue; + const rawOff = computeHierarchicalExplosionOffset(comp, 1, this.explosionPlan); + const baseVec = new THREE.Vector3(...rawOff); + const len = baseVec.length(); + if (len < 0.025) continue; + + const box = new THREE.Box3().setFromObject(obj); + if (box.isEmpty()) continue; + const center = box.getCenter(new THREE.Vector3()); + const size = box.getSize(new THREE.Vector3()); + + // Classify primary explosion axis ('y', 'x', 'z', or 'radial') + const ax = Math.abs(baseVec.x); + const ay = Math.abs(baseVec.y); + const az = Math.abs(baseVec.z); + let axisKey = 'radial'; + if (ay >= ax * 1.35 && ay >= az * 1.35) { + axisKey = 'y'; + } else if (ax >= ay * 1.35 && ax >= az * 1.35) { + axisKey = 'x'; + } else if (az >= ax * 1.35 && az >= ay * 1.35) { + axisKey = 'z'; + } + + const fullTarget = center.clone().add(baseVec); + const projCoord = + axisKey === 'y' ? fullTarget.y : axisKey === 'x' ? fullTarget.x : axisKey === 'z' ? fullTarget.z : len; + const halfSpan = + axisKey === 'y' + ? size.y * 0.5 + : axisKey === 'x' + ? size.x * 0.5 + : axisKey === 'z' + ? size.z * 0.5 + : size.length() * 0.28; + + slots.push({ + id: comp.id, + parentId: comp.parentId ?? undefined, + worldCenter: center, + halfHeight: Math.max(0.03, halfSpan), + halfRadius: Math.max(size.x, size.z) * 0.5, + baseOffset: baseVec, + axisKey, + projCoord, + }); + } + + // Resolve overlaps along major axial stacks (especially vertical Y stacks in engine, watch & processor) + for (const axis of ['y', 'x', 'z'] as const) { + const group = slots.filter((s) => s.axisKey === axis); + if (group.length < 2) continue; + + // Sort from bottom/negative to top/positive along the axis + group.sort((a, b) => a.projCoord - b.projCoord); + const minAirGap = Math.max(0.085, this.modelRadius * 0.11); + + // Forward & symmetric outward pass from stack median so parts fan out cleanly with visible daylight + const midIdx = Math.floor(group.length / 2); + const adjusted = group.map((g) => g.projCoord); + + for (let i = midIdx + 1; i < group.length; i++) { + const prev = group[i - 1]; + const curr = group[i]; + // Check lateral proximity perpendicular to explosion axis + const dx = axis === 'x' ? 0 : curr.worldCenter.x - prev.worldCenter.x; + const dy = axis === 'y' ? 0 : curr.worldCenter.y - prev.worldCenter.y; + const dz = axis === 'z' ? 0 : curr.worldCenter.z - prev.worldCenter.z; + if (prev.parentId === curr.parentId && Math.hypot(dx, dy, dz) < (prev.halfRadius + curr.halfRadius) * 0.85) { + const needed = adjusted[i - 1] + prev.halfHeight + curr.halfHeight + minAirGap; + if (adjusted[i] < needed) adjusted[i] = needed; + } + } + + for (let i = midIdx - 1; i >= 0; i--) { + const next = group[i + 1]; + const curr = group[i]; + const dx = axis === 'x' ? 0 : curr.worldCenter.x - next.worldCenter.x; + const dy = axis === 'y' ? 0 : curr.worldCenter.y - next.worldCenter.y; + const dz = axis === 'z' ? 0 : curr.worldCenter.z - next.worldCenter.z; + if (next.parentId === curr.parentId && Math.hypot(dx, dy, dz) < (next.halfRadius + curr.halfRadius) * 0.85) { + const maxAllowed = adjusted[i + 1] - (next.halfHeight + curr.halfHeight + minAirGap); + if (adjusted[i] > maxAllowed) adjusted[i] = maxAllowed; + } + } + + for (let i = 0; i < group.length; i++) { + const delta = adjusted[i] - group[i].projCoord; + // Amplify overall axial spread slightly (+22%) + non-overlapping stack delta, capped cleanly + const clampedDelta = THREE.MathUtils.clamp(delta, -this.modelRadius * 1.1, this.modelRadius * 1.1); + const extra: Vec3 = [ + group[i].baseOffset.x * 0.22 + (axis === 'x' ? clampedDelta : 0), + group[i].baseOffset.y * 0.22 + (axis === 'y' ? clampedDelta : 0), + group[i].baseOffset.z * 0.22 + (axis === 'z' ? clampedDelta : 0), + ]; + this.explosionExtraClearance.set(group[i].id, extra); + } + } + + // Give radial parts a clean +22% breathing boost too + for (const s of slots) { + if (!this.explosionExtraClearance.has(s.id)) { + this.explosionExtraClearance.set(s.id, [s.baseOffset.x * 0.22, s.baseOffset.y * 0.22, s.baseOffset.z * 0.22]); + } + } + } + + /** + * Builds real 3D tubular disassembly guide rods + seated origin rings (works in BOTH hardware & + * SwiftShader software WebGL, unlike 1px GL_LINES which vanish on Retina/mobile thumbnails!). + */ + private rebuildExplosionGuides(project: DecoderProject): void { + for (const item of this.explosionGuideItems.values()) { + item.rod.geometry.dispose(); + (item.rod.material as THREE.Material).dispose(); + item.originRing.geometry.dispose(); + (item.originRing.material as THREE.Material).dispose(); + item.partCollar.geometry.dispose(); + (item.partCollar.material as THREE.Material).dispose(); + } + this.explosionGuideItems.clear(); + this.explosionGuidesGroup.clear(); + + const rodRadius = Math.max(0.0045, this.modelRadius * 0.0048); + // Unit-height cylinder scaled dynamically between seated origin & exploded part + const unitRodGeo = new THREE.CylinderGeometry(rodRadius, rodRadius, 1, 8, 1, false); + const ringGeo = new THREE.TorusGeometry(rodRadius * 3.4, rodRadius * 0.85, 8, 20); + ringGeo.rotateX(Math.PI / 2); + const collarGeo = new THREE.SphereGeometry(rodRadius * 2.3, 10, 8); + + for (const comp of project.components) { + if (!comp.geometry || comp.layer === 'fluid') continue; + const maxOffset = computeHierarchicalExplosionOffset(comp, 1, this.explosionPlan); + if (Math.hypot(maxOffset[0], maxOffset[1], maxOffset[2]) < 0.04) continue; + + const rodMat = new THREE.MeshBasicMaterial({ + color: 0x94a3b8, + transparent: true, + opacity: 0, + depthWrite: false, + }); + const originMat = new THREE.MeshBasicMaterial({ + color: 0x64748b, + transparent: true, + opacity: 0, + depthWrite: false, + }); + const collarMat = new THREE.MeshBasicMaterial({ + color: 0xff4f9a, + transparent: true, + opacity: 0, + depthWrite: false, + }); + + const rod = new THREE.Mesh(unitRodGeo.clone(), rodMat); + const originRing = new THREE.Mesh(ringGeo.clone(), originMat); + const partCollar = new THREE.Mesh(collarGeo.clone(), collarMat); + + rod.frustumCulled = false; + this.explosionGuidesGroup.add(rod, originRing, partCollar); + this.explosionGuideItems.set(comp.id, { rod, originRing, partCollar }); + } + + unitRodGeo.dispose(); + ringGeo.dispose(); + collarGeo.dispose(); + } + + private rebuildStencilSectionPasses(project: DecoderProject): void { + for (const child of this.stencilCapGroup.children) { + const m = child as THREE.Mesh; + (m.material as THREE.Material | undefined)?.dispose(); + } + this.stencilCapGroup.clear(); + if (this.isSoftwareGl) return; + + for (const comp of project.components) { + if (!comp.geometry || comp.layer === 'fluid') continue; + const srcObj = this.componentObjects.get(comp.id); + if (!srcObj || !(srcObj as THREE.Mesh).isMesh) continue; + const geo = (srcObj as THREE.Mesh).geometry; + + const backStencilMat = new THREE.MeshBasicMaterial({ + side: THREE.BackSide, + clippingPlanes: [this.clipPlane], + colorWrite: false, + depthWrite: false, + depthTest: false, + stencilWrite: true, + stencilFunc: THREE.AlwaysStencilFunc, + stencilFail: THREE.KeepStencilOp, + stencilZFail: THREE.KeepStencilOp, + stencilZPass: THREE.IncrementWrapStencilOp, + }); + + const frontStencilMat = new THREE.MeshBasicMaterial({ + side: THREE.FrontSide, + clippingPlanes: [this.clipPlane], + colorWrite: false, + depthWrite: false, + depthTest: false, + stencilWrite: true, + stencilFunc: THREE.AlwaysStencilFunc, + stencilFail: THREE.KeepStencilOp, + stencilZFail: THREE.KeepStencilOp, + stencilZPass: THREE.DecrementWrapStencilOp, + }); + + const backMesh = new THREE.Mesh(geo, backStencilMat); + const frontMesh = new THREE.Mesh(geo, frontStencilMat); + backMesh.renderOrder = 1; + frontMesh.renderOrder = 1; + backMesh.matrixAutoUpdate = false; + frontMesh.matrixAutoUpdate = false; + backMesh.userData.sourceComponentId = comp.id; + frontMesh.userData.sourceComponentId = comp.id; + + this.stencilCapGroup.add(backMesh, frontMesh); + } + } + public loadProject(project: DecoderProject, resetCamera = true): void { this.project = project; this.runtime.setProject(project); this.lastGoodSimulation = undefined; this.state.time = 0; + this.currentExplosion = 0; + this.explosionVelocity = 0; this.paramValues = this.runtime.getDefaultParameters(); this.explosionPlan = buildExplosionPlan(project); this.pathTracerSceneSynced = false; + this.lastContactShadowExplosion = -1; this.transformControls.detach(); if (this.outlinePass) this.outlinePass.selectedObjects = []; @@ -834,7 +1406,7 @@ export class DecoderViewport { this.baseTransforms.set(comp.id, { pos, rot, scale }); this.componentObjects.set(comp.id, obj); objMap.set(comp.id, obj); - if ((obj as THREE.Mesh).isMesh) { + if ((obj as THREE.Mesh).isMesh || (obj as THREE.InstancedMesh).isInstancedMesh) { this.interactables.push(obj); } } @@ -848,21 +1420,46 @@ export class DecoderViewport { } } - // Scale ground contact shadow & grid height cleanly to model footprint this.modelRoot.updateMatrixWorld(true); _tmpBox.setFromObject(this.modelRoot); this.modelRadius = _tmpBox.isEmpty() ? 0 : _tmpBox.getSize(_tmpSize).length() / 2; this.restReach = this.measureReach(); this.explodeZoom = 1; this.lastFitExplosion = 0; + + this.computeExplosionClearanceMap(project); + this.rebuildExplosionGuides(project); + this.rebuildStencilSectionPasses(project); + _tmpBox.setFromObject(this.modelRoot); if (!_tmpBox.isEmpty()) { _tmpBox.getSize(_tmpSize); - const footprint = Math.max(2.2, Math.max(_tmpSize.x, _tmpSize.z) * 1.9); + _tmpBox.getCenter(_tmpCenter); + const footprint = Math.max(2.2, Math.max(_tmpSize.x, _tmpSize.z) * 2.15); this.shadowDisc.scale.set(footprint / 6.8, 1, footprint / 6.8); const floorY = Math.min(-0.02, _tmpBox.min.y - 0.015); - this.shadowDisc.position.y = floorY + 0.005; + this.shadowDisc.position.set(_tmpCenter.x, floorY + 0.005, _tmpCenter.z); + this.ptFloorCatcher.position.set(_tmpCenter.x, floorY + 0.002, _tmpCenter.z); this.gridHelper.position.y = floorY; + + if (this.contactShadowCam && this.contactShadowDepthMat) { + const halfSpan = footprint * 0.5; + this.contactShadowCam.left = -halfSpan; + this.contactShadowCam.right = halfSpan; + this.contactShadowCam.top = halfSpan; + this.contactShadowCam.bottom = -halfSpan; + this.contactShadowCam.far = Math.max(4.5, _tmpSize.y * 3.2); + this.contactShadowCam.position.set(_tmpCenter.x, floorY + 0.004, _tmpCenter.z); + this.contactShadowCam.updateProjectionMatrix(); + this.contactShadowDepthMat.uniforms['maxHeight'].value = Math.max(2.8, _tmpSize.y * 2.4); + } + + const shadowSpan = Math.max(2.0, this.modelRadius * 2.35); + this.keyLight.shadow.camera.left = -shadowSpan; + this.keyLight.shadow.camera.right = shadowSpan; + this.keyLight.shadow.camera.top = shadowSpan; + this.keyLight.shadow.camera.bottom = -shadowSpan; + this.keyLight.shadow.camera.updateProjectionMatrix(); } this.effectsManager.buildForProject(project.effects); @@ -994,8 +1591,6 @@ export class DecoderViewport { } public updateState(next: Partial): void { - // Playback time is owned by the viewport and changed only through setTime(), - // so a full UI state snapshot cannot rewind the simulation. const { time: _time, ...partial } = next; const prevPlaying = this.state.playing; const prevMode = this.state.examinationMode; @@ -1080,7 +1675,6 @@ export class DecoderViewport { } } - /** Heat haze whose source sits inside a casing; it is shown only while the inside is on show. */ private sealedHeatEffectIds = new Set(); private findSealedHeatEffects(project: DecoderProject): void { @@ -1100,7 +1694,6 @@ export class DecoderViewport { } } - /** Heat haze only reads as heat when the inside of the model is on show. */ private showsInterior(): boolean { const mode = this.state.examinationMode; return ( @@ -1147,7 +1740,6 @@ export class DecoderViewport { } const curve = new THREE.CatmullRomCurve3(pts); const style = RELATIONSHIP_LINE[rel.type] ?? 'solid'; - // Flows are neutral grey and told apart by line style; links in a feedback loop are pink. const color = loopIds.has(rel.id) ? FLOW_LOOP_COLOUR : FLOW_COLOUR; const baseOpacity = style === 'faint' ? 0.5 : 0.85; const mat = new THREE.MeshBasicMaterial({ @@ -1179,6 +1771,7 @@ export class DecoderViewport { mat.color.copy(baseMat.color); mat.roughness = baseMat.roughness; mat.metalness = baseMat.metalness; + mat.transmission = baseMat.transmission; mat.wireframe = false; mat.transparent = baseMat.transparent; mat.opacity = baseMat.opacity; @@ -1193,16 +1786,19 @@ export class DecoderViewport { } if (mode === 'cutaway' && (comp.layer === 'casing' || comp.layer === 'exterior')) { + mat.transmission = 0; mat.transparent = true; mat.opacity = 0.16; mat.depthWrite = false; } else if (mode === 'xray') { + mat.transmission = 0; mat.transparent = true; mat.opacity = comp.layer === 'core' || comp.layer === 'internal' ? 0.74 : 0.18; mat.depthWrite = false; mat.emissive.set('#6f7d8c'); mat.emissiveIntensity = 0.18; } else if (mode === 'transparent') { + mat.transmission = 0; mat.transparent = true; mat.opacity = 0.35; mat.depthWrite = false; @@ -1210,6 +1806,7 @@ export class DecoderViewport { mat.wireframe = true; } else if (mode === 'isolated' && selId) { if (comp.id !== selId && comp.parentId !== selId) { + mat.transmission = 0; mat.transparent = true; mat.opacity = 0.1; mat.depthWrite = false; @@ -1223,6 +1820,7 @@ export class DecoderViewport { mat.color.set(tint); mat.roughness = 0.5; mat.metalness = 0.1; + mat.transmission = 0; } else if (mode === 'material') { mat.wireframe = false; mat.transparent = false; @@ -1231,6 +1829,7 @@ export class DecoderViewport { } else if (mode === 'relationship_trace' && trace) { const isRelated = comp.id === selId || trace.upstreamIds.has(comp.id) || trace.downstreamIds.has(comp.id); if (!isRelated) { + mat.transmission = 0; mat.transparent = true; mat.opacity = 0.14; mat.depthWrite = false; @@ -1238,9 +1837,6 @@ export class DecoderViewport { } if (comp.id === selId || this.state.highlightedComponentIds.includes(comp.id)) { - // Selection is a thin pink outline plus a faint neutral lift, so the material keeps its colour. - // Selection is a thin pink outline (drawn by the outline pass) and a faint lift that keeps the - // material's own colour. Without post-processing, a low pink glow stands in for the outline. if (mat.emissiveIntensity < 0.06) { const outlined = Boolean(this.outlinePass) && !this.isSoftwareGl; mat.emissive.set(outlined ? '#ffffff' : '#ff4f9a'); @@ -1253,7 +1849,6 @@ export class DecoderViewport { this.updateSelectionOutline(); } - /** Feeds the selected and highlighted parts to the outline pass. */ private updateSelectionOutline(): void { if (!this.outlinePass) return; const selId = this.state.selectedComponentId; @@ -1280,6 +1875,8 @@ export class DecoderViewport { const active = sec.enabled || this.state.examinationMode === 'cross_section'; this.renderer.localClippingEnabled = active; this.sectionHelperMesh.visible = active; + this.stencilCapGroup.visible = active && !this.isSoftwareGl; + this.sectionCapMesh.visible = active && !this.isSoftwareGl; if (!active) { this.clipPlane.constant = 999; @@ -1301,6 +1898,104 @@ export class DecoderViewport { this.sectionHelperMesh.position.set(0, 0.5, sec.position * 2); } this.clipPlane.constant = sec.position * 2 * dir; + + this.clipPlane.coplanarPoint(this.sectionCapMesh.position); + this.sectionCapMesh.lookAt( + this.sectionCapMesh.position.x - this.clipPlane.normal.x, + this.sectionCapMesh.position.y - this.clipPlane.normal.y, + this.sectionCapMesh.position.z - this.clipPlane.normal.z, + ); + + if (this.stencilCapGroup.visible) { + this.modelRoot.updateMatrixWorld(true); + for (const child of this.stencilCapGroup.children) { + const cid = child.userData.sourceComponentId as string | undefined; + const src = cid ? this.componentObjects.get(cid) : undefined; + if (src) { + child.visible = src.visible; + child.matrix.copy(src.matrixWorld); + child.matrixWorld.copy(src.matrixWorld); + } + } + } + } + + private computeStagedComponentExplosionProgress(compId: string, globalExplosion: number): number { + if (globalExplosion <= 0.0005) return 0; + if (globalExplosion >= 0.999) return 1; + const order = this.explosionPlan.order; + const idx = order.indexOf(compId); + if (idx === -1 || order.length <= 1) return globalExplosion; + + const rankFrac = idx / (order.length - 1); + const windowSpan = 0.68; + const delay = rankFrac * (1 - windowSpan); + const t = THREE.MathUtils.clamp((globalExplosion - delay) / windowSpan, 0, 1); + return t * t * (3 - 2 * t); + } + + private updateExplosionGuideVisuals(): void { + const showGuides = this.currentExplosion > 0.03; + this.explosionGuidesGroup.visible = showGuides; + if (!showGuides) return; + + this.modelRoot.updateMatrixWorld(true); + const selId = this.state.selectedComponentId; + const globalFade = THREE.MathUtils.smoothstep(this.currentExplosion, 0.03, 0.2); + + for (const [cid, guide] of this.explosionGuideItems.entries()) { + const obj = this.componentObjects.get(cid); + const base = this.baseTransforms.get(cid); + if (!obj || !base || !obj.visible) { + guide.rod.visible = false; + guide.originRing.visible = false; + guide.partCollar.visible = false; + continue; + } + + obj.getWorldPosition(_wPosB); + if (obj.parent) { + _wPosA.set(base.pos[0], base.pos[1], base.pos[2]).applyMatrix4(obj.parent.matrixWorld); + } else { + _wPosA.set(base.pos[0], base.pos[1], base.pos[2]); + } + + _wDir.subVectors(_wPosB, _wPosA); + const dist = _wDir.length(); + if (dist < 0.035) { + guide.rod.visible = false; + guide.originRing.visible = false; + guide.partCollar.visible = false; + continue; + } + + guide.rod.visible = true; + guide.originRing.visible = true; + guide.partCollar.visible = true; + + // Orient & stretch 3D guide cylinder cleanly from seated origin to exploded component + guide.rod.position.copy(_wPosA).addScaledVector(_wDir, 0.5); + guide.rod.scale.set(1, dist, 1); + _wDir.normalize(); + guide.rod.quaternion.setFromUnitVectors(_upVec, _wDir); + + guide.originRing.position.copy(_wPosA); + guide.originRing.quaternion.setFromUnitVectors(_upVec, _wDir); + guide.partCollar.position.copy(_wPosB); + + const isSelected = cid === selId || this.state.highlightedComponentIds.includes(cid); + const rodMat = guide.rod.material as THREE.MeshBasicMaterial; + rodMat.color.setHex(isSelected ? 0xff4f9a : 0x7dd3fc); + rodMat.opacity = globalFade * (isSelected ? 0.88 : 0.36); + + const origMat = guide.originRing.material as THREE.MeshBasicMaterial; + origMat.color.setHex(isSelected ? 0xff4f9a : 0x94a3b8); + origMat.opacity = globalFade * (isSelected ? 0.9 : 0.48); + + const colMat = guide.partCollar.material as THREE.MeshBasicMaterial; + colMat.color.setHex(isSelected ? 0xff4f9a : 0xe2e8f0); + colMat.opacity = globalFade * (isSelected ? 0.95 : 0.62); + } } public stepSimulation(dt: number): EvaluatedSimulationState { @@ -1321,9 +2016,22 @@ export class DecoderViewport { const targetExp = this.state.examinationMode === 'exploded' ? Math.max(0.45, this.state.explosion) : this.state.explosion; - this.currentExplosion = this.isSoftwareGl - ? targetExp - : THREE.MathUtils.damp(this.currentExplosion, targetExp, 7, Math.max(0.016, dt)); + + if (this.isSoftwareGl || dt <= 0) { + this.currentExplosion = targetExp; + this.explosionVelocity = 0; + } else { + const omega = 11.5; + const x = this.currentExplosion - targetExp; + const expTerm = Math.exp(-omega * dt); + const temp = (this.explosionVelocity + omega * x) * dt; + this.explosionVelocity = (this.explosionVelocity - omega * temp) * expTerm; + this.currentExplosion = targetExp + (x + temp) * expTerm; + if (Math.abs(this.currentExplosion - targetExp) < 0.0004 && Math.abs(this.explosionVelocity) < 0.002) { + this.currentExplosion = targetExp; + this.explosionVelocity = 0; + } + } for (const comp of this.project.components) { const obj = this.componentObjects.get(comp.id); @@ -1331,12 +2039,18 @@ export class DecoderViewport { if (!obj || !base) continue; const beh = simState.transforms[comp.id]; - const expOffset = computeHierarchicalExplosionOffset(comp, this.currentExplosion, this.explosionPlan); + const stagedProgress = this.computeStagedComponentExplosionProgress(comp.id, this.currentExplosion); + const expOffset = computeHierarchicalExplosionOffset(comp, stagedProgress, this.explosionPlan); + const extraClear = this.explosionExtraClearance.get(comp.id); + + const ex = expOffset[0] + (extraClear ? extraClear[0] * stagedProgress : 0); + const ey = expOffset[1] + (extraClear ? extraClear[1] * stagedProgress : 0); + const ez = expOffset[2] + (extraClear ? extraClear[2] * stagedProgress : 0); obj.position.set( - base.pos[0] + (beh?.position_x ?? 0) + expOffset[0], - base.pos[1] + (beh?.position_y ?? 0) + expOffset[1], - base.pos[2] + (beh?.position_z ?? 0) + expOffset[2], + base.pos[0] + (beh?.position_x ?? 0) + ex, + base.pos[1] + (beh?.position_y ?? 0) + ey, + base.pos[2] + (beh?.position_z ?? 0) + ez, ); obj.rotation.set( base.rot[0] + (beh?.rotation_x ?? 0), @@ -1372,6 +2086,7 @@ export class DecoderViewport { } this.refitForExplosion(); + this.updateExplosionGuideVisuals(); this.applySectionPlane(); this.effectsManager.update( this.state.time, @@ -1381,7 +2096,6 @@ export class DecoderViewport { this.showsInterior() ? undefined : this.sealedHeatEffectIds, ); - // Update DOF focal distance dynamically when enabled if (this.bokehPass && this.bokehPass.enabled) { let focusDist = this.camera.position.distanceTo(this.controls.target); if (this.state.selectedComponentId) { @@ -1394,7 +2108,6 @@ export class DecoderViewport { (this.bokehPass.uniforms as Record)['focus'].value = Math.max(0.2, focusDist); } - // Camera tween damping if (this.cameraTweenTarget) { const alpha = 1 - Math.exp(-6 * Math.max(0.016, dt)); _dampPos.copy(this.camera.position).lerp(this.cameraTweenTarget.pos, alpha); @@ -1435,16 +2148,37 @@ export class DecoderViewport { private renderFrame(): void { if (this.shouldUsePathTracer()) { - // Swap equirectangular HDR texture for WebGLPathTracer sampling if (this.hdrEquirectTex && this.scene.environment !== this.hdrEquirectTex) { this.scene.environment = this.hdrEquirectTex; } if (!this.pathTracerSceneSynced) { + const prevEffects = this.effectsManager.root.visible; + const prevGrid = this.gridHelper.visible; + const prevShadow = this.shadowDisc.visible; + const prevGuides = this.explosionGuidesGroup.visible; + const prevSec = this.sectionHelperMesh.visible; + const prevCap = this.sectionCapMesh.visible; + const prevStencil = this.stencilCapGroup.visible; + this.effectsManager.root.visible = false; this.gridHelper.visible = false; + this.shadowDisc.visible = false; + this.explosionGuidesGroup.visible = false; + this.sectionHelperMesh.visible = false; + this.sectionCapMesh.visible = false; + this.stencilCapGroup.visible = false; + this.ptFloorCatcher.visible = true; + const ok = this.pathTracer.syncScene(this.scene, this.camera); - this.gridHelper.visible = true; - this.effectsManager.root.visible = this.state.showEffects; + + this.ptFloorCatcher.visible = false; + this.gridHelper.visible = prevGrid; + this.shadowDisc.visible = prevShadow; + this.explosionGuidesGroup.visible = prevGuides; + this.sectionHelperMesh.visible = prevSec; + this.sectionCapMesh.visible = prevCap; + this.stencilCapGroup.visible = prevStencil; + this.effectsManager.root.visible = prevEffects; this.pathTracerSceneSynced = ok; } if (this.pathTracerSceneSynced) { @@ -1454,11 +2188,12 @@ export class DecoderViewport { } } - // Restore PMREM environment for rasterization + EffectComposer if (this.pmremEnvTex && this.scene.environment !== this.pmremEnvTex) { this.scene.environment = this.pmremEnvTex; } + this.renderContactShadow(); + if (this.composer && !this.isSoftwareGl && this.state.transformMode === 'none') { this.composer.render(); } else { @@ -1497,14 +2232,22 @@ export class DecoderViewport { this.frameId = requestAnimationFrame(() => { if (this.disposed) return; this.renderDirty = false; + + const targetExp = + this.state.examinationMode === 'exploded' ? Math.max(0.45, this.state.explosion) : this.state.explosion; + const explosionSettling = !this.isSoftwareGl && Math.abs(this.currentExplosion - targetExp) > 0.0005; + if (explosionSettling || this.cameraTweenTarget) { + this.stepSimulation(0.016); + } + this.controls.update(); this.renderFrame(); const done = () => { this.renderBusy = false; + const stillExploding = !this.isSoftwareGl && Math.abs(this.currentExplosion - targetExp) > 0.0005; const ptNeedsMoreSamples = this.shouldUsePathTracer() && this.pathTracer.getStatus(true).samples < this.pathTracer.targetSamples; - if (this.renderDirty || this.cameraTweenTarget || ptNeedsMoreSamples) { - if (this.cameraTweenTarget) this.stepSimulation(0.016); + if (this.renderDirty || this.cameraTweenTarget || stillExploding || ptNeedsMoreSamples) { this.requestRender(); } }; @@ -1516,8 +2259,6 @@ export class DecoderViewport { private startLoop(): void { cancelAnimationFrame(this.frameId); clearTimeout(this.frameId); - // Cancelling may drop an on-demand render before its completion callback runs; release it so - // requestRender() is not locked out for good. this.renderBusy = false; const tick = () => { @@ -1577,7 +2318,34 @@ export class DecoderViewport { dom.removeEventListener('webglcontextrestored', this.onWebglContextRestored); window.removeEventListener('resize', this.onResize); + for (const item of this.explosionGuideItems.values()) { + item.rod.geometry.dispose(); + (item.rod.material as THREE.Material).dispose(); + item.originRing.geometry.dispose(); + (item.originRing.material as THREE.Material).dispose(); + item.partCollar.geometry.dispose(); + (item.partCollar.material as THREE.Material).dispose(); + } + this.explosionGuideItems.clear(); + + for (const child of this.stencilCapGroup.children) { + ((child as THREE.Mesh).material as THREE.Material | undefined)?.dispose(); + } + + this.contactShadowRT?.dispose(); + this.contactShadowBlurRT?.dispose(); + this.contactShadowDepthMat?.dispose(); + this.contactShadowHBlurMat?.dispose(); + this.contactShadowVBlurMat?.dispose(); + this.contactShadowBlurQuad?.geometry.dispose(); + + this.ptFloorCatcher.geometry.dispose(); + (this.ptFloorCatcher.material as THREE.Material).dispose(); + this.sectionCapMesh.geometry.dispose(); + (this.sectionCapMesh.material as THREE.Material).dispose(); + this.outlinePass?.dispose(); + this.bloomPass?.dispose(); this.pathTracer.dispose(); this.composer?.dispose(); this.transformControls.dispose();