@huaqiu/dsh-hardware-ui 0.7.23 → 0.7.25

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.
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Companion files: the MTL and textures an OBJ names, the buffers and images a
3
+ * glTF names.
4
+ *
5
+ * The rule the task sets (§5.4, §5.5) is that a document's dependencies are read
6
+ * through DSH's authorized file access and served from memory — never through a
7
+ * second HTTP file server, never by letting Three.js fetch a `file://` path, and
8
+ * never by following an absolute or remote URL a document happens to contain.
9
+ * So the flow is: read bytes through the Host, hand them to the loader as
10
+ * `blob:` URLs, and revoke every URL when the document closes.
11
+ *
12
+ * Three.js loaders resolve a declared reference against a base path and then ask
13
+ * their `LoadingManager` for the final URL, which is the one seam this module
14
+ * uses: `setURLModifier` maps that URL to the blob this module already holds. A
15
+ * reference this module could not read is left alone, so the loader reports the
16
+ * fetch failure itself and the model keeps whatever geometry it could parse.
17
+ *
18
+ * @module @huaqiu/dsh-hardware-ui/client/document/model/companions
19
+ */
20
+
21
+ import { LoadingManager } from 'three'
22
+ import type { CompanionReader } from './types.js'
23
+
24
+ /** Readable text of a `Uint8Array`, without a BOM. */
25
+ export function decodeText(bytes: Uint8Array): string {
26
+ const text = new TextDecoder('utf-8').decode(bytes)
27
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
28
+ }
29
+
30
+ /**
31
+ * Resolve one declared reference against the document that declared it.
32
+ *
33
+ * Mirrors the document-preview convention already used for child sheets: `/` and
34
+ * `\` are interchangeable, `.`/`..` collapse, and a reference that climbs above
35
+ * its directory stays as written — the Host, not this module, decides what is
36
+ * inside the authorized workspace.
37
+ * @param basePath - absolute path of the declaring document.
38
+ * @param reference - the reference exactly as the file wrote it.
39
+ * @returns the resolved path, or undefined for an empty or unusable reference.
40
+ */
41
+ export function resolveCompanionPath(basePath: string, reference: string): string | undefined {
42
+ const trimmed = reference.trim().replaceAll('\\', '/')
43
+ if (trimmed === '') return undefined
44
+ // A URI scheme, an absolute URL or a data URI is never a file beside this
45
+ // document: §5.5 forbids following a URL a document references on its own.
46
+ if (/^[a-z][a-z\d+.-]*:/iu.test(trimmed) && !/^[a-z]:\//iu.test(trimmed)) return undefined
47
+ if (trimmed.startsWith('//')) return undefined
48
+ const absolute = trimmed.startsWith('/') || /^[a-z]:\//iu.test(trimmed)
49
+ const normalizedBase = basePath.replaceAll('\\', '/')
50
+ const slash = normalizedBase.lastIndexOf('/')
51
+ const base = absolute ? '' : normalizedBase.slice(0, slash + 1)
52
+ const joined = absolute ? trimmed : `${base}${trimmed}`
53
+ // Whether the *result* is rooted is decided by whichever path supplied the
54
+ // root — a relative reference onto an absolute base must stay absolute, or the
55
+ // Host would resolve it against the wrong place.
56
+ const rooted = absolute ? trimmed.startsWith('/') : normalizedBase.startsWith('/')
57
+ const segments: string[] = []
58
+ for (const segment of joined.split('/')) {
59
+ if (segment === '' || segment === '.') continue
60
+ if (segment === '..') {
61
+ if (segments.length === 0 || segments[segments.length - 1] === '..') segments.push('..')
62
+ else segments.pop()
63
+ continue
64
+ }
65
+ segments.push(segment)
66
+ }
67
+ if (segments.length === 0) return undefined
68
+ return rooted ? `/${segments.join('/')}` : segments.join('/')
69
+ }
70
+
71
+ /** Directory part of a path, `\`- or `/`-separated. */
72
+ export function directoryOf(path: string): string {
73
+ const normalized = path.replaceAll('\\', '/')
74
+ const slash = normalized.lastIndexOf('/')
75
+ return slash === -1 ? '' : normalized.slice(0, slash)
76
+ }
77
+
78
+ /** Final segment of a path. */
79
+ export function nameOf(path: string): string {
80
+ const normalized = path.replaceAll('\\', '/')
81
+ return normalized.slice(normalized.lastIndexOf('/') + 1)
82
+ }
83
+
84
+ /** URL spelling of a filesystem path, which is what a loader will ask about. */
85
+ function urlKey(value: string): string {
86
+ let text = value.replaceAll('\\', '/')
87
+ const suffix = text.search(/[?#]/u)
88
+ if (suffix !== -1) text = text.slice(0, suffix)
89
+ if (text.startsWith('file://')) text = text.slice('file://'.length)
90
+ try {
91
+ text = decodeURIComponent(text)
92
+ } catch {
93
+ // A malformed escape is still the string the loader asked about.
94
+ }
95
+ return text.toLowerCase()
96
+ }
97
+
98
+ /** Media type for a texture, so the browser decodes it without sniffing. */
99
+ function mediaTypeOf(name: string): string {
100
+ const lower = name.toLowerCase()
101
+ if (lower.endsWith('.png')) return 'image/png'
102
+ if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'
103
+ if (lower.endsWith('.webp')) return 'image/webp'
104
+ if (lower.endsWith('.ktx2')) return 'image/ktx2'
105
+ if (lower.endsWith('.bin')) return 'application/octet-stream'
106
+ return 'application/octet-stream'
107
+ }
108
+
109
+ /** One companion file that was read successfully. */
110
+ export interface CompanionFile {
111
+ readonly bytes: Uint8Array
112
+ /** Absolute path it was read from; the base for that file's own references. */
113
+ readonly path: string
114
+ }
115
+
116
+ /** The resolving surface one adapter uses for a single document. */
117
+ export interface Companions {
118
+ /** A `LoadingManager` whose URL modifier answers from the files already read. */
119
+ readonly manager: LoadingManager
120
+ /**
121
+ * Read one declared reference through the Host.
122
+ * @param reference - reference as written in the declaring file.
123
+ * @param basePath - path of the declaring file; the document itself by default.
124
+ * @returns the bytes and their path, or undefined when they could not be read.
125
+ */
126
+ readBytes(reference: string, basePath?: string): Promise<CompanionFile | undefined>
127
+ /**
128
+ * Publish one read file to the loader as an object URL.
129
+ * @param file - bytes and the path they came from.
130
+ * @returns the blob URL now mapped for that path.
131
+ */
132
+ publish(file: CompanionFile): string
133
+ /** Problems worth telling the user about; never fatal (§5.4). */
134
+ readonly warnings: readonly string[]
135
+ /** Revoke every object URL this bundle created. Idempotent. */
136
+ dispose(): void
137
+ }
138
+
139
+ export interface CompanionsOptions {
140
+ /** Absolute path of the document that declares the references. */
141
+ readonly path?: string
142
+ readonly read?: CompanionReader
143
+ readonly signal: AbortSignal
144
+ }
145
+
146
+ /**
147
+ * Create the companion bundle for one document.
148
+ * @param options - the document's path, the Host reader, and the document lifetime.
149
+ * @returns the resolving surface; `dispose()` before the model is released.
150
+ */
151
+ export function createCompanions(options: CompanionsOptions): Companions {
152
+ const manager = new LoadingManager()
153
+ const byKey = new Map<string, string>()
154
+ const urls: string[] = []
155
+ const warnings: string[] = []
156
+ const warned = new Set<string>()
157
+ const pending = new Map<string, Promise<CompanionFile | undefined>>()
158
+ // One empty blob stands in for every reference this module will not fetch.
159
+ let blocked: string | undefined
160
+ let disposed = false
161
+
162
+ /** Record one unreadable reference once, however many requests mention it. */
163
+ const warn = (reference: string): void => {
164
+ if (warned.has(reference)) return
165
+ warned.add(reference)
166
+ warnings.push(reference)
167
+ }
168
+
169
+ const register = (absolutePath: string, url: string): void => {
170
+ byKey.set(urlKey(absolutePath), url)
171
+ // A loader may hand back only the file name after mangling a Windows base
172
+ // path; the name is the last resort, not the first answer.
173
+ const name = urlKey(nameOf(absolutePath))
174
+ if (!byKey.has(name)) byKey.set(name, url)
175
+ }
176
+
177
+ /**
178
+ * The one seam between a loader and the network.
179
+ *
180
+ * Three things happen here, and the second is the security-relevant one: a
181
+ * reference this module already read resolves to its in-memory blob, an
182
+ * embedded `data:` URI is left alone (no request is made for it), and anything
183
+ * else — an unreadable file, an `https://` URL a document declared — becomes an
184
+ * empty blob. That is §5.5's "do not fetch arbitrary external URLs" enforced at
185
+ * the only place a fetch can start, and it also keeps a missing texture from
186
+ * costing a network round trip before the model appears.
187
+ */
188
+ manager.setURLModifier((url) => {
189
+ const key = urlKey(url)
190
+ const direct = byKey.get(key)
191
+ if (direct !== undefined) return direct
192
+ const byName = byKey.get(urlKey(nameOf(key)))
193
+ if (byName !== undefined) return byName
194
+ if (/^data:/iu.test(url)) return url
195
+ // A remote reference is the one case the adapter never saw: its own reads
196
+ // only ever produced local paths, so this is where it becomes a warning.
197
+ if (/^[a-z][a-z\d+.-]*:\/\//iu.test(url)) warn(url)
198
+ if (blocked === undefined) {
199
+ blocked = URL.createObjectURL(new Blob([], { type: 'application/octet-stream' }))
200
+ urls.push(blocked)
201
+ }
202
+ return blocked
203
+ })
204
+
205
+ const readBytes = async (reference: string, basePath?: string): Promise<CompanionFile | undefined> => {
206
+ if (disposed) return undefined
207
+ const base = basePath ?? options.path
208
+ const key = `${base ?? ''}\u0000${reference}`
209
+ const cached = pending.get(key)
210
+ if (cached !== undefined) return cached
211
+ const task = (async (): Promise<CompanionFile | undefined> => {
212
+ if (base === undefined) {
213
+ // Without the Host's absolute path there is no base to resolve against,
214
+ // and guessing one would read the wrong file.
215
+ warn(reference)
216
+ return undefined
217
+ }
218
+ if (options.read === undefined) {
219
+ warn(reference)
220
+ return undefined
221
+ }
222
+ const resolved = resolveCompanionPath(base, reference)
223
+ if (resolved === undefined) {
224
+ warn(reference)
225
+ return undefined
226
+ }
227
+ const bytes = await options.read(resolved, options.signal).catch(() => undefined)
228
+ if (bytes === undefined || bytes.byteLength === 0) {
229
+ warn(reference)
230
+ return undefined
231
+ }
232
+ return { bytes, path: resolved }
233
+ })()
234
+ pending.set(key, task)
235
+ return task
236
+ }
237
+
238
+ const publish = (file: CompanionFile): string => {
239
+ const existing = byKey.get(urlKey(file.path))
240
+ if (existing !== undefined) return existing
241
+ const url = URL.createObjectURL(new Blob(
242
+ [file.bytes as unknown as BlobPart],
243
+ { type: mediaTypeOf(file.path) },
244
+ ))
245
+ urls.push(url)
246
+ register(file.path, url)
247
+ return url
248
+ }
249
+
250
+ return {
251
+ manager,
252
+ readBytes,
253
+ publish,
254
+ warnings,
255
+ dispose: () => {
256
+ if (disposed) return
257
+ disposed = true
258
+ for (const url of urls) URL.revokeObjectURL(url)
259
+ urls.length = 0
260
+ byKey.clear()
261
+ pending.clear()
262
+ },
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Wait until every request the manager was given has finished.
268
+ *
269
+ * Only the OBJ path needs this. `MTLLoader` hands back its materials
270
+ * synchronously, but each texture's image is still arriving when it does, and
271
+ * the viewer draws exactly one frame after a mount — a texture that lands after
272
+ * that frame stays invisible until the user moves the camera. Awaiting the
273
+ * manager means the first frame already has colour.
274
+ *
275
+ * The wait is bounded on purpose: a texture that never arrives must not hold a
276
+ * document open, because the geometry is worth showing without it (§5.8).
277
+ * @param manager - the loading manager that owns the queued requests.
278
+ * @param timeoutMs - longest time to wait before drawing without the stragglers.
279
+ * @returns a promise that resolves when the queue drains or the bound expires.
280
+ */
281
+ export function whenIdle(manager: LoadingManager, timeoutMs = 4_000): Promise<void> {
282
+ return new Promise((resolvePromise) => {
283
+ let settled = false
284
+ const previous = manager.onLoad
285
+ const settle = (): void => {
286
+ if (settled) return
287
+ settled = true
288
+ clearTimeout(timer)
289
+ manager.onLoad = previous
290
+ resolvePromise()
291
+ }
292
+ const timer = setTimeout(settle, timeoutMs)
293
+ manager.onLoad = () => {
294
+ previous()
295
+ settle()
296
+ }
297
+ })
298
+ }
299
+
300
+ /** Declared references in an MTL file: every `map_*` and the two bump spellings. */
301
+ export function mtlTextureReferences(text: string): string[] { const found: string[] = []
302
+ for (const line of text.split(/\r?\n/u)) {
303
+ const match = /^\s*(map_[a-z_]+|bump|disp|decal|refl|norm)\s+(?:-\S+\s+)*(.+?)\s*$/iu.exec(line)
304
+ if (match?.[2] !== undefined && match[2] !== '') found.push(match[2])
305
+ }
306
+ return found
307
+ }
308
+
309
+ /** Library references an OBJ declares (`mtllib` may list several names per line). */
310
+ export function objLibraryReferences(text: string): string[] {
311
+ const found: string[] = []
312
+ for (const line of text.split(/\r?\n/u)) {
313
+ const match = /^\s*mtllib\s+(.+?)\s*$/iu.exec(line)
314
+ if (match?.[1] === undefined) continue
315
+ for (const name of match[1].split(/\s+/u)) if (name !== '') found.push(name)
316
+ }
317
+ return found
318
+ }
319
+
320
+ /** One resource a glTF document declares outside itself. */
321
+ export interface GltfResource {
322
+ /** The `uri` exactly as the document wrote it. */
323
+ readonly reference: string
324
+ /**
325
+ * True for a buffer, false for an image.
326
+ *
327
+ * glTF draws the line itself: a `buffer` holds the accessor data the geometry
328
+ * is made of, while an `image` is a material's texture. A missing buffer
329
+ * leaves nothing to show and must be reported as a failed document; a missing
330
+ * image costs colour and is a warning (§5.4, §5.5).
331
+ */
332
+ readonly geometry: boolean
333
+ }
334
+
335
+ /**
336
+ * Resources a glTF JSON document declares outside itself.
337
+ * @param json - the parsed document.
338
+ * @returns buffers and images with relative or absolute `uri`s, buffers first.
339
+ */
340
+ export function gltfResourceReferences(json: unknown): GltfResource[] {
341
+ const found: GltfResource[] = []
342
+ if (json === null || typeof json !== 'object') return found
343
+ const record = json as { buffers?: unknown; images?: unknown }
344
+ for (const [list, geometry] of [[record.buffers, true], [record.images, false]] as const) {
345
+ if (!Array.isArray(list)) continue
346
+ for (const entry of list) {
347
+ if (entry === null || typeof entry !== 'object') continue
348
+ const uri = (entry as { uri?: unknown }).uri
349
+ // A `data:` URI is embedded, and an absolute or remote one is not this
350
+ // document's to fetch; both are left to the loader.
351
+ if (typeof uri === 'string' && uri !== '' && !uri.startsWith('data:')) found.push({ reference: uri, geometry })
352
+ }
353
+ }
354
+ return found
355
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The format registry and the mount that turns bytes into a live 3D view.
3
+ *
4
+ * One registry, one mount, one scene. A document body asks this module for the
5
+ * adapter that claims its suffix and hands it the bytes DSH already read; the
6
+ * module owns the size gate, the layout wait, the cancellation checks and the
7
+ * ownership hand-off to the shared viewer. That is the whole "smallest
8
+ * integration point" §4.1 asked for — the MDI and the renderer stay exactly as
9
+ * they were, and adding a format means adding one adapter here.
10
+ *
11
+ * STEP is deliberately not in this list: its reader is the OpenCascade wasm path
12
+ * in `../step.ts`, which the task preserves as-is (§3.2) and which must not be
13
+ * treated as a universal mesh importer (§3.3).
14
+ *
15
+ * @module @huaqiu/dsh-hardware-ui/client/document/model
16
+ */
17
+
18
+ import { DocumentRenderError, waitForLayout } from '../mount.js'
19
+ import { amfAdapter } from './adapters/amf.js'
20
+ import { gltfAdapter } from './adapters/gltf.js'
21
+ import { objAdapter } from './adapters/obj.js'
22
+ import { plyAdapter } from './adapters/ply.js'
23
+ import { stlAdapter } from './adapters/stl.js'
24
+ import { threeMfAdapter } from './adapters/threemf.js'
25
+ import { mountModelView } from './viewer.js'
26
+ import { MAX_MODEL_BYTES, type CompanionReader, type ModelFormatAdapter, type ModelMetadata } from './types.js'
27
+
28
+ /**
29
+ * Every mesh adapter, in the order the document toolbar and the capability line
30
+ * report them. Kept as a value (not a lookup table) so the list itself is
31
+ * testable and the type checker sees every adapter.
32
+ */
33
+ export const MODEL_ADAPTERS: readonly ModelFormatAdapter[] = Object.freeze([
34
+ stlAdapter, threeMfAdapter, objAdapter, gltfAdapter, plyAdapter, amfAdapter,
35
+ ])
36
+
37
+ /** Suffixes the 3D document body claims, derived from the adapters. */
38
+ export const MODEL_EXTENSIONS: readonly string[] = Object.freeze(
39
+ MODEL_ADAPTERS.flatMap(adapter => adapter.extensions),
40
+ )
41
+
42
+ /**
43
+ * The adapter that claims one file.
44
+ *
45
+ * Matching is on the final suffix, case-insensitively, exactly like the document
46
+ * registry's own matching — so `.STL` and `.stl` cannot disagree about who owns
47
+ * the file.
48
+ * @param path - absolute path, bare file name, or a resource address.
49
+ * @returns the adapter, or undefined when no mesh adapter claims this suffix.
50
+ */
51
+ export function modelAdapterFor(path: string): ModelFormatAdapter | undefined {
52
+ const withoutQuery = path.split(/[?#]/u)[0] ?? path
53
+ const lower = withoutQuery.toLowerCase()
54
+ const dot = lower.lastIndexOf('.')
55
+ if (dot === -1) return undefined
56
+ const suffix = lower.slice(dot + 1)
57
+ return MODEL_ADAPTERS.find(adapter => adapter.extensions.includes(suffix))
58
+ }
59
+
60
+ /** A live 3D document. */
61
+ export interface MountedModelDocument {
62
+ /** Release the model, the viewer and the canvas. Idempotent. */
63
+ dispose(): void
64
+ /** Re-fit the camera to the model bounds. */
65
+ fit(): void
66
+ /** What the status line reports about the file. */
67
+ readonly metadata: ModelMetadata
68
+ /** Extension-shaped format name. */
69
+ readonly format: string
70
+ }
71
+
72
+ export interface ModelDocumentRequest {
73
+ /** Exact document bytes; the source file is never modified. */
74
+ readonly bytes: Uint8Array
75
+ /** Absolute path the Host reported, when it reported one. */
76
+ readonly path?: string
77
+ readonly container: HTMLElement
78
+ readonly signal: AbortSignal
79
+ /** Reads this document's companion files through the Host. */
80
+ readonly readCompanion?: CompanionReader
81
+ }
82
+
83
+ /**
84
+ * Load one mesh document into a container.
85
+ * @param request - bytes, path, container, lifetime and companion reader.
86
+ * @returns the live mount; call `dispose()` when the document closes or reloads.
87
+ */
88
+ export async function mountModelDocument(request: ModelDocumentRequest): Promise<MountedModelDocument> {
89
+ const { bytes, container, signal } = request
90
+ if (signal.aborted) throw new DocumentRenderError('aborted', 'render abandoned')
91
+ if (bytes.byteLength === 0) throw new DocumentRenderError('parse', 'file is empty')
92
+ if (bytes.byteLength > MAX_MODEL_BYTES) {
93
+ throw new DocumentRenderError('toolarge', `${bytes.byteLength} bytes exceeds ${MAX_MODEL_BYTES}`)
94
+ }
95
+ const adapter = modelAdapterFor(request.path ?? '')
96
+ if (adapter === undefined) {
97
+ throw new DocumentRenderError('parse', `no importer for ${request.path ?? 'this file'}`)
98
+ }
99
+
100
+ await waitForLayout(container, signal)
101
+ if (signal.aborted) throw new DocumentRenderError('aborted', 'render abandoned')
102
+
103
+ const loaded = await adapter.load({
104
+ bytes,
105
+ ...(request.path === undefined ? {} : { path: request.path }),
106
+ signal,
107
+ ...(request.readCompanion === undefined ? {} : { readCompanion: request.readCompanion }),
108
+ })
109
+ // A tab that closed while the model was being parsed must not attach: the
110
+ // adapter's resources are released here and the caller sees an abort.
111
+ if (signal.aborted) {
112
+ loaded.dispose()
113
+ throw new DocumentRenderError('aborted', 'render abandoned')
114
+ }
115
+
116
+ const view = mountModelView({
117
+ object: loaded.object,
118
+ container,
119
+ // The adapter owns its geometries, materials, textures and object URLs; the
120
+ // viewer calls this exactly once, on dispose or when WebGL is unavailable.
121
+ disposeModel: loaded.dispose,
122
+ canvasAttribute: 'modelCanvas',
123
+ })
124
+ return {
125
+ fit: view.fit,
126
+ dispose: view.dispose,
127
+ metadata: loaded.metadata,
128
+ format: loaded.format,
129
+ }
130
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Shared arithmetic for the mesh adapters: bytes to a parser's input, and one
3
+ * correct release of whatever a loader produced.
4
+ *
5
+ * Disposal is the part worth centralising. Each loader hands back a different
6
+ * shape — a bare `BufferGeometry` (STL, PLY), a `Group` of meshes with materials
7
+ * (3MF, AMF, OBJ), a scene graph with textures (glTF) — and a document tab can be
8
+ * opened and closed all day, so missing one material leaks one GPU buffer per
9
+ * visit (§5.9).
10
+ *
11
+ * @module @huaqiu/dsh-hardware-ui/client/document/model/mesh
12
+ */
13
+
14
+ import {
15
+ DoubleSide, Group, Mesh, MeshStandardMaterial, type BufferGeometry, type Material, type Object3D, type Texture,
16
+ } from 'three'
17
+
18
+ /** Neutral steel, matching the STEP reader's default so formats look alike. */
19
+ export const DEFAULT_MODEL_COLOR = 0xb8bcc4
20
+
21
+ /**
22
+ * A parser-ready `ArrayBuffer` view of document bytes.
23
+ *
24
+ * The bytes arrive as a `Uint8Array` that may be a window into a larger buffer
25
+ * (a paged read, a subarray); handing the whole buffer to a parser would prepend
26
+ * whatever surrounds the document and break every magic-number check.
27
+ *
28
+ * The realm check is not paranoia: every Three.js loader branches on
29
+ * `data instanceof ArrayBuffer`, and a `Uint8Array` created by another realm —
30
+ * an iframe, a test environment's own typed arrays — has a buffer that fails
31
+ * that check while being a perfectly good buffer. The loaders then quietly take
32
+ * their text branch and parse a binary file as ASCII, which succeeds and returns
33
+ * nothing, so the failure surfaces as "no geometry" rather than as a type error.
34
+ * Copying into this realm's `ArrayBuffer` is the only reliable answer; the
35
+ * identity check keeps the common case allocation-free.
36
+ * @param bytes - document bytes.
37
+ * @returns exactly those bytes as an `ArrayBuffer` of this realm.
38
+ */
39
+ export function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
40
+ const whole = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
41
+ if (whole && Object.getPrototypeOf(bytes.buffer) === ArrayBuffer.prototype) return bytes.buffer as ArrayBuffer
42
+ const copy = new ArrayBuffer(bytes.byteLength)
43
+ new Uint8Array(copy).set(bytes)
44
+ return copy
45
+ }
46
+
47
+ /** Material every imported mesh gets: rough metal, double-sided, colour-aware. */
48
+ export function importedMaterial(vertexColors: boolean): MeshStandardMaterial {
49
+ return new MeshStandardMaterial({
50
+ color: vertexColors ? 0xffffff : DEFAULT_MODEL_COLOR,
51
+ metalness: 0.25,
52
+ roughness: 0.55,
53
+ // Imported meshes do not guarantee consistent winding; a single-sided
54
+ // material shows holes on inverted faces.
55
+ side: DoubleSide,
56
+ vertexColors,
57
+ })
58
+ }
59
+
60
+ /** One traversal's worth of disposable resources. */
61
+ interface Owned {
62
+ readonly geometries: Set<{ dispose(): void }>
63
+ readonly materials: Set<Material>
64
+ readonly textures: Set<Texture>
65
+ }
66
+
67
+ function collect(root: Object3D): Owned {
68
+ const owned: Owned = { geometries: new Set(), materials: new Set(), textures: new Set() }
69
+ root.traverse((object) => {
70
+ const mesh = object as {
71
+ geometry?: { dispose(): void }
72
+ material?: Material | readonly Material[]
73
+ }
74
+ if (mesh.geometry !== undefined) owned.geometries.add(mesh.geometry)
75
+ const materials = Array.isArray(mesh.material)
76
+ ? mesh.material
77
+ : mesh.material === undefined ? [] : [mesh.material as Material]
78
+ for (const material of materials) {
79
+ owned.materials.add(material)
80
+ // Textures are reached from the material that references them; disposing
81
+ // the material alone leaves the GPU upload behind.
82
+ for (const value of Object.values(material as unknown as Record<string, unknown>)) {
83
+ const texture = value as Texture | null
84
+ if (texture !== null && typeof texture === 'object' && texture.isTexture === true) owned.textures.add(texture)
85
+ }
86
+ }
87
+ })
88
+ return owned
89
+ }
90
+
91
+ /**
92
+ * Release every GPU resource a loaded model owns.
93
+ * @param root - the object returned by a loader.
94
+ * @returns a disposer that is safe to call twice.
95
+ */
96
+ export function disposerFor(root: Object3D): () => void {
97
+ const owned = collect(root)
98
+ let disposed = false
99
+ return () => {
100
+ if (disposed) return
101
+ disposed = true
102
+ for (const geometry of owned.geometries) geometry.dispose()
103
+ for (const texture of owned.textures) texture.dispose()
104
+ for (const material of owned.materials) material.dispose()
105
+ owned.geometries.clear()
106
+ owned.textures.clear()
107
+ owned.materials.clear()
108
+ }
109
+ }
110
+
111
+ /** Count what the status line reports: top-level objects and distinct materials. */
112
+ export function summarize(root: Object3D): { objectCount: number; materials: number } {
113
+ const materials = new Set<unknown>()
114
+ root.traverse((object) => {
115
+ const material = (object as { material?: Material | readonly Material[] }).material
116
+ if (Array.isArray(material)) for (const entry of material) materials.add(entry)
117
+ else if (material !== undefined) materials.add(material)
118
+ })
119
+ return { objectCount: root.children.length === 0 ? 1 : root.children.length, materials: materials.size }
120
+ }
121
+
122
+ /**
123
+ * Does this object carry any triangle at all? A loader can succeed on nothing.
124
+ *
125
+ * The distinction matters more than it looks: `OBJLoader` turns a file that has
126
+ * vertices but no `f` lines into a `Points` cloud, which is a *correct* parse of
127
+ * a point-cloud OBJ and an invisible document in a shaded viewer. Counting
128
+ * positions would call that a successful load and leave the tab showing nothing,
129
+ * so the test is "is there something that draws a surface": a mesh, with at
130
+ * least one triangle's worth of vertices, that is not a point or line primitive.
131
+ * @param root - the object a loader returned.
132
+ * @returns true when at least one drawable surface exists.
133
+ */
134
+ export function hasGeometry(root: Object3D): boolean {
135
+ let found = false
136
+ root.traverse((object) => {
137
+ if (found) return
138
+ const holder = object as { geometry?: BufferGeometry; isPoints?: boolean; isLine?: boolean }
139
+ if (holder.isPoints === true || holder.isLine === true) return
140
+ const position = holder.geometry?.getAttribute?.('position')
141
+ if (position !== undefined && (position.count ?? 0) >= 3) found = true
142
+ })
143
+ return found
144
+ }
145
+
146
+ /** Wrap one bare geometry in the group every adapter returns, so the shape is uniform. */
147
+ export function singleMeshGroup(
148
+ geometry: BufferGeometry,
149
+ vertexColors: boolean,
150
+ ): { group: Group; dispose(): void } {
151
+ const material = importedMaterial(vertexColors)
152
+ const mesh = new Mesh(geometry, material)
153
+ mesh.name = ''
154
+ const group = new Group()
155
+ group.add(mesh)
156
+ return {
157
+ group,
158
+ dispose: () => {
159
+ geometry.dispose()
160
+ material.dispose()
161
+ },
162
+ }
163
+ }