@selvajs/visualization 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -182,14 +182,16 @@ const LOOK_PRESETS = {
182
182
  night: {
183
183
  toneMapping: three.ACESFilmicToneMapping,
184
184
  toneMappingExposure: 1,
185
- envMapIntensity: .32,
186
- environmentIntensity: .15,
187
- hemisphereIntensity: .26,
188
- ambientIntensity: .05,
185
+ envMapIntensity: .12,
186
+ metalReflection: .05,
187
+ environmentIntensity: .04,
188
+ hemisphereIntensity: .06,
189
+ ambientIntensity: .02,
189
190
  cullBackfaces: false,
190
191
  ambientOcclusion: true,
191
- sunlightIntensity: .14,
192
+ sunlightIntensity: .03,
192
193
  background: 658962,
194
+ emissiveLightScale: 3,
193
195
  bloom: {
194
196
  strength: .2,
195
197
  radius: .3,
@@ -247,14 +249,15 @@ const OWN_ENV_MAP_INTENSITY = "selvaEnvMapIntensity";
247
249
  * reflection, which is all a metal shows. Blending toward 1 by metalness keeps a dielectric's fill
248
250
  * on the look and a metal's reflection the same in every look.
249
251
  */
250
- function lookEnvMapIntensity(lookValue, metalness) {
251
- return lookValue + (1 - lookValue) * Math.min(1, Math.max(0, metalness));
252
+ function lookEnvMapIntensity(lookValue, metalness, metalReflection = 1) {
253
+ return lookValue + (metalReflection - lookValue) * Math.min(1, Math.max(0, metalness));
252
254
  }
253
255
  /** Baked at parse time (not toggleable at runtime). */
254
256
  function materialAppearanceForLook(look) {
255
257
  const preset = LOOK_PRESETS[look];
256
258
  return {
257
259
  envMapIntensity: preset.envMapIntensity,
260
+ metalReflection: preset.metalReflection,
258
261
  cullBackfaces: preset.cullBackfaces
259
262
  };
260
263
  }
@@ -511,4 +514,4 @@ Object.defineProperty(exports, "setLogger", {
511
514
  }
512
515
  });
513
516
 
514
- //# sourceMappingURL=gpu-dispose-D66GqIWS.cjs.map
517
+ //# sourceMappingURL=gpu-dispose-0c_-KS12.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gpu-dispose-0c_-KS12.cjs","names":["THREE","THREE","canDisposeMaterial","THREE","cachedSourceOf"],"sources":["../src/shared/errors.ts","../src/shared/logger.ts","../src/shared/looks.ts","../src/shared/geometry.ts","../src/shared/gpu-capabilities.ts","../src/shared/glass.ts","../src/shared/gpu-dispose.ts"],"sourcesContent":["/**\n * Errors for the visualization package. Replaces `@selvajs/compute`'s `RhinoComputeError`, which\n * mis-named failures on paths (e.g. the plugin WebSocket) that never touch Rhino.Compute. `code`\n * values match compute's so existing catch-sites keep working.\n */\n\nexport const ErrorCodes = {\n\t/** Structural check failed: bad magic bytes, out-of-window index, malformed metadata. */\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\t/** No `DecompressionStream`, no WebGL context, etc. */\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\t/** Base64 input could not be decoded. */\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\nexport class VisualizationError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'VisualizationError';\n\t\tthis.code = code;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n}\n","/**\n * Logging facility for the visualization package. Deliberately local rather than imported from\n * `@selvajs/compute` (logging isn't a compute concern). Mirrors compute's logger shape so a host\n * wanting one sink for both can call `setLogger(computeLogger.getLogger())`.\n */\n\nimport { VisualizationError, ErrorCodes } from './errors.js';\n\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\nclass NoOpLogger implements Logger {\n\tdebug(): void {}\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n}\n\nclass ConsoleLogger implements Logger {\n\tdebug(message: string, ...args: unknown[]): void {\n\t\t// eslint-disable-next-line no-console -- this class exists to be the console sink\n\t\tconsole.debug(message, ...args);\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tconsole.info(message, ...args);\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tconsole.warn(message, ...args);\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tconsole.error(message, ...args);\n\t}\n}\n\n// Defaults to no-op: a library that writes to the console uninvited is a nuisance in a host with\n// its own logging. Opt in with setLogger or enableDebugLogging.\nlet internalLogger: Logger = new NoOpLogger();\n\n// Call per-use rather than caching — the sink is settable at any time.\nexport function getLogger(): Logger {\n\treturn internalLogger;\n}\n\n// Validates logger shape up front: failing here beats a confusing \"getLogger().debug is not a\n// function\" at some later, unrelated call site.\nexport function setLogger(logger: Logger | Console | null): void {\n\tif (logger === null) {\n\t\tinternalLogger = new NoOpLogger();\n\t\treturn;\n\t}\n\n\tconst missing = (['debug', 'info', 'warn', 'error'] as const).filter(\n\t\t(method) => typeof (logger as unknown as Record<string, unknown>)[method] !== 'function'\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new VisualizationError(\n\t\t\t`Logger is missing required method(s): ${missing.join(', ')}. A logger must implement debug, info, warn and error.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { missingMethods: missing } }\n\t\t);\n\t}\n\n\tinternalLogger = logger as Logger;\n}\n\nexport function enableDebugLogging(): void {\n\tsetLogger(new ConsoleLogger());\n}\n","import * as THREE from 'three';\n\nimport type { Look, LookPreset, MaterialAppearanceOptions } from './types.js';\n\n/** The look applied when the caller passes no `look` option. */\nexport const DEFAULT_LOOK: Look = 'technical';\n\n/**\n * Single source of truth for both `applyDefaults` (construction) and `setLook` (runtime), so the two\n * can't drift.\n *\n * Every shaded look pairs a key light with contact shading (GTAO), because image-based lighting on\n * its own lights all faces of a box nearly equally — the result is a white silhouette with no\n * readable form. GTAO is a full-screen pass and does cost frames; `xray` skips it since there are no\n * opaque contacts left to shade.\n */\nexport const LOOK_PRESETS: Record<Look, LookPreset> = {\n\t// Fills shadows in (vs. showcase, which lets them fall off), but still key-lit: ACES plus a\n\t// moderate sun, with fill high enough that shadowed faces keep detail.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 0.85,\n\t\themisphereIntensity: 0.5,\n\t\tambientIntensity: 0.25,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 1.6\n\t},\n\t// The sun carries this look and the ambient/IBL only lift shadows off black. Fill was the thing\n\t// making it read as flat white paper: every source except the sun is orientation-independent, so\n\t// the more of them you stack the less the three faces of a corner differ.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.55,\n\t\tenvironmentIntensity: 0.6,\n\t\themisphereIntensity: 0.25,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.2\n\t},\n\t// Fill pulled furthest DOWN and the sun pushed hardest, so light-to-shadow falloff is steepest —\n\t// a dramatic hero shot, unlike `studio` which fills shadows back in.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.15,\n\t\tenvMapIntensity: 1.4,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.2,\n\t\tambientIntensity: 0.1,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.6\n\t},\n\t// Every mesh forced to one near-white clay, so form and shadow carry the image instead of the\n\t// model's own colours. AO on: with all albedo differences gone, contact shading is the only thing\n\t// left separating touching parts — without it the model reads as one white blob.\n\tarctic: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1.05,\n\t\tenvMapIntensity: 0.85,\n\t\tenvironmentIntensity: 1.1,\n\t\themisphereIntensity: 0.3,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.0,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0xeef1f5,\n\t\t\tmetalness: 0,\n\t\t\troughness: 0.75,\n\t\t\temissiveIntensity: 0\n\t\t}\n\t},\n\t// See-through blue-white with depth writes off, so interior geometry shows through the shell.\n\t// Exposure pushed up because stacked transparent layers darken fast; the sun is dialled back\n\t// because a hard highlight on a transparent shell hides what is behind it.\n\txray: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1.3,\n\t\tenvMapIntensity: 0.4,\n\t\tenvironmentIntensity: 0.8,\n\t\themisphereIntensity: 0.6,\n\t\tambientIntensity: 0.6,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0.6,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0x9fc4e8,\n\t\t\tmetalness: 0,\n\t\t\troughness: 0.9,\n\t\t\temissiveIntensity: 0,\n\t\t\topacity: 0.28,\n\t\t\tdepthWrite: false,\n\t\t\tside: THREE.DoubleSide\n\t\t}\n\t},\n\t// The architectural line drawing: feature edges over flat white faces. The faces are the whole\n\t// point even though you never really see them — they still write depth, so a near member hides\n\t// the ones behind it. True wireframe can't do that, and on a dense frame (thousands of members,\n\t// every edge of every one drawn at once) it collapses into a black mass.\n\t//\n\t// Unlit on purpose: any directional shading would compete with the lines for the eye. Ambient\n\t// alone lands every face on the same flat white, so the only contrast in the image is the edges.\n\t// AO is off for the same reason — a grey contact smear under a line drawing just muddies it.\n\tlineart: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\t// The faces are MeshPhysicalMaterial, so they take their brightness from lighting, not from\n\t\t// `color`: zero out the lights and they render black however white the override is. Hemisphere\n\t\t// and ambient carry it rather than IBL, because `scene.environment` only exists if the host\n\t\t// loaded an HDR — leaning on IBL would render this look black in any viewer without one. Both\n\t\t// are orientation-independent, so every face lands on the same flat white and the edges stay\n\t\t// the only contrast in the image. Ambient is weighted over hemisphere because hemisphere's\n\t\t// ground colour is a warm brown by default: leaning on it tints every downward face grey and\n\t\t// the drawing stops reading as one flat white.\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.6,\n\t\tambientIntensity: 3.2,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0,\n\t\trequiresEdges: true,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0xf7f8fa,\n\t\t\tmetalness: 0,\n\t\t\troughness: 1,\n\t\t\temissiveIntensity: 0\n\t\t}\n\t},\n\t// After dark: the only real light comes from what the model emits, so a lamp lights its desk.\n\t// A little sky stays so the unlit half of the model keeps its shape instead of going black.\n\t//\n\t// The fill is cut to where white paint away from the lamp reads about 0.2 of display white:\n\t// any more and the fill, not the lamp, lights the scene. A metal takes no hemisphere or ambient\n\t// light, only its reflection, so `metalReflection` is set where a metal in the dark lands beside\n\t// that white paint instead of reflecting a lit studio. `pnpm lab:night` measures both.\n\tnight: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.12,\n\t\tmetalReflection: 0.05,\n\t\tenvironmentIntensity: 0.04,\n\t\themisphereIntensity: 0.06,\n\t\tambientIntensity: 0.02,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 0.03,\n\t\tbackground: 0x0a0e12,\n\t\t// Lumens map to light for a room exposed for daylight; a room at night is exposed for its\n\t\t// lamps. Here rather than in `toneMappingExposure`, which would lift the background too.\n\t\temissiveLightScale: 3,\n\t\t// Above what the environment reaches on polished metal, so only emitters glow.\n\t\tbloom: { strength: 0.2, radius: 0.3, threshold: 1.8 },\n\t\temissiveLights: true,\n\t\t// Full-screen passes are the cost here: AO alone takes a quarter of the frame on an integrated\n\t\t// GPU, and without it there is no composer. A bounce light costs next to nothing and is all\n\t\t// that lights the room outside the shade, so one stays with its key.\n\t\tlowPower: {\n\t\t\tambientOcclusion: false,\n\t\t\tbloom: undefined,\n\t\t\tmaxEmissiveLights: 1,\n\t\t\tmaxPixelRatio: 1.5\n\t\t}\n\t},\n\t// Triangle edges only — the tessellation itself, diagonals and all. That makes it a mesh-\n\t// inspection tool, not a drawing: for a readable line drawing use `lineart`, which draws\n\t// feature edges and lets near faces occlude far ones. Nothing here is a lit surface:\n\t// the sun is off and fill carries the image, because a directional light on a line renders it\n\t// black wherever the line runs away from the key. AO is off for the same reason — a full-screen\n\t// contact pass has no contacts to find between wires, and it only costs frames.\n\twireframe: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\t// Lit for the same reason as lineart (see there): PBR lines are black unlit, and hemisphere\n\t\t// plus ambient work with no HDR loaded. Dimmer than lineart because these lines are dark\n\t\t// on white, not white on dark.\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.4,\n\t\tambientIntensity: 2.0,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0x2b3138,\n\t\t\tmetalness: 0,\n\t\t\troughness: 1,\n\t\t\temissiveIntensity: 0,\n\t\t\twireframe: true,\n\t\t\tside: THREE.DoubleSide\n\t\t}\n\t}\n};\n\n/** A look's preset, with its `lowPower` fields applied on a low-power device. */\nexport function lookPreset(look: Look, lowPower = false): LookPreset {\n\tconst preset = LOOK_PRESETS[look];\n\treturn lowPower ? { ...preset, ...preset.lowPower } : preset;\n}\n\n/** `userData` key marking a material whose emission came from the wire, not from a selection tint. */\nexport const OWN_EMISSIVE = 'selvaEmissive';\n\n/** `userData` key holding the light a material casts, from real lumens rather than its look. */\nexport const EMISSIVE_LIGHT = 'selvaEmissiveLight';\n\n/**\n * `userData` key holding a material's own `envMapIntensity`, set by the parser when the wire\n * material carries one. `setLook` keeps it instead of the look's value, except in looks with a\n * `materialOverride`: those restyle every mesh alike, so the look's value wins there.\n */\nexport const OWN_ENV_MAP_INTENSITY = 'selvaEnvMapIntensity';\n\n/**\n * A look dims `envMapIntensity` to turn down fill, but three scales a material's diffuse and\n * specular IBL together. A metal has no diffuse, so the same dimming would only take away its\n * reflection, which is all a metal shows. Blending toward 1 by metalness keeps a dielectric's fill\n * on the look and a metal's reflection the same in every look.\n */\nexport function lookEnvMapIntensity(\n\tlookValue: number,\n\tmetalness: number,\n\tmetalReflection = 1\n): number {\n\treturn lookValue + (metalReflection - lookValue) * Math.min(1, Math.max(0, metalness));\n}\n\n/** Baked at parse time (not toggleable at runtime). */\nexport function materialAppearanceForLook(look: Look): MaterialAppearanceOptions {\n\tconst preset = LOOK_PRESETS[look];\n\treturn {\n\t\tenvMapIntensity: preset.envMapIntensity,\n\t\tmetalReflection: preset.metalReflection,\n\t\tcullBackfaces: preset.cullBackfaces\n\t};\n}\n","import * as THREE from 'three';\n\nimport { getLogger } from './logger.js';\n\n// parse/ needs these and must never import upward from render/, so they live in shared/ instead\n// of render's three-helpers.\n\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// `new THREE.Color(name)` never throws on unknown names (it logs its own warning and leaves the\n\t// color white), so validate against three's CSS name table instead.\n\tconst named = trimmed.toLowerCase();\n\tif (named in THREE.Color.NAMES) {\n\t\treturn new THREE.Color(THREE.Color.NAMES[named as keyof typeof THREE.Color.NAMES]);\n\t}\n\n\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\treturn new THREE.Color(0xffffff);\n}\n\n/** Defaults to `z` (Rhino's up axis); pass an explicit axis when the scene uses a different `sceneUp`. */\nexport function applyOffset(\n\tmeshes: THREE.Object3D[],\n\toffset: number,\n\taxis: 'x' | 'y' | 'z' = 'z'\n): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position[axis] -= offset;\n\t});\n}\n\nexport function computeCombinedBoundingBox(meshes: THREE.Object3D[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n","// ============================================================================\n// GPU capabilities — published by the renderer, read by whoever needs them\n// ============================================================================\n\n// Lets a renderer publish GPU capabilities (max anisotropy) without `render/` and `parse/` importing\n// each other: the renderer publishes on init, interested parties subscribe.\n\ntype AnisotropyObserver = (value: number) => void;\n\nconst observers = new Set<AnisotropyObserver>();\n\n// Module load order between layers isn't guaranteed, so a subscriber arriving after init still\n// needs the current value rather than waiting for a second renderer to publish.\nlet maxAnisotropy = 1;\n\nexport function publishMaxAnisotropy(value: number): void {\n\tconst next = Math.max(1, value);\n\tif (next === maxAnisotropy) return;\n\tmaxAnisotropy = next;\n\tfor (const observe of observers) observe(next);\n}\n\n/** Fires immediately with the current value (1 until a renderer has reported), then on every change. */\nexport function observeMaxAnisotropy(observe: AnisotropyObserver): () => void {\n\tobservers.add(observe);\n\tobserve(maxAnisotropy);\n\treturn () => observers.delete(observe);\n}\n","import type * as THREE from 'three';\n\n/**\n * `userData` key marking a material the parser built as glass. AO, the edge pass and shadow maps\n * skip it: each treats a surface as opaque, so glass would darken, outline and shade what it shows.\n */\nexport const GLASS = 'selvaGlass';\n\nexport function isGlass(material: THREE.Material | THREE.Material[] | undefined): boolean {\n\tif (!material) return false;\n\treturn Array.isArray(material)\n\t\t? material.some((m) => m.userData[GLASS] === true)\n\t\t: material.userData[GLASS] === true;\n}\n\n/**\n * Hides every visible mesh drawn in glass under `root` and returns the call that shows them again.\n * For passes that redraw the scene with an override material, which would otherwise draw glass as\n * a solid surface.\n */\nexport function hideGlass(root: THREE.Object3D): () => void {\n\tconst hidden: THREE.Object3D[] = [];\n\troot.traverse((object) => {\n\t\tif (object.visible && isGlass((object as THREE.Mesh).material)) {\n\t\t\tobject.visible = false;\n\t\t\thidden.push(object);\n\t\t}\n\t});\n\treturn () => {\n\t\tfor (const object of hidden) object.visible = true;\n\t};\n}\n","import * as THREE from 'three';\n\nimport { cachedSourceOf, canDisposeMaterial } from './gpu-ownership.js';\n\n// ============================================================================\n// The disposal walkers — every teardown path in the package goes through these\n// ============================================================================\n\n/** Frees a material and its textures, respecting ownership (`./gpu-ownership.ts`). */\nexport function disposeMaterial(material: THREE.Material): void {\n\tif (!canDisposeMaterial(material)) return;\n\n\tfor (const [key, value] of Object.entries(material)) {\n\t\t// An envMap is the scene's, shared by every metal: freeing it here would blank them all.\n\t\tif (key === 'envMap') continue;\n\t\tif (value instanceof THREE.Texture) {\n\t\t\tvalue.dispose();\n\t\t}\n\t}\n\tmaterial.dispose();\n}\n\nfunction disposeMaterials(material: THREE.Material | THREE.Material[] | undefined): void {\n\tif (!material) return;\n\tif (Array.isArray(material)) material.forEach(disposeMaterial);\n\telse disposeMaterial(material);\n}\n\nexport interface DisposeOptions {\n\t/** Free materials and their textures too. Default true; the solve memo passes false. */\n\tmaterials?: boolean;\n\t/** Called for each geometry before disposal, so a subsystem can free derived resources keyed on it (e.g. edge caches). */\n\tonGeometry?: (geometry: THREE.BufferGeometry) => void;\n\t/**\n\t * Cached geometries whose GPU copy survives. When given, every other cached geometry this walk\n\t * reaches loses its GPU copy.\n\t */\n\tkeepUploaded?: ReadonlySet<THREE.BufferGeometry>;\n}\n\n/**\n * Frees the GPU resources of an object subtree, respecting ownership. **The only traversal that\n * should dispose scene content** — a second disposing `traverse` risks missing an ownership guard.\n */\nexport function disposeObjectTree(root: THREE.Object3D, options: DisposeOptions = {}): void {\n\tconst { materials = true, keepUploaded } = options;\n\n\troot.traverse((object) => {\n\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\tif (renderable.geometry) disposeGeometry(renderable.geometry, keepUploaded);\n\n\t\tif (materials) disposeMaterials(renderable.material);\n\t});\n}\n\nfunction disposeGeometry(\n\tgeometry: THREE.BufferGeometry,\n\tkeepUploaded: ReadonlySet<THREE.BufferGeometry> | undefined\n): void {\n\tconst source = cachedSourceOf(geometry);\n\tif (source !== geometry) {\n\t\t// three's dispose frees the GPU buffers of whatever attributes are attached, so a borrower\n\t\t// lets go of the cache's attributes first.\n\t\tif (source) {\n\t\t\tgeometry.setIndex(null);\n\t\t\tfor (const name of Object.keys(geometry.attributes)) geometry.deleteAttribute(name);\n\t\t}\n\t\tgeometry.dispose();\n\t}\n\tif (source && keepUploaded && !keepUploaded.has(source)) source.dispose();\n}\n"],"mappings":";;;;;;;;;AAMA,MAAa,aAAa;;CAEzB,kBAAkB;CAClB,eAAe;;CAEf,mBAAmB;CACnB,gBAAgB;;CAEhB,gBAAgB;CAChB,eAAe;AAChB;AAIA,IAAa,qBAAb,cAAwC,MAAM;CAC7C;CACA;CACA;CAEA,YACC,SACA,OAAkB,WAAW,eAC7B,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU,SAAS;EACxB,KAAK,gBAAgB,SAAS;EAC9B,IAAI,SAAS,eACZ,KAA8B,QAAQ,QAAQ;CAEhD;AACD;;;;;;;ACxBA,IAAM,aAAN,MAAmC;CAClC,QAAc,CAAC;CACf,OAAa,CAAC;CACd,OAAa,CAAC;CACd,QAAc,CAAC;AAChB;AAEA,IAAM,gBAAN,MAAsC;CACrC,MAAM,SAAiB,GAAG,MAAuB;EAEhD,QAAQ,MAAM,SAAS,GAAG,IAAI;CAC/B;CAEA,KAAK,SAAiB,GAAG,MAAuB;EAC/C,QAAQ,KAAK,SAAS,GAAG,IAAI;CAC9B;CAEA,KAAK,SAAiB,GAAG,MAAuB;EAC/C,QAAQ,KAAK,SAAS,GAAG,IAAI;CAC9B;CAEA,MAAM,SAAiB,GAAG,MAAuB;EAChD,QAAQ,MAAM,SAAS,GAAG,IAAI;CAC/B;AACD;AAIA,IAAI,iBAAyB,IAAI,WAAW;AAG5C,SAAgB,YAAoB;CACnC,OAAO;AACR;AAIA,SAAgB,UAAU,QAAuC;CAChE,IAAI,WAAW,MAAM;EACpB,iBAAiB,IAAI,WAAW;EAChC;CACD;CAEA,MAAM,UAAW;EAAC;EAAS;EAAQ;EAAQ;CAAO,CAAC,CAAW,QAC5D,WAAW,OAAQ,OAA8C,YAAY,UAC/E;CACA,IAAI,QAAQ,SAAS,GAC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M,QAAQ,QAAQ,GAAG,SAAS,QAAQ,eAAe;MACxD,gBAAgB,QAAQ;AAC9B;;;;;AAkBA,SAAgB,kBAAkB,MAAsB,UAA0B,CAAC,GAAS;CAC3F,MAAM,EAAE,YAAY,MAAM,iBAAiB;CAE3C,KAAK,UAAU,WAAW;EACzB,MAAM,aAAa;EACnB,IAAI,CAAC,WAAW,YAAY,CAAC,WAAW,UAAU;EAElD,IAAI,WAAW,UAAU,gBAAgB,WAAW,UAAU,YAAY;EAE1E,IAAI,WAAW,iBAAiB,WAAW,QAAQ;CACpD,CAAC;AACF;AAEA,SAAS,gBACR,UACA,cACO;CACP,MAAM,SAASC,sBAAAA,eAAe,QAAQ;CACtC,IAAI,WAAW,UAAU;EAGxB,IAAI,QAAQ;GACX,SAAS,SAAS,IAAI;GACtB,KAAK,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU,GAAG,SAAS,gBAAgB,IAAI;EACnF;EACA,SAAS,QAAQ;CAClB;CACA,IAAI,UAAU,gBAAgB,CAAC,aAAa,IAAI,MAAM,GAAG,OAAO,QAAQ;AACzE"}
@@ -181,14 +181,16 @@ const LOOK_PRESETS = {
181
181
  night: {
182
182
  toneMapping: THREE.ACESFilmicToneMapping,
183
183
  toneMappingExposure: 1,
184
- envMapIntensity: .32,
185
- environmentIntensity: .15,
186
- hemisphereIntensity: .26,
187
- ambientIntensity: .05,
184
+ envMapIntensity: .12,
185
+ metalReflection: .05,
186
+ environmentIntensity: .04,
187
+ hemisphereIntensity: .06,
188
+ ambientIntensity: .02,
188
189
  cullBackfaces: false,
189
190
  ambientOcclusion: true,
190
- sunlightIntensity: .14,
191
+ sunlightIntensity: .03,
191
192
  background: 658962,
193
+ emissiveLightScale: 3,
192
194
  bloom: {
193
195
  strength: .2,
194
196
  radius: .3,
@@ -246,14 +248,15 @@ const OWN_ENV_MAP_INTENSITY = "selvaEnvMapIntensity";
246
248
  * reflection, which is all a metal shows. Blending toward 1 by metalness keeps a dielectric's fill
247
249
  * on the look and a metal's reflection the same in every look.
248
250
  */
249
- function lookEnvMapIntensity(lookValue, metalness) {
250
- return lookValue + (1 - lookValue) * Math.min(1, Math.max(0, metalness));
251
+ function lookEnvMapIntensity(lookValue, metalness, metalReflection = 1) {
252
+ return lookValue + (metalReflection - lookValue) * Math.min(1, Math.max(0, metalness));
251
253
  }
252
254
  /** Baked at parse time (not toggleable at runtime). */
253
255
  function materialAppearanceForLook(look) {
254
256
  const preset = LOOK_PRESETS[look];
255
257
  return {
256
258
  envMapIntensity: preset.envMapIntensity,
259
+ metalReflection: preset.metalReflection,
257
260
  cullBackfaces: preset.cullBackfaces
258
261
  };
259
262
  }
@@ -379,4 +382,4 @@ function disposeGeometry(geometry, keepUploaded) {
379
382
  }
380
383
  export { VisualizationError as S, materialAppearanceForLook as _, observeMaxAnisotropy as a, setLogger as b, computeCombinedBoundingBox as c, EMISSIVE_LIGHT as d, LOOK_PRESETS as f, lookPreset as g, lookEnvMapIntensity as h, isGlass as i, parseColor as l, OWN_ENV_MAP_INTENSITY as m, GLASS as n, publishMaxAnisotropy as o, OWN_EMISSIVE as p, hideGlass as r, applyOffset as s, disposeObjectTree as t, DEFAULT_LOOK as u, enableDebugLogging as v, ErrorCodes as x, getLogger as y };
381
384
 
382
- //# sourceMappingURL=gpu-dispose-Di_nxeXF.js.map
385
+ //# sourceMappingURL=gpu-dispose-k_Gq-ygL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gpu-dispose-k_Gq-ygL.js","names":[],"sources":["../src/shared/errors.ts","../src/shared/logger.ts","../src/shared/looks.ts","../src/shared/geometry.ts","../src/shared/gpu-capabilities.ts","../src/shared/glass.ts","../src/shared/gpu-dispose.ts"],"sourcesContent":["/**\n * Errors for the visualization package. Replaces `@selvajs/compute`'s `RhinoComputeError`, which\n * mis-named failures on paths (e.g. the plugin WebSocket) that never touch Rhino.Compute. `code`\n * values match compute's so existing catch-sites keep working.\n */\n\nexport const ErrorCodes = {\n\t/** Structural check failed: bad magic bytes, out-of-window index, malformed metadata. */\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\t/** No `DecompressionStream`, no WebGL context, etc. */\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\t/** Base64 input could not be decoded. */\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\nexport class VisualizationError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'VisualizationError';\n\t\tthis.code = code;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n}\n","/**\n * Logging facility for the visualization package. Deliberately local rather than imported from\n * `@selvajs/compute` (logging isn't a compute concern). Mirrors compute's logger shape so a host\n * wanting one sink for both can call `setLogger(computeLogger.getLogger())`.\n */\n\nimport { VisualizationError, ErrorCodes } from './errors.js';\n\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\nclass NoOpLogger implements Logger {\n\tdebug(): void {}\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n}\n\nclass ConsoleLogger implements Logger {\n\tdebug(message: string, ...args: unknown[]): void {\n\t\t// eslint-disable-next-line no-console -- this class exists to be the console sink\n\t\tconsole.debug(message, ...args);\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tconsole.info(message, ...args);\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tconsole.warn(message, ...args);\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tconsole.error(message, ...args);\n\t}\n}\n\n// Defaults to no-op: a library that writes to the console uninvited is a nuisance in a host with\n// its own logging. Opt in with setLogger or enableDebugLogging.\nlet internalLogger: Logger = new NoOpLogger();\n\n// Call per-use rather than caching — the sink is settable at any time.\nexport function getLogger(): Logger {\n\treturn internalLogger;\n}\n\n// Validates logger shape up front: failing here beats a confusing \"getLogger().debug is not a\n// function\" at some later, unrelated call site.\nexport function setLogger(logger: Logger | Console | null): void {\n\tif (logger === null) {\n\t\tinternalLogger = new NoOpLogger();\n\t\treturn;\n\t}\n\n\tconst missing = (['debug', 'info', 'warn', 'error'] as const).filter(\n\t\t(method) => typeof (logger as unknown as Record<string, unknown>)[method] !== 'function'\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new VisualizationError(\n\t\t\t`Logger is missing required method(s): ${missing.join(', ')}. A logger must implement debug, info, warn and error.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { missingMethods: missing } }\n\t\t);\n\t}\n\n\tinternalLogger = logger as Logger;\n}\n\nexport function enableDebugLogging(): void {\n\tsetLogger(new ConsoleLogger());\n}\n","import * as THREE from 'three';\n\nimport type { Look, LookPreset, MaterialAppearanceOptions } from './types.js';\n\n/** The look applied when the caller passes no `look` option. */\nexport const DEFAULT_LOOK: Look = 'technical';\n\n/**\n * Single source of truth for both `applyDefaults` (construction) and `setLook` (runtime), so the two\n * can't drift.\n *\n * Every shaded look pairs a key light with contact shading (GTAO), because image-based lighting on\n * its own lights all faces of a box nearly equally — the result is a white silhouette with no\n * readable form. GTAO is a full-screen pass and does cost frames; `xray` skips it since there are no\n * opaque contacts left to shade.\n */\nexport const LOOK_PRESETS: Record<Look, LookPreset> = {\n\t// Fills shadows in (vs. showcase, which lets them fall off), but still key-lit: ACES plus a\n\t// moderate sun, with fill high enough that shadowed faces keep detail.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 0.85,\n\t\themisphereIntensity: 0.5,\n\t\tambientIntensity: 0.25,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 1.6\n\t},\n\t// The sun carries this look and the ambient/IBL only lift shadows off black. Fill was the thing\n\t// making it read as flat white paper: every source except the sun is orientation-independent, so\n\t// the more of them you stack the less the three faces of a corner differ.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.55,\n\t\tenvironmentIntensity: 0.6,\n\t\themisphereIntensity: 0.25,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.2\n\t},\n\t// Fill pulled furthest DOWN and the sun pushed hardest, so light-to-shadow falloff is steepest —\n\t// a dramatic hero shot, unlike `studio` which fills shadows back in.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.15,\n\t\tenvMapIntensity: 1.4,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.2,\n\t\tambientIntensity: 0.1,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.6\n\t},\n\t// Every mesh forced to one near-white clay, so form and shadow carry the image instead of the\n\t// model's own colours. AO on: with all albedo differences gone, contact shading is the only thing\n\t// left separating touching parts — without it the model reads as one white blob.\n\tarctic: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1.05,\n\t\tenvMapIntensity: 0.85,\n\t\tenvironmentIntensity: 1.1,\n\t\themisphereIntensity: 0.3,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 2.0,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0xeef1f5,\n\t\t\tmetalness: 0,\n\t\t\troughness: 0.75,\n\t\t\temissiveIntensity: 0\n\t\t}\n\t},\n\t// See-through blue-white with depth writes off, so interior geometry shows through the shell.\n\t// Exposure pushed up because stacked transparent layers darken fast; the sun is dialled back\n\t// because a hard highlight on a transparent shell hides what is behind it.\n\txray: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1.3,\n\t\tenvMapIntensity: 0.4,\n\t\tenvironmentIntensity: 0.8,\n\t\themisphereIntensity: 0.6,\n\t\tambientIntensity: 0.6,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0.6,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0x9fc4e8,\n\t\t\tmetalness: 0,\n\t\t\troughness: 0.9,\n\t\t\temissiveIntensity: 0,\n\t\t\topacity: 0.28,\n\t\t\tdepthWrite: false,\n\t\t\tside: THREE.DoubleSide\n\t\t}\n\t},\n\t// The architectural line drawing: feature edges over flat white faces. The faces are the whole\n\t// point even though you never really see them — they still write depth, so a near member hides\n\t// the ones behind it. True wireframe can't do that, and on a dense frame (thousands of members,\n\t// every edge of every one drawn at once) it collapses into a black mass.\n\t//\n\t// Unlit on purpose: any directional shading would compete with the lines for the eye. Ambient\n\t// alone lands every face on the same flat white, so the only contrast in the image is the edges.\n\t// AO is off for the same reason — a grey contact smear under a line drawing just muddies it.\n\tlineart: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\t// The faces are MeshPhysicalMaterial, so they take their brightness from lighting, not from\n\t\t// `color`: zero out the lights and they render black however white the override is. Hemisphere\n\t\t// and ambient carry it rather than IBL, because `scene.environment` only exists if the host\n\t\t// loaded an HDR — leaning on IBL would render this look black in any viewer without one. Both\n\t\t// are orientation-independent, so every face lands on the same flat white and the edges stay\n\t\t// the only contrast in the image. Ambient is weighted over hemisphere because hemisphere's\n\t\t// ground colour is a warm brown by default: leaning on it tints every downward face grey and\n\t\t// the drawing stops reading as one flat white.\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.6,\n\t\tambientIntensity: 3.2,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0,\n\t\trequiresEdges: true,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0xf7f8fa,\n\t\t\tmetalness: 0,\n\t\t\troughness: 1,\n\t\t\temissiveIntensity: 0\n\t\t}\n\t},\n\t// After dark: the only real light comes from what the model emits, so a lamp lights its desk.\n\t// A little sky stays so the unlit half of the model keeps its shape instead of going black.\n\t//\n\t// The fill is cut to where white paint away from the lamp reads about 0.2 of display white:\n\t// any more and the fill, not the lamp, lights the scene. A metal takes no hemisphere or ambient\n\t// light, only its reflection, so `metalReflection` is set where a metal in the dark lands beside\n\t// that white paint instead of reflecting a lit studio. `pnpm lab:night` measures both.\n\tnight: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.12,\n\t\tmetalReflection: 0.05,\n\t\tenvironmentIntensity: 0.04,\n\t\themisphereIntensity: 0.06,\n\t\tambientIntensity: 0.02,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: true,\n\t\tsunlightIntensity: 0.03,\n\t\tbackground: 0x0a0e12,\n\t\t// Lumens map to light for a room exposed for daylight; a room at night is exposed for its\n\t\t// lamps. Here rather than in `toneMappingExposure`, which would lift the background too.\n\t\temissiveLightScale: 3,\n\t\t// Above what the environment reaches on polished metal, so only emitters glow.\n\t\tbloom: { strength: 0.2, radius: 0.3, threshold: 1.8 },\n\t\temissiveLights: true,\n\t\t// Full-screen passes are the cost here: AO alone takes a quarter of the frame on an integrated\n\t\t// GPU, and without it there is no composer. A bounce light costs next to nothing and is all\n\t\t// that lights the room outside the shade, so one stays with its key.\n\t\tlowPower: {\n\t\t\tambientOcclusion: false,\n\t\t\tbloom: undefined,\n\t\t\tmaxEmissiveLights: 1,\n\t\t\tmaxPixelRatio: 1.5\n\t\t}\n\t},\n\t// Triangle edges only — the tessellation itself, diagonals and all. That makes it a mesh-\n\t// inspection tool, not a drawing: for a readable line drawing use `lineart`, which draws\n\t// feature edges and lets near faces occlude far ones. Nothing here is a lit surface:\n\t// the sun is off and fill carries the image, because a directional light on a line renders it\n\t// black wherever the line runs away from the key. AO is off for the same reason — a full-screen\n\t// contact pass has no contacts to find between wires, and it only costs frames.\n\twireframe: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\t// Lit for the same reason as lineart (see there): PBR lines are black unlit, and hemisphere\n\t\t// plus ambient work with no HDR loaded. Dimmer than lineart because these lines are dark\n\t\t// on white, not white on dark.\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.4,\n\t\tambientIntensity: 2.0,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false,\n\t\tsunlightIntensity: 0,\n\t\tmaterialOverride: {\n\t\t\tcolor: 0x2b3138,\n\t\t\tmetalness: 0,\n\t\t\troughness: 1,\n\t\t\temissiveIntensity: 0,\n\t\t\twireframe: true,\n\t\t\tside: THREE.DoubleSide\n\t\t}\n\t}\n};\n\n/** A look's preset, with its `lowPower` fields applied on a low-power device. */\nexport function lookPreset(look: Look, lowPower = false): LookPreset {\n\tconst preset = LOOK_PRESETS[look];\n\treturn lowPower ? { ...preset, ...preset.lowPower } : preset;\n}\n\n/** `userData` key marking a material whose emission came from the wire, not from a selection tint. */\nexport const OWN_EMISSIVE = 'selvaEmissive';\n\n/** `userData` key holding the light a material casts, from real lumens rather than its look. */\nexport const EMISSIVE_LIGHT = 'selvaEmissiveLight';\n\n/**\n * `userData` key holding a material's own `envMapIntensity`, set by the parser when the wire\n * material carries one. `setLook` keeps it instead of the look's value, except in looks with a\n * `materialOverride`: those restyle every mesh alike, so the look's value wins there.\n */\nexport const OWN_ENV_MAP_INTENSITY = 'selvaEnvMapIntensity';\n\n/**\n * A look dims `envMapIntensity` to turn down fill, but three scales a material's diffuse and\n * specular IBL together. A metal has no diffuse, so the same dimming would only take away its\n * reflection, which is all a metal shows. Blending toward 1 by metalness keeps a dielectric's fill\n * on the look and a metal's reflection the same in every look.\n */\nexport function lookEnvMapIntensity(\n\tlookValue: number,\n\tmetalness: number,\n\tmetalReflection = 1\n): number {\n\treturn lookValue + (metalReflection - lookValue) * Math.min(1, Math.max(0, metalness));\n}\n\n/** Baked at parse time (not toggleable at runtime). */\nexport function materialAppearanceForLook(look: Look): MaterialAppearanceOptions {\n\tconst preset = LOOK_PRESETS[look];\n\treturn {\n\t\tenvMapIntensity: preset.envMapIntensity,\n\t\tmetalReflection: preset.metalReflection,\n\t\tcullBackfaces: preset.cullBackfaces\n\t};\n}\n","import * as THREE from 'three';\n\nimport { getLogger } from './logger.js';\n\n// parse/ needs these and must never import upward from render/, so they live in shared/ instead\n// of render's three-helpers.\n\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// `new THREE.Color(name)` never throws on unknown names (it logs its own warning and leaves the\n\t// color white), so validate against three's CSS name table instead.\n\tconst named = trimmed.toLowerCase();\n\tif (named in THREE.Color.NAMES) {\n\t\treturn new THREE.Color(THREE.Color.NAMES[named as keyof typeof THREE.Color.NAMES]);\n\t}\n\n\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\treturn new THREE.Color(0xffffff);\n}\n\n/** Defaults to `z` (Rhino's up axis); pass an explicit axis when the scene uses a different `sceneUp`. */\nexport function applyOffset(\n\tmeshes: THREE.Object3D[],\n\toffset: number,\n\taxis: 'x' | 'y' | 'z' = 'z'\n): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position[axis] -= offset;\n\t});\n}\n\nexport function computeCombinedBoundingBox(meshes: THREE.Object3D[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n","// ============================================================================\n// GPU capabilities — published by the renderer, read by whoever needs them\n// ============================================================================\n\n// Lets a renderer publish GPU capabilities (max anisotropy) without `render/` and `parse/` importing\n// each other: the renderer publishes on init, interested parties subscribe.\n\ntype AnisotropyObserver = (value: number) => void;\n\nconst observers = new Set<AnisotropyObserver>();\n\n// Module load order between layers isn't guaranteed, so a subscriber arriving after init still\n// needs the current value rather than waiting for a second renderer to publish.\nlet maxAnisotropy = 1;\n\nexport function publishMaxAnisotropy(value: number): void {\n\tconst next = Math.max(1, value);\n\tif (next === maxAnisotropy) return;\n\tmaxAnisotropy = next;\n\tfor (const observe of observers) observe(next);\n}\n\n/** Fires immediately with the current value (1 until a renderer has reported), then on every change. */\nexport function observeMaxAnisotropy(observe: AnisotropyObserver): () => void {\n\tobservers.add(observe);\n\tobserve(maxAnisotropy);\n\treturn () => observers.delete(observe);\n}\n","import type * as THREE from 'three';\n\n/**\n * `userData` key marking a material the parser built as glass. AO, the edge pass and shadow maps\n * skip it: each treats a surface as opaque, so glass would darken, outline and shade what it shows.\n */\nexport const GLASS = 'selvaGlass';\n\nexport function isGlass(material: THREE.Material | THREE.Material[] | undefined): boolean {\n\tif (!material) return false;\n\treturn Array.isArray(material)\n\t\t? material.some((m) => m.userData[GLASS] === true)\n\t\t: material.userData[GLASS] === true;\n}\n\n/**\n * Hides every visible mesh drawn in glass under `root` and returns the call that shows them again.\n * For passes that redraw the scene with an override material, which would otherwise draw glass as\n * a solid surface.\n */\nexport function hideGlass(root: THREE.Object3D): () => void {\n\tconst hidden: THREE.Object3D[] = [];\n\troot.traverse((object) => {\n\t\tif (object.visible && isGlass((object as THREE.Mesh).material)) {\n\t\t\tobject.visible = false;\n\t\t\thidden.push(object);\n\t\t}\n\t});\n\treturn () => {\n\t\tfor (const object of hidden) object.visible = true;\n\t};\n}\n","import * as THREE from 'three';\n\nimport { cachedSourceOf, canDisposeMaterial } from './gpu-ownership.js';\n\n// ============================================================================\n// The disposal walkers — every teardown path in the package goes through these\n// ============================================================================\n\n/** Frees a material and its textures, respecting ownership (`./gpu-ownership.ts`). */\nexport function disposeMaterial(material: THREE.Material): void {\n\tif (!canDisposeMaterial(material)) return;\n\n\tfor (const [key, value] of Object.entries(material)) {\n\t\t// An envMap is the scene's, shared by every metal: freeing it here would blank them all.\n\t\tif (key === 'envMap') continue;\n\t\tif (value instanceof THREE.Texture) {\n\t\t\tvalue.dispose();\n\t\t}\n\t}\n\tmaterial.dispose();\n}\n\nfunction disposeMaterials(material: THREE.Material | THREE.Material[] | undefined): void {\n\tif (!material) return;\n\tif (Array.isArray(material)) material.forEach(disposeMaterial);\n\telse disposeMaterial(material);\n}\n\nexport interface DisposeOptions {\n\t/** Free materials and their textures too. Default true; the solve memo passes false. */\n\tmaterials?: boolean;\n\t/** Called for each geometry before disposal, so a subsystem can free derived resources keyed on it (e.g. edge caches). */\n\tonGeometry?: (geometry: THREE.BufferGeometry) => void;\n\t/**\n\t * Cached geometries whose GPU copy survives. When given, every other cached geometry this walk\n\t * reaches loses its GPU copy.\n\t */\n\tkeepUploaded?: ReadonlySet<THREE.BufferGeometry>;\n}\n\n/**\n * Frees the GPU resources of an object subtree, respecting ownership. **The only traversal that\n * should dispose scene content** — a second disposing `traverse` risks missing an ownership guard.\n */\nexport function disposeObjectTree(root: THREE.Object3D, options: DisposeOptions = {}): void {\n\tconst { materials = true, keepUploaded } = options;\n\n\troot.traverse((object) => {\n\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\tif (renderable.geometry) disposeGeometry(renderable.geometry, keepUploaded);\n\n\t\tif (materials) disposeMaterials(renderable.material);\n\t});\n}\n\nfunction disposeGeometry(\n\tgeometry: THREE.BufferGeometry,\n\tkeepUploaded: ReadonlySet<THREE.BufferGeometry> | undefined\n): void {\n\tconst source = cachedSourceOf(geometry);\n\tif (source !== geometry) {\n\t\t// three's dispose frees the GPU buffers of whatever attributes are attached, so a borrower\n\t\t// lets go of the cache's attributes first.\n\t\tif (source) {\n\t\t\tgeometry.setIndex(null);\n\t\t\tfor (const name of Object.keys(geometry.attributes)) geometry.deleteAttribute(name);\n\t\t}\n\t\tgeometry.dispose();\n\t}\n\tif (source && keepUploaded && !keepUploaded.has(source)) source.dispose();\n}\n"],"mappings":";;;;;;;;AAMA,MAAa,aAAa;;CAEzB,kBAAkB;CAClB,eAAe;;CAEf,mBAAmB;CACnB,gBAAgB;;CAEhB,gBAAgB;CAChB,eAAe;AAChB;AAIA,IAAa,qBAAb,cAAwC,MAAM;CAC7C;CACA;CACA;CAEA,YACC,SACA,OAAkB,WAAW,eAC7B,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAA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AI,WAAW,UAAU;EAGxB,IAAI,QAAQ;GACX,SAAS,SAAS,IAAI;GACtB,KAAK,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU,GAAG,SAAS,gBAAgB,IAAI;EACnF;EACA,SAAS,QAAQ;CAClB;CACA,IAAI,UAAU,gBAAgB,CAAC,aAAa,IAAI,MAAM,GAAG,OAAO,QAAQ;AACzE"}
package/dist/parse.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_gpu_ownership = require("./gpu-ownership-ADRZBxxs.cjs");
3
- const require_gpu_dispose = require("./gpu-dispose-D66GqIWS.cjs");
3
+ const require_gpu_dispose = require("./gpu-dispose-0c_-KS12.cjs");
4
4
  let three = require("three");
5
5
  three = require_gpu_ownership.__toESM(three, 1);
6
6
  let three_addons_lines_Line2_js = require("three/addons/lines/Line2.js");
@@ -1684,29 +1684,58 @@ function applyTexture(material, url, slot, mapSize) {
1684
1684
  const f$1 = (n) => n.toFixed(4);
1685
1685
  const PITH = 120;
1686
1686
  const PITH_SPREAD = 120;
1687
- const PLANK = 180;
1687
+ const PLANK = 160;
1688
+ const SEAM_JITTER = .7;
1688
1689
  const LEAN = .0105;
1690
+ const BOARD_SHADE = .14;
1691
+ const PORE_ROW = .35;
1692
+ const PORE_FILL = .3;
1693
+ const PORE_DARK = .4;
1694
+ const PORE_MEAN = PORE_FILL * .7 * .42;
1695
+ const seam = (k) => `( ( ${k} ) + ( selvaHash( vec2( ${k}, 6.0 ) ) - 0.5 ) * ${f$1(SEAM_JITTER)} ) * ${f$1(PLANK)}`;
1689
1696
  const wood = ({ ring, latewood, band, pores, streaks }) => `
1690
- float plank = floor( uv.y / ${f$1(PLANK)} );
1691
- float s = uv.y - ( plank + 0.5 ) * ${f$1(PLANK)};
1697
+ float cell = floor( uv.y / ${f$1(PLANK)} );
1698
+ float plank = cell + ( uv.y < ${seam("cell")} ? -1.0 : ( uv.y >= ${seam("cell + 1.0")} ? 1.0 : 0.0 ) );
1699
+ float lo = ${seam("plank")};
1700
+ float hi = ${seam("plank + 1.0")};
1701
+ // Each plank starts somewhere else along its log.
1702
+ float along = uv.x + selvaHash( vec2( plank, 9.0 ) ) * 5000.0;
1703
+ // The pith lies anywhere under the plank, sometimes past its edge, which leaves straight
1704
+ // rift grain on that side.
1705
+ float heart = mix( lo, hi, selvaHash( vec2( plank, 3.0 ) ) * 1.6 - 0.3 );
1706
+ heart += ( selvaNoise( vec2( along * 0.0006, plank * 7.0 ) ) - 0.5 ) * 50.0;
1707
+ float s = uv.y - heart;
1692
1708
  float pith = ${f$1(PITH)} + selvaHash( vec2( plank, 2.0 ) ) * ${f$1(PITH_SPREAD)};
1709
+ pith += ( selvaFbm( vec2( along * 0.0004, plank * 5.0 + 1.0 ) ) - 0.5 ) * ${f$1(50)};
1710
+ float lean = ${f$1(LEAN)} * ( 0.5 + selvaHash( vec2( plank, 8.0 ) ) );
1693
1711
  // Rings wander a few mm and vary in spacing, as growth does from year to year.
1694
- float wander = ( selvaFbm( uv * vec2( 0.003, 0.008 ) ) - 0.5 ) * ${f$1(ring * 2)};
1695
- float r = sqrt( pith * pith + s * s ) + uv.x * ${f$1(LEAN)} + wander;
1712
+ float wander = ( selvaFbm( vec2( along * 0.003, uv.y * 0.008 ) ) - 0.5 ) * ${f$1(ring * 2)};
1713
+ float r = sqrt( pith * pith + s * s ) + along * lean + wander;
1696
1714
  r += selvaFbm( vec2( r * 0.02, plank ) ) * ${f$1(ring * 3)} + selvaHash( vec2( plank, 1.0 ) ) * ${f$1(ring * 20)};
1697
1715
  float year = fract( r / ${f$1(ring)} );
1698
1716
  float late = smoothstep( ${f$1(1 - band)}, ${f$1(1 - band * .4)}, year ) * ( 1.0 - smoothstep( 0.95, 1.0, year ) );
1699
1717
  // Open-pored wood shows its rings as a broken band of pores, not a clean line.
1700
- late *= 1.0 - ${f$1(pores * .6)} * ( 1.0 - smoothstep( 0.3, 0.7, selvaNoise( uv * vec2( 0.25, 2.0 ) ) ) );
1718
+ float broken = 1.0 - smoothstep( 0.3, 0.7, selvaNoise( uv * vec2( 0.25, 2.0 ) ) );
1719
+ late *= 1.0 - ${f$1(pores * .45)} * mix( 0.5, broken, selvaDetail( 0.5 ) );
1701
1720
  late *= selvaDetail( ${f$1(ring)} );
1702
1721
  float fibre = ( selvaNoise( uv * vec2( 0.04, 1.6 ) ) - 0.5 ) * selvaDetail( 1.0 );
1703
- float pore = smoothstep( 0.62, 0.8, selvaNoise( uv * vec2( 0.3, 2.5 ) ) ) * ( 1.0 - 0.6 * late );
1704
- pore *= ${f$1(pores)} * selvaDetail( 0.8 );
1705
- float streak = ( selvaFbm( uv * vec2( 0.0015, 0.012 ) ) - 0.5 ) * ${f$1(streaks)};
1706
- float shade = 1.0 + ${f$1(latewood * band)} - late * ${f$1(latewood)} + fibre * 0.1 - pore * 0.45 + streak * 0.6;
1707
- tone = vec3( shade );
1722
+ // Pores: thin dashes along the grain, most of each row empty. Smaller than a pixel they
1723
+ // show as their average shade, or they would be static.
1724
+ float poreRow = floor( uv.y / ${f$1(PORE_ROW)} );
1725
+ float poreAlong = uv.x / mix( 1.5, 5.0, selvaHash( vec2( poreRow, 11.0 ) ) ) + selvaHash( vec2( poreRow, 12.0 ) );
1726
+ float poreT = fract( poreAlong );
1727
+ float pore = step( ${f$1(.7)}, selvaHash( vec2( poreRow, 13.0 + 1.618 * floor( poreAlong ) ) ) );
1728
+ pore *= smoothstep( 0.0, 0.3, poreT ) * smoothstep( 1.0, 0.7, poreT );
1729
+ pore *= 1.0 - smoothstep( 0.12, 0.3, abs( fract( uv.y / ${f$1(PORE_ROW)} ) - 0.5 ) );
1730
+ pore = mix( ${f$1(PORE_MEAN)}, pore, selvaDetail( ${f$1(PORE_ROW)} ) ) * ${f$1(pores)} * ( 1.0 - 0.6 * late );
1731
+ float streak = ( selvaFbm( vec2( along * 0.0015, uv.y * 0.012 ) ) - 0.5 ) * ${f$1(streaks)};
1732
+ float shade = 1.0 + ${f$1(latewood * band)} - late * ${f$1(latewood)} + fibre * 0.1 - pore * ${f$1(PORE_DARK)} + streak * 0.6;
1733
+ float board = ( selvaHash( vec2( plank, 4.0 ) ) - 0.5 ) * selvaDetail( ${f$1(PLANK * .5)} );
1734
+ float warmth = ( selvaHash( vec2( plank, 5.0 ) ) - 0.5 ) * selvaDetail( ${f$1(PLANK * .5)} );
1735
+ tone = vec3( shade ) * ( 1.0 + board * ${f$1(BOARD_SHADE)} ) * vec3( 1.0 + warmth * 0.06, 1.0, 1.0 - warmth * 0.06 );
1708
1736
  gloss = 1.0 + late * 0.08 + pore * 0.4 - fibre * 0.2;
1709
- height = ( fibre * 0.00008 - pore * 0.00015 ) * selvaDetail( 0.6 );`;
1737
+ // No relief from pores: a bump from screen derivatives beads any dash under a few pixels wide.
1738
+ height = fibre * 0.00008 * selvaDetail( 0.6 );`;
1710
1739
  /**
1711
1740
  * Procedural surfaces, so a preset looks like its material with no texture files to ship or upload.
1712
1741
  * UVs are millimetres, so a brick is brick-sized at any model scale. Each recipe sets `tone` (albedo
@@ -2016,6 +2045,7 @@ const RECIPES = {
2016
2045
  };
2017
2046
  const TILT = .6;
2018
2047
  const FIBRE_FADE = .35;
2048
+ const FIBRE_ASPECT = 16;
2019
2049
  const f = (n) => n.toFixed(4);
2020
2050
  /** The shader patch for a finish, or null when it would draw nothing. `key` extends the program cache key. */
2021
2051
  function finishPatch(finish, strength) {
@@ -2047,7 +2077,8 @@ function finishPatch(finish, strength) {
2047
2077
  // of the part. depth * |depth| keeps most fibres faint and a few deep.
2048
2078
  float selvaFibreRow( vec2 uv, float pitch, vec2 len, float seed ) {
2049
2079
  float row = floor( uv.y / pitch );
2050
- float l = mix( len.x, len.y, selvaHash( vec2( row, seed + 1.0 ) ) );
2080
+ // A coarse cell stays a streak: as wide as it is long it reads as speckle, not grain.
2081
+ float l = max( mix( len.x, len.y, selvaHash( vec2( row, seed + 1.0 ) ) ), pitch * ${f(FIBRE_ASPECT)} );
2051
2082
  float along = uv.x / l + selvaHash( vec2( row, seed + 2.0 ) );
2052
2083
  float seg = floor( along );
2053
2084
  float depth = selvaHash( vec2( row, seed + 3.0 + 1.618 * seg ) ) * 2.0 - 1.0;
@@ -2141,7 +2172,7 @@ function createMaterial(matData, options) {
2141
2172
  if (matData.envMapIntensity != null) {
2142
2173
  material.envMapIntensity = matData.envMapIntensity;
2143
2174
  material.userData[require_gpu_dispose.OWN_ENV_MAP_INTENSITY] = matData.envMapIntensity;
2144
- } else if (appearance?.envMapIntensity != null) material.envMapIntensity = require_gpu_dispose.lookEnvMapIntensity(appearance.envMapIntensity, matData.metalness);
2175
+ } else if (appearance?.envMapIntensity != null) material.envMapIntensity = require_gpu_dispose.lookEnvMapIntensity(appearance.envMapIntensity, matData.metalness, appearance.metalReflection);
2145
2176
  if (matData.emissive != null) {
2146
2177
  material.emissive.set(matData.emissive);
2147
2178
  material.emissiveIntensity = matData.emissiveIntensity ?? 1;
@@ -2159,7 +2190,7 @@ function createMaterial(matData, options) {
2159
2190
  }
2160
2191
  if (matData.anisotropy != null && matData.anisotropy > 0 && options?.hasUvs) {
2161
2192
  material.anisotropy = matData.anisotropy;
2162
- material.anisotropyRotation = matData.anisotropyRotation ?? 0;
2193
+ material.anisotropyRotation = (matData.anisotropyRotation ?? 0) + Math.PI / 2;
2163
2194
  }
2164
2195
  if (matData.ior != null) material.ior = matData.ior;
2165
2196
  if (matData.transmission != null && matData.transmission > 0) applyGlass(material, matData);