@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/queue.ts","../src/cache.ts","../src/keys.ts","../src/loaders.ts","../src/preload.ts","../src/wave.ts","../src/plugin.ts"],"sourcesContent":["// Concurrency for asset work: request slots for the network and decode slots for parsing,\n// handed out by priority.\nimport type { Off } from '@dioramajs/core'\nimport type { Priority } from './types'\n\nexport const RANK: Readonly<Record<Priority, number>> = { low: 0, normal: 1, high: 2 }\n/** Parallel decodes: createImageBitmap, glTF parsing. */\nconst DECODES = 2\n/** Low requests at once, and only while no high one waits. */\nconst LOW = 2\n\nexport type Lane = 'request' | 'decode'\n\ninterface Ticket {\n readonly lane: Lane\n readonly priority: () => Priority\n readonly seq: number\n grant(): void\n}\n\nexport const abortError = (): DOMException => new DOMException('aborted', 'AbortError')\n\n/**\n * Request and decode slots. Priorities are read at every step, so a lease that raises an entry's\n * priority moves it up in its lane. Low-only work doesn't start while a pause is held.\n */\nexport class Queue {\n concurrency: number\n readonly #waiting: Ticket[] = []\n readonly #active: Record<Lane | 'low', number> = { request: 0, decode: 0, low: 0 }\n #pauses = 0\n #seq = 0\n /** Once stopped, every slot is granted at once and detached entries finish on their own. */\n #open = false\n\n constructor(concurrency: number) {\n this.concurrency = concurrency\n }\n\n /** Resolves with the slot's release once granted. Rejects with AbortError on abort. */\n slot(lane: Lane, priority: () => Priority, signal: AbortSignal): Promise<Off> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(abortError())\n const abort = (): void => {\n const index = this.#waiting.indexOf(ticket)\n if (index >= 0) this.#waiting.splice(index, 1)\n reject(abortError())\n }\n const ticket: Ticket = {\n lane,\n priority,\n seq: this.#seq++,\n grant: () => {\n signal.removeEventListener('abort', abort)\n const low = lane === 'request' && priority() === 'low'\n this.#active[lane]++\n if (low) this.#active.low++\n let done = false\n resolve(() => {\n if (done) return\n done = true\n this.#active[lane]--\n if (low) this.#active.low--\n this.pump()\n })\n },\n }\n signal.addEventListener('abort', abort, { once: true })\n this.#waiting.push(ticket)\n this.pump()\n })\n }\n\n pause(): Off {\n this.#pauses++\n let done = false\n return () => {\n if (done) return\n done = true\n this.#pauses--\n this.pump()\n }\n }\n\n open(): void {\n this.#open = true\n this.pump()\n }\n\n /** Grants every ticket the rules allow, highest priority first, then in arrival order. */\n pump(): void {\n for (let next = this.#next(); next; next = this.#next()) {\n this.#waiting.splice(this.#waiting.indexOf(next), 1)\n next.grant()\n }\n }\n\n #next(): Ticket | undefined {\n const ranked = this.#waiting\n .map((ticket) => ({ ticket, priority: ticket.priority() }))\n .sort((a, b) => RANK[b.priority] - RANK[a.priority] || a.ticket.seq - b.ticket.seq)\n if (this.#open) return ranked[0]?.ticket\n const high = ranked.some((t) => t.ticket.lane === 'request' && t.priority === 'high')\n const active = this.#active\n for (const { ticket, priority } of ranked) {\n if (priority === 'low' && this.#pauses > 0) continue\n if (ticket.lane === 'decode') {\n if (active.decode < DECODES) return ticket\n } else if (active.request < this.concurrency) {\n if (priority !== 'low' || (active.low < LOW && !high)) return ticket\n }\n }\n return undefined\n }\n}\n","// The asset cache: one entry per key, shared by every lease on it. An entry loads once through\n// the queue, then lives while any lease does; after the last one it is retained by size or freed.\nimport { type Off, type Signal, signal } from '@dioramajs/core'\nimport type { RenderApi } from '@dioramajs/render'\nimport { AssetError, isAbort, linked, noop } from './errors'\nimport { abortError, type Queue, RANK } from './queue'\nimport type {\n Asset,\n AssetStatus,\n CrossOrigin,\n DecoderOptions,\n Loaded,\n LoaderContext,\n LoadOptions,\n Priority,\n} from './types'\nimport type { Item, Wave } from './wave'\n\n/** Progress weight of work of unknown size. */\nexport const ESTIMATE = 100_000\n\nexport type Make = (context: LoaderContext) => Promise<Loaded<unknown>>\n\nexport interface Spec {\n readonly key: string\n readonly url: string\n readonly type: string\n readonly crossOrigin: CrossOrigin\n readonly options: Readonly<Record<string, string | number | boolean>>\n /** Resolves the loader. A lazy module may fail with ASSET_TYPE. */\n readonly make: () => Make | Promise<Make>\n /** `load()` leases see foreign errors as AssetError, `acquire()` leases see them as they are. */\n readonly wrap: boolean\n readonly weight?: number\n}\n\nexport interface CacheHost {\n readonly queue: Queue\n readonly wave: Wave\n readonly retain: number\n readonly decoders: Readonly<Partial<DecoderOptions>>\n report(error: unknown, url: string): void\n transform(value: unknown, type: string, url: string): unknown\n render(signal: AbortSignal): Promise<RenderApi>\n load(url: string, options: LoadOptions): Asset<unknown>\n}\n\ninterface Lease {\n readonly entry: Entry\n readonly priority: Priority\n /** Load leases report a failure, preloads and acquire don't. */\n readonly report: boolean\n readonly wrap: boolean\n readonly status: Signal<AssetStatus>\n readonly ready: Promise<unknown>\n resolve(value: unknown): void\n reject(error: unknown): void\n released: boolean\n off?: () => void\n}\n\nclass Entry implements Item {\n readonly spec: Omit<Spec, 'make'>\n /** Cleared once run, since the loader may hold its source (an <img> of a page that is gone). */\n make: Spec['make'] | undefined\n readonly leases: Set<Lease> = new Set()\n readonly abort: AbortController = new AbortController()\n state: 'loading' | 'ready' | 'failed' = 'loading'\n result: Loaded<unknown> | undefined\n value: unknown\n /** What the loader threw, and the same wrapped as AssetError. */\n cause: unknown\n error: AssetError | undefined\n bytes = 0\n total: number\n loaded = 0\n waved = false\n /** Out of the cache because the plugin stopped. Freed with its last lease. */\n detached = false\n /** Its renderer stopped (KTX2). Freed with its last lease, never retained. */\n stale = false\n\n constructor({ make, ...spec }: Spec) {\n this.spec = spec\n this.make = make\n this.total = spec.weight ?? ESTIMATE\n }\n\n priority(): Priority {\n let best: Priority = 'low'\n for (const lease of this.leases) if (RANK[lease.priority] > RANK[best]) best = lease.priority\n return best\n }\n}\n\n/** Unknown sizes weigh ESTIMATE. At 0 bytes `retain` would keep them forever. */\nconst estimate = (value: unknown): number => {\n const sized = value as { byteLength?: number; width?: number; height?: number } | null\n return sized?.byteLength || (sized?.width ?? 0) * (sized?.height ?? 0) * 4 || ESTIMATE\n}\n\nconst failure = (lease: Lease): unknown => (lease.wrap ? lease.entry.error : lease.entry.cause)\n\n/**\n * Entries by key with leases. An entry lives while any lease does, then it is aborted, retained\n * (LRU by bytes, no timers) or disposed once.\n */\nexport class Cache {\n readonly #host: CacheHost\n readonly #entries = new Map<string, Entry>()\n /** Ready entries without leases, oldest first. */\n readonly #retained = new Set<Entry>()\n /** Stale entries out of the map that still have leases. Counted until their last lease. */\n readonly #stale = new Set<Entry>()\n\n constructor(host: CacheHost) {\n this.#host = host\n }\n\n get<T, E = AssetError>(\n spec: Spec,\n priority: Priority,\n report: boolean,\n signal?: AbortSignal,\n ): Asset<T, E> {\n let entry = this.#entries.get(spec.key)\n const created = !entry\n if (!entry) {\n entry = new Entry(spec)\n this.#entries.set(spec.key, entry)\n }\n this.#retained.delete(entry)\n const lease = this.#lease(entry, priority, report, spec.wrap)\n if (created) void this.#run(entry)\n this.#changed(entry)\n const asset = this.#asset<T, E>(lease)\n if (signal?.aborted) asset.release()\n else if (signal) {\n signal.addEventListener('abort', asset.release, { once: true })\n lease.off = () => signal.removeEventListener('abort', asset.release)\n }\n return asset\n }\n\n release(lease: Lease): void {\n if (lease.released) return\n lease.released = true\n lease.off?.()\n const { entry } = lease\n entry.leases.delete(lease)\n if (lease.status.peek() === 'loading') {\n lease.reject(\n linked(new AssetError('ASSET_ABORTED', 'released before ready', { url: entry.spec.url })),\n )\n }\n lease.status.value = 'released'\n if (entry.leases.size) {\n this.#changed(entry)\n return\n }\n const { retain } = this.#host\n if (entry.state === 'ready' && !entry.detached && !entry.stale && entry.bytes <= retain) {\n this.#retained.add(entry)\n let bytes = this.#bytes()\n for (const old of this.#retained) {\n if (bytes <= retain) break\n bytes -= old.bytes\n this.#drop(old)\n }\n } else this.#drop(entry)\n }\n\n /** Whether the key has an entry, loading, ready or retained. */\n has(key: string): boolean {\n return this.#entries.has(key)\n }\n\n stats(): { entries: number; used: number; retained: number; pending: number } {\n const all = [...this.#entries.values(), ...this.#stale]\n return {\n entries: all.length,\n used: all.filter((entry) => entry.leases.size > 0).length,\n retained: this.#bytes(),\n pending: all.filter((entry) => entry.state === 'loading').length,\n }\n }\n\n /** `render` stopped. Renderer-bound entries go at once or with their last lease. */\n rebind(): void {\n for (const entry of [...this.#entries.values()]) {\n if (!entry.result?.renderBound) continue\n if (!entry.leases.size) this.#drop(entry)\n else {\n // Take it out of the cache so a new load transcodes for the new renderer.\n entry.stale = true\n this.#entries.delete(entry.spec.key)\n this.#stale.add(entry)\n }\n }\n }\n\n /**\n * The plugin stops. `remove('assets')` keeps entries with leases until their last one, since an\n * effect's texture may still show the bitmap. `destroy` releases everything at once.\n */\n close(hard: boolean): void {\n this.#host.queue.open()\n for (const entry of [...this.#entries.values(), ...this.#stale]) {\n this.#entries.delete(entry.spec.key)\n entry.detached = true\n if (!entry.leases.size) this.#drop(entry)\n else if (hard) for (const lease of [...entry.leases]) this.release(lease)\n }\n this.#host.wave.close()\n }\n\n #bytes(): number {\n let bytes = 0\n for (const entry of this.#retained) bytes += entry.bytes\n return bytes\n }\n\n #drop(entry: Entry): void {\n if (this.#entries.get(entry.spec.key) === entry) this.#entries.delete(entry.spec.key)\n this.#retained.delete(entry)\n this.#stale.delete(entry)\n this.#unwave(entry)\n if (entry.state === 'loading') entry.abort.abort()\n const { result } = entry\n entry.result = entry.value = undefined\n result?.dispose?.()\n }\n\n /** A lease came or went. The queue re-reads priorities and low-only work leaves the wave. */\n #changed(entry: Entry): void {\n if (entry.state === 'loading' && !entry.detached) {\n if (entry.priority() !== 'low') {\n if (!entry.waved) this.#host.wave.add(entry)\n entry.waved = true\n } else this.#unwave(entry)\n }\n this.#host.queue.pump()\n }\n\n #unwave(entry: Entry): void {\n if (!entry.waved) return\n entry.waved = false\n this.#host.wave.done(entry)\n }\n\n #lease(entry: Entry, priority: Priority, report: boolean, wrap: boolean): Lease {\n let resolve!: (value: unknown) => void\n let reject!: (error: unknown) => void\n const ready = new Promise<unknown>((res, rej) => {\n resolve = res\n reject = rej\n })\n // Reading `ready` is optional, so nobody awaiting it is not an unhandled rejection.\n ready.catch(noop)\n const initial =\n entry.state === 'ready' ? 'ready' : entry.state === 'failed' ? 'failed' : 'loading'\n const status = signal<AssetStatus>(initial)\n const lease: Lease = {\n entry,\n priority,\n report,\n wrap,\n status,\n ready,\n resolve,\n reject,\n released: false,\n }\n entry.leases.add(lease)\n if (entry.state === 'ready') resolve(entry.value)\n else if (entry.state === 'failed') reject(failure(lease))\n return lease\n }\n\n #asset<T, E>(lease: Lease): Asset<T, E> {\n const { entry } = lease\n const release = (): void => this.release(lease)\n const asset = Object.assign(release, {\n release,\n dispose: release,\n key: entry.spec.key,\n url: entry.spec.url,\n status: lease.status,\n ready: lease.ready,\n })\n return Object.defineProperties(asset, {\n value: { get: () => (lease.status.peek() === 'ready' ? entry.value : undefined) },\n error: { get: () => (lease.status.peek() === 'failed' ? failure(lease) : undefined) },\n }) as unknown as Asset<T, E>\n }\n\n /** Loads the entry once its loader resolves and a request slot is free. */\n async #run(entry: Entry): Promise<void> {\n const { spec } = entry\n const { signal } = entry.abort\n const host = this.#host\n let free: Off | undefined\n const resolve = entry.make as Spec['make']\n entry.make = undefined\n try {\n const make = await resolve()\n if (signal.aborted) throw abortError()\n free = await host.queue.slot('request', () => entry.priority(), signal)\n const result = await make(this.#context(entry, () => free?.()))\n free()\n if (signal.aborted) {\n result.dispose?.()\n return\n }\n const value = entry.detached\n ? result.value\n : host.transform(result.value, spec.type, spec.url)\n entry.result = result\n entry.value = value\n entry.bytes = result.bytes ?? estimate(value)\n entry.state = 'ready'\n this.#unwave(entry)\n for (const lease of entry.leases) {\n lease.status.value = 'ready'\n lease.resolve(value)\n }\n } catch (cause) {\n free?.()\n // Released meanwhile. Nobody waits and nothing is reported.\n if (signal.aborted || entry.leases.size === 0) return\n const error = linked(\n cause instanceof AssetError\n ? cause\n : new AssetError(isAbort(cause) ? 'ASSET_ABORTED' : 'ASSET_PARSE', String(cause), {\n url: spec.url,\n cause,\n }),\n )\n entry.cause = cause\n entry.error = error\n entry.state = 'failed'\n this.#unwave(entry)\n const leases = [...entry.leases]\n for (const lease of leases) {\n lease.status.value = 'failed'\n lease.reject(failure(lease))\n }\n if (!entry.detached && leases.some((lease) => lease.report)) host.report(error, spec.url)\n }\n }\n\n #context(entry: Entry, free: () => void): LoaderContext {\n const { spec } = entry\n const { url, crossOrigin } = spec\n const { signal } = entry.abort\n const host = this.#host\n const wave = host.wave\n return {\n url,\n key: spec.key,\n get priority() {\n return entry.priority()\n },\n crossOrigin,\n options: spec.options,\n signal,\n async fetch(init) {\n const priority = entry.priority()\n let response: Response\n try {\n response = await fetch(url, {\n signal,\n priority: priority === 'normal' ? 'auto' : priority,\n credentials: crossOrigin === 'use-credentials' ? 'include' : 'same-origin',\n ...init,\n } as RequestInit)\n } catch (cause) {\n if (signal.aborted) throw abortError()\n throw new AssetError('ASSET_LOAD', `cannot fetch ${url}`, { url, cause })\n }\n if (!response.ok) {\n throw new AssetError('ASSET_LOAD', `${response.status} ${url}`, { url })\n }\n return response\n },\n async bytes(response) {\n // Content-Length counts the compressed body, so only an identity one is a usable weight.\n const length = Number(response.headers.get('content-length'))\n if (length > 0 && !response.headers.has('content-encoding')) entry.total = length\n const reader = response.body?.getReader()\n if (!reader) {\n const buffer = await response.arrayBuffer()\n entry.loaded = entry.total\n wave.changed()\n return buffer\n }\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n chunks.push(value)\n size += value.byteLength\n entry.loaded = Math.min(size, entry.total)\n wave.changed()\n }\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body.buffer\n },\n async decode(work) {\n free()\n const done = await host.queue.slot('decode', () => entry.priority(), signal)\n try {\n return await work()\n } finally {\n done()\n }\n },\n // Waiting on another entry or on render is not network work. Holding the request slot\n // meanwhile, cold textures would take every slot from the pictures they wait for.\n load(dependency, options) {\n free()\n return host.load(dependency, { ...options, signal }) as never\n },\n render() {\n free()\n return host.render(signal)\n },\n decoders: host.decoders,\n }\n }\n}\n","import type { CrossOrigin } from './types'\n\n/** Asset type by file extension, for loads without an explicit type. */\nexport const BY_EXTENSION: Readonly<Record<string, string>> = {\n glb: 'gltf',\n gltf: 'gltf',\n ktx2: 'ktx2',\n jpg: 'texture',\n jpeg: 'texture',\n png: 'texture',\n webp: 'texture',\n avif: 'texture',\n gif: 'texture',\n}\n\n/** Absolute URL without the fragment, which never reaches the request. */\nexport function absolute(url: string, base?: string | URL): string {\n const parsed = new URL(url, base ?? document.baseURI)\n parsed.hash = ''\n return parsed.href\n}\n\n/**\n * CORS mode of a texture load. Pixels of another origin fetched without CORS are tainted and the\n * GPU upload throws SecurityError on every draw, so such a texture is always asked in CORS mode.\n */\nexport function textureCors(url: string, crossOrigin: CrossOrigin): CrossOrigin {\n if (crossOrigin) return crossOrigin\n const page = globalThis.location?.origin\n const target = new URL(url)\n return page && /^https?:$/.test(target.protocol) && target.origin !== page ? 'anonymous' : ''\n}\n\n/** Lower-case extension of an absolute URL's path, without the dot. '' for none. */\nexport const extensionOf = (url: string): string =>\n /\\.([a-z0-9]+)$/i.exec(new URL(url).pathname)?.[1]?.toLowerCase() ?? ''\n\n/**\n * Cache key `type url[ crossOrigin][ options]`. The CORS mode is part of it, as in the browser's\n * image cache. The effects pool builds `image <currentSrc>[ crossOrigin]` keys the same way.\n */\nexport function keyOf(\n type: string,\n url: string,\n crossOrigin: CrossOrigin,\n options: Readonly<Record<string, unknown>>,\n): string {\n const entries = Object.entries(options).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n let key = `${type} ${url}`\n if (crossOrigin) key += ` ${crossOrigin}`\n if (entries.length) key += ` ${JSON.stringify(entries)}`\n return key\n}\n\n/** URL and type of a `keyOf` key. A key without a space stands for both. */\nexport const parseKey = (key: string): { readonly url: string; readonly type: string } => ({\n url: key.split(' ')[1] ?? key,\n type: key.split(' ')[0] ?? key,\n})\n\nconst CANDIDATE = /[\\s,]*(\\S+)/y\n\n/**\n * A srcset with absolute candidate URLs. A URL is a run of non-spaces, so commas inside stay\n * (CDN transforms like `w_400,c_fill`). Per the HTML spec, one ending in commas has no descriptors.\n */\nexport function srcset(value: string, base: string): string {\n const out: string[] = []\n for (let i = 0; ; ) {\n CANDIDATE.lastIndex = i\n const match = CANDIDATE.exec(value)\n if (!match) break\n let url = match[1] as string\n i = CANDIDATE.lastIndex\n let descriptor = ''\n if (url.endsWith(',')) url = url.replace(/,+$/, '')\n else {\n const end = value.indexOf(',', i)\n descriptor = value.slice(i, end < 0 ? undefined : end).trim()\n i = end < 0 ? value.length : end + 1\n }\n const href = new URL(url, base).href\n out.push(descriptor ? `${href} ${descriptor}` : href)\n }\n return out.join(', ')\n}\n","import { AssetError } from './errors'\nimport { abortError } from './queue'\nimport type { AssetLoader, Loaded, LoaderContext } from './types'\n\n/** Resolves once the image has loaded, or rejects with ASSET_LOAD. Aborting stops the request. */\nexport function loaded(img: HTMLImageElement, url: string, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(abortError())\n // A cached image may be complete at once. happy-dom never loads and reports complete.\n if (img.complete && (img.currentSrc || img.src)) return resolve()\n const done = (): void => {\n img.removeEventListener('load', ok)\n img.removeEventListener('error', fail)\n signal.removeEventListener('abort', abort)\n }\n const ok = (): void => {\n done()\n resolve()\n }\n const fail = (): void => {\n done()\n // In CORS mode a server without Access-Control-Allow-Origin fails the same way as a 404.\n const foreign = new URL(url, location.href).origin !== location.origin\n const hint =\n foreign && img.crossOrigin !== null\n ? ': is it served with Access-Control-Allow-Origin?'\n : ''\n reject(new AssetError('ASSET_LOAD', `cannot load ${url}${hint}`, { url }))\n }\n const abort = (): void => {\n done()\n img.removeAttribute('srcset')\n img.removeAttribute('src')\n reject(abortError())\n }\n img.addEventListener('load', ok)\n img.addEventListener('error', fail)\n signal.addEventListener('abort', abort)\n })\n}\n\nconst FLIP: ImageBitmapOptions = { imageOrientation: 'flipY' }\n\n/**\n * The image's bytes decoded, or `undefined` when they cannot be read. Chrome decodes a Blob off\n * the main thread, but an <img> on it: about 60 ms for 1920×1080. The bytes come from the HTTP\n * cache, where the image left them. Mirrors `fromBytes` of the effects pool.\n */\nasync function fromBytes(img: HTMLImageElement): Promise<ImageBitmap | undefined> {\n try {\n const mode = img.crossOrigin\n const target = new URL(img.currentSrc || img.src, location.href)\n // A no-CORS image of another origin: opaque bytes, and pixels no texture may use anyway\n if (mode === null && target.origin !== location.origin && target.protocol !== 'data:') return\n const response = await fetch(target, {\n credentials: mode === 'use-credentials' ? 'include' : 'same-origin',\n cache: 'force-cache',\n })\n if (!response.ok) return\n return await createImageBitmap(await response.blob(), FLIP)\n } catch {\n return undefined\n }\n}\n\n/** Shared with the effects pool. Decodes, then flips the pixels like effects textures. */\nexport async function bitmap(img: HTMLImageElement, url: string): Promise<Loaded<ImageBitmap>> {\n try {\n let pixels = await fromBytes(img)\n if (!pixels) {\n await img.decode()\n pixels = await createImageBitmap(img, FLIP)\n }\n return {\n value: pixels,\n bytes: pixels.width * pixels.height * 4,\n dispose: () => pixels.close(),\n }\n } catch (cause) {\n throw new AssetError('ASSET_PARSE', `cannot decode ${url}`, { url, cause })\n }\n}\n\n/** A detached image. The browser makes the request, then it takes a decode slot. */\nexport const image: AssetLoader<ImageBitmap> = {\n async load(context) {\n const img = new Image()\n if (context.crossOrigin) img.crossOrigin = context.crossOrigin\n if (context.priority !== 'normal') img.setAttribute('fetchpriority', context.priority)\n img.src = context.url\n await loaded(img, context.url, context.signal)\n return context.decode(() => bitmap(img, context.url))\n },\n}\n\nasync function body(context: LoaderContext): Promise<ArrayBuffer> {\n return context.bytes(await context.fetch())\n}\n\nexport const buffer: AssetLoader<ArrayBuffer> = {\n async load(context) {\n const value = await body(context)\n return { value, bytes: value.byteLength }\n },\n}\n\nexport const json: AssetLoader<unknown> = {\n async load(context) {\n const bytes = await body(context)\n try {\n return { value: JSON.parse(new TextDecoder().decode(bytes)), bytes: bytes.byteLength }\n } catch (cause) {\n throw new AssetError('ASSET_PARSE', `${context.url} is not JSON`, {\n url: context.url,\n cause,\n })\n }\n },\n}\n","// Preloads: `assets.preload` from code, and `data-dio-preload` markup that loads on intent\n// (hover, focus or touch). Only the latest preload of each kind holds its leases.\nimport type { Off } from '@dioramajs/core'\nimport { withDocs } from '@dioramajs/core/dev'\nimport { DEV, isAbort, noop } from './errors'\nimport { absolute, keyOf, srcset } from './keys'\nimport { bitmap, loaded } from './loaders'\nimport type {\n Asset,\n CrossOrigin,\n LoaderContext,\n LoadOptions,\n Preload,\n PreloadOptions,\n PreloadSource,\n Priority,\n} from './types'\n\n/** Hover longer than this is an intent to follow the link. */\nconst INTENT_MS = 65\nconst IMAGES = 'img[data-dio], img[data-dio-key]'\nconst MARKUP = '[data-dio-preload]'\n\nexport interface PreloadHost {\n /** A preload lease. Failures are not reported. */\n load(url: string, options: LoadOptions & { readonly type: string }): Asset<unknown>\n acquire(\n key: string,\n make: (context: LoaderContext) => Promise<never>,\n priority: Priority,\n ): Asset<unknown, unknown>\n /** An entry under the key, loading, ready or retained. */\n has(key: string): boolean\n /** A request slot for the browser's own request of a detached image. */\n slot(priority: Priority, signal: AbortSignal): Promise<Off>\n /** The type of an absolute URL by its extension. Undefined for a page address. */\n typeOf(url: string): string | undefined\n track(work: Promise<unknown>, priority: Priority): void\n warn(message: string): void\n}\n\ninterface Target {\n readonly href: string\n readonly type: string\n readonly crossOrigin: CrossOrigin\n readonly key: string\n}\n\ninterface Connection {\n readonly saveData?: boolean\n readonly effectiveType?: string\n}\n\n/** Nothing is preloaded under Save-Data or on a 2g connection. */\nexport function frugal(): boolean {\n const connection = (globalThis.navigator as { connection?: Connection } | undefined)?.connection\n return connection?.saveData === true || /(^|-)2g$/.test(connection?.effectiveType ?? '')\n}\n\n/** The CORS mode of an element as a key part. No attribute gives '' (no CORS). */\nexport function corsOf(el: Element): CrossOrigin {\n const value = el.getAttribute('crossorigin')\n if (value === null) return ''\n return value.toLowerCase() === 'use-credentials' ? 'use-credentials' : 'anonymous'\n}\n\ninterface Copy {\n readonly img: HTMLImageElement\n /** Called once the queue gives a slot. */\n start(): void\n}\n\n/**\n * A detached image that picks the candidate the element would. Same `crossorigin`, `sizes` and\n * absolute `srcset`, inside a copy of its <picture>.\n */\nfunction copy(source: Element, base: string, priority: Priority): Copy | undefined {\n const src = source.getAttribute('src')\n const set = source.getAttribute('srcset')\n if (!src && !set) return undefined\n const img = new Image()\n const cors = source.getAttribute('crossorigin')\n if (cors !== null) img.setAttribute('crossorigin', cors)\n const sizes = source.getAttribute('sizes')\n if (sizes) img.setAttribute('sizes', sizes)\n if (priority !== 'normal') img.setAttribute('fetchpriority', priority)\n let holder: HTMLPictureElement | undefined\n const picture = source.parentElement\n if (picture?.localName === 'picture') {\n holder = document.createElement('picture')\n for (const child of picture.children) {\n if (child.localName !== 'source') continue\n const item = document.createElement('source')\n for (const { name, value } of child.attributes) {\n item.setAttribute(name, name === 'srcset' ? srcset(value, base) : value)\n }\n holder.append(item)\n }\n }\n return {\n img,\n start() {\n // Each of these makes the image pick a source and load it.\n holder?.append(img)\n if (set) img.setAttribute('srcset', srcset(set, base))\n if (src) img.src = new URL(src, base).href\n },\n }\n}\n\nconst words = (el: Element): string[] => (el.getAttribute('data-dio-preload') ?? '').split(/\\s+/)\n\nclass PreloadImpl implements Preload {\n readonly leases: Asset<unknown, unknown>[] = []\n readonly abort: AbortController = new AbortController()\n settled: Promise<void> = Promise.resolve()\n\n release = (): void => {\n this.abort.abort()\n for (const lease of this.leases.splice(0)) lease.release()\n }\n\n dispose: () => void = this.release\n\n // biome-ignore lint/suspicious/noThenProperty: a preload is thenable by design\n then: PromiseLike<void>['then'] = (fulfilled, rejected) => this.settled.then(fulfilled, rejected)\n}\n\n/** API and markup preloads. Only the last of each kind holds its leases. */\nexport class Preloads {\n readonly #host: PreloadHost\n readonly #last = new Map<'api' | 'markup', PreloadImpl>()\n /** A broken link warns once in development, not on every intent. */\n readonly #warned = new Set<string>()\n\n constructor(host: PreloadHost) {\n this.#host = host\n }\n\n preload(\n source: PreloadSource,\n options: PreloadOptions = {},\n kind: 'api' | 'markup' = 'api',\n ): Preload {\n const preload = new PreloadImpl()\n if (frugal()) return preload\n const priority = options.priority ?? 'low'\n const base = this.#base(source, options.base)\n const jobs: Promise<unknown>[] = []\n const url = (href: string, cors: CrossOrigin): void => {\n if (href) jobs.push(this.#url(preload, href, base, priority, cors))\n }\n const cors = options.crossOrigin ?? ''\n if (typeof source === 'string') url(source, cors)\n else if (Array.isArray(source)) for (const href of source as readonly string[]) url(href, cors)\n else if (typeof source === 'object') {\n const root = source as ParentNode\n const own = root instanceof Element ? [root] : []\n for (const el of [...own, ...root.querySelectorAll(IMAGES)]) {\n if (el.matches(IMAGES)) jobs.push(this.#image(preload, el, base, priority))\n }\n for (const el of [...own, ...root.querySelectorAll(MARKUP)]) {\n if (el.matches(MARKUP)) for (const href of words(el)) url(href, corsOf(el))\n }\n }\n preload.settled = Promise.all(jobs).then(noop)\n if (priority !== 'low') this.#host.track(preload.settled, priority)\n // Release after taking the new leases, so shared entries skip a trip through `retain`.\n this.#last.get(kind)?.release()\n this.#last.set(kind, preload)\n return preload\n }\n\n /** `data-dio-preload` on intent: hover (65 ms), focus or touch. */\n listen(signal: AbortSignal): void {\n let hovered: Element | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n const target = (event: Event): Element | null =>\n (event.target as Element | null)?.closest?.(MARKUP) ?? null\n const intent = (el: Element | null): void => {\n if (!el) return\n const urls = words(el)\n const crossOrigin = corsOf(el)\n // Load again only what the cache lost: a preload dropped mid-load by the next intent, an\n // evicted or failed entry. The new preload holds all of the link's URLs.\n const lost = (url: string): boolean => {\n const wanted = this.#target(url, document.baseURI, crossOrigin)\n return typeof wanted === 'string' || !this.#host.has(wanted.key)\n }\n if (urls.some((url) => url && lost(url))) this.preload(urls, { crossOrigin }, 'markup')\n }\n const options = { signal, passive: true }\n document.addEventListener(\n 'pointerover',\n (event) => {\n const el = target(event)\n if (!el || el === hovered) return\n clearTimeout(timer)\n hovered = el\n timer = setTimeout(() => intent(el), INTENT_MS)\n },\n options,\n )\n document.addEventListener(\n 'pointerout',\n (event) => {\n const el = target(event)\n if (!el || el !== hovered || el.contains((event as PointerEvent).relatedTarget as Node)) {\n return\n }\n clearTimeout(timer)\n hovered = undefined\n },\n options,\n )\n document.addEventListener('focusin', (event) => intent(target(event)), options)\n document.addEventListener('touchstart', (event) => intent(target(event)), options)\n signal.addEventListener('abort', () => clearTimeout(timer), { once: true })\n }\n\n close(): void {\n for (const preload of this.#last.values()) preload.release()\n this.#last.clear()\n }\n\n #base(source: PreloadSource, base: string | URL | undefined): string {\n if (base !== undefined) return new URL(base, document.baseURI).href\n const doc = (source as Partial<Node>).nodeType === 9 ? (source as Document) : undefined\n const href = doc?.querySelector('base[href]')?.getAttribute('href')\n return href ? new URL(href, document.baseURI).href : document.baseURI\n }\n\n /** The entry a preload of the URL takes, or the reason there is none. */\n #target(url: string, base: string, cors: CrossOrigin): Target | string {\n let href: string\n try {\n href = absolute(url, base)\n } catch {\n return `${url} is not a URL`\n }\n const found = this.#host.typeOf(href)\n // A page address. Router integrations pass the fetched Document instead.\n if (!found)\n return withDocs(\n `ASSET_TYPE: ${href} has no asset type: preload takes asset URLs or a Document`,\n 'ASSET_TYPE',\n )\n // Images preload their pixels, since `texture` and the effects pool share the `image` entry.\n // Only images key by CORS mode. Models load like a `load()` without `crossOrigin`.\n const type = found === 'texture' ? 'image' : found\n const crossOrigin = type === 'image' ? cors : ''\n return { href, type, crossOrigin, key: keyOf(type, href, crossOrigin, {}) }\n }\n\n #url(\n preload: PreloadImpl,\n url: string,\n base: string,\n priority: Priority,\n cors: CrossOrigin,\n ): Promise<void> {\n const target = this.#target(url, base, cors)\n if (typeof target === 'string') return this.#failed(target)\n const { href, type, crossOrigin } = target\n const { signal } = preload.abort\n return this.#hold(preload, this.#host.load(href, { type, priority, crossOrigin, signal }), href)\n }\n\n /**\n * A failed lease goes at once, so the entry leaves the cache and the page's own load is a new\n * attempt, reported if it fails too.\n */\n async #hold(preload: PreloadImpl, lease: Asset<unknown, unknown>, url: string): Promise<void> {\n preload.leases.push(lease)\n try {\n await lease.ready\n } catch (error) {\n const at = preload.leases.indexOf(lease)\n if (at >= 0) preload.leases.splice(at, 1)\n lease.release()\n return this.#failed(error, url)\n }\n }\n\n async #image(\n preload: PreloadImpl,\n source: Element,\n base: string,\n priority: Priority,\n ): Promise<void> {\n const { signal } = preload.abort\n let made: Copy | undefined\n try {\n made = copy(source, base, priority)\n } catch {\n return\n }\n if (!made) return\n const { img } = made\n const url = source.getAttribute('src') ?? source.getAttribute('srcset') ?? ''\n try {\n const free = await this.#host.slot(priority, signal)\n try {\n made.start()\n await loaded(img, url, signal)\n } finally {\n free()\n }\n } catch (error) {\n return this.#failed(error, url)\n }\n if (signal.aborted) return\n // The browser picked the candidate, so its URL is the key the page's <img> will have.\n const src = absolute(img.currentSrc || img.src)\n const key = keyOf('image', src, corsOf(img), {})\n const target = img\n const lease = this.#host.acquire(\n key,\n (context) => context.decode(() => bitmap(target, src)) as Promise<never>,\n priority,\n )\n return this.#hold(preload, lease, src)\n }\n\n #failed(error: unknown, url?: string): Promise<void> {\n // The page loads it itself, so only warn in development.\n if (DEV && !isAbort(error)) {\n const message =\n typeof error === 'string' ? error : `preload of ${url} failed: ${String(error)}`\n if (!this.#warned.has(message)) this.#host.warn(message)\n this.#warned.add(message)\n }\n return Promise.resolve()\n }\n}\n","// Load progress for `assets.progress`, `ready()` and `data-dio-progress` bars.\nimport { type ReadonlySignal, type Signal, signal } from '@dioramajs/core'\n\n/** Work in the wave, in bytes or an estimate. `loaded` never exceeds `total`. */\nexport interface Item {\n total: number\n loaded: number\n}\n\n/** Progress stops here until the wave is done. 1 means `ready()` resolved. */\nconst BEFORE_END = 0.99\n\n/**\n * The current wave of high and normal work. It starts when pending items appear, only grows,\n * and stays at 1 until the next wave starts from 0. Work of no weight (a decode the next frame\n * waits for) holds `ready()` but starts no wave of its own: the bar stays where it is.\n * `data-dio-progress` elements follow the first wave and the waves that start during a page\n * transition only: a texture loading as its section nears does not pull a bar back mid-scroll.\n */\nexport class Wave {\n readonly #progress: Signal<number> = signal(0)\n readonly progress: ReadonlySignal<number> = this.#progress\n readonly #pending = new Set<Item>()\n #done = 0\n /** The wave has weighed work, so progress moves. */\n #shown = false\n /** No weighed wave has ended yet: the page is still loading. */\n #first = true\n /** `data-dio-progress` elements follow this wave. */\n #bar = true\n #waiters: (() => void)[] = []\n #elements: HTMLElement[] = []\n readonly #find: () => HTMLElement[]\n\n constructor(find: () => HTMLElement[]) {\n this.#find = find\n this.#elements = find()\n this.#write()\n }\n\n add(item: Item): void {\n if (this.#pending.has(item)) return\n if (!this.#pending.size) {\n this.#done = 0\n this.#shown = false\n }\n this.#pending.add(item)\n if (!this.#shown && item.total > 0) {\n this.#shown = true\n this.#bar =\n this.#first ||\n (typeof document !== 'undefined' &&\n document.documentElement.hasAttribute('data-dio-transition'))\n if (this.#bar) this.#elements = this.#find()\n this.#set(0)\n }\n this.changed()\n }\n\n /** A page change: the bar follows the wave under way, or else the next one. */\n page(): void {\n this.#first = true\n if (!this.#shown || this.#bar || !this.#pending.size) return\n this.#bar = true\n this.#elements = this.#find()\n this.#write()\n }\n\n /** The item settled, failed or became low and left the wave. Counted as done. */\n done(item: Item): void {\n if (!this.#pending.delete(item)) return\n this.#done += item.total\n if (this.#pending.size) {\n this.changed()\n return\n }\n if (this.#shown || this.#progress.peek() < 1) this.#set(1)\n if (this.#shown) this.#first = false\n for (const resolve of this.#waiters.splice(0)) resolve()\n }\n\n changed(): void {\n if (!this.#pending.size || !this.#shown) return\n let loaded = this.#done\n let total = this.#done\n for (const item of this.#pending) {\n loaded += Math.min(item.loaded, item.total)\n total += item.total\n }\n const ratio = total > 0 ? Math.min(loaded / total, BEFORE_END) : 0\n if (ratio > this.#progress.peek()) this.#set(ratio)\n }\n\n ready(): Promise<void> {\n return this.#pending.size\n ? new Promise((resolve) => this.#waiters.push(resolve))\n : Promise.resolve()\n }\n\n /** Ends the wave and settles waiters. */\n close(): void {\n this.#pending.clear()\n for (const resolve of this.#waiters.splice(0)) resolve()\n }\n\n #set(value: number): void {\n this.#progress.value = value\n if (this.#bar) this.#write()\n }\n\n #write(): void {\n const value = String(this.#progress.peek())\n for (const el of this.#elements) el.style.setProperty('--dio-progress', value)\n }\n}\n","import {\n definePlugin,\n isCancel,\n type Off,\n type Plugin,\n type PluginApp,\n signal,\n} from '@dioramajs/core'\nimport type { RenderApi } from '@dioramajs/render'\nimport { Cache, ESTIMATE, type Make, type Spec } from './cache'\nimport { AssetError, DEV, linked, noop } from './errors'\nimport { absolute, BY_EXTENSION, extensionOf, keyOf, parseKey, textureCors } from './keys'\nimport { buffer, image, json } from './loaders'\nimport { frugal, Preloads } from './preload'\nimport { abortError, Queue } from './queue'\nimport type {\n Asset,\n AssetLoader,\n AssetStatus,\n AssetsApi,\n AssetsOptions,\n LoadOptions,\n Preload,\n} from './types'\nimport { Wave } from './wave'\n\ntype View = PluginApp<{ readonly render?: RenderApi }>\ntype ThreeModule = typeof import('./three/index')\n\nconst BUILT_IN: Readonly<Record<string, AssetLoader>> = { image, buffer, json }\nconst THREE_TYPES = ['texture', 'gltf', 'ktx2'] as const\n/** KTX2 waits for `render`. Show a development hint after this long. */\nconst RENDER_WAIT_MS = 5000\n\nconst defaults: AssetsOptions = {\n loaders: {},\n decoders: {},\n concurrency: 6,\n retain: 32 * 1024 * 1024,\n preload: true,\n}\n\nconst isThree = (type: string): type is (typeof THREE_TYPES)[number] =>\n (THREE_TYPES as readonly string[]).includes(type)\n\n/** A lease that failed before it began, for SSR or a URL that doesn't parse. */\nfunction failed<T>(url: string, error: AssetError): Asset<T> {\n linked(error)\n const ready = Promise.reject(error)\n ready.catch(noop)\n // A fresh function, since the handle carries its own key and url.\n const release = (): void => {}\n return Object.assign(release, {\n release,\n dispose: release,\n key: url,\n url,\n status: signal<AssetStatus>('failed'),\n ready,\n value: undefined,\n error,\n }) as unknown as Asset<T>\n}\n\nconst settled: Preload = Object.freeze({\n release: noop,\n dispose: noop,\n // biome-ignore lint/suspicious/noThenProperty: a preload is thenable by design\n then: (fulfilled, rejected) => Promise.resolve().then(fulfilled, rejected),\n} satisfies Preload)\n\n/** Without a DOM (SSR) loads fail silently and nothing waits. */\nfunction inert(): AssetsApi {\n const none = (url: string): Asset<never> =>\n failed(url, new AssetError('ASSET_LOAD', 'no DOM to load in', { url }))\n return {\n load: none,\n acquire: none,\n preload: () => settled,\n track: noop,\n pause: () => noop,\n progress: signal(0),\n ready: () => Promise.resolve(),\n stats: () => ({ entries: 0, used: 0, retained: 0, pending: 0 }),\n }\n}\n\n/** One cache, queue, wave and preloads per app. */\nclass Assets {\n readonly api: AssetsApi\n readonly #app: View\n readonly #options: AssetsOptions\n readonly #queue: Queue\n readonly #wave: Wave\n readonly #cache: Cache\n readonly #preloads: Preloads\n #three: Promise<ThreeModule> | undefined\n #module: ThreeModule | undefined\n #leave: Off | undefined\n #renderer: object | undefined\n #destroying = false\n\n constructor(app: View, options: AssetsOptions) {\n this.#app = app\n this.#options = options\n this.#queue = new Queue(options.concurrency)\n this.#wave = new Wave(() => [...document.querySelectorAll<HTMLElement>('[data-dio-progress]')])\n const decoders = { meshopt: true, workers: undefined, ...options.decoders }\n this.#cache = new Cache({\n queue: this.#queue,\n wave: this.#wave,\n retain: options.retain,\n decoders,\n report: (error, url) => app.report(error, `asset:${url}`),\n transform: (value, type, url) => {\n const result = app.callHook('assets:transform', value, { type, url })\n return isCancel(result) ? value : result\n },\n render: (abort) => this.#render(abort),\n load: (url, options) => this.#load(url, options, false),\n })\n this.#preloads = new Preloads({\n load: (url, options) => this.#load(url, options, false),\n acquire: (key, make, priority) => this.api.acquire(key, make, { priority }),\n has: (key) => this.#cache.has(key),\n slot: (priority, abort) => this.#queue.slot('request', () => priority, abort),\n typeOf: (url) => this.#typeOf(url),\n track: (work, priority) => this.api.track(work, { priority }),\n warn: (message) => app.log.warn(message),\n })\n if (options.preload && !frugal()) this.#preloads.listen(app.abortSignal)\n app.on('app:destroy', () => {\n this.#destroying = true\n })\n // Emitted by @dioramajs/transitions on every page change, explicit or auto.\n const events = app as unknown as { on(name: string, fn: () => void): void }\n events.on('page:leave', () => this.#wave.page())\n app.on('plugin:status', ({ name, status }) => {\n if (name !== 'render' || status !== 'stopping') return\n if (this.#renderer) this.#module?.forget(this.#renderer)\n this.#renderer = undefined\n this.#cache.rebind()\n })\n app.onDispose(() => {\n this.#preloads.close()\n this.#cache.close(this.#destroying)\n this.#leave?.()\n })\n\n const wave = this.#wave\n this.api = {\n load: (url: string, options?: LoadOptions) => this.#load(url, options ?? {}, true),\n acquire: (key, make, { priority, weight } = {}) =>\n this.#cache.get(\n {\n key,\n // `type url` keys (effects bitmaps) name their URL. Other keys are their own URL.\n ...parseKey(key),\n crossOrigin: '',\n options: {},\n make: () => make as Make,\n wrap: false,\n weight,\n },\n priority ?? 'normal',\n false,\n ),\n preload: (source, preload) => this.#preloads.preload(source, preload),\n track(work, { priority, weight } = {}) {\n if (priority === 'low') return\n const item = { total: weight ?? ESTIMATE, loaded: 0 }\n wave.add(item)\n const done = (): void => wave.done(item)\n Promise.resolve(work).then(done, done)\n },\n pause: () => this.#queue.pause(),\n progress: wave.progress,\n ready: () => wave.ready(),\n stats: () => this.#cache.stats(),\n } as AssetsApi\n }\n\n #load<T>(url: string, options: LoadOptions, report: boolean): Asset<T> {\n let href: string\n try {\n href = absolute(url)\n } catch (cause) {\n const error = linked(new AssetError('ASSET_LOAD', `${url} is not a URL`, { url, cause }))\n if (report) this.#app.report(error, `asset:${url}`)\n return failed(url, error)\n }\n const type = options.type ?? this.#typeOf(href)\n const name = type ?? '?'\n const crossOrigin =\n name === 'texture'\n ? textureCors(href, options.crossOrigin ?? '')\n : (options.crossOrigin ?? '')\n const params = options.options ?? {}\n const spec: Spec = {\n key: keyOf(name, href, crossOrigin, params),\n url: href,\n type: name,\n crossOrigin,\n options: params,\n make: () => this.#loader(type, href).then((loader) => (context) => loader.load(context)),\n wrap: true,\n }\n return this.#cache.get(spec, options.priority ?? 'normal', report, options.signal)\n }\n\n /** Own loaders' extensions first, then the built-in table. */\n #typeOf(url: string): string | undefined {\n const extension = extensionOf(url)\n if (!extension) return undefined\n for (const [type, entry] of Object.entries(this.#options.loaders)) {\n const extensions = typeof entry === 'function' ? undefined : entry.extensions\n if (extensions?.some((e) => e.replace(/^\\./, '').toLowerCase() === extension)) return type\n }\n return BY_EXTENSION[extension]\n }\n\n async #loader(type: string | undefined, url: string): Promise<AssetLoader> {\n const known = [\n ...new Set([...Object.keys(this.#options.loaders), ...Object.keys(BUILT_IN), ...THREE_TYPES]),\n ]\n if (type === undefined) {\n const message = `no type for ${url}: pass { type } (known: ${known.join(', ')}); a page address is not an asset`\n throw new AssetError('ASSET_TYPE', message, { url })\n }\n const own = this.#options.loaders[type]\n try {\n if (own) {\n const found = typeof own === 'function' ? await own() : own\n const loader = 'default' in found ? found.default : found\n if (typeof loader?.load === 'function') return loader\n } else if (BUILT_IN[type]) return BUILT_IN[type]\n else if (isThree(type)) return (await this.#import())[type] as AssetLoader\n } catch (cause) {\n throw new AssetError('ASSET_TYPE', `the loader of \"${type}\" did not load`, { url, cause })\n }\n throw new AssetError('ASSET_TYPE', `no loader for \"${type}\" (known: ${known.join(', ')})`, {\n url,\n })\n }\n\n /** The three loaders, once per app. The app joins the decoders shared by the page. */\n #import(): Promise<ThreeModule> {\n if (!this.#three) {\n const pending = import('./three/index').then((module) => {\n if (!this.#app.abortSignal.aborted && !this.#module) this.#leave = module.join()\n this.#module = module\n return module\n })\n this.#three = pending\n pending.catch(() => {\n if (this.#three === pending) this.#three = undefined\n })\n }\n return this.#three\n }\n\n #render(abort: AbortSignal): Promise<RenderApi> {\n const app = this.#app\n const found = app.find('render')\n if (found) {\n this.#renderer = found.renderer\n return Promise.resolve(found)\n }\n if (abort.aborted || app.abortSignal.aborted) return Promise.reject(abortError())\n return new Promise((resolve, reject) => {\n const timer = DEV\n ? setTimeout(() => app.log.warn('assets: a KTX2 load waits for render'), RENDER_WAIT_MS)\n : undefined\n const done = (): void => {\n off()\n clearTimeout(timer)\n abort.removeEventListener('abort', stop)\n }\n const stop = (): void => {\n done()\n reject(abortError())\n }\n const off = app.on('plugin:status', ({ name, status }) => {\n const render = name === 'render' && status === 'running' ? app.find('render') : undefined\n if (!render) return\n done()\n this.#renderer = render.renderer\n resolve(render)\n })\n abort.addEventListener('abort', stop, { once: true })\n })\n }\n}\n\n/**\n * `app.assets`. One cache with leases for media and models, a priority queue, preloading of\n * the next page and the progress wave of a preloader.\n */\nexport const assets: Plugin<'assets', AssetsOptions, AssetsApi> = /*#__PURE__*/ definePlugin<\n 'assets',\n AssetsOptions,\n typeof defaults,\n AssetsApi,\n [],\n ['render']\n>({\n name: 'assets',\n optionalDependencies: ['render'],\n defaults,\n setup(app, options): AssetsApi {\n return typeof document === 'undefined'\n ? inert()\n : new Assets(app as unknown as View, options).api\n },\n})\n"],"mappings":";;;;AAKA,MAAa,OAA2C;CAAE,KAAK;CAAG,QAAQ;CAAG,MAAM;AAAE;;AAErF,MAAM,UAAU;;AAEhB,MAAM,MAAM;AAWZ,MAAa,mBAAiC,IAAI,aAAa,WAAW,YAAY;;;;;AAMtF,IAAa,QAAb,MAAmB;CACjB;CACA,WAA8B,CAAC;CAC/B,UAAiD;EAAE,SAAS;EAAG,QAAQ;EAAG,KAAK;CAAE;CACjF,UAAU;CACV,OAAO;;CAEP,QAAQ;CAER,YAAY,aAAqB;EAC/B,KAAK,cAAc;CACrB;;CAGA,KAAK,MAAY,UAA0B,QAAmC;EAC5E,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,IAAI,OAAO,SAAS,OAAO,OAAO,WAAW,CAAC;GAC9C,MAAM,cAAoB;IACxB,MAAM,QAAQ,KAAK,SAAS,QAAQ,MAAM;IAC1C,IAAI,SAAS,GAAG,KAAK,SAAS,OAAO,OAAO,CAAC;IAC7C,OAAO,WAAW,CAAC;GACrB;GACA,MAAM,SAAiB;IACrB;IACA;IACA,KAAK,KAAK;IACV,aAAa;KACX,OAAO,oBAAoB,SAAS,KAAK;KACzC,MAAM,MAAM,SAAS,aAAa,SAAS,MAAM;KACjD,KAAK,QAAQ,KAAK;KAClB,IAAI,KAAK,KAAK,QAAQ;KACtB,IAAI,OAAO;KACX,cAAc;MACZ,IAAI,MAAM;MACV,OAAO;MACP,KAAK,QAAQ,KAAK;MAClB,IAAI,KAAK,KAAK,QAAQ;MACtB,KAAK,KAAK;KACZ,CAAC;IACH;GACF;GACA,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;GACtD,KAAK,SAAS,KAAK,MAAM;GACzB,KAAK,KAAK;EACZ,CAAC;CACH;CAEA,QAAa;EACX,KAAK;EACL,IAAI,OAAO;EACX,aAAa;GACX,IAA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IAAI,KAAK,WAAW,SAAS,KAAK,SAAS,KAAA;GAC7C,CAAC;EACH;EACA,OAAO,KAAK;CACd;CAEA,QAAQ,OAAwC;EAC9C,MAAM,MAAM,KAAK;EACjB,MAAM,QAAQ,IAAI,KAAK,QAAQ;EAC/B,IAAI,OAAO;GACT,KAAK,YAAY,MAAM;GACvB,OAAO,QAAQ,QAAQ,KAAK;EAC9B;EACA,IAAI,MAAM,WAAW,IAAI,YAAY,SAAS,OAAO,QAAQ,OAAO,WAAW,CAAC;EAChF,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,QAAQ,MACV,iBAAiB,IAAI,IAAI,KAAK,sCAAsC,GAAG,cAAc,IACrF,KAAA;GACJ,MAAM,aAAmB;IACvB,IAAI;IACJ,aAAa,KAAK;IAClB,MAAM,oBAAoB,SAAS,IAAI;GACzC;GACA,MAAM,aAAmB;IACvB,KAAK;IACL,OAAO,WAAW,CAAC;GACrB;GACA,MAAM,MAAM,IAAI,GAAG,kBAAkB,EAAE,MAAM,aAAa;IACxD,MAAM,SAAS,SAAS,YAAY,WAAW,YAAY,IAAI,KAAK,QAAQ,IAAI,KAAA;IAChF,IAAI,CAAC,QAAQ;IACb,KAAK;IACL,KAAK,YAAY,OAAO;IACxB,QAAQ,MAAM;GAChB,CAAC;GACD,MAAM,iBAAiB,SAAS,MAAM,EAAE,MAAM,KAAK,CAAC;EACtD,CAAC;CACH;AACF;;;;;AAMA,MAAa,SAAmE,2BAO9E;CACA,MAAM;CACN,sBAAsB,CAAC,QAAQ;CAC/B;CACA,MAAM,KAAK,SAAoB;EAC7B,OAAO,OAAO,aAAa,cACvB,MAAM,IACN,IAAI,OAAO,KAAwB,OAAO,CAAC,CAAC;CAClD;AACF,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { g as Model, i as AssetLoader } from "../errors-C0aoug0G.js";
|
|
2
|
+
import { Off } from "@dioramajs/core";
|
|
3
|
+
import { CompressedTexture, Texture } from "three/webgpu";
|
|
4
|
+
import "three/addons/loaders/DRACOLoader.js";
|
|
5
|
+
import "three/addons/loaders/KTX2Loader.js";
|
|
6
|
+
/** One per app that loads through this module. The last one out frees the decoders. */
|
|
7
|
+
export declare function join(): Off;
|
|
8
|
+
/** Drops the KTX2Loader of a stopped renderer, since it read that renderer's formats. */
|
|
9
|
+
export declare function forget(renderer: object): void;
|
|
10
|
+
/** glTF and GLB with the decoders their `extensionsUsed` name, loaded on demand. */
|
|
11
|
+
export declare const gltf: AssetLoader<Model>;
|
|
12
|
+
/**
|
|
13
|
+
* A KTX2 (Basis) texture, transcoded for the formats of the app's renderer, so it waits for
|
|
14
|
+
* `render`. Origin top-left like glTF, and `flipY` can't be set.
|
|
15
|
+
*/
|
|
16
|
+
export declare const ktx2: AssetLoader<CompressedTexture>;
|
|
17
|
+
/**
|
|
18
|
+
* A Texture over the pixels of the `image` entry with the same URL and CORS mode, which a
|
|
19
|
+
* preload or an effect may have decoded already. Origin bottom-left like effects textures.
|
|
20
|
+
* `options.colorSpace` is 'srgb' (default), 'linear' or 'none' for data maps.
|
|
21
|
+
*/
|
|
22
|
+
export declare const texture: AssetLoader<Texture>;
|
|
23
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/three/decoders.ts","../../src/three/gltf.ts","../../src/three/ktx2.ts","../../src/three/texture.ts"],"mappings":";;;;;;wBAkDgB,QAAQ;;wBAiBR,OAAO;;qBC0CV,MAAM,YAAY;;;;;qBCrGlB,MAAM,YAAY;;;;;;qBCSlB,SAAS,YAAY"}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { r as isAbort, t as AssetError } from "../errors-DgHytoOg.js";
|
|
2
|
+
import { LinearSRGBColorSpace, NoColorSpace, SRGBColorSpace, Texture } from "three/webgpu";
|
|
3
|
+
// src/three/decoders.ts
|
|
4
|
+
const DRACO$1 = "KHR_draco_mesh_compression";
|
|
5
|
+
const KTX2 = "KTX2 (KHR_texture_basisu)";
|
|
6
|
+
const CSP = "decoders run in blob: workers and WebAssembly: the Content Security Policy needs worker-src blob: and script-src 'wasm-unsafe-eval'";
|
|
7
|
+
/** A worker or WebAssembly refused, most likely by the CSP. */
|
|
8
|
+
const blocked = (cause) => cause?.name === "SecurityError" || /Content Security Policy|wasm-unsafe-eval|WebAssembly|Worker/i.test(String(cause));
|
|
9
|
+
const decoderError = (message, url, cause) => cause instanceof AssetError ? cause : new AssetError("ASSET_DECODER", blocked(cause) ? `${message}: ${CSP}` : message, {
|
|
10
|
+
url,
|
|
11
|
+
cause
|
|
12
|
+
});
|
|
13
|
+
const refused = (what, option, url) => new AssetError("ASSET_DECODER", `the file uses ${what} and decoders.${option} is false`, { url });
|
|
14
|
+
/** Aborts pass through, a refused decoder worker is ASSET_DECODER, the rest ASSET_PARSE. */
|
|
15
|
+
function parseError(cause, context, decoders) {
|
|
16
|
+
if (context.signal.aborted || isAbort(cause) || cause instanceof AssetError) return cause;
|
|
17
|
+
if (decoders && blocked(cause)) return decoderError("a decoder failed", context.url, cause);
|
|
18
|
+
return new AssetError("ASSET_PARSE", `cannot parse ${context.url}`, {
|
|
19
|
+
url: context.url,
|
|
20
|
+
cause
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
let apps = 0;
|
|
24
|
+
let draco;
|
|
25
|
+
let meshopt;
|
|
26
|
+
let meshoptWorkers = false;
|
|
27
|
+
const ktx2$1 = /* @__PURE__ */ new Map();
|
|
28
|
+
let probe;
|
|
29
|
+
/** One per app that loads through this module. The last one out frees the decoders. */
|
|
30
|
+
function join() {
|
|
31
|
+
apps++;
|
|
32
|
+
let done = false;
|
|
33
|
+
return () => {
|
|
34
|
+
if (done) return;
|
|
35
|
+
done = true;
|
|
36
|
+
if (--apps > 0) return;
|
|
37
|
+
const workers = meshoptWorkers;
|
|
38
|
+
draco?.then((loader) => loader.dispose(), noop);
|
|
39
|
+
meshopt?.then((decoder) => workers && decoder.useWorkers(0), noop);
|
|
40
|
+
for (const renderer of [...ktx2$1.keys()]) forget(renderer);
|
|
41
|
+
draco = meshopt = probe = void 0;
|
|
42
|
+
meshoptWorkers = false;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Drops the KTX2Loader of a stopped renderer, since it read that renderer's formats. */
|
|
46
|
+
function forget(renderer) {
|
|
47
|
+
const pending = ktx2$1.get(renderer);
|
|
48
|
+
ktx2$1.delete(renderer);
|
|
49
|
+
pending?.then((loader) => loader.dispose(), noop);
|
|
50
|
+
}
|
|
51
|
+
const noop = () => {};
|
|
52
|
+
/**
|
|
53
|
+
* three's decoders run in blob: workers. A worker refused by the CSP doesn't throw in Chrome, it
|
|
54
|
+
* fires `error`, and DRACOLoader and KTX2Loader would wait for its answer forever. Probe first
|
|
55
|
+
* with an empty worker that compiles an empty WebAssembly module, as theirs do.
|
|
56
|
+
*/
|
|
57
|
+
function workers() {
|
|
58
|
+
if (typeof Worker === "undefined") return Promise.resolve();
|
|
59
|
+
probe ??= new Promise((resolve, reject) => {
|
|
60
|
+
const url = URL.createObjectURL(new Blob(["WebAssembly.compile(new Uint8Array([0,97,115,109,1,0,0,0])).then(()=>postMessage(\"\"),e=>postMessage(String(e)))"]));
|
|
61
|
+
let worker;
|
|
62
|
+
const done = (error) => {
|
|
63
|
+
worker?.terminate();
|
|
64
|
+
URL.revokeObjectURL(url);
|
|
65
|
+
if (error) reject(new Error(error));
|
|
66
|
+
else resolve();
|
|
67
|
+
};
|
|
68
|
+
try {
|
|
69
|
+
worker = new Worker(url);
|
|
70
|
+
worker.onmessage = (event) => done(event.data);
|
|
71
|
+
worker.onerror = () => done("a blob: Worker was refused");
|
|
72
|
+
} catch (cause) {
|
|
73
|
+
done(String(cause));
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
return probe;
|
|
77
|
+
}
|
|
78
|
+
/** Keeps a decoder promise for reuse unless it failed, so the next file tries again. */
|
|
79
|
+
function shared(pending, clear) {
|
|
80
|
+
pending.catch(clear);
|
|
81
|
+
return pending;
|
|
82
|
+
}
|
|
83
|
+
function dracoLoader(options, url) {
|
|
84
|
+
const path = options.draco;
|
|
85
|
+
if (path === false) return Promise.reject(refused(DRACO$1, "draco", url));
|
|
86
|
+
if (!draco) {
|
|
87
|
+
const pending = (async () => {
|
|
88
|
+
const [{ DRACOLoader, DRACO_GLTF_CONFIG }] = await Promise.all([import("three/addons/loaders/DRACOLoader.js"), workers()]);
|
|
89
|
+
const loader = new DRACOLoader().setDecoderPath(path ?? DRACO_GLTF_CONFIG);
|
|
90
|
+
if (options.workers) loader.setWorkerLimit(options.workers);
|
|
91
|
+
await loader.preload().decoderPending;
|
|
92
|
+
return loader;
|
|
93
|
+
})();
|
|
94
|
+
draco = shared(pending, () => {
|
|
95
|
+
if (draco === pending) draco = void 0;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const where = typeof path === "object" ? path.js : path ?? "three/examples/jsm/libs/draco/gltf/";
|
|
99
|
+
return draco.catch((cause) => {
|
|
100
|
+
throw decoderError(`the Draco decoder did not load from ${where}`, url, cause);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function meshoptDecoder(options, url) {
|
|
104
|
+
if (options.meshopt === false) return Promise.reject(refused("meshopt compression", "meshopt", url));
|
|
105
|
+
if (!meshopt) {
|
|
106
|
+
const pending = (async () => {
|
|
107
|
+
const { MeshoptDecoder } = await import("three/addons/libs/meshopt_decoder.module.js");
|
|
108
|
+
if (!MeshoptDecoder.supported) throw new AssetError("ASSET_DECODER", "meshopt decoding needs WebAssembly", { url });
|
|
109
|
+
await MeshoptDecoder.ready;
|
|
110
|
+
if (options.workers) {
|
|
111
|
+
await workers();
|
|
112
|
+
MeshoptDecoder.useWorkers(options.workers);
|
|
113
|
+
meshoptWorkers = true;
|
|
114
|
+
}
|
|
115
|
+
return MeshoptDecoder;
|
|
116
|
+
})();
|
|
117
|
+
meshopt = shared(pending, () => {
|
|
118
|
+
if (meshopt === pending) meshopt = void 0;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return meshopt.catch((cause) => {
|
|
122
|
+
throw decoderError("the meshopt decoder did not start", url, cause);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/** One per renderer, after its init, since detectSupport reads the renderer's features. */
|
|
126
|
+
function ktx2Loader(renderer, options, url) {
|
|
127
|
+
const path = options.ktx2;
|
|
128
|
+
if (path === false) return Promise.reject(refused(KTX2, "ktx2", url));
|
|
129
|
+
let pending = ktx2$1.get(renderer);
|
|
130
|
+
if (!pending) {
|
|
131
|
+
const created = (async () => {
|
|
132
|
+
const [{ KTX2Loader }] = await Promise.all([import("three/addons/loaders/KTX2Loader.js"), workers()]);
|
|
133
|
+
const loader = new KTX2Loader();
|
|
134
|
+
if (path) loader.setTranscoderPath(path);
|
|
135
|
+
if (options.workers) loader.setWorkerLimit(options.workers);
|
|
136
|
+
loader.detectSupport(renderer);
|
|
137
|
+
try {
|
|
138
|
+
await loader.init();
|
|
139
|
+
} catch (cause) {
|
|
140
|
+
loader.dispose();
|
|
141
|
+
throw cause;
|
|
142
|
+
}
|
|
143
|
+
return loader;
|
|
144
|
+
})();
|
|
145
|
+
pending = shared(created, () => {
|
|
146
|
+
if (ktx2$1.get(renderer) === created) ktx2$1.delete(renderer);
|
|
147
|
+
});
|
|
148
|
+
ktx2$1.set(renderer, pending);
|
|
149
|
+
}
|
|
150
|
+
const where = path || "three/examples/jsm/libs/basis/";
|
|
151
|
+
return pending.catch((cause) => {
|
|
152
|
+
throw decoderError(`the Basis transcoder did not load from ${where}`, url, cause);
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
// src/three/texture.ts
|
|
156
|
+
const COLOR_SPACES = {
|
|
157
|
+
linear: LinearSRGBColorSpace,
|
|
158
|
+
none: NoColorSpace
|
|
159
|
+
};
|
|
160
|
+
/** GPU bytes of an RGBA8 texture. Mipmaps add a third. */
|
|
161
|
+
const rgbaBytes = ({ width = 0, height = 0 }) => Math.round(width * height * 16 / 3);
|
|
162
|
+
/**
|
|
163
|
+
* A Texture over the pixels of the `image` entry with the same URL and CORS mode, which a
|
|
164
|
+
* preload or an effect may have decoded already. Origin bottom-left like effects textures.
|
|
165
|
+
* `options.colorSpace` is 'srgb' (default), 'linear' or 'none' for data maps.
|
|
166
|
+
*/
|
|
167
|
+
const texture = { async load(context) {
|
|
168
|
+
const { crossOrigin, priority } = context;
|
|
169
|
+
const pixels = context.load(context.url, {
|
|
170
|
+
type: "image",
|
|
171
|
+
crossOrigin,
|
|
172
|
+
priority
|
|
173
|
+
});
|
|
174
|
+
let bitmap;
|
|
175
|
+
try {
|
|
176
|
+
bitmap = await pixels.ready;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
pixels.release();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
const value = new Texture(bitmap);
|
|
182
|
+
value.flipY = false;
|
|
183
|
+
value.colorSpace = COLOR_SPACES[String(context.options.colorSpace)] ?? SRGBColorSpace;
|
|
184
|
+
value.needsUpdate = true;
|
|
185
|
+
value.userData.keep = true;
|
|
186
|
+
return {
|
|
187
|
+
value,
|
|
188
|
+
bytes: rgbaBytes(bitmap),
|
|
189
|
+
dispose() {
|
|
190
|
+
value.dispose();
|
|
191
|
+
pixels.release();
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
} };
|
|
195
|
+
// src/three/gltf.ts
|
|
196
|
+
const GLB = 1179937895;
|
|
197
|
+
const JSON_CHUNK = 1313821514;
|
|
198
|
+
const DRACO = "KHR_draco_mesh_compression";
|
|
199
|
+
const MESHOPT = ["EXT_meshopt_compression", "KHR_meshopt_compression"];
|
|
200
|
+
const BASISU = "KHR_texture_basisu";
|
|
201
|
+
/**
|
|
202
|
+
* The extensions a file uses, from the JSON chunk of a GLB or the .gltf text. Reads
|
|
203
|
+
* `extensionsUsed`, not only the required ones, or an optional one would fall back silently.
|
|
204
|
+
*/
|
|
205
|
+
function extensionsUsed(buffer) {
|
|
206
|
+
const view = new DataView(buffer);
|
|
207
|
+
let text = new Uint8Array(buffer);
|
|
208
|
+
if (buffer.byteLength >= 20 && view.getUint32(0, true) === GLB) {
|
|
209
|
+
if (view.getUint32(16, true) !== JSON_CHUNK) throw new Error("the GLB has no JSON chunk");
|
|
210
|
+
text = new Uint8Array(buffer, 20, view.getUint32(12, true));
|
|
211
|
+
}
|
|
212
|
+
const json = JSON.parse(new TextDecoder().decode(text));
|
|
213
|
+
return /* @__PURE__ */ new Set([...json.extensionsUsed ?? [], ...json.extensionsRequired ?? []]);
|
|
214
|
+
}
|
|
215
|
+
function resources(root) {
|
|
216
|
+
const found = {
|
|
217
|
+
geometries: /* @__PURE__ */ new Set(),
|
|
218
|
+
materials: /* @__PURE__ */ new Set(),
|
|
219
|
+
textures: /* @__PURE__ */ new Set()
|
|
220
|
+
};
|
|
221
|
+
root.traverse((object) => {
|
|
222
|
+
const { geometry, material } = object;
|
|
223
|
+
if (geometry) found.geometries.add(geometry);
|
|
224
|
+
for (const each of [material ?? []].flat()) {
|
|
225
|
+
found.materials.add(each);
|
|
226
|
+
for (const value of Object.values(each)) if (value?.isTexture) found.textures.add(value);
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
return found;
|
|
230
|
+
}
|
|
231
|
+
const geometryBytes = (geometry) => [...Object.values(geometry.attributes), geometry.index].reduce((sum, attribute) => sum + ((attribute?.array)?.byteLength ?? 0), 0);
|
|
232
|
+
function textureBytes(texture) {
|
|
233
|
+
const compressed = texture;
|
|
234
|
+
if (compressed.isCompressedTexture) return compressed.mipmaps.reduce((sum, level) => sum + (level.data?.byteLength ?? 0), 0);
|
|
235
|
+
return rgbaBytes(texture.image ?? {});
|
|
236
|
+
}
|
|
237
|
+
/** Shared resources are marked `userData.keep`, effects get clones. */
|
|
238
|
+
function model(gltf, cloneSkinned) {
|
|
239
|
+
const { scene, animations } = gltf;
|
|
240
|
+
const found = resources(scene);
|
|
241
|
+
for (const set of [
|
|
242
|
+
found.geometries,
|
|
243
|
+
found.materials,
|
|
244
|
+
found.textures
|
|
245
|
+
]) for (const resource of set) resource.userData.keep = true;
|
|
246
|
+
let skinned = false;
|
|
247
|
+
scene.traverse((object) => {
|
|
248
|
+
if (object.isSkinnedMesh) skinned = true;
|
|
249
|
+
});
|
|
250
|
+
const textures = [...found.textures];
|
|
251
|
+
return {
|
|
252
|
+
value: {
|
|
253
|
+
scene,
|
|
254
|
+
animations,
|
|
255
|
+
instance: () => skinned ? cloneSkinned(scene) : scene.clone()
|
|
256
|
+
},
|
|
257
|
+
bytes: [...found.geometries].reduce((sum, g) => sum + geometryBytes(g), 0) + textures.reduce((sum, t) => sum + textureBytes(t), 0),
|
|
258
|
+
renderBound: textures.some((t) => t.isCompressedTexture),
|
|
259
|
+
dispose() {
|
|
260
|
+
scene.traverse((object) => object.dispose());
|
|
261
|
+
for (const geometry of found.geometries) geometry.dispose();
|
|
262
|
+
for (const material of found.materials) material.dispose();
|
|
263
|
+
for (const texture of textures) {
|
|
264
|
+
texture.dispose();
|
|
265
|
+
texture.image?.close?.();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
/** glTF and GLB with the decoders their `extensionsUsed` name, loaded on demand. */
|
|
271
|
+
const gltf = { async load(context) {
|
|
272
|
+
const { url } = context;
|
|
273
|
+
const [{ GLTFLoader }, { clone }, buffer] = await Promise.all([
|
|
274
|
+
import("three/addons/loaders/GLTFLoader.js"),
|
|
275
|
+
import("three/addons/utils/SkeletonUtils.js"),
|
|
276
|
+
context.fetch().then((response) => context.bytes(response))
|
|
277
|
+
]);
|
|
278
|
+
let used;
|
|
279
|
+
try {
|
|
280
|
+
used = extensionsUsed(buffer);
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
throw new AssetError("ASSET_PARSE", `${url} is not glTF`, {
|
|
283
|
+
url,
|
|
284
|
+
cause
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const loader = new GLTFLoader();
|
|
288
|
+
if (context.crossOrigin === "use-credentials") loader.setCrossOrigin("use-credentials").setWithCredentials(true);
|
|
289
|
+
loader.setPriority(context.priority === "normal" ? "auto" : context.priority);
|
|
290
|
+
const { decoders } = context;
|
|
291
|
+
const meshopt = MESHOPT.some((name) => used.has(name));
|
|
292
|
+
if (used.has(DRACO)) loader.setDRACOLoader(await dracoLoader(decoders, url));
|
|
293
|
+
if (meshopt) loader.setMeshoptDecoder(await meshoptDecoder(decoders, url));
|
|
294
|
+
if (used.has(BASISU)) {
|
|
295
|
+
if (decoders.ktx2 === false) throw refused(KTX2, "ktx2", url);
|
|
296
|
+
const { renderer } = await context.render();
|
|
297
|
+
loader.setKTX2Loader(await ktx2Loader(renderer, decoders, url));
|
|
298
|
+
}
|
|
299
|
+
const base = url.slice(0, url.lastIndexOf("/") + 1);
|
|
300
|
+
try {
|
|
301
|
+
return model(await context.decode(() => loader.parseAsync(buffer, base)), clone);
|
|
302
|
+
} catch (cause) {
|
|
303
|
+
throw parseError(cause, context, meshopt || used.has(DRACO) || used.has(BASISU));
|
|
304
|
+
}
|
|
305
|
+
} };
|
|
306
|
+
// src/three/ktx2.ts
|
|
307
|
+
/**
|
|
308
|
+
* A KTX2 (Basis) texture, transcoded for the formats of the app's renderer, so it waits for
|
|
309
|
+
* `render`. Origin top-left like glTF, and `flipY` can't be set.
|
|
310
|
+
*/
|
|
311
|
+
const ktx2 = { async load(context) {
|
|
312
|
+
if (context.decoders.ktx2 === false) throw refused(KTX2, "ktx2", context.url);
|
|
313
|
+
const buffer = await context.bytes(await context.fetch());
|
|
314
|
+
const { renderer } = await context.render();
|
|
315
|
+
const loader = await ktx2Loader(renderer, context.decoders, context.url);
|
|
316
|
+
let value;
|
|
317
|
+
try {
|
|
318
|
+
value = await context.decode(() => new Promise((resolve, reject) => loader.parse(buffer, resolve, reject)));
|
|
319
|
+
} catch (cause) {
|
|
320
|
+
throw parseError(cause, context, true);
|
|
321
|
+
}
|
|
322
|
+
value.userData.keep = true;
|
|
323
|
+
return {
|
|
324
|
+
value,
|
|
325
|
+
bytes: buffer.byteLength,
|
|
326
|
+
renderBound: true,
|
|
327
|
+
dispose: () => value.dispose()
|
|
328
|
+
};
|
|
329
|
+
} };
|
|
330
|
+
export { forget, gltf, join, ktx2, texture };
|
|
331
|
+
|
|
332
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["DRACO","ktx2"],"sources":["../../src/three/decoders.ts","../../src/three/texture.ts","../../src/three/gltf.ts","../../src/three/ktx2.ts"],"sourcesContent":["import type { Off } from '@dioramajs/core'\nimport type { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'\nimport type { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js'\nimport type { WebGPURenderer } from 'three/webgpu'\nimport { AssetError, isAbort } from '../errors'\nimport type { DecoderOptions, LoaderContext } from '../types'\n\ntype Meshopt = typeof import('three/addons/libs/meshopt_decoder.module.js').MeshoptDecoder\ntype Options = Readonly<Partial<DecoderOptions>>\n\nconst DRACO = 'KHR_draco_mesh_compression'\nexport const KTX2 = 'KTX2 (KHR_texture_basisu)'\n\nconst CSP =\n \"decoders run in blob: workers and WebAssembly: the Content Security Policy needs worker-src blob: and script-src 'wasm-unsafe-eval'\"\n\n/** A worker or WebAssembly refused, most likely by the CSP. */\nconst blocked = (cause: unknown): boolean =>\n (cause as { name?: string } | null)?.name === 'SecurityError' ||\n /Content Security Policy|wasm-unsafe-eval|WebAssembly|Worker/i.test(String(cause))\n\nconst decoderError = (message: string, url: string, cause?: unknown): AssetError =>\n cause instanceof AssetError\n ? cause\n : new AssetError('ASSET_DECODER', blocked(cause) ? `${message}: ${CSP}` : message, {\n url,\n cause,\n })\n\nexport const refused = (what: string, option: keyof DecoderOptions, url: string): AssetError =>\n new AssetError('ASSET_DECODER', `the file uses ${what} and decoders.${option} is false`, { url })\n\n/** Aborts pass through, a refused decoder worker is ASSET_DECODER, the rest ASSET_PARSE. */\nexport function parseError(cause: unknown, context: LoaderContext, decoders: boolean): unknown {\n if (context.signal.aborted || isAbort(cause) || cause instanceof AssetError) return cause\n if (decoders && blocked(cause)) return decoderError('a decoder failed', context.url, cause)\n return new AssetError('ASSET_PARSE', `cannot parse ${context.url}`, { url: context.url, cause })\n}\n\n// Shared by every app of the page. three's MeshoptDecoder is a module singleton with global\n// workers, and a second active KTX2Loader warns. Created on first need and freed after the last\n// app. `workers` comes from the app that created the decoder.\nlet apps = 0\nlet draco: Promise<DRACOLoader> | undefined\nlet meshopt: Promise<Meshopt> | undefined\nlet meshoptWorkers = false\nconst ktx2 = new Map<object, Promise<KTX2Loader>>()\nlet probe: Promise<void> | undefined\n\n/** One per app that loads through this module. The last one out frees the decoders. */\nexport function join(): Off {\n apps++\n let done = false\n return () => {\n if (done) return\n done = true\n if (--apps > 0) return\n const workers = meshoptWorkers\n void draco?.then((loader) => loader.dispose(), noop)\n void meshopt?.then((decoder) => workers && decoder.useWorkers(0), noop)\n for (const renderer of [...ktx2.keys()]) forget(renderer)\n draco = meshopt = probe = undefined\n meshoptWorkers = false\n }\n}\n\n/** Drops the KTX2Loader of a stopped renderer, since it read that renderer's formats. */\nexport function forget(renderer: object): void {\n const pending = ktx2.get(renderer)\n ktx2.delete(renderer)\n void pending?.then((loader) => loader.dispose(), noop)\n}\n\n// Local copy. Importing it from ../errors adds a binding across the lazy chunk boundary.\nconst noop = (): void => {}\n\n/**\n * three's decoders run in blob: workers. A worker refused by the CSP doesn't throw in Chrome, it\n * fires `error`, and DRACOLoader and KTX2Loader would wait for its answer forever. Probe first\n * with an empty worker that compiles an empty WebAssembly module, as theirs do.\n */\nfunction workers(): Promise<void> {\n if (typeof Worker === 'undefined') return Promise.resolve()\n probe ??= new Promise<void>((resolve, reject) => {\n const url = URL.createObjectURL(\n new Blob([\n 'WebAssembly.compile(new Uint8Array([0,97,115,109,1,0,0,0])).then(()=>postMessage(\"\"),e=>postMessage(String(e)))',\n ]),\n )\n let worker: Worker | undefined\n const done = (error?: string): void => {\n worker?.terminate()\n URL.revokeObjectURL(url)\n if (error) reject(new Error(error))\n else resolve()\n }\n try {\n worker = new Worker(url)\n worker.onmessage = (event) => done(event.data)\n worker.onerror = () => done('a blob: Worker was refused')\n } catch (cause) {\n done(String(cause))\n }\n })\n return probe\n}\n\n/** Keeps a decoder promise for reuse unless it failed, so the next file tries again. */\nfunction shared<T>(pending: Promise<T>, clear: () => void): Promise<T> {\n pending.catch(clear)\n return pending\n}\n\nexport function dracoLoader(options: Options, url: string): Promise<DRACOLoader> {\n const path = options.draco\n if (path === false) return Promise.reject(refused(DRACO, 'draco', url))\n if (!draco) {\n const pending = (async () => {\n const [{ DRACOLoader, DRACO_GLTF_CONFIG }] = await Promise.all([\n import('three/addons/loaders/DRACOLoader.js'),\n workers(),\n ])\n const loader = new DRACOLoader().setDecoderPath(path ?? DRACO_GLTF_CONFIG)\n if (options.workers) loader.setWorkerLimit(options.workers)\n // three keeps the decoder files' promise on the loader after preload().\n await (loader.preload() as unknown as { decoderPending: Promise<void> }).decoderPending\n return loader\n })()\n draco = shared(pending, () => {\n if (draco === pending) draco = undefined\n })\n }\n const where = typeof path === 'object' ? path.js : (path ?? 'three/examples/jsm/libs/draco/gltf/')\n return draco.catch((cause: unknown) => {\n throw decoderError(`the Draco decoder did not load from ${where}`, url, cause)\n })\n}\n\nexport function meshoptDecoder(options: Options, url: string): Promise<Meshopt> {\n if (options.meshopt === false)\n return Promise.reject(refused('meshopt compression', 'meshopt', url))\n if (!meshopt) {\n const pending = (async () => {\n const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js')\n if (!MeshoptDecoder.supported) {\n throw new AssetError('ASSET_DECODER', 'meshopt decoding needs WebAssembly', { url })\n }\n await MeshoptDecoder.ready\n if (options.workers) {\n await workers()\n MeshoptDecoder.useWorkers(options.workers)\n meshoptWorkers = true\n }\n return MeshoptDecoder\n })()\n meshopt = shared(pending, () => {\n if (meshopt === pending) meshopt = undefined\n })\n }\n return meshopt.catch((cause: unknown) => {\n throw decoderError('the meshopt decoder did not start', url, cause)\n })\n}\n\n/** One per renderer, after its init, since detectSupport reads the renderer's features. */\nexport function ktx2Loader(renderer: object, options: Options, url: string): Promise<KTX2Loader> {\n const path = options.ktx2\n if (path === false) return Promise.reject(refused(KTX2, 'ktx2', url))\n let pending = ktx2.get(renderer)\n if (!pending) {\n const created = (async () => {\n const [{ KTX2Loader }] = await Promise.all([\n import('three/addons/loaders/KTX2Loader.js'),\n workers(),\n ])\n const loader = new KTX2Loader()\n if (path) loader.setTranscoderPath(path)\n if (options.workers) loader.setWorkerLimit(options.workers)\n loader.detectSupport(renderer as WebGPURenderer)\n try {\n await loader.init()\n } catch (cause) {\n loader.dispose()\n throw cause\n }\n return loader\n })()\n pending = shared(created, () => {\n if (ktx2.get(renderer) === created) ktx2.delete(renderer)\n })\n ktx2.set(renderer, pending)\n }\n const where = path || 'three/examples/jsm/libs/basis/'\n return pending.catch((cause: unknown) => {\n throw decoderError(`the Basis transcoder did not load from ${where}`, url, cause)\n })\n}\n","import { LinearSRGBColorSpace, NoColorSpace, SRGBColorSpace, Texture } from 'three/webgpu'\nimport type { AssetLoader } from '../types'\n\nconst COLOR_SPACES: Readonly<Record<string, string>> = {\n linear: LinearSRGBColorSpace,\n none: NoColorSpace,\n}\n\n/** GPU bytes of an RGBA8 texture. Mipmaps add a third. */\nexport const rgbaBytes = ({ width = 0, height = 0 }: { width?: number; height?: number }): number =>\n Math.round((width * height * 16) / 3)\n\n/**\n * A Texture over the pixels of the `image` entry with the same URL and CORS mode, which a\n * preload or an effect may have decoded already. Origin bottom-left like effects textures.\n * `options.colorSpace` is 'srgb' (default), 'linear' or 'none' for data maps.\n */\nexport const texture: AssetLoader<Texture> = {\n async load(context) {\n const { crossOrigin, priority } = context\n const pixels = context.load<ImageBitmap>(context.url, { type: 'image', crossOrigin, priority })\n let bitmap: ImageBitmap\n try {\n bitmap = await pixels.ready\n } catch (error) {\n pixels.release()\n throw error\n }\n const value = new Texture(bitmap)\n // Decoded flipped already, so both backends upload it as is.\n value.flipY = false\n value.colorSpace = COLOR_SPACES[String(context.options.colorSpace)] ?? SRGBColorSpace\n value.needsUpdate = true\n value.userData.keep = true\n return {\n value,\n bytes: rgbaBytes(bitmap),\n dispose() {\n value.dispose()\n pixels.release()\n },\n }\n },\n}\n","import type { GLTF } from 'three/addons/loaders/GLTFLoader.js'\nimport type {\n BufferGeometry,\n CompressedTexture,\n Material,\n Mesh,\n Object3D,\n SkinnedMesh,\n Texture,\n} from 'three/webgpu'\nimport { AssetError } from '../errors'\nimport type { AssetLoader, Loaded, Model } from '../types'\nimport { dracoLoader, KTX2, ktx2Loader, meshoptDecoder, parseError, refused } from './decoders'\nimport { rgbaBytes } from './texture'\n\nconst GLB = 0x46546c67\nconst JSON_CHUNK = 0x4e4f534a\nconst DRACO = 'KHR_draco_mesh_compression'\nconst MESHOPT = ['EXT_meshopt_compression', 'KHR_meshopt_compression']\nconst BASISU = 'KHR_texture_basisu'\n\n/**\n * The extensions a file uses, from the JSON chunk of a GLB or the .gltf text. Reads\n * `extensionsUsed`, not only the required ones, or an optional one would fall back silently.\n */\nexport function extensionsUsed(buffer: ArrayBuffer): Set<string> {\n const view = new DataView(buffer)\n let text = new Uint8Array(buffer)\n if (buffer.byteLength >= 20 && view.getUint32(0, true) === GLB) {\n if (view.getUint32(16, true) !== JSON_CHUNK) throw new Error('the GLB has no JSON chunk')\n text = new Uint8Array(buffer, 20, view.getUint32(12, true))\n }\n const json = JSON.parse(new TextDecoder().decode(text)) as {\n extensionsUsed?: string[]\n extensionsRequired?: string[]\n }\n return new Set([...(json.extensionsUsed ?? []), ...(json.extensionsRequired ?? [])])\n}\n\ninterface Resources {\n readonly geometries: Set<BufferGeometry>\n readonly materials: Set<Material>\n readonly textures: Set<Texture>\n}\n\nfunction resources(root: Object3D): Resources {\n const found: Resources = { geometries: new Set(), materials: new Set(), textures: new Set() }\n root.traverse((object) => {\n const { geometry, material } = object as Mesh\n if (geometry) found.geometries.add(geometry)\n for (const each of [material ?? []].flat() as Material[]) {\n found.materials.add(each)\n for (const value of Object.values(each)) {\n if ((value as Texture | null)?.isTexture) found.textures.add(value)\n }\n }\n })\n return found\n}\n\nconst geometryBytes = (geometry: BufferGeometry): number =>\n [...Object.values(geometry.attributes), geometry.index].reduce(\n (sum, attribute) => sum + ((attribute?.array as ArrayBufferView | undefined)?.byteLength ?? 0),\n 0,\n )\n\nfunction textureBytes(texture: Texture): number {\n const compressed = texture as CompressedTexture\n if (compressed.isCompressedTexture) {\n return compressed.mipmaps.reduce((sum, level) => sum + (level.data?.byteLength ?? 0), 0)\n }\n return rgbaBytes(texture.image ?? {})\n}\n\n/** Shared resources are marked `userData.keep`, effects get clones. */\nfunction model(gltf: GLTF, cloneSkinned: (root: Object3D) => Object3D): Loaded<Model> {\n const { scene, animations } = gltf\n const found = resources(scene)\n for (const set of [found.geometries, found.materials, found.textures]) {\n for (const resource of set) resource.userData.keep = true\n }\n let skinned = false\n scene.traverse((object) => {\n if ((object as SkinnedMesh).isSkinnedMesh) skinned = true\n })\n const textures = [...found.textures]\n return {\n value: {\n scene,\n animations,\n instance: () => (skinned ? cloneSkinned(scene) : scene.clone()),\n },\n bytes:\n [...found.geometries].reduce((sum, g) => sum + geometryBytes(g), 0) +\n textures.reduce((sum, t) => sum + textureBytes(t), 0),\n renderBound: textures.some((t) => (t as CompressedTexture).isCompressedTexture),\n dispose() {\n scene.traverse((object) => object.dispose())\n for (const geometry of found.geometries) geometry.dispose()\n for (const material of found.materials) material.dispose()\n for (const texture of textures) {\n texture.dispose()\n ;(texture.image as { close?: () => void } | null)?.close?.()\n }\n },\n }\n}\n\n/** glTF and GLB with the decoders their `extensionsUsed` name, loaded on demand. */\nexport const gltf: AssetLoader<Model> = {\n async load(context) {\n const { url } = context\n const [{ GLTFLoader }, { clone }, buffer] = await Promise.all([\n import('three/addons/loaders/GLTFLoader.js'),\n import('three/addons/utils/SkeletonUtils.js'),\n context.fetch().then((response) => context.bytes(response)),\n ])\n let used: Set<string>\n try {\n used = extensionsUsed(buffer)\n } catch (cause) {\n throw new AssetError('ASSET_PARSE', `${url} is not glTF`, { url, cause })\n }\n const loader = new GLTFLoader()\n if (context.crossOrigin === 'use-credentials') {\n loader.setCrossOrigin('use-credentials').setWithCredentials(true)\n }\n loader.setPriority(context.priority === 'normal' ? 'auto' : context.priority)\n const { decoders } = context\n const meshopt = MESHOPT.some((name) => used.has(name))\n if (used.has(DRACO)) loader.setDRACOLoader(await dracoLoader(decoders, url))\n if (meshopt) loader.setMeshoptDecoder(await meshoptDecoder(decoders, url))\n if (used.has(BASISU)) {\n // Refused before waiting for a render that may never come.\n if (decoders.ktx2 === false) throw refused(KTX2, 'ktx2', url)\n const { renderer } = await context.render()\n loader.setKTX2Loader(await ktx2Loader(renderer, decoders, url))\n }\n const base = url.slice(0, url.lastIndexOf('/') + 1)\n try {\n return model(await context.decode(() => loader.parseAsync(buffer, base)), clone)\n } catch (cause) {\n throw parseError(cause, context, meshopt || used.has(DRACO) || used.has(BASISU))\n }\n },\n}\n","import type { CompressedTexture } from 'three/webgpu'\nimport type { AssetLoader } from '../types'\nimport { KTX2, ktx2Loader, parseError, refused } from './decoders'\n\n/**\n * A KTX2 (Basis) texture, transcoded for the formats of the app's renderer, so it waits for\n * `render`. Origin top-left like glTF, and `flipY` can't be set.\n */\nexport const ktx2: AssetLoader<CompressedTexture> = {\n async load(context) {\n if (context.decoders.ktx2 === false) throw refused(KTX2, 'ktx2', context.url)\n const buffer = await context.bytes(await context.fetch())\n // Wait for render after the request, which frees its slot.\n const { renderer } = await context.render()\n const loader = await ktx2Loader(renderer, context.decoders, context.url)\n let value: CompressedTexture\n try {\n value = await context.decode(\n () => new Promise((resolve, reject) => loader.parse(buffer, resolve, reject)),\n )\n } catch (cause) {\n throw parseError(cause, context, true)\n }\n value.userData.keep = true\n return { value, bytes: buffer.byteLength, renderBound: true, dispose: () => value.dispose() }\n },\n}\n"],"mappings":";;;AAUA,MAAMA,UAAQ;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