@dioramajs/assets 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +20 -2
- package/dist/errors-C0aoug0G.d.ts +263 -0
- package/dist/errors-C0aoug0G.d.ts.map +1 -0
- package/dist/errors-DgHytoOg.js +29 -0
- package/dist/errors-DgHytoOg.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1211 -0
- package/dist/index.js.map +1 -0
- package/dist/three/index.d.ts +23 -0
- package/dist/three/index.d.ts.map +1 -0
- package/dist/three/index.js +332 -0
- package/dist/three/index.js.map +1 -0
- package/package.json +66 -3
- package/src/cache.ts +437 -0
- package/src/errors.ts +39 -0
- package/src/index.ts +4 -0
- package/src/keys.ts +86 -0
- package/src/loaders.ts +119 -0
- package/src/plugin.ts +315 -0
- package/src/preload.ts +335 -0
- package/src/queue.ts +115 -0
- package/src/three/decoders.ts +197 -0
- package/src/three/gltf.ts +146 -0
- package/src/three/index.ts +5 -0
- package/src/three/ktx2.ts +27 -0
- package/src/three/texture.ts +44 -0
- package/src/types.ts +269 -0
- package/src/wave.ts +115 -0
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dioramajs/assets",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Asset loading for Diorama: cache, preload and progress; glTF with Draco, Meshopt and KTX2.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"diorama",
|
|
7
|
+
"three",
|
|
8
|
+
"threejs",
|
|
9
|
+
"webgpu",
|
|
10
|
+
"webgl",
|
|
11
|
+
"tsl",
|
|
12
|
+
"loader",
|
|
13
|
+
"gltf",
|
|
14
|
+
"ktx2"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://dioramajs.dev",
|
|
17
|
+
"bugs": "https://github.com/MasterKurosava/diorama/issues",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/MasterKurosava/diorama.git",
|
|
21
|
+
"directory": "packages/assets"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"@dioramajs/source": "./src/index.ts",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./three": {
|
|
33
|
+
"@dioramajs/source": "./src/three/index.ts",
|
|
34
|
+
"types": "./dist/three/index.d.ts",
|
|
35
|
+
"default": "./dist/three/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"src"
|
|
42
|
+
],
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@dioramajs/core": "^0.1.0",
|
|
45
|
+
"@dioramajs/render": "^0.1.0",
|
|
46
|
+
"three": "^0.187.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"@dioramajs/render": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@dioramajs/core": "0.1.0",
|
|
55
|
+
"@dioramajs/render": "0.1.0",
|
|
56
|
+
"@types/node": "26.6.6",
|
|
57
|
+
"@types/three": "^0.187.0",
|
|
58
|
+
"three": "^0.187.0",
|
|
59
|
+
"tsdown": "0.23.4",
|
|
60
|
+
"typescript": "^7.0.2"
|
|
61
|
+
},
|
|
62
|
+
"publishConfig": {
|
|
63
|
+
"access": "public"
|
|
64
|
+
},
|
|
65
|
+
"scripts": {
|
|
66
|
+
"build": "tsdown",
|
|
67
|
+
"typecheck": "tsc"
|
|
68
|
+
}
|
|
6
69
|
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
// The asset cache: one entry per key, shared by every lease on it. An entry loads once through
|
|
2
|
+
// the queue, then lives while any lease does; after the last one it is retained by size or freed.
|
|
3
|
+
import { type Off, type Signal, signal } from '@dioramajs/core'
|
|
4
|
+
import type { RenderApi } from '@dioramajs/render'
|
|
5
|
+
import { AssetError, isAbort, linked, noop } from './errors'
|
|
6
|
+
import { abortError, type Queue, RANK } from './queue'
|
|
7
|
+
import type {
|
|
8
|
+
Asset,
|
|
9
|
+
AssetStatus,
|
|
10
|
+
CrossOrigin,
|
|
11
|
+
DecoderOptions,
|
|
12
|
+
Loaded,
|
|
13
|
+
LoaderContext,
|
|
14
|
+
LoadOptions,
|
|
15
|
+
Priority,
|
|
16
|
+
} from './types'
|
|
17
|
+
import type { Item, Wave } from './wave'
|
|
18
|
+
|
|
19
|
+
/** Progress weight of work of unknown size. */
|
|
20
|
+
export const ESTIMATE = 100_000
|
|
21
|
+
|
|
22
|
+
export type Make = (context: LoaderContext) => Promise<Loaded<unknown>>
|
|
23
|
+
|
|
24
|
+
export interface Spec {
|
|
25
|
+
readonly key: string
|
|
26
|
+
readonly url: string
|
|
27
|
+
readonly type: string
|
|
28
|
+
readonly crossOrigin: CrossOrigin
|
|
29
|
+
readonly options: Readonly<Record<string, string | number | boolean>>
|
|
30
|
+
/** Resolves the loader. A lazy module may fail with ASSET_TYPE. */
|
|
31
|
+
readonly make: () => Make | Promise<Make>
|
|
32
|
+
/** `load()` leases see foreign errors as AssetError, `acquire()` leases see them as they are. */
|
|
33
|
+
readonly wrap: boolean
|
|
34
|
+
readonly weight?: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface CacheHost {
|
|
38
|
+
readonly queue: Queue
|
|
39
|
+
readonly wave: Wave
|
|
40
|
+
readonly retain: number
|
|
41
|
+
readonly decoders: Readonly<Partial<DecoderOptions>>
|
|
42
|
+
report(error: unknown, url: string): void
|
|
43
|
+
transform(value: unknown, type: string, url: string): unknown
|
|
44
|
+
render(signal: AbortSignal): Promise<RenderApi>
|
|
45
|
+
load(url: string, options: LoadOptions): Asset<unknown>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface Lease {
|
|
49
|
+
readonly entry: Entry
|
|
50
|
+
readonly priority: Priority
|
|
51
|
+
/** Load leases report a failure, preloads and acquire don't. */
|
|
52
|
+
readonly report: boolean
|
|
53
|
+
readonly wrap: boolean
|
|
54
|
+
readonly status: Signal<AssetStatus>
|
|
55
|
+
readonly ready: Promise<unknown>
|
|
56
|
+
resolve(value: unknown): void
|
|
57
|
+
reject(error: unknown): void
|
|
58
|
+
released: boolean
|
|
59
|
+
off?: () => void
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class Entry implements Item {
|
|
63
|
+
readonly spec: Omit<Spec, 'make'>
|
|
64
|
+
/** Cleared once run, since the loader may hold its source (an <img> of a page that is gone). */
|
|
65
|
+
make: Spec['make'] | undefined
|
|
66
|
+
readonly leases: Set<Lease> = new Set()
|
|
67
|
+
readonly abort: AbortController = new AbortController()
|
|
68
|
+
state: 'loading' | 'ready' | 'failed' = 'loading'
|
|
69
|
+
result: Loaded<unknown> | undefined
|
|
70
|
+
value: unknown
|
|
71
|
+
/** What the loader threw, and the same wrapped as AssetError. */
|
|
72
|
+
cause: unknown
|
|
73
|
+
error: AssetError | undefined
|
|
74
|
+
bytes = 0
|
|
75
|
+
total: number
|
|
76
|
+
loaded = 0
|
|
77
|
+
waved = false
|
|
78
|
+
/** Out of the cache because the plugin stopped. Freed with its last lease. */
|
|
79
|
+
detached = false
|
|
80
|
+
/** Its renderer stopped (KTX2). Freed with its last lease, never retained. */
|
|
81
|
+
stale = false
|
|
82
|
+
|
|
83
|
+
constructor({ make, ...spec }: Spec) {
|
|
84
|
+
this.spec = spec
|
|
85
|
+
this.make = make
|
|
86
|
+
this.total = spec.weight ?? ESTIMATE
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
priority(): Priority {
|
|
90
|
+
let best: Priority = 'low'
|
|
91
|
+
for (const lease of this.leases) if (RANK[lease.priority] > RANK[best]) best = lease.priority
|
|
92
|
+
return best
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Unknown sizes weigh ESTIMATE. At 0 bytes `retain` would keep them forever. */
|
|
97
|
+
const estimate = (value: unknown): number => {
|
|
98
|
+
const sized = value as { byteLength?: number; width?: number; height?: number } | null
|
|
99
|
+
return sized?.byteLength || (sized?.width ?? 0) * (sized?.height ?? 0) * 4 || ESTIMATE
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const failure = (lease: Lease): unknown => (lease.wrap ? lease.entry.error : lease.entry.cause)
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Entries by key with leases. An entry lives while any lease does, then it is aborted, retained
|
|
106
|
+
* (LRU by bytes, no timers) or disposed once.
|
|
107
|
+
*/
|
|
108
|
+
export class Cache {
|
|
109
|
+
readonly #host: CacheHost
|
|
110
|
+
readonly #entries = new Map<string, Entry>()
|
|
111
|
+
/** Ready entries without leases, oldest first. */
|
|
112
|
+
readonly #retained = new Set<Entry>()
|
|
113
|
+
/** Stale entries out of the map that still have leases. Counted until their last lease. */
|
|
114
|
+
readonly #stale = new Set<Entry>()
|
|
115
|
+
|
|
116
|
+
constructor(host: CacheHost) {
|
|
117
|
+
this.#host = host
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
get<T, E = AssetError>(
|
|
121
|
+
spec: Spec,
|
|
122
|
+
priority: Priority,
|
|
123
|
+
report: boolean,
|
|
124
|
+
signal?: AbortSignal,
|
|
125
|
+
): Asset<T, E> {
|
|
126
|
+
let entry = this.#entries.get(spec.key)
|
|
127
|
+
const created = !entry
|
|
128
|
+
if (!entry) {
|
|
129
|
+
entry = new Entry(spec)
|
|
130
|
+
this.#entries.set(spec.key, entry)
|
|
131
|
+
}
|
|
132
|
+
this.#retained.delete(entry)
|
|
133
|
+
const lease = this.#lease(entry, priority, report, spec.wrap)
|
|
134
|
+
if (created) void this.#run(entry)
|
|
135
|
+
this.#changed(entry)
|
|
136
|
+
const asset = this.#asset<T, E>(lease)
|
|
137
|
+
if (signal?.aborted) asset.release()
|
|
138
|
+
else if (signal) {
|
|
139
|
+
signal.addEventListener('abort', asset.release, { once: true })
|
|
140
|
+
lease.off = () => signal.removeEventListener('abort', asset.release)
|
|
141
|
+
}
|
|
142
|
+
return asset
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
release(lease: Lease): void {
|
|
146
|
+
if (lease.released) return
|
|
147
|
+
lease.released = true
|
|
148
|
+
lease.off?.()
|
|
149
|
+
const { entry } = lease
|
|
150
|
+
entry.leases.delete(lease)
|
|
151
|
+
if (lease.status.peek() === 'loading') {
|
|
152
|
+
lease.reject(
|
|
153
|
+
linked(new AssetError('ASSET_ABORTED', 'released before ready', { url: entry.spec.url })),
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
lease.status.value = 'released'
|
|
157
|
+
if (entry.leases.size) {
|
|
158
|
+
this.#changed(entry)
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
const { retain } = this.#host
|
|
162
|
+
if (entry.state === 'ready' && !entry.detached && !entry.stale && entry.bytes <= retain) {
|
|
163
|
+
this.#retained.add(entry)
|
|
164
|
+
let bytes = this.#bytes()
|
|
165
|
+
for (const old of this.#retained) {
|
|
166
|
+
if (bytes <= retain) break
|
|
167
|
+
bytes -= old.bytes
|
|
168
|
+
this.#drop(old)
|
|
169
|
+
}
|
|
170
|
+
} else this.#drop(entry)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Whether the key has an entry, loading, ready or retained. */
|
|
174
|
+
has(key: string): boolean {
|
|
175
|
+
return this.#entries.has(key)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
stats(): { entries: number; used: number; retained: number; pending: number } {
|
|
179
|
+
const all = [...this.#entries.values(), ...this.#stale]
|
|
180
|
+
return {
|
|
181
|
+
entries: all.length,
|
|
182
|
+
used: all.filter((entry) => entry.leases.size > 0).length,
|
|
183
|
+
retained: this.#bytes(),
|
|
184
|
+
pending: all.filter((entry) => entry.state === 'loading').length,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** `render` stopped. Renderer-bound entries go at once or with their last lease. */
|
|
189
|
+
rebind(): void {
|
|
190
|
+
for (const entry of [...this.#entries.values()]) {
|
|
191
|
+
if (!entry.result?.renderBound) continue
|
|
192
|
+
if (!entry.leases.size) this.#drop(entry)
|
|
193
|
+
else {
|
|
194
|
+
// Take it out of the cache so a new load transcodes for the new renderer.
|
|
195
|
+
entry.stale = true
|
|
196
|
+
this.#entries.delete(entry.spec.key)
|
|
197
|
+
this.#stale.add(entry)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The plugin stops. `remove('assets')` keeps entries with leases until their last one, since an
|
|
204
|
+
* effect's texture may still show the bitmap. `destroy` releases everything at once.
|
|
205
|
+
*/
|
|
206
|
+
close(hard: boolean): void {
|
|
207
|
+
this.#host.queue.open()
|
|
208
|
+
for (const entry of [...this.#entries.values(), ...this.#stale]) {
|
|
209
|
+
this.#entries.delete(entry.spec.key)
|
|
210
|
+
entry.detached = true
|
|
211
|
+
if (!entry.leases.size) this.#drop(entry)
|
|
212
|
+
else if (hard) for (const lease of [...entry.leases]) this.release(lease)
|
|
213
|
+
}
|
|
214
|
+
this.#host.wave.close()
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
#bytes(): number {
|
|
218
|
+
let bytes = 0
|
|
219
|
+
for (const entry of this.#retained) bytes += entry.bytes
|
|
220
|
+
return bytes
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
#drop(entry: Entry): void {
|
|
224
|
+
if (this.#entries.get(entry.spec.key) === entry) this.#entries.delete(entry.spec.key)
|
|
225
|
+
this.#retained.delete(entry)
|
|
226
|
+
this.#stale.delete(entry)
|
|
227
|
+
this.#unwave(entry)
|
|
228
|
+
if (entry.state === 'loading') entry.abort.abort()
|
|
229
|
+
const { result } = entry
|
|
230
|
+
entry.result = entry.value = undefined
|
|
231
|
+
result?.dispose?.()
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** A lease came or went. The queue re-reads priorities and low-only work leaves the wave. */
|
|
235
|
+
#changed(entry: Entry): void {
|
|
236
|
+
if (entry.state === 'loading' && !entry.detached) {
|
|
237
|
+
if (entry.priority() !== 'low') {
|
|
238
|
+
if (!entry.waved) this.#host.wave.add(entry)
|
|
239
|
+
entry.waved = true
|
|
240
|
+
} else this.#unwave(entry)
|
|
241
|
+
}
|
|
242
|
+
this.#host.queue.pump()
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
#unwave(entry: Entry): void {
|
|
246
|
+
if (!entry.waved) return
|
|
247
|
+
entry.waved = false
|
|
248
|
+
this.#host.wave.done(entry)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
#lease(entry: Entry, priority: Priority, report: boolean, wrap: boolean): Lease {
|
|
252
|
+
let resolve!: (value: unknown) => void
|
|
253
|
+
let reject!: (error: unknown) => void
|
|
254
|
+
const ready = new Promise<unknown>((res, rej) => {
|
|
255
|
+
resolve = res
|
|
256
|
+
reject = rej
|
|
257
|
+
})
|
|
258
|
+
// Reading `ready` is optional, so nobody awaiting it is not an unhandled rejection.
|
|
259
|
+
ready.catch(noop)
|
|
260
|
+
const initial =
|
|
261
|
+
entry.state === 'ready' ? 'ready' : entry.state === 'failed' ? 'failed' : 'loading'
|
|
262
|
+
const status = signal<AssetStatus>(initial)
|
|
263
|
+
const lease: Lease = {
|
|
264
|
+
entry,
|
|
265
|
+
priority,
|
|
266
|
+
report,
|
|
267
|
+
wrap,
|
|
268
|
+
status,
|
|
269
|
+
ready,
|
|
270
|
+
resolve,
|
|
271
|
+
reject,
|
|
272
|
+
released: false,
|
|
273
|
+
}
|
|
274
|
+
entry.leases.add(lease)
|
|
275
|
+
if (entry.state === 'ready') resolve(entry.value)
|
|
276
|
+
else if (entry.state === 'failed') reject(failure(lease))
|
|
277
|
+
return lease
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
#asset<T, E>(lease: Lease): Asset<T, E> {
|
|
281
|
+
const { entry } = lease
|
|
282
|
+
const release = (): void => this.release(lease)
|
|
283
|
+
const asset = Object.assign(release, {
|
|
284
|
+
release,
|
|
285
|
+
dispose: release,
|
|
286
|
+
key: entry.spec.key,
|
|
287
|
+
url: entry.spec.url,
|
|
288
|
+
status: lease.status,
|
|
289
|
+
ready: lease.ready,
|
|
290
|
+
})
|
|
291
|
+
return Object.defineProperties(asset, {
|
|
292
|
+
value: { get: () => (lease.status.peek() === 'ready' ? entry.value : undefined) },
|
|
293
|
+
error: { get: () => (lease.status.peek() === 'failed' ? failure(lease) : undefined) },
|
|
294
|
+
}) as unknown as Asset<T, E>
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Loads the entry once its loader resolves and a request slot is free. */
|
|
298
|
+
async #run(entry: Entry): Promise<void> {
|
|
299
|
+
const { spec } = entry
|
|
300
|
+
const { signal } = entry.abort
|
|
301
|
+
const host = this.#host
|
|
302
|
+
let free: Off | undefined
|
|
303
|
+
const resolve = entry.make as Spec['make']
|
|
304
|
+
entry.make = undefined
|
|
305
|
+
try {
|
|
306
|
+
const make = await resolve()
|
|
307
|
+
if (signal.aborted) throw abortError()
|
|
308
|
+
free = await host.queue.slot('request', () => entry.priority(), signal)
|
|
309
|
+
const result = await make(this.#context(entry, () => free?.()))
|
|
310
|
+
free()
|
|
311
|
+
if (signal.aborted) {
|
|
312
|
+
result.dispose?.()
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
const value = entry.detached
|
|
316
|
+
? result.value
|
|
317
|
+
: host.transform(result.value, spec.type, spec.url)
|
|
318
|
+
entry.result = result
|
|
319
|
+
entry.value = value
|
|
320
|
+
entry.bytes = result.bytes ?? estimate(value)
|
|
321
|
+
entry.state = 'ready'
|
|
322
|
+
this.#unwave(entry)
|
|
323
|
+
for (const lease of entry.leases) {
|
|
324
|
+
lease.status.value = 'ready'
|
|
325
|
+
lease.resolve(value)
|
|
326
|
+
}
|
|
327
|
+
} catch (cause) {
|
|
328
|
+
free?.()
|
|
329
|
+
// Released meanwhile. Nobody waits and nothing is reported.
|
|
330
|
+
if (signal.aborted || entry.leases.size === 0) return
|
|
331
|
+
const error = linked(
|
|
332
|
+
cause instanceof AssetError
|
|
333
|
+
? cause
|
|
334
|
+
: new AssetError(isAbort(cause) ? 'ASSET_ABORTED' : 'ASSET_PARSE', String(cause), {
|
|
335
|
+
url: spec.url,
|
|
336
|
+
cause,
|
|
337
|
+
}),
|
|
338
|
+
)
|
|
339
|
+
entry.cause = cause
|
|
340
|
+
entry.error = error
|
|
341
|
+
entry.state = 'failed'
|
|
342
|
+
this.#unwave(entry)
|
|
343
|
+
const leases = [...entry.leases]
|
|
344
|
+
for (const lease of leases) {
|
|
345
|
+
lease.status.value = 'failed'
|
|
346
|
+
lease.reject(failure(lease))
|
|
347
|
+
}
|
|
348
|
+
if (!entry.detached && leases.some((lease) => lease.report)) host.report(error, spec.url)
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
#context(entry: Entry, free: () => void): LoaderContext {
|
|
353
|
+
const { spec } = entry
|
|
354
|
+
const { url, crossOrigin } = spec
|
|
355
|
+
const { signal } = entry.abort
|
|
356
|
+
const host = this.#host
|
|
357
|
+
const wave = host.wave
|
|
358
|
+
return {
|
|
359
|
+
url,
|
|
360
|
+
key: spec.key,
|
|
361
|
+
get priority() {
|
|
362
|
+
return entry.priority()
|
|
363
|
+
},
|
|
364
|
+
crossOrigin,
|
|
365
|
+
options: spec.options,
|
|
366
|
+
signal,
|
|
367
|
+
async fetch(init) {
|
|
368
|
+
const priority = entry.priority()
|
|
369
|
+
let response: Response
|
|
370
|
+
try {
|
|
371
|
+
response = await fetch(url, {
|
|
372
|
+
signal,
|
|
373
|
+
priority: priority === 'normal' ? 'auto' : priority,
|
|
374
|
+
credentials: crossOrigin === 'use-credentials' ? 'include' : 'same-origin',
|
|
375
|
+
...init,
|
|
376
|
+
} as RequestInit)
|
|
377
|
+
} catch (cause) {
|
|
378
|
+
if (signal.aborted) throw abortError()
|
|
379
|
+
throw new AssetError('ASSET_LOAD', `cannot fetch ${url}`, { url, cause })
|
|
380
|
+
}
|
|
381
|
+
if (!response.ok) {
|
|
382
|
+
throw new AssetError('ASSET_LOAD', `${response.status} ${url}`, { url })
|
|
383
|
+
}
|
|
384
|
+
return response
|
|
385
|
+
},
|
|
386
|
+
async bytes(response) {
|
|
387
|
+
// Content-Length counts the compressed body, so only an identity one is a usable weight.
|
|
388
|
+
const length = Number(response.headers.get('content-length'))
|
|
389
|
+
if (length > 0 && !response.headers.has('content-encoding')) entry.total = length
|
|
390
|
+
const reader = response.body?.getReader()
|
|
391
|
+
if (!reader) {
|
|
392
|
+
const buffer = await response.arrayBuffer()
|
|
393
|
+
entry.loaded = entry.total
|
|
394
|
+
wave.changed()
|
|
395
|
+
return buffer
|
|
396
|
+
}
|
|
397
|
+
const chunks: Uint8Array[] = []
|
|
398
|
+
let size = 0
|
|
399
|
+
for (;;) {
|
|
400
|
+
const { done, value } = await reader.read()
|
|
401
|
+
if (done) break
|
|
402
|
+
chunks.push(value)
|
|
403
|
+
size += value.byteLength
|
|
404
|
+
entry.loaded = Math.min(size, entry.total)
|
|
405
|
+
wave.changed()
|
|
406
|
+
}
|
|
407
|
+
const body = new Uint8Array(size)
|
|
408
|
+
let offset = 0
|
|
409
|
+
for (const chunk of chunks) {
|
|
410
|
+
body.set(chunk, offset)
|
|
411
|
+
offset += chunk.byteLength
|
|
412
|
+
}
|
|
413
|
+
return body.buffer
|
|
414
|
+
},
|
|
415
|
+
async decode(work) {
|
|
416
|
+
free()
|
|
417
|
+
const done = await host.queue.slot('decode', () => entry.priority(), signal)
|
|
418
|
+
try {
|
|
419
|
+
return await work()
|
|
420
|
+
} finally {
|
|
421
|
+
done()
|
|
422
|
+
}
|
|
423
|
+
},
|
|
424
|
+
// Waiting on another entry or on render is not network work. Holding the request slot
|
|
425
|
+
// meanwhile, cold textures would take every slot from the pictures they wait for.
|
|
426
|
+
load(dependency, options) {
|
|
427
|
+
free()
|
|
428
|
+
return host.load(dependency, { ...options, signal }) as never
|
|
429
|
+
},
|
|
430
|
+
render() {
|
|
431
|
+
free()
|
|
432
|
+
return host.render(signal)
|
|
433
|
+
},
|
|
434
|
+
decoders: host.decoders,
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { withDocs } from '@dioramajs/core/dev'
|
|
2
|
+
import type { AssetErrorCode } from './types'
|
|
3
|
+
|
|
4
|
+
export { DEV } from '@dioramajs/core/dev'
|
|
5
|
+
|
|
6
|
+
export const noop = (): void => {}
|
|
7
|
+
|
|
8
|
+
/** Rejects `Asset.ready`. Reported as `asset:<url>`, which the kernel wraps as `REPORTED`. */
|
|
9
|
+
export class AssetError extends Error {
|
|
10
|
+
/** Always `AssetError`. */
|
|
11
|
+
override readonly name: 'AssetError' = 'AssetError'
|
|
12
|
+
/** Error code, the key of its page in the docs. */
|
|
13
|
+
readonly code: AssetErrorCode
|
|
14
|
+
/** URL of the asset, if the error has one. */
|
|
15
|
+
readonly url: string | undefined
|
|
16
|
+
|
|
17
|
+
constructor(
|
|
18
|
+
code: AssetErrorCode,
|
|
19
|
+
message: string,
|
|
20
|
+
options: { readonly url?: string; readonly cause?: unknown } = {},
|
|
21
|
+
) {
|
|
22
|
+
super(`${code}: ${message}`, options.cause === undefined ? undefined : { cause: options.cause })
|
|
23
|
+
this.code = code
|
|
24
|
+
this.url = options.url
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Adds the docs page to the message in development builds. Errors pass here on their way out of
|
|
30
|
+
* the plugin, so the three.js loaders don't carry it.
|
|
31
|
+
*/
|
|
32
|
+
export function linked<E extends AssetError>(error: E): E {
|
|
33
|
+
error.message = withDocs(error.message, error.code)
|
|
34
|
+
return error
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const isAbort = (error: unknown): boolean =>
|
|
38
|
+
(error as { name?: string } | null)?.name === 'AbortError' ||
|
|
39
|
+
(error as { code?: string } | null)?.code === 'ASSET_ABORTED'
|
package/src/index.ts
ADDED
package/src/keys.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { CrossOrigin } from './types'
|
|
2
|
+
|
|
3
|
+
/** Asset type by file extension, for loads without an explicit type. */
|
|
4
|
+
export const BY_EXTENSION: Readonly<Record<string, string>> = {
|
|
5
|
+
glb: 'gltf',
|
|
6
|
+
gltf: 'gltf',
|
|
7
|
+
ktx2: 'ktx2',
|
|
8
|
+
jpg: 'texture',
|
|
9
|
+
jpeg: 'texture',
|
|
10
|
+
png: 'texture',
|
|
11
|
+
webp: 'texture',
|
|
12
|
+
avif: 'texture',
|
|
13
|
+
gif: 'texture',
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Absolute URL without the fragment, which never reaches the request. */
|
|
17
|
+
export function absolute(url: string, base?: string | URL): string {
|
|
18
|
+
const parsed = new URL(url, base ?? document.baseURI)
|
|
19
|
+
parsed.hash = ''
|
|
20
|
+
return parsed.href
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* CORS mode of a texture load. Pixels of another origin fetched without CORS are tainted and the
|
|
25
|
+
* GPU upload throws SecurityError on every draw, so such a texture is always asked in CORS mode.
|
|
26
|
+
*/
|
|
27
|
+
export function textureCors(url: string, crossOrigin: CrossOrigin): CrossOrigin {
|
|
28
|
+
if (crossOrigin) return crossOrigin
|
|
29
|
+
const page = globalThis.location?.origin
|
|
30
|
+
const target = new URL(url)
|
|
31
|
+
return page && /^https?:$/.test(target.protocol) && target.origin !== page ? 'anonymous' : ''
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Lower-case extension of an absolute URL's path, without the dot. '' for none. */
|
|
35
|
+
export const extensionOf = (url: string): string =>
|
|
36
|
+
/\.([a-z0-9]+)$/i.exec(new URL(url).pathname)?.[1]?.toLowerCase() ?? ''
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Cache key `type url[ crossOrigin][ options]`. The CORS mode is part of it, as in the browser's
|
|
40
|
+
* image cache. The effects pool builds `image <currentSrc>[ crossOrigin]` keys the same way.
|
|
41
|
+
*/
|
|
42
|
+
export function keyOf(
|
|
43
|
+
type: string,
|
|
44
|
+
url: string,
|
|
45
|
+
crossOrigin: CrossOrigin,
|
|
46
|
+
options: Readonly<Record<string, unknown>>,
|
|
47
|
+
): string {
|
|
48
|
+
const entries = Object.entries(options).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
49
|
+
let key = `${type} ${url}`
|
|
50
|
+
if (crossOrigin) key += ` ${crossOrigin}`
|
|
51
|
+
if (entries.length) key += ` ${JSON.stringify(entries)}`
|
|
52
|
+
return key
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** URL and type of a `keyOf` key. A key without a space stands for both. */
|
|
56
|
+
export const parseKey = (key: string): { readonly url: string; readonly type: string } => ({
|
|
57
|
+
url: key.split(' ')[1] ?? key,
|
|
58
|
+
type: key.split(' ')[0] ?? key,
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const CANDIDATE = /[\s,]*(\S+)/y
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A srcset with absolute candidate URLs. A URL is a run of non-spaces, so commas inside stay
|
|
65
|
+
* (CDN transforms like `w_400,c_fill`). Per the HTML spec, one ending in commas has no descriptors.
|
|
66
|
+
*/
|
|
67
|
+
export function srcset(value: string, base: string): string {
|
|
68
|
+
const out: string[] = []
|
|
69
|
+
for (let i = 0; ; ) {
|
|
70
|
+
CANDIDATE.lastIndex = i
|
|
71
|
+
const match = CANDIDATE.exec(value)
|
|
72
|
+
if (!match) break
|
|
73
|
+
let url = match[1] as string
|
|
74
|
+
i = CANDIDATE.lastIndex
|
|
75
|
+
let descriptor = ''
|
|
76
|
+
if (url.endsWith(',')) url = url.replace(/,+$/, '')
|
|
77
|
+
else {
|
|
78
|
+
const end = value.indexOf(',', i)
|
|
79
|
+
descriptor = value.slice(i, end < 0 ? undefined : end).trim()
|
|
80
|
+
i = end < 0 ? value.length : end + 1
|
|
81
|
+
}
|
|
82
|
+
const href = new URL(url, base).href
|
|
83
|
+
out.push(descriptor ? `${href} ${descriptor}` : href)
|
|
84
|
+
}
|
|
85
|
+
return out.join(', ')
|
|
86
|
+
}
|