@dioramajs/assets 0.0.0-stage → 0.1.1
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,146 @@
|
|
|
1
|
+
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js'
|
|
2
|
+
import type {
|
|
3
|
+
BufferGeometry,
|
|
4
|
+
CompressedTexture,
|
|
5
|
+
Material,
|
|
6
|
+
Mesh,
|
|
7
|
+
Object3D,
|
|
8
|
+
SkinnedMesh,
|
|
9
|
+
Texture,
|
|
10
|
+
} from 'three/webgpu'
|
|
11
|
+
import { AssetError } from '../errors'
|
|
12
|
+
import type { AssetLoader, Loaded, Model } from '../types'
|
|
13
|
+
import { dracoLoader, KTX2, ktx2Loader, meshoptDecoder, parseError, refused } from './decoders'
|
|
14
|
+
import { rgbaBytes } from './texture'
|
|
15
|
+
|
|
16
|
+
const GLB = 0x46546c67
|
|
17
|
+
const JSON_CHUNK = 0x4e4f534a
|
|
18
|
+
const DRACO = 'KHR_draco_mesh_compression'
|
|
19
|
+
const MESHOPT = ['EXT_meshopt_compression', 'KHR_meshopt_compression']
|
|
20
|
+
const BASISU = 'KHR_texture_basisu'
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The extensions a file uses, from the JSON chunk of a GLB or the .gltf text. Reads
|
|
24
|
+
* `extensionsUsed`, not only the required ones, or an optional one would fall back silently.
|
|
25
|
+
*/
|
|
26
|
+
export function extensionsUsed(buffer: ArrayBuffer): Set<string> {
|
|
27
|
+
const view = new DataView(buffer)
|
|
28
|
+
let text = new Uint8Array(buffer)
|
|
29
|
+
if (buffer.byteLength >= 20 && view.getUint32(0, true) === GLB) {
|
|
30
|
+
if (view.getUint32(16, true) !== JSON_CHUNK) throw new Error('the GLB has no JSON chunk')
|
|
31
|
+
text = new Uint8Array(buffer, 20, view.getUint32(12, true))
|
|
32
|
+
}
|
|
33
|
+
const json = JSON.parse(new TextDecoder().decode(text)) as {
|
|
34
|
+
extensionsUsed?: string[]
|
|
35
|
+
extensionsRequired?: string[]
|
|
36
|
+
}
|
|
37
|
+
return new Set([...(json.extensionsUsed ?? []), ...(json.extensionsRequired ?? [])])
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Resources {
|
|
41
|
+
readonly geometries: Set<BufferGeometry>
|
|
42
|
+
readonly materials: Set<Material>
|
|
43
|
+
readonly textures: Set<Texture>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function resources(root: Object3D): Resources {
|
|
47
|
+
const found: Resources = { geometries: new Set(), materials: new Set(), textures: new Set() }
|
|
48
|
+
root.traverse((object) => {
|
|
49
|
+
const { geometry, material } = object as Mesh
|
|
50
|
+
if (geometry) found.geometries.add(geometry)
|
|
51
|
+
for (const each of [material ?? []].flat() as Material[]) {
|
|
52
|
+
found.materials.add(each)
|
|
53
|
+
for (const value of Object.values(each)) {
|
|
54
|
+
if ((value as Texture | null)?.isTexture) found.textures.add(value)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
return found
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const geometryBytes = (geometry: BufferGeometry): number =>
|
|
62
|
+
[...Object.values(geometry.attributes), geometry.index].reduce(
|
|
63
|
+
(sum, attribute) => sum + ((attribute?.array as ArrayBufferView | undefined)?.byteLength ?? 0),
|
|
64
|
+
0,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
function textureBytes(texture: Texture): number {
|
|
68
|
+
const compressed = texture as CompressedTexture
|
|
69
|
+
if (compressed.isCompressedTexture) {
|
|
70
|
+
return compressed.mipmaps.reduce((sum, level) => sum + (level.data?.byteLength ?? 0), 0)
|
|
71
|
+
}
|
|
72
|
+
return rgbaBytes(texture.image ?? {})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Shared resources are marked `userData.keep`, effects get clones. */
|
|
76
|
+
function model(gltf: GLTF, cloneSkinned: (root: Object3D) => Object3D): Loaded<Model> {
|
|
77
|
+
const { scene, animations } = gltf
|
|
78
|
+
const found = resources(scene)
|
|
79
|
+
for (const set of [found.geometries, found.materials, found.textures]) {
|
|
80
|
+
for (const resource of set) resource.userData.keep = true
|
|
81
|
+
}
|
|
82
|
+
let skinned = false
|
|
83
|
+
scene.traverse((object) => {
|
|
84
|
+
if ((object as SkinnedMesh).isSkinnedMesh) skinned = true
|
|
85
|
+
})
|
|
86
|
+
const textures = [...found.textures]
|
|
87
|
+
return {
|
|
88
|
+
value: {
|
|
89
|
+
scene,
|
|
90
|
+
animations,
|
|
91
|
+
instance: () => (skinned ? cloneSkinned(scene) : scene.clone()),
|
|
92
|
+
},
|
|
93
|
+
bytes:
|
|
94
|
+
[...found.geometries].reduce((sum, g) => sum + geometryBytes(g), 0) +
|
|
95
|
+
textures.reduce((sum, t) => sum + textureBytes(t), 0),
|
|
96
|
+
renderBound: textures.some((t) => (t as CompressedTexture).isCompressedTexture),
|
|
97
|
+
dispose() {
|
|
98
|
+
scene.traverse((object) => object.dispose())
|
|
99
|
+
for (const geometry of found.geometries) geometry.dispose()
|
|
100
|
+
for (const material of found.materials) material.dispose()
|
|
101
|
+
for (const texture of textures) {
|
|
102
|
+
texture.dispose()
|
|
103
|
+
;(texture.image as { close?: () => void } | null)?.close?.()
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** glTF and GLB with the decoders their `extensionsUsed` name, loaded on demand. */
|
|
110
|
+
export const gltf: AssetLoader<Model> = {
|
|
111
|
+
async load(context) {
|
|
112
|
+
const { url } = context
|
|
113
|
+
const [{ GLTFLoader }, { clone }, buffer] = await Promise.all([
|
|
114
|
+
import('three/addons/loaders/GLTFLoader.js'),
|
|
115
|
+
import('three/addons/utils/SkeletonUtils.js'),
|
|
116
|
+
context.fetch().then((response) => context.bytes(response)),
|
|
117
|
+
])
|
|
118
|
+
let used: Set<string>
|
|
119
|
+
try {
|
|
120
|
+
used = extensionsUsed(buffer)
|
|
121
|
+
} catch (cause) {
|
|
122
|
+
throw new AssetError('ASSET_PARSE', `${url} is not glTF`, { url, cause })
|
|
123
|
+
}
|
|
124
|
+
const loader = new GLTFLoader()
|
|
125
|
+
if (context.crossOrigin === 'use-credentials') {
|
|
126
|
+
loader.setCrossOrigin('use-credentials').setWithCredentials(true)
|
|
127
|
+
}
|
|
128
|
+
loader.setPriority(context.priority === 'normal' ? 'auto' : context.priority)
|
|
129
|
+
const { decoders } = context
|
|
130
|
+
const meshopt = MESHOPT.some((name) => used.has(name))
|
|
131
|
+
if (used.has(DRACO)) loader.setDRACOLoader(await dracoLoader(decoders, url))
|
|
132
|
+
if (meshopt) loader.setMeshoptDecoder(await meshoptDecoder(decoders, url))
|
|
133
|
+
if (used.has(BASISU)) {
|
|
134
|
+
// Refused before waiting for a render that may never come.
|
|
135
|
+
if (decoders.ktx2 === false) throw refused(KTX2, 'ktx2', url)
|
|
136
|
+
const { renderer } = await context.render()
|
|
137
|
+
loader.setKTX2Loader(await ktx2Loader(renderer, decoders, url))
|
|
138
|
+
}
|
|
139
|
+
const base = url.slice(0, url.lastIndexOf('/') + 1)
|
|
140
|
+
try {
|
|
141
|
+
return model(await context.decode(() => loader.parseAsync(buffer, base)), clone)
|
|
142
|
+
} catch (cause) {
|
|
143
|
+
throw parseError(cause, context, meshopt || used.has(DRACO) || used.has(BASISU))
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CompressedTexture } from 'three/webgpu'
|
|
2
|
+
import type { AssetLoader } from '../types'
|
|
3
|
+
import { KTX2, ktx2Loader, parseError, refused } from './decoders'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A KTX2 (Basis) texture, transcoded for the formats of the app's renderer, so it waits for
|
|
7
|
+
* `render`. Origin top-left like glTF, and `flipY` can't be set.
|
|
8
|
+
*/
|
|
9
|
+
export const ktx2: AssetLoader<CompressedTexture> = {
|
|
10
|
+
async load(context) {
|
|
11
|
+
if (context.decoders.ktx2 === false) throw refused(KTX2, 'ktx2', context.url)
|
|
12
|
+
const buffer = await context.bytes(await context.fetch())
|
|
13
|
+
// Wait for render after the request, which frees its slot.
|
|
14
|
+
const { renderer } = await context.render()
|
|
15
|
+
const loader = await ktx2Loader(renderer, context.decoders, context.url)
|
|
16
|
+
let value: CompressedTexture
|
|
17
|
+
try {
|
|
18
|
+
value = await context.decode(
|
|
19
|
+
() => new Promise((resolve, reject) => loader.parse(buffer, resolve, reject)),
|
|
20
|
+
)
|
|
21
|
+
} catch (cause) {
|
|
22
|
+
throw parseError(cause, context, true)
|
|
23
|
+
}
|
|
24
|
+
value.userData.keep = true
|
|
25
|
+
return { value, bytes: buffer.byteLength, renderBound: true, dispose: () => value.dispose() }
|
|
26
|
+
},
|
|
27
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { LinearSRGBColorSpace, NoColorSpace, SRGBColorSpace, Texture } from 'three/webgpu'
|
|
2
|
+
import type { AssetLoader } from '../types'
|
|
3
|
+
|
|
4
|
+
const COLOR_SPACES: Readonly<Record<string, string>> = {
|
|
5
|
+
linear: LinearSRGBColorSpace,
|
|
6
|
+
none: NoColorSpace,
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** GPU bytes of an RGBA8 texture. Mipmaps add a third. */
|
|
10
|
+
export const rgbaBytes = ({ width = 0, height = 0 }: { width?: number; height?: number }): number =>
|
|
11
|
+
Math.round((width * height * 16) / 3)
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A Texture over the pixels of the `image` entry with the same URL and CORS mode, which a
|
|
15
|
+
* preload or an effect may have decoded already. Origin bottom-left like effects textures.
|
|
16
|
+
* `options.colorSpace` is 'srgb' (default), 'linear' or 'none' for data maps.
|
|
17
|
+
*/
|
|
18
|
+
export const texture: AssetLoader<Texture> = {
|
|
19
|
+
async load(context) {
|
|
20
|
+
const { crossOrigin, priority } = context
|
|
21
|
+
const pixels = context.load<ImageBitmap>(context.url, { type: 'image', crossOrigin, priority })
|
|
22
|
+
let bitmap: ImageBitmap
|
|
23
|
+
try {
|
|
24
|
+
bitmap = await pixels.ready
|
|
25
|
+
} catch (error) {
|
|
26
|
+
pixels.release()
|
|
27
|
+
throw error
|
|
28
|
+
}
|
|
29
|
+
const value = new Texture(bitmap)
|
|
30
|
+
// Decoded flipped already, so both backends upload it as is.
|
|
31
|
+
value.flipY = false
|
|
32
|
+
value.colorSpace = COLOR_SPACES[String(context.options.colorSpace)] ?? SRGBColorSpace
|
|
33
|
+
value.needsUpdate = true
|
|
34
|
+
value.userData.keep = true
|
|
35
|
+
return {
|
|
36
|
+
value,
|
|
37
|
+
bytes: rgbaBytes(bitmap),
|
|
38
|
+
dispose() {
|
|
39
|
+
value.dispose()
|
|
40
|
+
pixels.release()
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import type { Off, ReadonlySignal } from '@dioramajs/core'
|
|
2
|
+
import type { RenderApi } from '@dioramajs/render'
|
|
3
|
+
import type { AnimationClip, CompressedTexture, Group, Object3D, Texture } from 'three/webgpu'
|
|
4
|
+
import type { AssetError } from './errors'
|
|
5
|
+
|
|
6
|
+
/** Request priority. An entry runs at the highest priority among its leases. */
|
|
7
|
+
export type Priority = 'high' | 'normal' | 'low'
|
|
8
|
+
/** State of a lease. */
|
|
9
|
+
export type AssetStatus = 'loading' | 'ready' | 'failed' | 'released'
|
|
10
|
+
/** `''` (default) sends no CORS mode, like an <img> without `crossorigin`. */
|
|
11
|
+
export type CrossOrigin = '' | 'anonymous' | 'use-credentials'
|
|
12
|
+
|
|
13
|
+
/** Value types of typed loads. Extend via declaration merging for your own loaders. */
|
|
14
|
+
export interface AssetTypes {
|
|
15
|
+
/** Decoded pixels, flipped like effects textures (`imageOrientation: 'flipY'`). */
|
|
16
|
+
image: ImageBitmap
|
|
17
|
+
/** Origin bottom-left like effects textures, built from the `image` entry. Shared, never dispose it. */
|
|
18
|
+
texture: Texture
|
|
19
|
+
/** A glTF model owned by the cache. */
|
|
20
|
+
gltf: Model
|
|
21
|
+
/** Origin top-left like glTF, and `flipY` can't be changed. Shared, never dispose it. */
|
|
22
|
+
ktx2: CompressedTexture
|
|
23
|
+
/** Raw bytes. */
|
|
24
|
+
buffer: ArrayBuffer
|
|
25
|
+
/** Parsed JSON. */
|
|
26
|
+
json: unknown
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A glTF owned by the cache. Place instances and never dispose their resources. */
|
|
30
|
+
export interface Model {
|
|
31
|
+
/** The loaded scene. Place instances, not this group. */
|
|
32
|
+
readonly scene: Group
|
|
33
|
+
/** Animation clips of the file. */
|
|
34
|
+
readonly animations: readonly AnimationClip[]
|
|
35
|
+
/**
|
|
36
|
+
* A clone sharing geometry, materials and textures (SkeletonUtils for skinned). The shared
|
|
37
|
+
* resources carry `userData.keep`. The clone's own objects are disposed with the effect.
|
|
38
|
+
*/
|
|
39
|
+
instance(): Object3D
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Options of `assets.load`. */
|
|
43
|
+
export interface LoadOptions<K extends string = string> {
|
|
44
|
+
/** Guessed from the extension when omitted: gltf for .glb and .gltf, ktx2 for .ktx2, texture for images. */
|
|
45
|
+
readonly type?: K
|
|
46
|
+
/** Default 'normal'. An entry runs at the highest priority among its leases. */
|
|
47
|
+
readonly priority?: Priority
|
|
48
|
+
/**
|
|
49
|
+
* Part of the key, as the browser keys its image cache by CORS mode. A `texture` of another
|
|
50
|
+
* origin is always asked in CORS mode: `''` becomes `'anonymous'`, since the GPU refuses
|
|
51
|
+
* pixels fetched without it.
|
|
52
|
+
*/
|
|
53
|
+
readonly crossOrigin?: CrossOrigin
|
|
54
|
+
/** Loader options, part of the key. For example `{ colorSpace: 'linear' }`. */
|
|
55
|
+
readonly options?: Readonly<Record<string, string | number | boolean>>
|
|
56
|
+
/** Aborting it releases the lease. */
|
|
57
|
+
readonly signal?: AbortSignal
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A lease, returned synchronously. The entry lives while any lease does. Calling it releases it.
|
|
62
|
+
* `E` is the failure type, AssetError for `load()` and whatever `make` threw for `acquire()`.
|
|
63
|
+
*/
|
|
64
|
+
export interface Asset<T, E = AssetError> {
|
|
65
|
+
(): void
|
|
66
|
+
/** Releases the lease. The entry goes when its last lease does. */
|
|
67
|
+
release(): void
|
|
68
|
+
/** Same as release, so `ctx.onDispose(asset)` ties it to an effect. */
|
|
69
|
+
dispose(): void
|
|
70
|
+
/** Cache key: type, URL, CORS mode and options. */
|
|
71
|
+
readonly key: string
|
|
72
|
+
/** Absolute URL. */
|
|
73
|
+
readonly url: string
|
|
74
|
+
/** State of the lease. */
|
|
75
|
+
readonly status: ReadonlySignal<AssetStatus>
|
|
76
|
+
/** Rejects with `E`, or with an unreported ASSET_ABORTED if released before ready. */
|
|
77
|
+
readonly ready: Promise<T>
|
|
78
|
+
/** The value while the lease is ready, undefined before and after. */
|
|
79
|
+
readonly value: T | undefined
|
|
80
|
+
/** The failure while the lease is failed. */
|
|
81
|
+
readonly error: E | undefined
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** What a loader resolves with. */
|
|
85
|
+
export interface Loaded<T> {
|
|
86
|
+
/** The loaded value. */
|
|
87
|
+
readonly value: T
|
|
88
|
+
/** Approximate size in bytes for `retain` and progress weights. Estimated when absent. */
|
|
89
|
+
readonly bytes?: number
|
|
90
|
+
/** Frees what the value holds. Called once, by the cache only. */
|
|
91
|
+
dispose?(): void
|
|
92
|
+
/** Depends on the renderer's formats (KTX2), so it is evicted when render restarts. */
|
|
93
|
+
readonly renderBound?: boolean
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What a loader gets for one entry. */
|
|
97
|
+
export interface LoaderContext {
|
|
98
|
+
/** Absolute URL to load. */
|
|
99
|
+
readonly url: string
|
|
100
|
+
/** Cache key of the entry. */
|
|
101
|
+
readonly key: string
|
|
102
|
+
/** The highest priority among the entry's leases. */
|
|
103
|
+
readonly priority: Priority
|
|
104
|
+
/** CORS mode of the request. */
|
|
105
|
+
readonly crossOrigin: CrossOrigin
|
|
106
|
+
/** Loader options from `load()`. */
|
|
107
|
+
readonly options: Readonly<Record<string, string | number | boolean>>
|
|
108
|
+
/** Aborts when the last lease goes before the load ends. */
|
|
109
|
+
readonly signal: AbortSignal
|
|
110
|
+
/** fetch() with the priority hint and signal. HTTP errors throw ASSET_LOAD. */
|
|
111
|
+
fetch(init?: RequestInit): Promise<Response>
|
|
112
|
+
/** Reads a body, counting bytes into the progress. */
|
|
113
|
+
bytes(response: Response): Promise<ArrayBuffer>
|
|
114
|
+
/**
|
|
115
|
+
* Runs CPU-heavy work (createImageBitmap, parsing) in one of two decode slots and frees the
|
|
116
|
+
* request slot, so call it once the network part is done. Low-only entries wait while a pause
|
|
117
|
+
* is held.
|
|
118
|
+
*/
|
|
119
|
+
decode<R>(work: () => Promise<R>): Promise<R>
|
|
120
|
+
/**
|
|
121
|
+
* Loads a dependency. Its lease is released if this load is aborted, otherwise release it in
|
|
122
|
+
* `dispose`. Like `render()` it frees the request slot, so call both after the network part.
|
|
123
|
+
*/
|
|
124
|
+
load<T = unknown>(url: string, options?: LoadOptions): Asset<T>
|
|
125
|
+
/** Resolves once `render` runs (after renderer.init()). */
|
|
126
|
+
render(): Promise<RenderApi>
|
|
127
|
+
/** The app's decoder options. Unset fields take three's defaults. */
|
|
128
|
+
readonly decoders: Readonly<Partial<DecoderOptions>>
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Loads one type of asset. */
|
|
132
|
+
export interface AssetLoader<T = unknown> {
|
|
133
|
+
/** Extensions this loader handles when no type is given, e.g. ['.glb', '.gltf']. */
|
|
134
|
+
readonly extensions?: readonly string[]
|
|
135
|
+
/** Loads the value of one entry. */
|
|
136
|
+
load(context: LoaderContext): Promise<Loaded<T>>
|
|
137
|
+
}
|
|
138
|
+
/** A loader, or a lazy module exporting one. Three-based loaders come through import(). */
|
|
139
|
+
export type LoaderEntry =
|
|
140
|
+
| AssetLoader
|
|
141
|
+
| (() => Promise<AssetLoader | { readonly default: AssetLoader }>)
|
|
142
|
+
|
|
143
|
+
/** Where Draco, KTX2 and Meshopt decoders come from. */
|
|
144
|
+
export interface DecoderOptions {
|
|
145
|
+
/** A directory or `{ js, wasm }`, false refuses. Defaults to three's glTF-only build next to DRACOLoader. */
|
|
146
|
+
readonly draco: string | { readonly js: string; readonly wasm: string } | false
|
|
147
|
+
/** A directory, false refuses. Defaults to three's Basis transcoder next to KTX2Loader. */
|
|
148
|
+
readonly ktx2: string | false
|
|
149
|
+
/** EXT_/KHR_meshopt_compression through three's decoder module (wasm inside). Default true. */
|
|
150
|
+
readonly meshopt: boolean
|
|
151
|
+
/** Workers per decoder, three's default if unset. The first app that creates a decoder sets it. */
|
|
152
|
+
readonly workers: number | undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What `preload` takes: URLs, a parsed Document or a container element. */
|
|
156
|
+
export type PreloadSource = string | readonly string[] | ParentNode
|
|
157
|
+
|
|
158
|
+
/** Options of `assets.preload`. */
|
|
159
|
+
export interface PreloadOptions {
|
|
160
|
+
/** Default 'low'. */
|
|
161
|
+
readonly priority?: Priority
|
|
162
|
+
/**
|
|
163
|
+
* CORS mode of images given as URLs. Match the `<img crossorigin>` that will show them, since
|
|
164
|
+
* it is part of the key. Images from markup or a document carry their own `crossorigin`.
|
|
165
|
+
*/
|
|
166
|
+
readonly crossOrigin?: CrossOrigin
|
|
167
|
+
/** Base for relative URLs and srcset, i.e. the next page's URL. Defaults to <base href>, then document.baseURI. */
|
|
168
|
+
readonly base?: string | URL
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Settles once everything has settled. Never rejects. */
|
|
172
|
+
export interface Preload extends PromiseLike<void> {
|
|
173
|
+
/** Drops the leases now. Otherwise they are held until the next preload of the same kind. */
|
|
174
|
+
release(): void
|
|
175
|
+
/** Same as release, for `page.onDispose(app.assets.preload(doc))`. */
|
|
176
|
+
dispose(): void
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Counters of the cache. */
|
|
180
|
+
export interface AssetsStats {
|
|
181
|
+
/** Entries in the cache. */
|
|
182
|
+
readonly entries: number
|
|
183
|
+
/** Entries with leases. */
|
|
184
|
+
readonly used: number
|
|
185
|
+
/** Bytes of entries without leases, kept by `retain`. */
|
|
186
|
+
readonly retained: number
|
|
187
|
+
/** Entries still loading. */
|
|
188
|
+
readonly pending: number
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Options of the `assets` plugin. */
|
|
192
|
+
export interface AssetsOptions {
|
|
193
|
+
/** Own loaders by type, next to the built-in ones. A lazy one is picked by `type` only. */
|
|
194
|
+
readonly loaders: Readonly<Record<string, LoaderEntry>>
|
|
195
|
+
/** Where the Draco, KTX2 and Meshopt decoders come from. */
|
|
196
|
+
readonly decoders: Partial<DecoderOptions>
|
|
197
|
+
/** Parallel requests. Default 6. At most 2 of them low, and only while no high request waits. */
|
|
198
|
+
readonly concurrency: number
|
|
199
|
+
/** Bytes of unused entries kept for reuse (back navigation, preloads), LRU. Default 32 MB, 0 disables. */
|
|
200
|
+
readonly retain: number
|
|
201
|
+
/** Reads data-dio-preload. Default true. Off under Save-Data or 2g. */
|
|
202
|
+
readonly preload: boolean
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The `assets` service: a shared cache of media and models with progress. */
|
|
206
|
+
export interface AssetsApi {
|
|
207
|
+
/**
|
|
208
|
+
* Loads a URL and returns a lease at once. The type comes from `type` or the extension.
|
|
209
|
+
* Never throws: `ready` rejects with an AssetError, `ASSET_TYPE` for an unknown type,
|
|
210
|
+
* `ASSET_LOAD` for a network or HTTP failure, `ASSET_PARSE` or `ASSET_DECODER` for bad data.
|
|
211
|
+
*/
|
|
212
|
+
load<K extends keyof AssetTypes>(
|
|
213
|
+
url: string,
|
|
214
|
+
options: LoadOptions<K> & { readonly type: K },
|
|
215
|
+
): Asset<AssetTypes[K]>
|
|
216
|
+
load<T = unknown>(url: string, options?: LoadOptions): Asset<T>
|
|
217
|
+
/**
|
|
218
|
+
* Get-or-create by key with a lease. Plugins share values they build this way (effects
|
|
219
|
+
* bitmaps). Errors of `make` reject `ready` unchanged and the owner reports them.
|
|
220
|
+
*/
|
|
221
|
+
acquire<T>(
|
|
222
|
+
key: string,
|
|
223
|
+
make: (context: LoaderContext) => Promise<Loaded<T>>,
|
|
224
|
+
options?: { readonly priority?: Priority; readonly weight?: number },
|
|
225
|
+
): Asset<T, unknown>
|
|
226
|
+
/** Next page's media and models: URLs, a parsed Document (Astro, Swup) or a container (Barba). */
|
|
227
|
+
preload(source: PreloadSource, options?: PreloadOptions): Preload
|
|
228
|
+
/**
|
|
229
|
+
* Counts outside work in the current wave, like first-screen effects, fonts or page HTML.
|
|
230
|
+
* `weight: 0` holds `ready()` without moving progress or starting a wave of its own.
|
|
231
|
+
*/
|
|
232
|
+
track(
|
|
233
|
+
work: PromiseLike<unknown>,
|
|
234
|
+
options?: { readonly weight?: number; readonly priority?: Priority },
|
|
235
|
+
): void
|
|
236
|
+
/**
|
|
237
|
+
* Low-priority loads and decodes wait while any pause is held (a flight). `reason` labels the
|
|
238
|
+
* call, as in `app.pause`.
|
|
239
|
+
*/
|
|
240
|
+
pause(reason?: string): Off
|
|
241
|
+
/** Progress of the current wave of high and normal work, 0..1. Never goes back within a wave. */
|
|
242
|
+
readonly progress: ReadonlySignal<number>
|
|
243
|
+
/** Settles when the current wave is done, or at once without one. Failures count as done. */
|
|
244
|
+
ready(): Promise<void>
|
|
245
|
+
/** Counters of the cache. */
|
|
246
|
+
stats(): AssetsStats
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Codes of `AssetError`. */
|
|
250
|
+
export type AssetErrorCode =
|
|
251
|
+
| 'ASSET_LOAD'
|
|
252
|
+
| 'ASSET_PARSE'
|
|
253
|
+
| 'ASSET_TYPE'
|
|
254
|
+
| 'ASSET_DECODER'
|
|
255
|
+
| 'ASSET_ABORTED'
|
|
256
|
+
|
|
257
|
+
declare module '@dioramajs/core' {
|
|
258
|
+
interface Services {
|
|
259
|
+
/** Asset cache and preloading, see `AssetsApi`. */
|
|
260
|
+
assets: AssetsApi
|
|
261
|
+
}
|
|
262
|
+
interface Hooks {
|
|
263
|
+
/** Runs synchronously once per entry, before caching. For colour space, material tweaks, userData. */
|
|
264
|
+
'assets:transform': (
|
|
265
|
+
value: unknown,
|
|
266
|
+
context: { readonly type: string; readonly url: string },
|
|
267
|
+
) => unknown
|
|
268
|
+
}
|
|
269
|
+
}
|
package/src/wave.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Load progress for `assets.progress`, `ready()` and `data-dio-progress` bars.
|
|
2
|
+
import { type ReadonlySignal, type Signal, signal } from '@dioramajs/core'
|
|
3
|
+
|
|
4
|
+
/** Work in the wave, in bytes or an estimate. `loaded` never exceeds `total`. */
|
|
5
|
+
export interface Item {
|
|
6
|
+
total: number
|
|
7
|
+
loaded: number
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Progress stops here until the wave is done. 1 means `ready()` resolved. */
|
|
11
|
+
const BEFORE_END = 0.99
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The current wave of high and normal work. It starts when pending items appear, only grows,
|
|
15
|
+
* and stays at 1 until the next wave starts from 0. Work of no weight (a decode the next frame
|
|
16
|
+
* waits for) holds `ready()` but starts no wave of its own: the bar stays where it is.
|
|
17
|
+
* `data-dio-progress` elements follow the first wave and the waves that start during a page
|
|
18
|
+
* transition only: a texture loading as its section nears does not pull a bar back mid-scroll.
|
|
19
|
+
*/
|
|
20
|
+
export class Wave {
|
|
21
|
+
readonly #progress: Signal<number> = signal(0)
|
|
22
|
+
readonly progress: ReadonlySignal<number> = this.#progress
|
|
23
|
+
readonly #pending = new Set<Item>()
|
|
24
|
+
#done = 0
|
|
25
|
+
/** The wave has weighed work, so progress moves. */
|
|
26
|
+
#shown = false
|
|
27
|
+
/** No weighed wave has ended yet: the page is still loading. */
|
|
28
|
+
#first = true
|
|
29
|
+
/** `data-dio-progress` elements follow this wave. */
|
|
30
|
+
#bar = true
|
|
31
|
+
#waiters: (() => void)[] = []
|
|
32
|
+
#elements: HTMLElement[] = []
|
|
33
|
+
readonly #find: () => HTMLElement[]
|
|
34
|
+
|
|
35
|
+
constructor(find: () => HTMLElement[]) {
|
|
36
|
+
this.#find = find
|
|
37
|
+
this.#elements = find()
|
|
38
|
+
this.#write()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
add(item: Item): void {
|
|
42
|
+
if (this.#pending.has(item)) return
|
|
43
|
+
if (!this.#pending.size) {
|
|
44
|
+
this.#done = 0
|
|
45
|
+
this.#shown = false
|
|
46
|
+
}
|
|
47
|
+
this.#pending.add(item)
|
|
48
|
+
if (!this.#shown && item.total > 0) {
|
|
49
|
+
this.#shown = true
|
|
50
|
+
this.#bar =
|
|
51
|
+
this.#first ||
|
|
52
|
+
(typeof document !== 'undefined' &&
|
|
53
|
+
document.documentElement.hasAttribute('data-dio-transition'))
|
|
54
|
+
if (this.#bar) this.#elements = this.#find()
|
|
55
|
+
this.#set(0)
|
|
56
|
+
}
|
|
57
|
+
this.changed()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A page change: the bar follows the wave under way, or else the next one. */
|
|
61
|
+
page(): void {
|
|
62
|
+
this.#first = true
|
|
63
|
+
if (!this.#shown || this.#bar || !this.#pending.size) return
|
|
64
|
+
this.#bar = true
|
|
65
|
+
this.#elements = this.#find()
|
|
66
|
+
this.#write()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The item settled, failed or became low and left the wave. Counted as done. */
|
|
70
|
+
done(item: Item): void {
|
|
71
|
+
if (!this.#pending.delete(item)) return
|
|
72
|
+
this.#done += item.total
|
|
73
|
+
if (this.#pending.size) {
|
|
74
|
+
this.changed()
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
if (this.#shown || this.#progress.peek() < 1) this.#set(1)
|
|
78
|
+
if (this.#shown) this.#first = false
|
|
79
|
+
for (const resolve of this.#waiters.splice(0)) resolve()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
changed(): void {
|
|
83
|
+
if (!this.#pending.size || !this.#shown) return
|
|
84
|
+
let loaded = this.#done
|
|
85
|
+
let total = this.#done
|
|
86
|
+
for (const item of this.#pending) {
|
|
87
|
+
loaded += Math.min(item.loaded, item.total)
|
|
88
|
+
total += item.total
|
|
89
|
+
}
|
|
90
|
+
const ratio = total > 0 ? Math.min(loaded / total, BEFORE_END) : 0
|
|
91
|
+
if (ratio > this.#progress.peek()) this.#set(ratio)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
ready(): Promise<void> {
|
|
95
|
+
return this.#pending.size
|
|
96
|
+
? new Promise((resolve) => this.#waiters.push(resolve))
|
|
97
|
+
: Promise.resolve()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Ends the wave and settles waiters. */
|
|
101
|
+
close(): void {
|
|
102
|
+
this.#pending.clear()
|
|
103
|
+
for (const resolve of this.#waiters.splice(0)) resolve()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#set(value: number): void {
|
|
107
|
+
this.#progress.value = value
|
|
108
|
+
if (this.#bar) this.#write()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#write(): void {
|
|
112
|
+
const value = String(this.#progress.peek())
|
|
113
|
+
for (const el of this.#elements) el.style.setProperty('--dio-progress', value)
|
|
114
|
+
}
|
|
115
|
+
}
|