@selvajs/visualization 1.8.0-beta.8 → 1.8.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.
- package/dist/{gpu-dispose-0c_-KS12.cjs → gpu-dispose--5MA0CcI.cjs} +10 -9
- package/dist/{gpu-dispose-0c_-KS12.cjs.map → gpu-dispose--5MA0CcI.cjs.map} +1 -1
- package/dist/{gpu-dispose-k_Gq-ygL.js → gpu-dispose-m5ywfM1f.js} +8 -8
- package/dist/{gpu-dispose-k_Gq-ygL.js.map → gpu-dispose-m5ywfM1f.js.map} +1 -1
- package/dist/{gpu-ownership-Bs9l7hrU.js → gpu-ownership-5o7F_lc2.js} +1 -1
- package/dist/{gpu-ownership-Bs9l7hrU.js.map → gpu-ownership-5o7F_lc2.js.map} +1 -1
- package/dist/{gpu-ownership-ADRZBxxs.cjs → gpu-ownership-BtECafMd.cjs} +1 -28
- package/dist/{gpu-ownership-ADRZBxxs.cjs.map → gpu-ownership-BtECafMd.cjs.map} +1 -1
- package/dist/{merged-draw-CO4rr2Co.js → merged-draw-BE0616Nv.js} +2 -2
- package/dist/{merged-draw-CO4rr2Co.js.map → merged-draw-BE0616Nv.js.map} +1 -1
- package/dist/{merged-draw-ma_2r4N8.cjs → merged-draw-C9jFRnos.cjs} +4 -3
- package/dist/merged-draw-C9jFRnos.cjs.map +1 -0
- package/dist/parse.cjs +23 -25
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.d.cts +9 -3
- package/dist/parse.d.ts +9 -3
- package/dist/parse.js +21 -24
- package/dist/parse.js.map +1 -1
- package/dist/render.cjs +35 -34
- package/dist/render.cjs.map +1 -1
- package/dist/render.d.cts +10 -6
- package/dist/render.d.ts +14 -7
- package/dist/render.js +33 -33
- package/dist/render.js.map +1 -1
- package/dist/rolldown-runtime-CmQyd0Gu.cjs +27 -0
- package/dist/scene.cjs +3 -3
- package/dist/scene.cjs.map +1 -1
- package/dist/scene.d.cts +10 -2
- package/dist/scene.d.ts +10 -2
- package/dist/scene.js +1 -1
- package/dist/{types-i9wRcHK7.d.ts → types-8Qx4xyyR.d.ts} +1 -2
- package/dist/{types-i9wRcHK7.d.cts → types-D1PpOP_H.d.cts} +1 -2
- package/package.json +8 -8
- package/dist/merged-draw-ma_2r4N8.cjs.map +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
|
|
2
|
+
const require_gpu_ownership = require("./gpu-ownership-BtECafMd.cjs");
|
|
2
3
|
let three = require("three");
|
|
3
|
-
three =
|
|
4
|
+
three = require_rolldown_runtime.__toESM(three, 1);
|
|
4
5
|
// src/shared/errors.ts
|
|
5
6
|
/**
|
|
6
7
|
* Errors for the visualization package. Replaces `@selvajs/compute`'s `RhinoComputeError`, which
|
|
@@ -135,7 +136,7 @@ const LOOK_PRESETS = {
|
|
|
135
136
|
ambientOcclusion: true,
|
|
136
137
|
sunlightIntensity: 2,
|
|
137
138
|
materialOverride: {
|
|
138
|
-
color:
|
|
139
|
+
color: 0xeef1f5,
|
|
139
140
|
metalness: 0,
|
|
140
141
|
roughness: .75,
|
|
141
142
|
emissiveIntensity: 0
|
|
@@ -152,7 +153,7 @@ const LOOK_PRESETS = {
|
|
|
152
153
|
ambientOcclusion: false,
|
|
153
154
|
sunlightIntensity: .6,
|
|
154
155
|
materialOverride: {
|
|
155
|
-
color:
|
|
156
|
+
color: 0x9fc4e8,
|
|
156
157
|
metalness: 0,
|
|
157
158
|
roughness: .9,
|
|
158
159
|
emissiveIntensity: 0,
|
|
@@ -173,7 +174,7 @@ const LOOK_PRESETS = {
|
|
|
173
174
|
sunlightIntensity: 0,
|
|
174
175
|
requiresEdges: true,
|
|
175
176
|
materialOverride: {
|
|
176
|
-
color:
|
|
177
|
+
color: 0xf7f8fa,
|
|
177
178
|
metalness: 0,
|
|
178
179
|
roughness: 1,
|
|
179
180
|
emissiveIntensity: 0
|
|
@@ -265,7 +266,7 @@ function materialAppearanceForLook(look) {
|
|
|
265
266
|
function parseColor(colorString) {
|
|
266
267
|
if (!colorString || typeof colorString !== "string") {
|
|
267
268
|
getLogger().warn(`Invalid color input: ${colorString}, using white`);
|
|
268
|
-
return new three.Color(
|
|
269
|
+
return new three.Color(0xffffff);
|
|
269
270
|
}
|
|
270
271
|
const trimmed = colorString.trim();
|
|
271
272
|
if (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) try {
|
|
@@ -273,7 +274,7 @@ function parseColor(colorString) {
|
|
|
273
274
|
return new three.Color(hex);
|
|
274
275
|
} catch {
|
|
275
276
|
getLogger().warn(`Invalid hex color: ${colorString}, using white`);
|
|
276
|
-
return new three.Color(
|
|
277
|
+
return new three.Color(0xffffff);
|
|
277
278
|
}
|
|
278
279
|
if (trimmed.includes(",")) {
|
|
279
280
|
const rgb = trimmed.split(",").map((c) => parseInt(c.trim(), 10));
|
|
@@ -282,7 +283,7 @@ function parseColor(colorString) {
|
|
|
282
283
|
const named = trimmed.toLowerCase();
|
|
283
284
|
if (named in three.Color.NAMES) return new three.Color(three.Color.NAMES[named]);
|
|
284
285
|
getLogger().warn(`Invalid color string: ${colorString}, using white`);
|
|
285
|
-
return new three.Color(
|
|
286
|
+
return new three.Color(0xffffff);
|
|
286
287
|
}
|
|
287
288
|
/** Defaults to `z` (Rhino's up axis); pass an explicit axis when the scene uses a different `sceneUp`. */
|
|
288
289
|
function applyOffset(meshes, offset, axis = "z") {
|
|
@@ -514,4 +515,4 @@ Object.defineProperty(exports, "setLogger", {
|
|
|
514
515
|
}
|
|
515
516
|
});
|
|
516
517
|
|
|
517
|
-
//# sourceMappingURL=gpu-dispose
|
|
518
|
+
//# sourceMappingURL=gpu-dispose--5MA0CcI.cjs.map
|
|
@@ -1 +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":";;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AAS;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"}
|
|
1
|
+
{"version":3,"file":"gpu-dispose--5MA0CcI.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;CAC7B;CACA;CACA;CAEhB,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,eACX,KAA6B,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,QAA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;AACzE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as cachedSourceOf, r as canDisposeMaterial } from "./gpu-ownership-
|
|
1
|
+
import { n as cachedSourceOf, r as canDisposeMaterial } from "./gpu-ownership-5o7F_lc2.js";
|
|
2
2
|
import * as THREE from "three";
|
|
3
3
|
// src/shared/errors.ts
|
|
4
4
|
/**
|
|
@@ -134,7 +134,7 @@ const LOOK_PRESETS = {
|
|
|
134
134
|
ambientOcclusion: true,
|
|
135
135
|
sunlightIntensity: 2,
|
|
136
136
|
materialOverride: {
|
|
137
|
-
color:
|
|
137
|
+
color: 0xeef1f5,
|
|
138
138
|
metalness: 0,
|
|
139
139
|
roughness: .75,
|
|
140
140
|
emissiveIntensity: 0
|
|
@@ -151,7 +151,7 @@ const LOOK_PRESETS = {
|
|
|
151
151
|
ambientOcclusion: false,
|
|
152
152
|
sunlightIntensity: .6,
|
|
153
153
|
materialOverride: {
|
|
154
|
-
color:
|
|
154
|
+
color: 0x9fc4e8,
|
|
155
155
|
metalness: 0,
|
|
156
156
|
roughness: .9,
|
|
157
157
|
emissiveIntensity: 0,
|
|
@@ -172,7 +172,7 @@ const LOOK_PRESETS = {
|
|
|
172
172
|
sunlightIntensity: 0,
|
|
173
173
|
requiresEdges: true,
|
|
174
174
|
materialOverride: {
|
|
175
|
-
color:
|
|
175
|
+
color: 0xf7f8fa,
|
|
176
176
|
metalness: 0,
|
|
177
177
|
roughness: 1,
|
|
178
178
|
emissiveIntensity: 0
|
|
@@ -264,7 +264,7 @@ function materialAppearanceForLook(look) {
|
|
|
264
264
|
function parseColor(colorString) {
|
|
265
265
|
if (!colorString || typeof colorString !== "string") {
|
|
266
266
|
getLogger().warn(`Invalid color input: ${colorString}, using white`);
|
|
267
|
-
return new THREE.Color(
|
|
267
|
+
return new THREE.Color(0xffffff);
|
|
268
268
|
}
|
|
269
269
|
const trimmed = colorString.trim();
|
|
270
270
|
if (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) try {
|
|
@@ -272,7 +272,7 @@ function parseColor(colorString) {
|
|
|
272
272
|
return new THREE.Color(hex);
|
|
273
273
|
} catch {
|
|
274
274
|
getLogger().warn(`Invalid hex color: ${colorString}, using white`);
|
|
275
|
-
return new THREE.Color(
|
|
275
|
+
return new THREE.Color(0xffffff);
|
|
276
276
|
}
|
|
277
277
|
if (trimmed.includes(",")) {
|
|
278
278
|
const rgb = trimmed.split(",").map((c) => parseInt(c.trim(), 10));
|
|
@@ -281,7 +281,7 @@ function parseColor(colorString) {
|
|
|
281
281
|
const named = trimmed.toLowerCase();
|
|
282
282
|
if (named in THREE.Color.NAMES) return new THREE.Color(THREE.Color.NAMES[named]);
|
|
283
283
|
getLogger().warn(`Invalid color string: ${colorString}, using white`);
|
|
284
|
-
return new THREE.Color(
|
|
284
|
+
return new THREE.Color(0xffffff);
|
|
285
285
|
}
|
|
286
286
|
/** Defaults to `z` (Rhino's up axis); pass an explicit axis when the scene uses a different `sceneUp`. */
|
|
287
287
|
function applyOffset(meshes, offset, axis = "z") {
|
|
@@ -382,4 +382,4 @@ function disposeGeometry(geometry, keepUploaded) {
|
|
|
382
382
|
}
|
|
383
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 };
|
|
384
384
|
|
|
385
|
-
//# sourceMappingURL=gpu-dispose-
|
|
385
|
+
//# sourceMappingURL=gpu-dispose-m5ywfM1f.js.map
|
|
@@ -1 +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":";;;;;;;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AiB;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,SAAS,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"}
|
|
1
|
+
{"version":3,"file":"gpu-dispose-m5ywfM1f.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;CAC7B;CACA;CACA;CAEhB,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,eACX,KAA6B,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,S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ry as o, canDisposeMaterial as r, borrowGeometry as t };
|
|
39
39
|
|
|
40
|
-
//# sourceMappingURL=gpu-ownership-
|
|
40
|
+
//# sourceMappingURL=gpu-ownership-5o7F_lc2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gpu-ownership-
|
|
1
|
+
{"version":3,"file":"gpu-ownership-5o7F_lc2.js","names":[],"sources":["../src/shared/gpu-ownership.ts"],"sourcesContent":["import type * as THREE from 'three';\n\n// ============================================================================\n// GPU resource ownership — the single rule every disposal path obeys\n// ============================================================================\n\n/**\n * A GPU resource has exactly one owner: a **module singleton** (nobody ever frees it), a **cache**\n * (frees it on eviction) or the **scene** (freed on teardown). Every disposal path asks\n * {@link canDisposeMaterial} before freeing a material. Textures are always scene-owned.\n *\n * A cached geometry's data belongs to the cache, but its GPU copy lives only while a scene draws it.\n * Scene teardown resolves each geometry with {@link cachedSourceOf} and frees the GPU copy of every\n * cached geometry the next scene does not draw; three uploads it again if it comes back. A cached\n * geometry can back several meshes at once, so nothing may write to its arrays.\n */\n\n// Module-scope singletons from `render/three-materials.ts`, shared across meshes and solves —\n// disposing one would free textures still in use and force a recompile. Held here (not imported\n// there) to avoid an import cycle.\nconst protectedMaterials = new Set<THREE.Material>();\n\n/** Register materials as never-disposable. Called once by `render/three-materials.ts`. */\nexport function protectMaterials(materials: Iterable<THREE.Material>): void {\n\tfor (const material of materials) protectedMaterials.add(material);\n}\n\n/** True when `material` is scene-owned (not one of the protected singletons). */\nexport function canDisposeMaterial(material: THREE.Material | undefined): boolean {\n\tif (!material) return false;\n\treturn !protectedMaterials.has(material);\n}\n\n// Geometries the parser's finished-geometry cache hands out across solves.\nconst sharedGeometries = new WeakSet<THREE.BufferGeometry>();\n\nexport function shareGeometry(geometry: THREE.BufferGeometry): void {\n\tsharedGeometries.add(geometry);\n}\n\nexport function unshareGeometry(geometry: THREE.BufferGeometry): void {\n\tsharedGeometries.delete(geometry);\n}\n\nexport function isCachedGeometry(geometry: THREE.BufferGeometry): boolean {\n\treturn sharedGeometries.has(geometry);\n}\n\n// Scene-owned geometries drawing a cached geometry's attributes under their own groups. Disposing\n// one as is would free those attributes' GPU buffers out from under the cache.\nconst borrowers = new WeakMap<THREE.BufferGeometry, THREE.BufferGeometry>();\n\nexport function borrowGeometry(borrower: THREE.BufferGeometry, source: THREE.BufferGeometry): void {\n\tborrowers.set(borrower, source);\n}\n\n/** The cached geometry whose GPU buffers `geometry` draws, or null when it owns its own. */\nexport function cachedSourceOf(geometry: THREE.BufferGeometry): THREE.BufferGeometry | null {\n\tif (sharedGeometries.has(geometry)) return geometry;\n\t// Once evicted, the source is scene-owned like any other geometry, and the borrower frees it.\n\tconst source = borrowers.get(geometry);\n\treturn source && sharedGeometries.has(source) ? source : null;\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,qCAAqB,IAAI,IAAoB;;AAQnD,SAAgB,mBAAmB,UAA+C;CACjF,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO,CAAC,mBAAmB,IAAI,QAAQ;AACxC;AAGA,MAAM,mCAAmB,IAAI,QAA8B;AAE3D,SAAgB,cAAc,UAAsC;CACnE,iBAAiB,IAAI,QAAQ;AAC9B;AAEA,SAAgB,gBAAgB,UAAsC;CACrE,iBAAiB,OAAO,QAAQ;AACjC;AAEA,SAAgB,iBAAiB,UAAyC;CACzE,OAAO,iBAAiB,IAAI,QAAQ;AACrC;AAIA,MAAM,4BAAY,IAAI,QAAoD;AAE1E,SAAgB,eAAe,UAAgC,QAAoC;CAClG,UAAU,IAAI,UAAU,MAAM;AAC/B;;AAGA,SAAgB,eAAe,UAA6D;CAC3F,IAAI,iBAAiB,IAAI,QAAQ,GAAG,OAAO;CAE3C,MAAM,SAAS,UAAU,IAAI,QAAQ;CACrC,OAAO,UAAU,iBAAiB,IAAI,MAAM,IAAI,SAAS;AAC1D"}
|
|
@@ -1,24 +1,3 @@
|
|
|
1
|
-
// \0rolldown/runtime.js
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
-
key = keys[i];
|
|
11
|
-
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
-
get: ((k) => from[k]).bind(null, key),
|
|
13
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
|
-
value: mod,
|
|
20
|
-
enumerable: true
|
|
21
|
-
}) : target, mod));
|
|
22
1
|
// src/shared/gpu-ownership.ts
|
|
23
2
|
/**
|
|
24
3
|
* A GPU resource has exactly one owner: a **module singleton** (nobody ever frees it), a **cache**
|
|
@@ -56,12 +35,6 @@ function cachedSourceOf(geometry) {
|
|
|
56
35
|
const source = borrowers.get(geometry);
|
|
57
36
|
return source && sharedGeometries.has(source) ? source : null;
|
|
58
37
|
}
|
|
59
|
-
Object.defineProperty(exports, "__toESM", {
|
|
60
|
-
enumerable: true,
|
|
61
|
-
get: function() {
|
|
62
|
-
return __toESM;
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
38
|
Object.defineProperty(exports, "borrowGeometry", {
|
|
66
39
|
enumerable: true,
|
|
67
40
|
get: function() {
|
|
@@ -99,4 +72,4 @@ Object.defineProperty(exports, "unshareGeometry", {
|
|
|
99
72
|
}
|
|
100
73
|
});
|
|
101
74
|
|
|
102
|
-
//# sourceMappingURL=gpu-ownership-
|
|
75
|
+
//# sourceMappingURL=gpu-ownership-BtECafMd.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gpu-ownership-
|
|
1
|
+
{"version":3,"file":"gpu-ownership-BtECafMd.cjs","names":[],"sources":["../src/shared/gpu-ownership.ts"],"sourcesContent":["import type * as THREE from 'three';\n\n// ============================================================================\n// GPU resource ownership — the single rule every disposal path obeys\n// ============================================================================\n\n/**\n * A GPU resource has exactly one owner: a **module singleton** (nobody ever frees it), a **cache**\n * (frees it on eviction) or the **scene** (freed on teardown). Every disposal path asks\n * {@link canDisposeMaterial} before freeing a material. Textures are always scene-owned.\n *\n * A cached geometry's data belongs to the cache, but its GPU copy lives only while a scene draws it.\n * Scene teardown resolves each geometry with {@link cachedSourceOf} and frees the GPU copy of every\n * cached geometry the next scene does not draw; three uploads it again if it comes back. A cached\n * geometry can back several meshes at once, so nothing may write to its arrays.\n */\n\n// Module-scope singletons from `render/three-materials.ts`, shared across meshes and solves —\n// disposing one would free textures still in use and force a recompile. Held here (not imported\n// there) to avoid an import cycle.\nconst protectedMaterials = new Set<THREE.Material>();\n\n/** Register materials as never-disposable. Called once by `render/three-materials.ts`. */\nexport function protectMaterials(materials: Iterable<THREE.Material>): void {\n\tfor (const material of materials) protectedMaterials.add(material);\n}\n\n/** True when `material` is scene-owned (not one of the protected singletons). */\nexport function canDisposeMaterial(material: THREE.Material | undefined): boolean {\n\tif (!material) return false;\n\treturn !protectedMaterials.has(material);\n}\n\n// Geometries the parser's finished-geometry cache hands out across solves.\nconst sharedGeometries = new WeakSet<THREE.BufferGeometry>();\n\nexport function shareGeometry(geometry: THREE.BufferGeometry): void {\n\tsharedGeometries.add(geometry);\n}\n\nexport function unshareGeometry(geometry: THREE.BufferGeometry): void {\n\tsharedGeometries.delete(geometry);\n}\n\nexport function isCachedGeometry(geometry: THREE.BufferGeometry): boolean {\n\treturn sharedGeometries.has(geometry);\n}\n\n// Scene-owned geometries drawing a cached geometry's attributes under their own groups. Disposing\n// one as is would free those attributes' GPU buffers out from under the cache.\nconst borrowers = new WeakMap<THREE.BufferGeometry, THREE.BufferGeometry>();\n\nexport function borrowGeometry(borrower: THREE.BufferGeometry, source: THREE.BufferGeometry): void {\n\tborrowers.set(borrower, source);\n}\n\n/** The cached geometry whose GPU buffers `geometry` draws, or null when it owns its own. */\nexport function cachedSourceOf(geometry: THREE.BufferGeometry): THREE.BufferGeometry | null {\n\tif (sharedGeometries.has(geometry)) return geometry;\n\t// Once evicted, the source is scene-owned like any other geometry, and the borrower frees it.\n\tconst source = borrowers.get(geometry);\n\treturn source && sharedGeometries.has(source) ? source : null;\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,qCAAqB,IAAI,IAAoB;;AAQnD,SAAgB,mBAAmB,UAA+C;CACjF,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO,CAAC,mBAAmB,IAAI,QAAQ;AACxC;AAGA,MAAM,mCAAmB,IAAI,QAA8B;AAE3D,SAAgB,cAAc,UAAsC;CACnE,iBAAiB,IAAI,QAAQ;AAC9B;AAEA,SAAgB,gBAAgB,UAAsC;CACrE,iBAAiB,OAAO,QAAQ;AACjC;AAEA,SAAgB,iBAAiB,UAAyC;CACzE,OAAO,iBAAiB,IAAI,QAAQ;AACrC;AAIA,MAAM,4BAAY,IAAI,QAAoD;AAE1E,SAAgB,eAAe,UAAgC,QAAoC;CAClG,UAAU,IAAI,UAAU,MAAM;AAC/B;;AAGA,SAAgB,eAAe,UAA6D;CAC3F,IAAI,iBAAiB,IAAI,QAAQ,GAAG,OAAO;CAE3C,MAAM,SAAS,UAAU,IAAI,QAAQ;CACrC,OAAO,UAAU,iBAAiB,IAAI,MAAM,IAAI,SAAS;AAC1D"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as isCachedGeometry, t as borrowGeometry } from "./gpu-ownership-Bs9l7hrU.js";
|
|
2
1
|
import * as THREE from "three";
|
|
2
|
+
import { i as isCachedGeometry, t as borrowGeometry } from "./gpu-ownership-5o7F_lc2.js";
|
|
3
3
|
// src/shared/merged-draw.ts
|
|
4
4
|
const states = /* @__PURE__ */ new WeakMap();
|
|
5
5
|
const listeners = /* @__PURE__ */ new WeakMap();
|
|
@@ -126,4 +126,4 @@ function onMemberDrawChange(mesh, listener) {
|
|
|
126
126
|
}
|
|
127
127
|
export { onMemberDrawChange as a, getHiddenMembers as i, cloneForTint as n, setHiddenMembers as o, getBaseMaterial as r, setMemberHighlight as s, clearMemberHighlight as t };
|
|
128
128
|
|
|
129
|
-
//# sourceMappingURL=merged-draw-
|
|
129
|
+
//# sourceMappingURL=merged-draw-BE0616Nv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merged-draw-
|
|
1
|
+
{"version":3,"file":"merged-draw-BE0616Nv.js","names":[],"sources":["../src/shared/merged-draw.ts"],"sourcesContent":["// ============================================================================\n// Which parts of a merged mesh draw, and with what material\n// ============================================================================\n//\n// A merged mesh draws many source members in one call. Two features draw only part of it: hiding\n// a member (`scene/`) and tinting a selected or hovered member (`render/`). Both need geometry groups, and\n// three honours groups only when `material` is an array: with a single material it draws the whole\n// index range and ignores them. So one owner builds the groups and the material array from both\n// states together. Two writers each replacing the groups would undo each other.\n//\n// Members are addressed by their index in `userData.members`, which carries each member's window\n// into the index buffer (`finalizeMergedMesh`).\n\nimport * as THREE from 'three';\n\nimport { borrowGeometry, isCachedGeometry } from './gpu-ownership.js';\n\ninterface MemberWindow {\n\tindexStart?: number;\n\tindexCount?: number;\n}\n\nexport type HighlightKind = 'selection' | 'hover';\n\ninterface Highlight {\n\tmembers: ReadonlySet<number>;\n\tmaterial: THREE.Material;\n}\n\ninterface DrawState extends Record<HighlightKind, Highlight | null> {\n\t/** The mesh's own material, restored once nothing is hidden or highlighted. */\n\tbase: THREE.Material;\n\thidden: ReadonlySet<number>;\n}\n\nconst states = new WeakMap<THREE.Mesh, DrawState>();\nconst listeners = new WeakMap<THREE.Mesh, Set<() => void>>();\n\nconst tintOrigins = new WeakMap<THREE.Material, THREE.Material>();\n\nconst NONE: ReadonlySet<number> = new Set();\n\nfunction windowsOf(mesh: THREE.Mesh): Required<MemberWindow>[] | null {\n\tconst members = mesh.userData?.members as MemberWindow[] | undefined;\n\tif (!Array.isArray(members) || members.length === 0) return null;\n\t// One member without a window means the ranges can't be rebuilt without dropping geometry.\n\tif (members.some((m) => m.indexStart == null || m.indexCount == null)) return null;\n\treturn members as Required<MemberWindow>[];\n}\n\nfunction stateOf(mesh: THREE.Mesh): DrawState {\n\tlet state = states.get(mesh);\n\tif (!state) {\n\t\tconst base = Array.isArray(mesh.material) ? mesh.material[0]! : mesh.material;\n\t\tstate = { base, hidden: NONE, selection: null, hover: null };\n\t\tstates.set(mesh, state);\n\t}\n\treturn state;\n}\n\n// Groups live on the geometry, and a cached geometry can back two meshes at once (two identical\n// branches), so a mesh gets its own geometry over the same attributes before writing any.\nfunction ownGeometry(mesh: THREE.Mesh): THREE.BufferGeometry {\n\tconst shared = mesh.geometry;\n\tif (!isCachedGeometry(shared)) return shared;\n\n\tconst own = new THREE.BufferGeometry();\n\town.setIndex(shared.index);\n\tfor (const [name, attribute] of Object.entries(shared.attributes))\n\t\town.setAttribute(name, attribute);\n\town.boundingBox = shared.boundingBox?.clone() ?? null;\n\town.boundingSphere = shared.boundingSphere?.clone() ?? null;\n\tborrowGeometry(own, shared);\n\tmesh.geometry = own;\n\treturn own;\n}\n\nfunction rebuild(mesh: THREE.Mesh, windows: Required<MemberWindow>[], state: DrawState): void {\n\tconst geometry = ownGeometry(mesh);\n\tgeometry.clearGroups();\n\n\tconst { selection, hover } = state;\n\tif (state.hidden.size === 0 && !selection && !hover) {\n\t\tmesh.material = state.base;\n\t\tstates.delete(mesh);\n\t\treturn;\n\t}\n\n\tconst materials = [state.base];\n\tconst selectionSlot = selection ? materials.push(selection.material) - 1 : 0;\n\tconst hoverSlot = hover ? materials.push(hover.material) - 1 : 0;\n\n\t// Coalesce neighbours with the same material, so hiding one member costs two draws, not N.\n\tlet runStart = -1;\n\tlet runEnd = 0;\n\tlet runMaterial = 0;\n\tconst flush = () => {\n\t\tif (runStart >= 0) geometry.addGroup(runStart, runEnd - runStart, runMaterial);\n\t\trunStart = -1;\n\t};\n\tfor (let i = 0; i < windows.length; i++) {\n\t\tif (state.hidden.has(i)) {\n\t\t\tflush();\n\t\t\tcontinue;\n\t\t}\n\t\tconst { indexStart, indexCount } = windows[i]!;\n\t\t// Selection wins, so pointing at a selected member doesn't make it look unselected.\n\t\tconst material = selection?.members.has(i)\n\t\t\t? selectionSlot\n\t\t\t: hover?.members.has(i)\n\t\t\t\t? hoverSlot\n\t\t\t\t: 0;\n\t\tif (runStart < 0 || material !== runMaterial || indexStart !== runEnd) {\n\t\t\tflush();\n\t\t\trunStart = indexStart;\n\t\t\trunMaterial = material;\n\t\t}\n\t\trunEnd = indexStart + indexCount;\n\t}\n\tflush();\n\n\tmesh.material = materials;\n}\n\nfunction update(mesh: THREE.Mesh, change: (state: DrawState) => void): void {\n\tconst windows = windowsOf(mesh);\n\tif (!windows) return;\n\tconst state = stateOf(mesh);\n\tchange(state);\n\trebuild(mesh, windows, state);\n\tlisteners.get(mesh)?.forEach((listener) => listener());\n}\n\n/** Members of `mesh` not drawn, by index into `userData.members`. */\nexport function getHiddenMembers(mesh: THREE.Mesh): ReadonlySet<number> {\n\treturn states.get(mesh)?.hidden ?? NONE;\n}\n\nexport function setHiddenMembers(mesh: THREE.Mesh, hidden: ReadonlySet<number>): void {\n\tconst current = getHiddenMembers(mesh);\n\tif (current.size === hidden.size && [...hidden].every((i) => current.has(i))) return;\n\tupdate(mesh, (state) => {\n\t\tstate.hidden = new Set(hidden);\n\t});\n}\n\n/** The material `mesh` draws with when nothing is highlighted. */\nexport function getBaseMaterial(mesh: THREE.Mesh): THREE.Material {\n\tconst material =\n\t\tstates.get(mesh)?.base ?? (Array.isArray(mesh.material) ? mesh.material[0]! : mesh.material);\n\treturn tintOrigins.get(material) ?? material;\n}\n\n/** A clone to tint and swap onto a mesh. `getBaseMaterial` keeps answering with `material`. */\nexport function cloneForTint(material: THREE.Material): THREE.Material {\n\tconst clone = material.clone();\n\ttintOrigins.set(clone, tintOrigins.get(material) ?? material);\n\treturn clone;\n}\n\n/** Draws `members` with `material`. The caller owns `material` and disposes it. */\nexport function setMemberHighlight(\n\tmesh: THREE.Mesh,\n\tmembers: ReadonlySet<number>,\n\tmaterial: THREE.Material,\n\tkind: HighlightKind = 'selection'\n): void {\n\tupdate(mesh, (state) => {\n\t\tstate[kind] = { members, material };\n\t});\n}\n\nexport function clearMemberHighlight(mesh: THREE.Mesh, kind: HighlightKind = 'selection'): void {\n\tif (!states.get(mesh)?.[kind]) return;\n\tupdate(mesh, (state) => {\n\t\tstate[kind] = null;\n\t});\n}\n\n/** Calls `listener` after the hidden set or highlight of `mesh` changes. Returns an unsubscribe. */\nexport function onMemberDrawChange(mesh: THREE.Mesh, listener: () => void): () => void {\n\tlet set = listeners.get(mesh);\n\tif (!set) listeners.set(mesh, (set = new Set()));\n\tset.add(listener);\n\treturn () => set.delete(listener);\n}\n"],"mappings":";;;AAmCA,MAAM,yBAAS,IAAI,QAA+B;AAClD,MAAM,4BAAY,IAAI,QAAqC;AAE3D,MAAM,8BAAc,IAAI,QAAwC;AAEhE,MAAM,uBAA4B,IAAI,IAAI;AAE1C,SAAS,UAAU,MAAmD;CACrE,MAAM,UAAU,KAAK,UAAU;CAC/B,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAAG,OAAO;CAE5D,IAAI,QAAQ,MAAM,MAAM,EAAE,cAAc,QAAQ,EAAE,cAAc,IAAI,GAAG,OAAO;CAC9E,OAAO;AACR;AAEA,SAAS,QAAQ,MAA6B;CAC7C,IAAI,QAAQ,OAAO,IAAI,IAAI;CAC3B,IAAI,CAAC,OAAO;EAEX,QAA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ACf;CACP,OAAO,OAAO,UAAU;EACvB,MAAM,QAAQ;GAAE;GAAS;EAAS;CACnC,CAAC;AACF;AAEA,SAAgB,qBAAqB,MAAkB,OAAsB,aAAmB;CAC/F,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,GAAG,OAAO;CAC/B,OAAO,OAAO,UAAU;EACvB,MAAM,QAAQ;CACf,CAAC;AACF;;AAGA,SAAgB,mBAAmB,MAAkB,UAAkC;CACtF,IAAI,MAAM,UAAU,IAAI,IAAI;CAC5B,IAAI,CAAC,KAAK,UAAU,IAAI,MAAO,sBAAM,IAAI,IAAI,CAAE;CAC/C,IAAI,IAAI,QAAQ;CAChB,aAAa,IAAI,OAAO,QAAQ;AACjC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
|
|
2
2
|
let three = require("three");
|
|
3
|
-
|
|
3
|
+
const require_gpu_ownership = require("./gpu-ownership-BtECafMd.cjs");
|
|
4
|
+
three = require_rolldown_runtime.__toESM(three, 1);
|
|
4
5
|
// src/shared/merged-draw.ts
|
|
5
6
|
const states = /* @__PURE__ */ new WeakMap();
|
|
6
7
|
const listeners = /* @__PURE__ */ new WeakMap();
|
|
@@ -168,4 +169,4 @@ Object.defineProperty(exports, "setMemberHighlight", {
|
|
|
168
169
|
}
|
|
169
170
|
});
|
|
170
171
|
|
|
171
|
-
//# sourceMappingURL=merged-draw-
|
|
172
|
+
//# sourceMappingURL=merged-draw-C9jFRnos.cjs.map
|