@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/src/preload.ts
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// Preloads: `assets.preload` from code, and `data-dio-preload` markup that loads on intent
|
|
2
|
+
// (hover, focus or touch). Only the latest preload of each kind holds its leases.
|
|
3
|
+
import type { Off } from '@dioramajs/core'
|
|
4
|
+
import { withDocs } from '@dioramajs/core/dev'
|
|
5
|
+
import { DEV, isAbort, noop } from './errors'
|
|
6
|
+
import { absolute, keyOf, srcset } from './keys'
|
|
7
|
+
import { bitmap, loaded } from './loaders'
|
|
8
|
+
import type {
|
|
9
|
+
Asset,
|
|
10
|
+
CrossOrigin,
|
|
11
|
+
LoaderContext,
|
|
12
|
+
LoadOptions,
|
|
13
|
+
Preload,
|
|
14
|
+
PreloadOptions,
|
|
15
|
+
PreloadSource,
|
|
16
|
+
Priority,
|
|
17
|
+
} from './types'
|
|
18
|
+
|
|
19
|
+
/** Hover longer than this is an intent to follow the link. */
|
|
20
|
+
const INTENT_MS = 65
|
|
21
|
+
const IMAGES = 'img[data-dio], img[data-dio-key]'
|
|
22
|
+
const MARKUP = '[data-dio-preload]'
|
|
23
|
+
|
|
24
|
+
export interface PreloadHost {
|
|
25
|
+
/** A preload lease. Failures are not reported. */
|
|
26
|
+
load(url: string, options: LoadOptions & { readonly type: string }): Asset<unknown>
|
|
27
|
+
acquire(
|
|
28
|
+
key: string,
|
|
29
|
+
make: (context: LoaderContext) => Promise<never>,
|
|
30
|
+
priority: Priority,
|
|
31
|
+
): Asset<unknown, unknown>
|
|
32
|
+
/** An entry under the key, loading, ready or retained. */
|
|
33
|
+
has(key: string): boolean
|
|
34
|
+
/** A request slot for the browser's own request of a detached image. */
|
|
35
|
+
slot(priority: Priority, signal: AbortSignal): Promise<Off>
|
|
36
|
+
/** The type of an absolute URL by its extension. Undefined for a page address. */
|
|
37
|
+
typeOf(url: string): string | undefined
|
|
38
|
+
track(work: Promise<unknown>, priority: Priority): void
|
|
39
|
+
warn(message: string): void
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface Target {
|
|
43
|
+
readonly href: string
|
|
44
|
+
readonly type: string
|
|
45
|
+
readonly crossOrigin: CrossOrigin
|
|
46
|
+
readonly key: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface Connection {
|
|
50
|
+
readonly saveData?: boolean
|
|
51
|
+
readonly effectiveType?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Nothing is preloaded under Save-Data or on a 2g connection. */
|
|
55
|
+
export function frugal(): boolean {
|
|
56
|
+
const connection = (globalThis.navigator as { connection?: Connection } | undefined)?.connection
|
|
57
|
+
return connection?.saveData === true || /(^|-)2g$/.test(connection?.effectiveType ?? '')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The CORS mode of an element as a key part. No attribute gives '' (no CORS). */
|
|
61
|
+
export function corsOf(el: Element): CrossOrigin {
|
|
62
|
+
const value = el.getAttribute('crossorigin')
|
|
63
|
+
if (value === null) return ''
|
|
64
|
+
return value.toLowerCase() === 'use-credentials' ? 'use-credentials' : 'anonymous'
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface Copy {
|
|
68
|
+
readonly img: HTMLImageElement
|
|
69
|
+
/** Called once the queue gives a slot. */
|
|
70
|
+
start(): void
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A detached image that picks the candidate the element would. Same `crossorigin`, `sizes` and
|
|
75
|
+
* absolute `srcset`, inside a copy of its <picture>.
|
|
76
|
+
*/
|
|
77
|
+
function copy(source: Element, base: string, priority: Priority): Copy | undefined {
|
|
78
|
+
const src = source.getAttribute('src')
|
|
79
|
+
const set = source.getAttribute('srcset')
|
|
80
|
+
if (!src && !set) return undefined
|
|
81
|
+
const img = new Image()
|
|
82
|
+
const cors = source.getAttribute('crossorigin')
|
|
83
|
+
if (cors !== null) img.setAttribute('crossorigin', cors)
|
|
84
|
+
const sizes = source.getAttribute('sizes')
|
|
85
|
+
if (sizes) img.setAttribute('sizes', sizes)
|
|
86
|
+
if (priority !== 'normal') img.setAttribute('fetchpriority', priority)
|
|
87
|
+
let holder: HTMLPictureElement | undefined
|
|
88
|
+
const picture = source.parentElement
|
|
89
|
+
if (picture?.localName === 'picture') {
|
|
90
|
+
holder = document.createElement('picture')
|
|
91
|
+
for (const child of picture.children) {
|
|
92
|
+
if (child.localName !== 'source') continue
|
|
93
|
+
const item = document.createElement('source')
|
|
94
|
+
for (const { name, value } of child.attributes) {
|
|
95
|
+
item.setAttribute(name, name === 'srcset' ? srcset(value, base) : value)
|
|
96
|
+
}
|
|
97
|
+
holder.append(item)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
img,
|
|
102
|
+
start() {
|
|
103
|
+
// Each of these makes the image pick a source and load it.
|
|
104
|
+
holder?.append(img)
|
|
105
|
+
if (set) img.setAttribute('srcset', srcset(set, base))
|
|
106
|
+
if (src) img.src = new URL(src, base).href
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const words = (el: Element): string[] => (el.getAttribute('data-dio-preload') ?? '').split(/\s+/)
|
|
112
|
+
|
|
113
|
+
class PreloadImpl implements Preload {
|
|
114
|
+
readonly leases: Asset<unknown, unknown>[] = []
|
|
115
|
+
readonly abort: AbortController = new AbortController()
|
|
116
|
+
settled: Promise<void> = Promise.resolve()
|
|
117
|
+
|
|
118
|
+
release = (): void => {
|
|
119
|
+
this.abort.abort()
|
|
120
|
+
for (const lease of this.leases.splice(0)) lease.release()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
dispose: () => void = this.release
|
|
124
|
+
|
|
125
|
+
// biome-ignore lint/suspicious/noThenProperty: a preload is thenable by design
|
|
126
|
+
then: PromiseLike<void>['then'] = (fulfilled, rejected) => this.settled.then(fulfilled, rejected)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** API and markup preloads. Only the last of each kind holds its leases. */
|
|
130
|
+
export class Preloads {
|
|
131
|
+
readonly #host: PreloadHost
|
|
132
|
+
readonly #last = new Map<'api' | 'markup', PreloadImpl>()
|
|
133
|
+
/** A broken link warns once in development, not on every intent. */
|
|
134
|
+
readonly #warned = new Set<string>()
|
|
135
|
+
|
|
136
|
+
constructor(host: PreloadHost) {
|
|
137
|
+
this.#host = host
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
preload(
|
|
141
|
+
source: PreloadSource,
|
|
142
|
+
options: PreloadOptions = {},
|
|
143
|
+
kind: 'api' | 'markup' = 'api',
|
|
144
|
+
): Preload {
|
|
145
|
+
const preload = new PreloadImpl()
|
|
146
|
+
if (frugal()) return preload
|
|
147
|
+
const priority = options.priority ?? 'low'
|
|
148
|
+
const base = this.#base(source, options.base)
|
|
149
|
+
const jobs: Promise<unknown>[] = []
|
|
150
|
+
const url = (href: string, cors: CrossOrigin): void => {
|
|
151
|
+
if (href) jobs.push(this.#url(preload, href, base, priority, cors))
|
|
152
|
+
}
|
|
153
|
+
const cors = options.crossOrigin ?? ''
|
|
154
|
+
if (typeof source === 'string') url(source, cors)
|
|
155
|
+
else if (Array.isArray(source)) for (const href of source as readonly string[]) url(href, cors)
|
|
156
|
+
else if (typeof source === 'object') {
|
|
157
|
+
const root = source as ParentNode
|
|
158
|
+
const own = root instanceof Element ? [root] : []
|
|
159
|
+
for (const el of [...own, ...root.querySelectorAll(IMAGES)]) {
|
|
160
|
+
if (el.matches(IMAGES)) jobs.push(this.#image(preload, el, base, priority))
|
|
161
|
+
}
|
|
162
|
+
for (const el of [...own, ...root.querySelectorAll(MARKUP)]) {
|
|
163
|
+
if (el.matches(MARKUP)) for (const href of words(el)) url(href, corsOf(el))
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
preload.settled = Promise.all(jobs).then(noop)
|
|
167
|
+
if (priority !== 'low') this.#host.track(preload.settled, priority)
|
|
168
|
+
// Release after taking the new leases, so shared entries skip a trip through `retain`.
|
|
169
|
+
this.#last.get(kind)?.release()
|
|
170
|
+
this.#last.set(kind, preload)
|
|
171
|
+
return preload
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** `data-dio-preload` on intent: hover (65 ms), focus or touch. */
|
|
175
|
+
listen(signal: AbortSignal): void {
|
|
176
|
+
let hovered: Element | undefined
|
|
177
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
178
|
+
const target = (event: Event): Element | null =>
|
|
179
|
+
(event.target as Element | null)?.closest?.(MARKUP) ?? null
|
|
180
|
+
const intent = (el: Element | null): void => {
|
|
181
|
+
if (!el) return
|
|
182
|
+
const urls = words(el)
|
|
183
|
+
const crossOrigin = corsOf(el)
|
|
184
|
+
// Load again only what the cache lost: a preload dropped mid-load by the next intent, an
|
|
185
|
+
// evicted or failed entry. The new preload holds all of the link's URLs.
|
|
186
|
+
const lost = (url: string): boolean => {
|
|
187
|
+
const wanted = this.#target(url, document.baseURI, crossOrigin)
|
|
188
|
+
return typeof wanted === 'string' || !this.#host.has(wanted.key)
|
|
189
|
+
}
|
|
190
|
+
if (urls.some((url) => url && lost(url))) this.preload(urls, { crossOrigin }, 'markup')
|
|
191
|
+
}
|
|
192
|
+
const options = { signal, passive: true }
|
|
193
|
+
document.addEventListener(
|
|
194
|
+
'pointerover',
|
|
195
|
+
(event) => {
|
|
196
|
+
const el = target(event)
|
|
197
|
+
if (!el || el === hovered) return
|
|
198
|
+
clearTimeout(timer)
|
|
199
|
+
hovered = el
|
|
200
|
+
timer = setTimeout(() => intent(el), INTENT_MS)
|
|
201
|
+
},
|
|
202
|
+
options,
|
|
203
|
+
)
|
|
204
|
+
document.addEventListener(
|
|
205
|
+
'pointerout',
|
|
206
|
+
(event) => {
|
|
207
|
+
const el = target(event)
|
|
208
|
+
if (!el || el !== hovered || el.contains((event as PointerEvent).relatedTarget as Node)) {
|
|
209
|
+
return
|
|
210
|
+
}
|
|
211
|
+
clearTimeout(timer)
|
|
212
|
+
hovered = undefined
|
|
213
|
+
},
|
|
214
|
+
options,
|
|
215
|
+
)
|
|
216
|
+
document.addEventListener('focusin', (event) => intent(target(event)), options)
|
|
217
|
+
document.addEventListener('touchstart', (event) => intent(target(event)), options)
|
|
218
|
+
signal.addEventListener('abort', () => clearTimeout(timer), { once: true })
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
close(): void {
|
|
222
|
+
for (const preload of this.#last.values()) preload.release()
|
|
223
|
+
this.#last.clear()
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
#base(source: PreloadSource, base: string | URL | undefined): string {
|
|
227
|
+
if (base !== undefined) return new URL(base, document.baseURI).href
|
|
228
|
+
const doc = (source as Partial<Node>).nodeType === 9 ? (source as Document) : undefined
|
|
229
|
+
const href = doc?.querySelector('base[href]')?.getAttribute('href')
|
|
230
|
+
return href ? new URL(href, document.baseURI).href : document.baseURI
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The entry a preload of the URL takes, or the reason there is none. */
|
|
234
|
+
#target(url: string, base: string, cors: CrossOrigin): Target | string {
|
|
235
|
+
let href: string
|
|
236
|
+
try {
|
|
237
|
+
href = absolute(url, base)
|
|
238
|
+
} catch {
|
|
239
|
+
return `${url} is not a URL`
|
|
240
|
+
}
|
|
241
|
+
const found = this.#host.typeOf(href)
|
|
242
|
+
// A page address. Router integrations pass the fetched Document instead.
|
|
243
|
+
if (!found)
|
|
244
|
+
return withDocs(
|
|
245
|
+
`ASSET_TYPE: ${href} has no asset type: preload takes asset URLs or a Document`,
|
|
246
|
+
'ASSET_TYPE',
|
|
247
|
+
)
|
|
248
|
+
// Images preload their pixels, since `texture` and the effects pool share the `image` entry.
|
|
249
|
+
// Only images key by CORS mode. Models load like a `load()` without `crossOrigin`.
|
|
250
|
+
const type = found === 'texture' ? 'image' : found
|
|
251
|
+
const crossOrigin = type === 'image' ? cors : ''
|
|
252
|
+
return { href, type, crossOrigin, key: keyOf(type, href, crossOrigin, {}) }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#url(
|
|
256
|
+
preload: PreloadImpl,
|
|
257
|
+
url: string,
|
|
258
|
+
base: string,
|
|
259
|
+
priority: Priority,
|
|
260
|
+
cors: CrossOrigin,
|
|
261
|
+
): Promise<void> {
|
|
262
|
+
const target = this.#target(url, base, cors)
|
|
263
|
+
if (typeof target === 'string') return this.#failed(target)
|
|
264
|
+
const { href, type, crossOrigin } = target
|
|
265
|
+
const { signal } = preload.abort
|
|
266
|
+
return this.#hold(preload, this.#host.load(href, { type, priority, crossOrigin, signal }), href)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* A failed lease goes at once, so the entry leaves the cache and the page's own load is a new
|
|
271
|
+
* attempt, reported if it fails too.
|
|
272
|
+
*/
|
|
273
|
+
async #hold(preload: PreloadImpl, lease: Asset<unknown, unknown>, url: string): Promise<void> {
|
|
274
|
+
preload.leases.push(lease)
|
|
275
|
+
try {
|
|
276
|
+
await lease.ready
|
|
277
|
+
} catch (error) {
|
|
278
|
+
const at = preload.leases.indexOf(lease)
|
|
279
|
+
if (at >= 0) preload.leases.splice(at, 1)
|
|
280
|
+
lease.release()
|
|
281
|
+
return this.#failed(error, url)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async #image(
|
|
286
|
+
preload: PreloadImpl,
|
|
287
|
+
source: Element,
|
|
288
|
+
base: string,
|
|
289
|
+
priority: Priority,
|
|
290
|
+
): Promise<void> {
|
|
291
|
+
const { signal } = preload.abort
|
|
292
|
+
let made: Copy | undefined
|
|
293
|
+
try {
|
|
294
|
+
made = copy(source, base, priority)
|
|
295
|
+
} catch {
|
|
296
|
+
return
|
|
297
|
+
}
|
|
298
|
+
if (!made) return
|
|
299
|
+
const { img } = made
|
|
300
|
+
const url = source.getAttribute('src') ?? source.getAttribute('srcset') ?? ''
|
|
301
|
+
try {
|
|
302
|
+
const free = await this.#host.slot(priority, signal)
|
|
303
|
+
try {
|
|
304
|
+
made.start()
|
|
305
|
+
await loaded(img, url, signal)
|
|
306
|
+
} finally {
|
|
307
|
+
free()
|
|
308
|
+
}
|
|
309
|
+
} catch (error) {
|
|
310
|
+
return this.#failed(error, url)
|
|
311
|
+
}
|
|
312
|
+
if (signal.aborted) return
|
|
313
|
+
// The browser picked the candidate, so its URL is the key the page's <img> will have.
|
|
314
|
+
const src = absolute(img.currentSrc || img.src)
|
|
315
|
+
const key = keyOf('image', src, corsOf(img), {})
|
|
316
|
+
const target = img
|
|
317
|
+
const lease = this.#host.acquire(
|
|
318
|
+
key,
|
|
319
|
+
(context) => context.decode(() => bitmap(target, src)) as Promise<never>,
|
|
320
|
+
priority,
|
|
321
|
+
)
|
|
322
|
+
return this.#hold(preload, lease, src)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
#failed(error: unknown, url?: string): Promise<void> {
|
|
326
|
+
// The page loads it itself, so only warn in development.
|
|
327
|
+
if (DEV && !isAbort(error)) {
|
|
328
|
+
const message =
|
|
329
|
+
typeof error === 'string' ? error : `preload of ${url} failed: ${String(error)}`
|
|
330
|
+
if (!this.#warned.has(message)) this.#host.warn(message)
|
|
331
|
+
this.#warned.add(message)
|
|
332
|
+
}
|
|
333
|
+
return Promise.resolve()
|
|
334
|
+
}
|
|
335
|
+
}
|
package/src/queue.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Concurrency for asset work: request slots for the network and decode slots for parsing,
|
|
2
|
+
// handed out by priority.
|
|
3
|
+
import type { Off } from '@dioramajs/core'
|
|
4
|
+
import type { Priority } from './types'
|
|
5
|
+
|
|
6
|
+
export const RANK: Readonly<Record<Priority, number>> = { low: 0, normal: 1, high: 2 }
|
|
7
|
+
/** Parallel decodes: createImageBitmap, glTF parsing. */
|
|
8
|
+
const DECODES = 2
|
|
9
|
+
/** Low requests at once, and only while no high one waits. */
|
|
10
|
+
const LOW = 2
|
|
11
|
+
|
|
12
|
+
export type Lane = 'request' | 'decode'
|
|
13
|
+
|
|
14
|
+
interface Ticket {
|
|
15
|
+
readonly lane: Lane
|
|
16
|
+
readonly priority: () => Priority
|
|
17
|
+
readonly seq: number
|
|
18
|
+
grant(): void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const abortError = (): DOMException => new DOMException('aborted', 'AbortError')
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Request and decode slots. Priorities are read at every step, so a lease that raises an entry's
|
|
25
|
+
* priority moves it up in its lane. Low-only work doesn't start while a pause is held.
|
|
26
|
+
*/
|
|
27
|
+
export class Queue {
|
|
28
|
+
concurrency: number
|
|
29
|
+
readonly #waiting: Ticket[] = []
|
|
30
|
+
readonly #active: Record<Lane | 'low', number> = { request: 0, decode: 0, low: 0 }
|
|
31
|
+
#pauses = 0
|
|
32
|
+
#seq = 0
|
|
33
|
+
/** Once stopped, every slot is granted at once and detached entries finish on their own. */
|
|
34
|
+
#open = false
|
|
35
|
+
|
|
36
|
+
constructor(concurrency: number) {
|
|
37
|
+
this.concurrency = concurrency
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Resolves with the slot's release once granted. Rejects with AbortError on abort. */
|
|
41
|
+
slot(lane: Lane, priority: () => Priority, signal: AbortSignal): Promise<Off> {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
if (signal.aborted) return reject(abortError())
|
|
44
|
+
const abort = (): void => {
|
|
45
|
+
const index = this.#waiting.indexOf(ticket)
|
|
46
|
+
if (index >= 0) this.#waiting.splice(index, 1)
|
|
47
|
+
reject(abortError())
|
|
48
|
+
}
|
|
49
|
+
const ticket: Ticket = {
|
|
50
|
+
lane,
|
|
51
|
+
priority,
|
|
52
|
+
seq: this.#seq++,
|
|
53
|
+
grant: () => {
|
|
54
|
+
signal.removeEventListener('abort', abort)
|
|
55
|
+
const low = lane === 'request' && priority() === 'low'
|
|
56
|
+
this.#active[lane]++
|
|
57
|
+
if (low) this.#active.low++
|
|
58
|
+
let done = false
|
|
59
|
+
resolve(() => {
|
|
60
|
+
if (done) return
|
|
61
|
+
done = true
|
|
62
|
+
this.#active[lane]--
|
|
63
|
+
if (low) this.#active.low--
|
|
64
|
+
this.pump()
|
|
65
|
+
})
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
69
|
+
this.#waiting.push(ticket)
|
|
70
|
+
this.pump()
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pause(): Off {
|
|
75
|
+
this.#pauses++
|
|
76
|
+
let done = false
|
|
77
|
+
return () => {
|
|
78
|
+
if (done) return
|
|
79
|
+
done = true
|
|
80
|
+
this.#pauses--
|
|
81
|
+
this.pump()
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
open(): void {
|
|
86
|
+
this.#open = true
|
|
87
|
+
this.pump()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Grants every ticket the rules allow, highest priority first, then in arrival order. */
|
|
91
|
+
pump(): void {
|
|
92
|
+
for (let next = this.#next(); next; next = this.#next()) {
|
|
93
|
+
this.#waiting.splice(this.#waiting.indexOf(next), 1)
|
|
94
|
+
next.grant()
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
#next(): Ticket | undefined {
|
|
99
|
+
const ranked = this.#waiting
|
|
100
|
+
.map((ticket) => ({ ticket, priority: ticket.priority() }))
|
|
101
|
+
.sort((a, b) => RANK[b.priority] - RANK[a.priority] || a.ticket.seq - b.ticket.seq)
|
|
102
|
+
if (this.#open) return ranked[0]?.ticket
|
|
103
|
+
const high = ranked.some((t) => t.ticket.lane === 'request' && t.priority === 'high')
|
|
104
|
+
const active = this.#active
|
|
105
|
+
for (const { ticket, priority } of ranked) {
|
|
106
|
+
if (priority === 'low' && this.#pauses > 0) continue
|
|
107
|
+
if (ticket.lane === 'decode') {
|
|
108
|
+
if (active.decode < DECODES) return ticket
|
|
109
|
+
} else if (active.request < this.concurrency) {
|
|
110
|
+
if (priority !== 'low' || (active.low < LOW && !high)) return ticket
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return undefined
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import type { Off } from '@dioramajs/core'
|
|
2
|
+
import type { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'
|
|
3
|
+
import type { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js'
|
|
4
|
+
import type { WebGPURenderer } from 'three/webgpu'
|
|
5
|
+
import { AssetError, isAbort } from '../errors'
|
|
6
|
+
import type { DecoderOptions, LoaderContext } from '../types'
|
|
7
|
+
|
|
8
|
+
type Meshopt = typeof import('three/addons/libs/meshopt_decoder.module.js').MeshoptDecoder
|
|
9
|
+
type Options = Readonly<Partial<DecoderOptions>>
|
|
10
|
+
|
|
11
|
+
const DRACO = 'KHR_draco_mesh_compression'
|
|
12
|
+
export const KTX2 = 'KTX2 (KHR_texture_basisu)'
|
|
13
|
+
|
|
14
|
+
const CSP =
|
|
15
|
+
"decoders run in blob: workers and WebAssembly: the Content Security Policy needs worker-src blob: and script-src 'wasm-unsafe-eval'"
|
|
16
|
+
|
|
17
|
+
/** A worker or WebAssembly refused, most likely by the CSP. */
|
|
18
|
+
const blocked = (cause: unknown): boolean =>
|
|
19
|
+
(cause as { name?: string } | null)?.name === 'SecurityError' ||
|
|
20
|
+
/Content Security Policy|wasm-unsafe-eval|WebAssembly|Worker/i.test(String(cause))
|
|
21
|
+
|
|
22
|
+
const decoderError = (message: string, url: string, cause?: unknown): AssetError =>
|
|
23
|
+
cause instanceof AssetError
|
|
24
|
+
? cause
|
|
25
|
+
: new AssetError('ASSET_DECODER', blocked(cause) ? `${message}: ${CSP}` : message, {
|
|
26
|
+
url,
|
|
27
|
+
cause,
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
export const refused = (what: string, option: keyof DecoderOptions, url: string): AssetError =>
|
|
31
|
+
new AssetError('ASSET_DECODER', `the file uses ${what} and decoders.${option} is false`, { url })
|
|
32
|
+
|
|
33
|
+
/** Aborts pass through, a refused decoder worker is ASSET_DECODER, the rest ASSET_PARSE. */
|
|
34
|
+
export function parseError(cause: unknown, context: LoaderContext, decoders: boolean): unknown {
|
|
35
|
+
if (context.signal.aborted || isAbort(cause) || cause instanceof AssetError) return cause
|
|
36
|
+
if (decoders && blocked(cause)) return decoderError('a decoder failed', context.url, cause)
|
|
37
|
+
return new AssetError('ASSET_PARSE', `cannot parse ${context.url}`, { url: context.url, cause })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Shared by every app of the page. three's MeshoptDecoder is a module singleton with global
|
|
41
|
+
// workers, and a second active KTX2Loader warns. Created on first need and freed after the last
|
|
42
|
+
// app. `workers` comes from the app that created the decoder.
|
|
43
|
+
let apps = 0
|
|
44
|
+
let draco: Promise<DRACOLoader> | undefined
|
|
45
|
+
let meshopt: Promise<Meshopt> | undefined
|
|
46
|
+
let meshoptWorkers = false
|
|
47
|
+
const ktx2 = new Map<object, Promise<KTX2Loader>>()
|
|
48
|
+
let probe: Promise<void> | undefined
|
|
49
|
+
|
|
50
|
+
/** One per app that loads through this module. The last one out frees the decoders. */
|
|
51
|
+
export function join(): Off {
|
|
52
|
+
apps++
|
|
53
|
+
let done = false
|
|
54
|
+
return () => {
|
|
55
|
+
if (done) return
|
|
56
|
+
done = true
|
|
57
|
+
if (--apps > 0) return
|
|
58
|
+
const workers = meshoptWorkers
|
|
59
|
+
void draco?.then((loader) => loader.dispose(), noop)
|
|
60
|
+
void meshopt?.then((decoder) => workers && decoder.useWorkers(0), noop)
|
|
61
|
+
for (const renderer of [...ktx2.keys()]) forget(renderer)
|
|
62
|
+
draco = meshopt = probe = undefined
|
|
63
|
+
meshoptWorkers = false
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Drops the KTX2Loader of a stopped renderer, since it read that renderer's formats. */
|
|
68
|
+
export function forget(renderer: object): void {
|
|
69
|
+
const pending = ktx2.get(renderer)
|
|
70
|
+
ktx2.delete(renderer)
|
|
71
|
+
void pending?.then((loader) => loader.dispose(), noop)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Local copy. Importing it from ../errors adds a binding across the lazy chunk boundary.
|
|
75
|
+
const noop = (): void => {}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* three's decoders run in blob: workers. A worker refused by the CSP doesn't throw in Chrome, it
|
|
79
|
+
* fires `error`, and DRACOLoader and KTX2Loader would wait for its answer forever. Probe first
|
|
80
|
+
* with an empty worker that compiles an empty WebAssembly module, as theirs do.
|
|
81
|
+
*/
|
|
82
|
+
function workers(): Promise<void> {
|
|
83
|
+
if (typeof Worker === 'undefined') return Promise.resolve()
|
|
84
|
+
probe ??= new Promise<void>((resolve, reject) => {
|
|
85
|
+
const url = URL.createObjectURL(
|
|
86
|
+
new Blob([
|
|
87
|
+
'WebAssembly.compile(new Uint8Array([0,97,115,109,1,0,0,0])).then(()=>postMessage(""),e=>postMessage(String(e)))',
|
|
88
|
+
]),
|
|
89
|
+
)
|
|
90
|
+
let worker: Worker | undefined
|
|
91
|
+
const done = (error?: string): void => {
|
|
92
|
+
worker?.terminate()
|
|
93
|
+
URL.revokeObjectURL(url)
|
|
94
|
+
if (error) reject(new Error(error))
|
|
95
|
+
else resolve()
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
worker = new Worker(url)
|
|
99
|
+
worker.onmessage = (event) => done(event.data)
|
|
100
|
+
worker.onerror = () => done('a blob: Worker was refused')
|
|
101
|
+
} catch (cause) {
|
|
102
|
+
done(String(cause))
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
return probe
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Keeps a decoder promise for reuse unless it failed, so the next file tries again. */
|
|
109
|
+
function shared<T>(pending: Promise<T>, clear: () => void): Promise<T> {
|
|
110
|
+
pending.catch(clear)
|
|
111
|
+
return pending
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function dracoLoader(options: Options, url: string): Promise<DRACOLoader> {
|
|
115
|
+
const path = options.draco
|
|
116
|
+
if (path === false) return Promise.reject(refused(DRACO, 'draco', url))
|
|
117
|
+
if (!draco) {
|
|
118
|
+
const pending = (async () => {
|
|
119
|
+
const [{ DRACOLoader, DRACO_GLTF_CONFIG }] = await Promise.all([
|
|
120
|
+
import('three/addons/loaders/DRACOLoader.js'),
|
|
121
|
+
workers(),
|
|
122
|
+
])
|
|
123
|
+
const loader = new DRACOLoader().setDecoderPath(path ?? DRACO_GLTF_CONFIG)
|
|
124
|
+
if (options.workers) loader.setWorkerLimit(options.workers)
|
|
125
|
+
// three keeps the decoder files' promise on the loader after preload().
|
|
126
|
+
await (loader.preload() as unknown as { decoderPending: Promise<void> }).decoderPending
|
|
127
|
+
return loader
|
|
128
|
+
})()
|
|
129
|
+
draco = shared(pending, () => {
|
|
130
|
+
if (draco === pending) draco = undefined
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
const where = typeof path === 'object' ? path.js : (path ?? 'three/examples/jsm/libs/draco/gltf/')
|
|
134
|
+
return draco.catch((cause: unknown) => {
|
|
135
|
+
throw decoderError(`the Draco decoder did not load from ${where}`, url, cause)
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function meshoptDecoder(options: Options, url: string): Promise<Meshopt> {
|
|
140
|
+
if (options.meshopt === false)
|
|
141
|
+
return Promise.reject(refused('meshopt compression', 'meshopt', url))
|
|
142
|
+
if (!meshopt) {
|
|
143
|
+
const pending = (async () => {
|
|
144
|
+
const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js')
|
|
145
|
+
if (!MeshoptDecoder.supported) {
|
|
146
|
+
throw new AssetError('ASSET_DECODER', 'meshopt decoding needs WebAssembly', { url })
|
|
147
|
+
}
|
|
148
|
+
await MeshoptDecoder.ready
|
|
149
|
+
if (options.workers) {
|
|
150
|
+
await workers()
|
|
151
|
+
MeshoptDecoder.useWorkers(options.workers)
|
|
152
|
+
meshoptWorkers = true
|
|
153
|
+
}
|
|
154
|
+
return MeshoptDecoder
|
|
155
|
+
})()
|
|
156
|
+
meshopt = shared(pending, () => {
|
|
157
|
+
if (meshopt === pending) meshopt = undefined
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
return meshopt.catch((cause: unknown) => {
|
|
161
|
+
throw decoderError('the meshopt decoder did not start', url, cause)
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** One per renderer, after its init, since detectSupport reads the renderer's features. */
|
|
166
|
+
export function ktx2Loader(renderer: object, options: Options, url: string): Promise<KTX2Loader> {
|
|
167
|
+
const path = options.ktx2
|
|
168
|
+
if (path === false) return Promise.reject(refused(KTX2, 'ktx2', url))
|
|
169
|
+
let pending = ktx2.get(renderer)
|
|
170
|
+
if (!pending) {
|
|
171
|
+
const created = (async () => {
|
|
172
|
+
const [{ KTX2Loader }] = await Promise.all([
|
|
173
|
+
import('three/addons/loaders/KTX2Loader.js'),
|
|
174
|
+
workers(),
|
|
175
|
+
])
|
|
176
|
+
const loader = new KTX2Loader()
|
|
177
|
+
if (path) loader.setTranscoderPath(path)
|
|
178
|
+
if (options.workers) loader.setWorkerLimit(options.workers)
|
|
179
|
+
loader.detectSupport(renderer as WebGPURenderer)
|
|
180
|
+
try {
|
|
181
|
+
await loader.init()
|
|
182
|
+
} catch (cause) {
|
|
183
|
+
loader.dispose()
|
|
184
|
+
throw cause
|
|
185
|
+
}
|
|
186
|
+
return loader
|
|
187
|
+
})()
|
|
188
|
+
pending = shared(created, () => {
|
|
189
|
+
if (ktx2.get(renderer) === created) ktx2.delete(renderer)
|
|
190
|
+
})
|
|
191
|
+
ktx2.set(renderer, pending)
|
|
192
|
+
}
|
|
193
|
+
const where = path || 'three/examples/jsm/libs/basis/'
|
|
194
|
+
return pending.catch((cause: unknown) => {
|
|
195
|
+
throw decoderError(`the Basis transcoder did not load from ${where}`, url, cause)
|
|
196
|
+
})
|
|
197
|
+
}
|