Line data Source code
1 : import type * as THREE from 'three'
2 :
3 : import { MeshModelAdapter } from './MeshModelAdapter'
4 : import { createAdapterRef, fetchModelData } from './ModelAdapter'
5 : import type {
6 : AdapterRef,
7 : ModelAdapter,
8 : ModelAdapterCapabilities,
9 : ModelLoadContext,
10 : ModelLoadResult
11 : } from './ModelAdapter'
12 : import { PointCloudModelAdapter } from './PointCloudModelAdapter'
13 : import { SplatModelAdapter } from './SplatModelAdapter'
14 : import { disposeObject3D } from './SceneModelManager'
15 : import type {
16 : EventManagerInterface,
17 : Load3dHost,
18 : LoadModelOptions,
19 : LoadModelOutcome,
20 : LoaderManagerInterface,
21 : ModelManagerInterface
22 : } from './interfaces'
23 :
24 2 : function isNotFoundError(error: unknown): boolean {
25 2 : if (!(error instanceof Error)) return false
26 2 : if (
27 : 'response' in error &&
28 : typeof error.response === 'object' &&
29 : error.response !== null &&
30 : 'status' in error.response &&
31 : error.response.status === 404
32 : ) {
33 0 : return true
34 : }
35 2 : return /\b404\b/.test(error.message)
36 : }
37 :
38 : /**
39 : * Default adapter set: mesh + splat + pointCloud. Each adapter declares the
40 : * file extensions it owns. For shared extensions (.ply), the adapter with an
41 : * async `matches()` tiebreaker is tried first; the unconditional adapter acts
42 : * as the fallback — so SplatModelAdapter precedes PointCloudModelAdapter.
43 : */
44 27 : function defaultAdapters(host: Load3dHost): ModelAdapter[] {
45 27 : return [
46 : new MeshModelAdapter(),
47 : new SplatModelAdapter(),
48 : new PointCloudModelAdapter(host.getPLYEngine)
49 : ]
50 : }
51 :
52 24 : export class LoaderManager implements LoaderManagerInterface {
53 : private readonly modelManager: ModelManagerInterface
54 : private readonly eventManager: EventManagerInterface
55 : private readonly host: Load3dHost
56 : private readonly adapters: ModelAdapter[]
57 : private readonly adapterRef: AdapterRef
58 : private currentLoadId: number = 0
59 : private disposed = false
60 :
61 : constructor(
62 : modelManager: ModelManagerInterface,
63 : eventManager: EventManagerInterface,
64 : host: Load3dHost,
65 : adapters?: readonly ModelAdapter[],
66 : adapterRef?: AdapterRef
67 : ) {
68 27 : this.modelManager = modelManager
69 27 : this.eventManager = eventManager
70 27 : this.host = host
71 27 : this.adapters = adapters ? [...adapters] : defaultAdapters(host)
72 27 : this.adapterRef = adapterRef ?? createAdapterRef()
73 : }
74 :
75 : getCurrentAdapter(): ModelAdapter | null {
76 0 : return this.adapterRef.current
77 : }
78 :
79 : init(): void {
80 27 : this.disposed = false
81 : }
82 :
83 : dispose(): void {
84 1 : this.disposed = true
85 1 : this.currentLoadId += 1
86 : }
87 :
88 : async loadModel(
89 : url: string,
90 : originalFileName?: string,
91 : options?: LoadModelOptions
92 : ): Promise<LoadModelOutcome> {
93 19 : if (this.disposed) return 'cancelled'
94 19 : const loadId = ++this.currentLoadId
95 :
96 19 : try {
97 19 : this.eventManager.emitEvent('modelLoadingStart', null)
98 :
99 19 : this.modelManager.clearModel()
100 19 : this.adapterRef.current = null
101 19 : this.adapterRef.capabilities = null
102 :
103 19 : this.modelManager.originalURL = url
104 :
105 19 : const fileExtension = this.setOriginalFileName(url, originalFileName)
106 :
107 19 : if (!fileExtension) {
108 : // The agent path may pass a credential-bearing URL, so keep this
109 : // error URL-free; the thumbnail caller redacts what it reports.
110 0 : if (options?.silent) throw new TypeError('Unknown model file type')
111 0 : this.eventManager.emitEvent('modelLoadingEnd', null)
112 0 : return 'unknown-type'
113 : }
114 :
115 19 : const result = await this.loadModelInternal(
116 : url,
117 : fileExtension,
118 : loadId,
119 : options?.silent,
120 : options?.signal
121 : )
122 19 : if (options?.signal?.aborted) {
123 0 : return this.cancelAbandonedLoad(result, loadId)
124 : }
125 19 : return await this.publishLoadResult(
126 : result,
127 : loadId,
128 : fileExtension,
129 : options?.silent
130 : )
131 : } catch (error) {
132 2 : if (options?.signal?.aborted) {
133 0 : return this.cancelAbandonedLoad(null, loadId)
134 : }
135 2 : return this.handleLoadError(error, loadId, options)
136 : }
137 : }
138 :
139 : /**
140 : * Parsers ignore the signal, so an aborted load can still resolve — and
141 : * `loadId` does not catch it when the caller starts no newer load.
142 : */
143 : private cancelAbandonedLoad(
144 : result: (ModelLoadResult & { adapter: ModelAdapter }) | null,
145 : loadId: number
146 : ): LoadModelOutcome {
147 0 : if (result) this.disposeLoadResult(result)
148 0 : if (loadId === this.currentLoadId) {
149 0 : this.eventManager.emitEvent('modelLoadingEnd', null)
150 : }
151 0 : return 'cancelled'
152 : }
153 :
154 : private async publishLoadResult(
155 : result: (ModelLoadResult & { adapter: ModelAdapter }) | null,
156 : loadId: number,
157 : fileExtension: string,
158 : silent?: boolean
159 : ): Promise<LoadModelOutcome> {
160 17 : if (loadId !== this.currentLoadId) {
161 : // A newer loadModel has superseded us. createLoadContext gates on
162 : // loadId, so the result never entered the scene and is safe to dispose.
163 0 : if (result) this.disposeLoadResult(result)
164 0 : return 'cancelled'
165 : }
166 17 : if (!result && silent) {
167 0 : throw new TypeError(`No model was produced for type: ${fileExtension}`)
168 : }
169 17 : if (result) {
170 17 : this.adapterRef.current = result.adapter
171 17 : this.adapterRef.capabilities = result.capabilities
172 17 : await this.modelManager.setupModel(result.object)
173 17 : if (loadId !== this.currentLoadId) return 'cancelled'
174 : }
175 17 : this.eventManager.emitEvent('modelLoadingEnd', null)
176 17 : return result ? 'loaded' : 'empty'
177 : }
178 :
179 : private setOriginalFileName(
180 : url: string,
181 : originalFileName?: string
182 : ): string | undefined {
183 19 : if (originalFileName) {
184 12 : this.modelManager.originalFileName =
185 : originalFileName.split('/').pop()?.split('.')[0] || 'model'
186 12 : return originalFileName.split('.').pop()?.toLowerCase()
187 : }
188 :
189 7 : const filename = new URLSearchParams(url.split('?')[1]).get('filename')
190 19 : this.modelManager.originalFileName = filename
191 : ? filename.split('.')[0] || 'model'
192 : : 'model'
193 19 : return filename?.split('.').pop()?.toLowerCase()
194 : }
195 :
196 : private handleLoadError(
197 : error: unknown,
198 : loadId: number,
199 : options?: LoadModelOptions
200 : ): LoadModelOutcome {
201 2 : if (loadId !== this.currentLoadId) return 'cancelled'
202 2 : this.eventManager.emitEvent('modelLoadingEnd', null)
203 2 : if (options?.silent) throw error
204 2 : console.error('Error loading model:', error)
205 2 : return isNotFoundError(error) ? 'not-found' : 'failed'
206 : }
207 :
208 : private disposeLoadResult(
209 : result: ModelLoadResult & { adapter: ModelAdapter }
210 : ): void {
211 0 : result.adapter.disposeModel?.(result.object)
212 0 : disposeObject3D(result.object, this.modelManager.standardMaterial)
213 : }
214 :
215 : private async pickAdapter(
216 : extension: string,
217 : fetchBytes: () => Promise<ArrayBuffer>
218 : ): Promise<ModelAdapter | null> {
219 19 : const candidates = this.adapters.filter((a) =>
220 : a.extensions.includes(extension)
221 : )
222 19 : for (const adapter of candidates) {
223 19 : if (!adapter.matches) return adapter
224 0 : if (await adapter.matches(extension, fetchBytes)) return adapter
225 : }
226 0 : return null
227 : }
228 :
229 : private createLoadContext(
230 : loadId: number,
231 : signal?: AbortSignal
232 : ): ModelLoadContext {
233 19 : const mm = this.modelManager
234 : // Adapters write to modelManager synchronously during adapter.load(),
235 : // before staleness or an abort can be checked. Gating those writes keeps a
236 : // superseded or abandoned result out of modelManager, so it is safe to
237 : // dispose.
238 19 : const isCurrent = () => loadId === this.currentLoadId && !signal?.aborted
239 19 : return {
240 : setOriginalModel: (model) => {
241 2 : if (isCurrent()) mm.setOriginalModel(model)
242 : },
243 : registerOriginalMaterial: (mesh, material) => {
244 17 : if (isCurrent()) mm.originalMaterials.set(mesh, material)
245 : },
246 : get standardMaterial() {
247 0 : return mm.standardMaterial
248 : },
249 : get materialMode() {
250 15 : return mm.materialMode
251 : }
252 : }
253 : }
254 :
255 : private async loadModelInternal(
256 : url: string,
257 : fileExtension: string,
258 : loadId: number,
259 : silent?: boolean,
260 : signal?: AbortSignal
261 : ): Promise<{
262 : object: THREE.Object3D
263 : adapter: ModelAdapter
264 : capabilities: ModelAdapterCapabilities
265 : } | null> {
266 19 : const params = new URLSearchParams(url.split('?')[1])
267 19 : const filename = params.get('filename')
268 :
269 19 : if (!filename) {
270 : // Silent loads may carry a credential-bearing URL; never log it on the
271 : // caller's behalf.
272 0 : if (!silent) console.error('Missing filename in URL:', url)
273 0 : return null
274 : }
275 :
276 19 : const requestedType = params.get('type')
277 19 : const loadRootFolder =
278 : requestedType === 'output' || requestedType === 'temp'
279 : ? requestedType
280 : : 'input'
281 19 : const subfolder = params.get('subfolder') ?? ''
282 19 : const path =
283 : 'api/view?type=' +
284 : loadRootFolder +
285 : '&subfolder=' +
286 : encodeURIComponent(subfolder) +
287 : '&filename='
288 :
289 19 : let bytesPromise: Promise<ArrayBuffer> | null = null
290 19 : const fetchBytes = () =>
291 : (bytesPromise ??= fetchModelData(
292 : this.host.fetchApi,
293 : path,
294 : filename,
295 : signal
296 : ))
297 :
298 19 : const adapter = await this.pickAdapter(fileExtension, fetchBytes)
299 19 : if (!adapter) return null
300 19 : if (this.disposed) return null
301 :
302 19 : const loadResult = await adapter.load(
303 : this.createLoadContext(loadId, signal),
304 : path,
305 : filename,
306 : fetchBytes
307 : )
308 19 : return loadResult
309 : ? {
310 : object: loadResult.object,
311 : capabilities: loadResult.capabilities,
312 : adapter
313 : }
314 : : null
315 : }
316 : }
|