@openbone/three 0.0.0-stage → 0.3.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 +145 -2
- package/dist/index.d.ts +104 -0
- package/dist/index.js +474 -0
- package/package.json +53 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 UX Century and OpenBone contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @openbone/three
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OpenBone runtime for Three.js: an OpenBone document as an `Object3D`, with one material per atlas page.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@openbone/three)
|
|
6
|
+
[](https://github.com/UXCentury/open-bone/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
[OpenBone](https://github.com/UXCentury/open-bone) is open-source 2D skeletal animation: Spine-style rigging,
|
|
9
|
+
Rive-style state machines and an MCP server for AI agents. This package puts an OpenBone document into a Three.js
|
|
10
|
+
scene as a `Group` of meshes in its XY plane, with state machines, raycast pointer listeners, events, skins, scripts
|
|
11
|
+
and sound. Playback comes from [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit); each mesh
|
|
12
|
+
is one batch of the reference renderer, [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl),
|
|
13
|
+
drawn with the same shader maths and blend functions.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @openbone/three three
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`three` is a peer dependency (r160 or later: `>=0.160.0`). It uses `WebGLRenderer`.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import * as THREE from "three";
|
|
27
|
+
import { OpenBoneObject3D } from "@openbone/three";
|
|
28
|
+
|
|
29
|
+
// stencil: true is needed for clipping masks (Three.js no longer creates a stencil buffer by default).
|
|
30
|
+
const renderer = new THREE.WebGLRenderer({ antialias: true, stencil: true });
|
|
31
|
+
renderer.setSize(900, 600);
|
|
32
|
+
document.body.appendChild(renderer.domElement);
|
|
33
|
+
|
|
34
|
+
const scene = new THREE.Scene();
|
|
35
|
+
const camera = new THREE.PerspectiveCamera(35, 900 / 600, 0.1, 100);
|
|
36
|
+
camera.position.set(0, 0, 10);
|
|
37
|
+
|
|
38
|
+
const knight = await OpenBoneObject3D.from("/knight.obone", { stateMachine: "knight" });
|
|
39
|
+
knight.scale.setScalar(0.01); // skeleton units -> world units
|
|
40
|
+
const a = knight.artboard; // in skeleton units, y up
|
|
41
|
+
knight.position.set(-(a.x + a.width / 2) * 0.01, -(a.y + a.height / 2) * 0.01, 0); // centre the artboard
|
|
42
|
+
scene.add(knight);
|
|
43
|
+
knight.bindPointer(renderer.domElement, camera); // clicks and hovers raycast onto the skeleton's plane
|
|
44
|
+
|
|
45
|
+
knight.setInput("walk", true);
|
|
46
|
+
knight.onOpenBone("stateChange", (e) => console.log(e.layer, e.from, "->", e.to));
|
|
47
|
+
|
|
48
|
+
const clock = new THREE.Clock();
|
|
49
|
+
renderer.setAnimationLoop(() => {
|
|
50
|
+
knight.update(clock.getDelta());
|
|
51
|
+
renderer.render(scene, camera);
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`knight.obone` is in the repository's `examples/` folder. Skeleton units map to local units, y up, with the skeleton
|
|
56
|
+
origin at the object's origin. Unlike the other engine objects, this one does not tick itself: call `update(dt)` from
|
|
57
|
+
your loop.
|
|
58
|
+
|
|
59
|
+
## API
|
|
60
|
+
|
|
61
|
+
| Export | |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `OpenBoneObject3D` | The object (a `THREE.Group`). `await OpenBoneObject3D.from(src, options)` loads and creates it. |
|
|
64
|
+
| `loadOpenBone(src, options)` | Loads a document and its textures into an `OpenBoneAsset` that many objects can share. |
|
|
65
|
+
| `OpenBoneAsset` | `{ doc, baseUrl, textures }` (one `THREE.Texture` per image or atlas page id). |
|
|
66
|
+
| `prepareTexture(texture, mipmaps?, premultiplied?)` | Configures a texture the way OpenBone samples it (premultiplied, no flip, no colour space conversion, clamped). |
|
|
67
|
+
| `BLEND_FACTORS` | render-webgl's blend functions as Three.js factors. |
|
|
68
|
+
| `OpenBoneObjectOptions`, `LoadOptions`, `DriverOptions`, `InputValue`, `OpenBoneSource` | Option and value types. |
|
|
69
|
+
|
|
70
|
+
`src` is a URL, bytes (`ArrayBuffer` or `Uint8Array` of a `.obone` or `.obonb` file), a parsed document or, for
|
|
71
|
+
`OpenBoneObject3D.from`, an `OpenBoneAsset`.
|
|
72
|
+
|
|
73
|
+
### Options
|
|
74
|
+
|
|
75
|
+
| Option | Default | |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `stateMachine` / `animation` / `loop` | first state machine, else first animation | What to run. |
|
|
78
|
+
| `skin` | default skin | Skin (outfit) by name or id. |
|
|
79
|
+
| `scripts` | `"quickjs"` when the document has scripts | `"none"` or your own `ScriptHost`. |
|
|
80
|
+
| `audio` | `true` | `false` or `"muted"`. |
|
|
81
|
+
| `audioListener` | | Play sounds on a `THREE.AudioListener`'s context. |
|
|
82
|
+
| `audioContext`, `audioBaseUrl`, `resolveAudioUrl`, `unlockTarget`, `onEvent`, `onStateChange` | | As in engine-kit. |
|
|
83
|
+
| `depthTest` | `true` | Test against the scene's depth. OpenBone never writes depth; order comes from `renderOrder`. |
|
|
84
|
+
| `textResolution` | `2` | Pixels per skeleton unit for text. |
|
|
85
|
+
| `baseUrl`, `fetch` (loading) | the document's folder | Where relative image and audio paths load from, and the fetch to use. |
|
|
86
|
+
| `resolveImageUrl(src)` (loading) | | Map an image path to the URL to load. |
|
|
87
|
+
| `mipmaps` (loading) | `true` | Mipmapped textures: smoother when the object is small or seen at an angle. |
|
|
88
|
+
|
|
89
|
+
### Methods and properties
|
|
90
|
+
|
|
91
|
+
| Member | |
|
|
92
|
+
|---|---|
|
|
93
|
+
| `update(dt)` | Advance by `dt` seconds and rebuild the meshes. Call it every frame. |
|
|
94
|
+
| `setInput(name, value)`, `getInput(name)`, `fire(name)` | State machine inputs and triggers. |
|
|
95
|
+
| `play(animation, loop?)`, `useStateMachine(name?)` | Switch to an animation or a state machine. |
|
|
96
|
+
| `setSkin(name)`, `setText(slot, text)` | Outfit, and text for a slot's text attachment (`null` restores it). |
|
|
97
|
+
| `pause()`, `resume()`, `paused`, `speed` | Playback; pausing also pauses sounds. |
|
|
98
|
+
| `opacity` | Opacity of the whole object. |
|
|
99
|
+
| `onOpenBone(name, fn)` | Listen to `"event"`, `"stateChange"` or `"audio"`. Returns an unsubscribe function. |
|
|
100
|
+
| `artboard` | The artboard rectangle in local space (skeleton units, y up; `x, y` is the bottom-left corner). |
|
|
101
|
+
| `bindPointer(dom, camera)` | Raycast a canvas's pointer events through `camera` to the state machine. Returns an unbind function. |
|
|
102
|
+
| `pointer(type, ray)`, `rayToSkeleton(ray)` | Send your own ray (for example `raycaster.ray`), or find where it hits the plane. |
|
|
103
|
+
| `boundingBoxes()`, `skeletonToWorld(x, y)` | Bounding-box queries in skeleton space (y up): `const p = obj.rayToSkeleton(raycaster.ray); const hit = p && obj.boundingBoxes().containsPoint(...p)`. `skeletonToWorld` maps a skeleton point back to world space. |
|
|
104
|
+
| `redraw()`, `drawCalls` | Rebuild meshes after changing the pose by hand; batches drawn by the last redraw. |
|
|
105
|
+
| `driver`, `instance`, `skeleton`, `stateMachine`, `asset` | Lower-level access. |
|
|
106
|
+
| `dispose()` | Frees geometry, materials and text textures. The asset's textures are kept, since they may be shared. |
|
|
107
|
+
|
|
108
|
+
### Pointer input
|
|
109
|
+
|
|
110
|
+
`bindPointer` listens to `pointerdown`, `pointerup`, `pointermove` and `pointerleave` on the element, raycasts each
|
|
111
|
+
point onto the object's plane and sends hits inside the artboard to the state machine's listeners. Leaving the
|
|
112
|
+
artboard ends hovers. For VR controllers or custom picking, call `pointer("down", ray)` yourself.
|
|
113
|
+
|
|
114
|
+
## How it draws
|
|
115
|
+
|
|
116
|
+
Batches are render-webgl's (one per atlas page or texture and blend mode). Each is a `Mesh` with dynamic buffers (no
|
|
117
|
+
per-frame allocations) and a `ShaderMaterial` shared by every batch with the same texture and blend mode, using the
|
|
118
|
+
reference renderer's shader and blend functions in premultiplied alpha. Straight-alpha images are premultiplied on
|
|
119
|
+
upload; premultiplied atlas pages are uploaded as they are.
|
|
120
|
+
|
|
121
|
+
- **Two-colour tint**: batches with a slot `dark` colour use the material's `DARK` variant and an `obDark` attribute;
|
|
122
|
+
the others never declare or upload it.
|
|
123
|
+
- **Draw order** is `renderOrder` inside the group, which sorts as one unit against the rest of the scene.
|
|
124
|
+
- **Clipping** masks write a stencil reference that the clipped meshes test. Create the renderer with
|
|
125
|
+
`stencil: true`; without it the object logs a warning and clipping cannot work.
|
|
126
|
+
- **Text** attachments become canvas textures; **particles** use the built-in soft sprite.
|
|
127
|
+
|
|
128
|
+
## Demo
|
|
129
|
+
|
|
130
|
+
From a checkout: `pnpm --filter @openbone/examples engines`, then open http://localhost:5190/three/
|
|
131
|
+
(`?example=campfire`, `rocket`, `crash`…).
|
|
132
|
+
|
|
133
|
+
## Documentation
|
|
134
|
+
|
|
135
|
+
- [Architecture](https://github.com/UXCentury/open-bone/blob/main/docs/architecture.md): runtime model and rendering
|
|
136
|
+
- [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md)
|
|
137
|
+
- [Demo source](https://github.com/UXCentury/open-bone/blob/main/examples/engines/three/main.ts)
|
|
138
|
+
- Related packages: [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit),
|
|
139
|
+
[`@openbone/pixi`](https://www.npmjs.com/package/@openbone/pixi),
|
|
140
|
+
[`@openbone/phaser`](https://www.npmjs.com/package/@openbone/phaser),
|
|
141
|
+
[`@openbone/canvaskit`](https://www.npmjs.com/package/@openbone/canvaskit),
|
|
142
|
+
[`@openbone/player`](https://www.npmjs.com/package/@openbone/player)
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
MIT, © UX Century and OpenBone contributors. See [LICENSE](https://github.com/UXCentury/open-bone/blob/main/LICENSE).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { type OpenBoneDocument, type TextureSampling } from "@openbone/core";
|
|
2
|
+
import { type Batch, type DriverOptions, type FetchOptions, type InputValue, OpenBoneDriver, type OpenBoneSource } from "@openbone/engine-kit";
|
|
3
|
+
import * as THREE from "three";
|
|
4
|
+
export type { DriverOptions, InputValue, OpenBoneSource } from "@openbone/engine-kit";
|
|
5
|
+
/** A loaded document and its textures (one THREE.Texture per image or atlas page), shareable by many objects. */
|
|
6
|
+
export interface OpenBoneAsset {
|
|
7
|
+
doc: OpenBoneDocument;
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
textures: Map<string, THREE.Texture>;
|
|
10
|
+
}
|
|
11
|
+
export interface LoadOptions extends FetchOptions {
|
|
12
|
+
resolveImageUrl?: (src: string) => string;
|
|
13
|
+
/** Generate mipmaps (default true: smoother when the object is small or seen at an angle). */
|
|
14
|
+
mipmaps?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Configure a texture the way OpenBone samples it: premultiplied on upload, v down, colours passed through. */
|
|
17
|
+
export declare function prepareTexture<T extends THREE.Texture>(t: T, mipmaps?: boolean, premultiplied?: boolean, sampling?: TextureSampling): T;
|
|
18
|
+
/** Load a .obone / .obonb document and its images (atlas pages when packed) as Three.js textures. */
|
|
19
|
+
export declare function loadOpenBone(src: OpenBoneSource, opts?: LoadOptions): Promise<OpenBoneAsset>;
|
|
20
|
+
/** render-webgl's blend functions (premultiplied alpha), as Three.js factors. */
|
|
21
|
+
export declare const BLEND_FACTORS: Record<Batch["blend"], [THREE.BlendingSrcFactor, THREE.BlendingDstFactor]>;
|
|
22
|
+
export interface OpenBoneObjectOptions extends DriverOptions {
|
|
23
|
+
/** Share a Three.js AudioListener's context for the document's sounds. */
|
|
24
|
+
audioListener?: THREE.AudioListener;
|
|
25
|
+
/** Test depth against the scene (default true); OpenBone never writes depth, draw order comes from renderOrder. */
|
|
26
|
+
depthTest?: boolean;
|
|
27
|
+
/** Pixels per skeleton unit to rasterise text at (default 2). */
|
|
28
|
+
textResolution?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* An OpenBone document as a Three.js object: one Mesh per render-webgl batch, sharing one ShaderMaterial per
|
|
32
|
+
* texture (atlas page) and blend mode, in the XY plane (skeleton units, y up). Draw order comes from renderOrder
|
|
33
|
+
* (this is a Group, so it sorts as one unit against the rest of the scene). Clipping masks use the stencil buffer.
|
|
34
|
+
*/
|
|
35
|
+
export declare class OpenBoneObject3D extends THREE.Group {
|
|
36
|
+
readonly driver: OpenBoneDriver;
|
|
37
|
+
readonly asset: OpenBoneAsset;
|
|
38
|
+
private meshes;
|
|
39
|
+
private masks;
|
|
40
|
+
private materials;
|
|
41
|
+
private text;
|
|
42
|
+
private textTextures;
|
|
43
|
+
private dot;
|
|
44
|
+
private stencilRefs;
|
|
45
|
+
private white;
|
|
46
|
+
private depthTest;
|
|
47
|
+
private textResolution;
|
|
48
|
+
/** Opacity of the whole object (multiplies every slot). */
|
|
49
|
+
opacity: number;
|
|
50
|
+
paused: boolean;
|
|
51
|
+
/** Batches drawn by the last redraw. */
|
|
52
|
+
drawCalls: number;
|
|
53
|
+
constructor(asset: OpenBoneAsset, driver: OpenBoneDriver, opts?: OpenBoneObjectOptions);
|
|
54
|
+
/** Load a document (URL, bytes or parsed) and create the object; waits for images and the script sandbox. */
|
|
55
|
+
static from(src: OpenBoneSource | OpenBoneAsset, opts?: OpenBoneObjectOptions & LoadOptions): Promise<OpenBoneObject3D>;
|
|
56
|
+
get instance(): import("@openbone/runtime").OpenBoneInstance;
|
|
57
|
+
get skeleton(): import("@openbone/runtime").Skeleton;
|
|
58
|
+
get stateMachine(): import("@openbone/runtime").StateMachineInstance | null;
|
|
59
|
+
get speed(): number;
|
|
60
|
+
set speed(v: number);
|
|
61
|
+
setInput(name: string, value: InputValue): void;
|
|
62
|
+
getInput(name: string): InputValue | undefined;
|
|
63
|
+
fire(name: string): void;
|
|
64
|
+
setText(slot: string, text: string | null): void;
|
|
65
|
+
setSkin(name: string | null): void;
|
|
66
|
+
play(animation: string, loop?: boolean): void;
|
|
67
|
+
useStateMachine(name?: string): import("@openbone/runtime").StateMachineInstance;
|
|
68
|
+
/** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
|
|
69
|
+
onOpenBone: OpenBoneDriver["on"];
|
|
70
|
+
pause(): void;
|
|
71
|
+
resume(): void;
|
|
72
|
+
/** Advance by `dt` seconds and rebuild the meshes (call from your animation loop). */
|
|
73
|
+
update(dt: number): void;
|
|
74
|
+
/** The artboard rectangle in local space (skeleton units, y up): x, y = bottom-left. */
|
|
75
|
+
get artboard(): {
|
|
76
|
+
x: number;
|
|
77
|
+
y: number;
|
|
78
|
+
width: number;
|
|
79
|
+
height: number;
|
|
80
|
+
};
|
|
81
|
+
private material;
|
|
82
|
+
private textureFor;
|
|
83
|
+
private dropTexture;
|
|
84
|
+
/** Rebuild meshes from the current pose (call after changing the pose by hand). */
|
|
85
|
+
redraw(): void;
|
|
86
|
+
/** The drawn meshes in order, with `mask` set for clipping-mask (stencil) meshes. */
|
|
87
|
+
drawnMeshes(): {
|
|
88
|
+
mask: boolean;
|
|
89
|
+
vertices: number[][];
|
|
90
|
+
material: THREE.ShaderMaterial;
|
|
91
|
+
}[];
|
|
92
|
+
/** Where a ray hits the object's plane, in skeleton space (y up); null when parallel or behind. */
|
|
93
|
+
rayToSkeleton(ray: THREE.Ray): [number, number] | null;
|
|
94
|
+
/** Skeleton space (y up) to a world-space point on the object's plane. */
|
|
95
|
+
skeletonToWorld(x: number, y: number, target?: THREE.Vector3): THREE.Vector3;
|
|
96
|
+
/** The active bounding boxes (skeleton space): `const p = obj.rayToSkeleton(ray); p && obj.boundingBoxes().containsPoint(...p)`. */
|
|
97
|
+
boundingBoxes(): import("@openbone/runtime").SkeletonBounds;
|
|
98
|
+
/** Send a pointer event along a ray (e.g. raycaster.ray) to the state machine; outside the artboard ends hovers. */
|
|
99
|
+
pointer(type: "down" | "up" | "move", ray: THREE.Ray): void;
|
|
100
|
+
/** Route a canvas's pointer events (raycast through `camera`) to the state machine. Returns an unbind function. */
|
|
101
|
+
bindPointer(dom: HTMLElement, camera: THREE.Camera): () => void;
|
|
102
|
+
/** Free GPU resources (textures of the asset are kept: they may be shared). */
|
|
103
|
+
dispose(): void;
|
|
104
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import { filterParts, premultipliedTextures, textureSamplings } from "@openbone/core";
|
|
2
|
+
import { OpenBoneDriver, TextRasterizer, buildBatches, loadDocument, loadTextures, particleDotPixels, } from "@openbone/engine-kit";
|
|
3
|
+
import { PARTICLE_DOT_SIZE, PARTICLE_DOT_TEXTURE } from "@openbone/runtime";
|
|
4
|
+
import * as THREE from "three";
|
|
5
|
+
/** Configure a texture the way OpenBone samples it: premultiplied on upload, v down, colours passed through. */
|
|
6
|
+
export function prepareTexture(t, mipmaps = true, premultiplied = false, sampling) {
|
|
7
|
+
// Straight-alpha images are premultiplied on upload; premultiplied atlas pages already are.
|
|
8
|
+
t.premultiplyAlpha = !premultiplied;
|
|
9
|
+
t.flipY = false;
|
|
10
|
+
t.colorSpace = THREE.NoColorSpace;
|
|
11
|
+
t.generateMipmaps = mipmaps;
|
|
12
|
+
t.minFilter = mipmaps ? THREE.LinearMipmapLinearFilter : THREE.LinearFilter;
|
|
13
|
+
t.magFilter = THREE.LinearFilter;
|
|
14
|
+
t.wrapS = t.wrapT = THREE.ClampToEdgeWrapping;
|
|
15
|
+
if (sampling) {
|
|
16
|
+
// An atlas's own filter / wrap settings win over the `mipmaps` option.
|
|
17
|
+
const { texel, mip } = filterParts(sampling.min);
|
|
18
|
+
t.generateMipmaps = mip !== "none";
|
|
19
|
+
t.minFilter =
|
|
20
|
+
mip === "none" ? (texel === "nearest" ? THREE.NearestFilter : THREE.LinearFilter)
|
|
21
|
+
: mip === "nearest" ? (texel === "nearest" ? THREE.NearestMipmapNearestFilter : THREE.LinearMipmapNearestFilter)
|
|
22
|
+
: texel === "nearest" ? THREE.NearestMipmapLinearFilter
|
|
23
|
+
: THREE.LinearMipmapLinearFilter;
|
|
24
|
+
t.magFilter = sampling.mag === "nearest" ? THREE.NearestFilter : THREE.LinearFilter;
|
|
25
|
+
const wrap = (w) => (w === "repeat" ? THREE.RepeatWrapping : w === "mirroredRepeat" ? THREE.MirroredRepeatWrapping : THREE.ClampToEdgeWrapping);
|
|
26
|
+
t.wrapS = wrap(sampling.wrapX);
|
|
27
|
+
t.wrapT = wrap(sampling.wrapY);
|
|
28
|
+
}
|
|
29
|
+
t.needsUpdate = true;
|
|
30
|
+
return t;
|
|
31
|
+
}
|
|
32
|
+
/** Load a .obone / .obonb document and its images (atlas pages when packed) as Three.js textures. */
|
|
33
|
+
export async function loadOpenBone(src, opts = {}) {
|
|
34
|
+
const { doc, baseUrl } = await loadDocument(src, opts);
|
|
35
|
+
const images = await loadTextures(doc, baseUrl, { resolveImageUrl: opts.resolveImageUrl });
|
|
36
|
+
const textures = new Map();
|
|
37
|
+
const pma = premultipliedTextures(doc);
|
|
38
|
+
const sampling = textureSamplings(doc);
|
|
39
|
+
for (const [id, img] of images)
|
|
40
|
+
textures.set(id, prepareTexture(new THREE.Texture(img), opts.mipmaps ?? true, pma.has(id), sampling.get(id)));
|
|
41
|
+
return { doc, baseUrl, textures };
|
|
42
|
+
}
|
|
43
|
+
// DARK (materials of batches with a two-colour tint): rgb = dark + (light - dark) × texture rgb, on premultiplied
|
|
44
|
+
// texels, as render-webgl. Without it the dark attribute is neither declared nor uploaded.
|
|
45
|
+
const VERTEX = /* glsl */ `
|
|
46
|
+
attribute vec4 obColor;
|
|
47
|
+
varying vec2 vUv;
|
|
48
|
+
varying vec4 vColor;
|
|
49
|
+
#ifdef DARK
|
|
50
|
+
attribute vec3 obDark;
|
|
51
|
+
varying vec3 vDark;
|
|
52
|
+
#endif
|
|
53
|
+
void main() {
|
|
54
|
+
vUv = uv;
|
|
55
|
+
vColor = obColor;
|
|
56
|
+
#ifdef DARK
|
|
57
|
+
vDark = obDark;
|
|
58
|
+
#endif
|
|
59
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
60
|
+
}`;
|
|
61
|
+
// Same maths as render-webgl: premultiplied texture times straight vertex colour, output premultiplied.
|
|
62
|
+
const FRAGMENT = /* glsl */ `
|
|
63
|
+
uniform sampler2D map;
|
|
64
|
+
uniform float opacity;
|
|
65
|
+
varying vec2 vUv;
|
|
66
|
+
varying vec4 vColor;
|
|
67
|
+
#ifdef DARK
|
|
68
|
+
varying vec3 vDark;
|
|
69
|
+
#endif
|
|
70
|
+
void main() {
|
|
71
|
+
vec4 t = texture2D(map, vUv);
|
|
72
|
+
#ifdef DARK
|
|
73
|
+
gl_FragColor = vec4(vDark * (t.a - t.rgb) + t.rgb * vColor.rgb, t.a) * vColor.a * opacity;
|
|
74
|
+
#else
|
|
75
|
+
gl_FragColor = vec4(t.rgb * vColor.rgb, t.a) * vColor.a * opacity;
|
|
76
|
+
#endif
|
|
77
|
+
}`;
|
|
78
|
+
/** render-webgl's blend functions (premultiplied alpha), as Three.js factors. */
|
|
79
|
+
export const BLEND_FACTORS = {
|
|
80
|
+
normal: [THREE.OneFactor, THREE.OneMinusSrcAlphaFactor],
|
|
81
|
+
additive: [THREE.OneFactor, THREE.OneFactor],
|
|
82
|
+
multiply: [THREE.DstColorFactor, THREE.OneMinusSrcAlphaFactor],
|
|
83
|
+
screen: [THREE.OneFactor, THREE.OneMinusSrcColorFactor],
|
|
84
|
+
};
|
|
85
|
+
let warned = false;
|
|
86
|
+
/** Clipping needs a stencil buffer, which WebGLRenderer no longer creates by default (r163+). */
|
|
87
|
+
function warnWithoutStencil(renderer) {
|
|
88
|
+
if (warned)
|
|
89
|
+
return;
|
|
90
|
+
const attrs = renderer.getContext().getContextAttributes?.();
|
|
91
|
+
if (attrs && !attrs.stencil) {
|
|
92
|
+
warned = true;
|
|
93
|
+
console.warn("OpenBone: this document uses clipping masks; create the renderer with new THREE.WebGLRenderer({ stencil: true }).");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Stencil reference values handed to clipping masks, shared by every object so masks never collide in a frame. */
|
|
97
|
+
let stencilRef = 0;
|
|
98
|
+
const nextStencilRef = () => (stencilRef = (stencilRef % 255) + 1);
|
|
99
|
+
/** A batch mesh whose buffers grow as needed and are re-filled each frame (no per-frame allocations). */
|
|
100
|
+
class BatchMesh extends THREE.Mesh {
|
|
101
|
+
capV = 0;
|
|
102
|
+
capI = 0;
|
|
103
|
+
/** True while the mesh holds a two-colour (dark) batch. */
|
|
104
|
+
twoColor = false;
|
|
105
|
+
constructor() {
|
|
106
|
+
super(new THREE.BufferGeometry(), undefined);
|
|
107
|
+
this.frustumCulled = false;
|
|
108
|
+
}
|
|
109
|
+
alloc(nv, ni) {
|
|
110
|
+
if (nv <= this.capV && ni <= this.capI)
|
|
111
|
+
return;
|
|
112
|
+
this.geometry.dispose();
|
|
113
|
+
this.capV = Math.max(64, 2 ** Math.ceil(Math.log2(nv)));
|
|
114
|
+
this.capI = Math.max(96, 2 ** Math.ceil(Math.log2(ni)));
|
|
115
|
+
const g = new THREE.BufferGeometry();
|
|
116
|
+
g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(this.capV * 3), 3).setUsage(THREE.DynamicDrawUsage));
|
|
117
|
+
g.setAttribute("uv", new THREE.BufferAttribute(new Float32Array(this.capV * 2), 2).setUsage(THREE.DynamicDrawUsage));
|
|
118
|
+
g.setAttribute("obColor", new THREE.BufferAttribute(new Float32Array(this.capV * 4), 4).setUsage(THREE.DynamicDrawUsage));
|
|
119
|
+
g.setIndex(new THREE.BufferAttribute(new Uint16Array(this.capI), 1).setUsage(THREE.DynamicDrawUsage));
|
|
120
|
+
this.geometry = g;
|
|
121
|
+
}
|
|
122
|
+
/** The dark colour attribute, added the first time this mesh holds a dark batch (re-added after a grow). */
|
|
123
|
+
darkAttribute() {
|
|
124
|
+
const g = this.geometry;
|
|
125
|
+
let a = g.getAttribute("obDark");
|
|
126
|
+
if (!a) {
|
|
127
|
+
a = new THREE.BufferAttribute(new Float32Array(this.capV * 3), 3).setUsage(THREE.DynamicDrawUsage);
|
|
128
|
+
g.setAttribute("obDark", a);
|
|
129
|
+
}
|
|
130
|
+
return a;
|
|
131
|
+
}
|
|
132
|
+
/** Fill from x,y pairs (+ optional uvs / colours / dark colours). */
|
|
133
|
+
fill(vertices, indices, uvs, colors, dark) {
|
|
134
|
+
const nv = vertices.length / 2;
|
|
135
|
+
this.alloc(nv, indices.length);
|
|
136
|
+
const g = this.geometry;
|
|
137
|
+
const pos = g.attributes.position;
|
|
138
|
+
const p = pos.array;
|
|
139
|
+
for (let i = 0; i < nv; i++) {
|
|
140
|
+
p[i * 3] = vertices[i * 2];
|
|
141
|
+
p[i * 3 + 1] = vertices[i * 2 + 1];
|
|
142
|
+
p[i * 3 + 2] = 0;
|
|
143
|
+
}
|
|
144
|
+
const uv = g.attributes.uv;
|
|
145
|
+
const col = g.attributes.obColor;
|
|
146
|
+
if (uvs)
|
|
147
|
+
uv.array.set(uvs);
|
|
148
|
+
if (colors)
|
|
149
|
+
col.array.set(colors);
|
|
150
|
+
else
|
|
151
|
+
col.array.fill(1, 0, nv * 4);
|
|
152
|
+
g.index.array.set(indices);
|
|
153
|
+
for (const [a, n] of [
|
|
154
|
+
[pos, nv * 3],
|
|
155
|
+
[uv, nv * 2],
|
|
156
|
+
[col, nv * 4],
|
|
157
|
+
[g.index, indices.length],
|
|
158
|
+
]) {
|
|
159
|
+
a.clearUpdateRanges();
|
|
160
|
+
a.addUpdateRange(0, n);
|
|
161
|
+
a.needsUpdate = true;
|
|
162
|
+
}
|
|
163
|
+
this.twoColor = !!dark;
|
|
164
|
+
if (dark) {
|
|
165
|
+
const d = this.darkAttribute();
|
|
166
|
+
d.array.set(dark);
|
|
167
|
+
d.clearUpdateRanges();
|
|
168
|
+
d.addUpdateRange(0, nv * 3);
|
|
169
|
+
d.needsUpdate = true;
|
|
170
|
+
}
|
|
171
|
+
g.setDrawRange(0, indices.length);
|
|
172
|
+
}
|
|
173
|
+
/** Read back what is drawn: x, y, u, v, r, g, b, a, dark r, g, b per index (for tests and debugging). */
|
|
174
|
+
drawnVertices() {
|
|
175
|
+
const g = this.geometry;
|
|
176
|
+
const p = g.attributes.position.array;
|
|
177
|
+
const uv = g.attributes.uv.array;
|
|
178
|
+
const c = g.attributes.obColor.array;
|
|
179
|
+
const d = this.twoColor ? g.attributes.obDark.array : null;
|
|
180
|
+
const out = [];
|
|
181
|
+
const idx = g.index.array;
|
|
182
|
+
for (let k = 0; k < g.drawRange.count; k++) {
|
|
183
|
+
const i = idx[k];
|
|
184
|
+
out.push([p[i * 3], p[i * 3 + 1], uv[i * 2], uv[i * 2 + 1], c[i * 4], c[i * 4 + 1], c[i * 4 + 2], c[i * 4 + 3], d ? d[i * 3] : 0, d ? d[i * 3 + 1] : 0, d ? d[i * 3 + 2] : 0]);
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* An OpenBone document as a Three.js object: one Mesh per render-webgl batch, sharing one ShaderMaterial per
|
|
191
|
+
* texture (atlas page) and blend mode, in the XY plane (skeleton units, y up). Draw order comes from renderOrder
|
|
192
|
+
* (this is a Group, so it sorts as one unit against the rest of the scene). Clipping masks use the stencil buffer.
|
|
193
|
+
*/
|
|
194
|
+
export class OpenBoneObject3D extends THREE.Group {
|
|
195
|
+
driver;
|
|
196
|
+
asset;
|
|
197
|
+
meshes = [];
|
|
198
|
+
masks = [];
|
|
199
|
+
materials = new Map();
|
|
200
|
+
text = new TextRasterizer();
|
|
201
|
+
textTextures = new Map();
|
|
202
|
+
dot = null;
|
|
203
|
+
stencilRefs = [];
|
|
204
|
+
white;
|
|
205
|
+
depthTest;
|
|
206
|
+
textResolution;
|
|
207
|
+
/** Opacity of the whole object (multiplies every slot). */
|
|
208
|
+
opacity = 1;
|
|
209
|
+
paused = false;
|
|
210
|
+
/** Batches drawn by the last redraw. */
|
|
211
|
+
drawCalls = 0;
|
|
212
|
+
constructor(asset, driver, opts = {}) {
|
|
213
|
+
super();
|
|
214
|
+
this.asset = asset;
|
|
215
|
+
this.driver = driver;
|
|
216
|
+
this.depthTest = opts.depthTest ?? true;
|
|
217
|
+
this.textResolution = opts.textResolution ?? 2;
|
|
218
|
+
this.white = prepareTexture(new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1), false);
|
|
219
|
+
this.redraw();
|
|
220
|
+
}
|
|
221
|
+
/** Load a document (URL, bytes or parsed) and create the object; waits for images and the script sandbox. */
|
|
222
|
+
static async from(src, opts = {}) {
|
|
223
|
+
const asset = isAsset(src) ? src : await loadOpenBone(src, opts);
|
|
224
|
+
const driver = await OpenBoneDriver.create(asset.doc, asset.baseUrl, { audioContext: opts.audioListener?.context, ...opts });
|
|
225
|
+
return new OpenBoneObject3D(asset, driver, opts);
|
|
226
|
+
}
|
|
227
|
+
get instance() {
|
|
228
|
+
return this.driver.instance;
|
|
229
|
+
}
|
|
230
|
+
get skeleton() {
|
|
231
|
+
return this.driver.skeleton;
|
|
232
|
+
}
|
|
233
|
+
get stateMachine() {
|
|
234
|
+
return this.driver.stateMachine;
|
|
235
|
+
}
|
|
236
|
+
get speed() {
|
|
237
|
+
return this.driver.speed;
|
|
238
|
+
}
|
|
239
|
+
set speed(v) {
|
|
240
|
+
this.driver.speed = v;
|
|
241
|
+
}
|
|
242
|
+
setInput(name, value) {
|
|
243
|
+
this.driver.setInput(name, value);
|
|
244
|
+
}
|
|
245
|
+
getInput(name) {
|
|
246
|
+
return this.driver.getInput(name);
|
|
247
|
+
}
|
|
248
|
+
fire(name) {
|
|
249
|
+
this.driver.fire(name);
|
|
250
|
+
}
|
|
251
|
+
setText(slot, text) {
|
|
252
|
+
this.driver.setText(slot, text);
|
|
253
|
+
}
|
|
254
|
+
setSkin(name) {
|
|
255
|
+
this.driver.setSkin(name);
|
|
256
|
+
this.redraw();
|
|
257
|
+
}
|
|
258
|
+
play(animation, loop = true) {
|
|
259
|
+
this.driver.play(animation, loop);
|
|
260
|
+
}
|
|
261
|
+
useStateMachine(name) {
|
|
262
|
+
return this.driver.useStateMachine(name);
|
|
263
|
+
}
|
|
264
|
+
/** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
|
|
265
|
+
onOpenBone = (name, fn) => this.driver.on(name, fn);
|
|
266
|
+
pause() {
|
|
267
|
+
this.paused = true;
|
|
268
|
+
this.driver.pause();
|
|
269
|
+
}
|
|
270
|
+
resume() {
|
|
271
|
+
this.paused = false;
|
|
272
|
+
this.driver.resume();
|
|
273
|
+
}
|
|
274
|
+
/** Advance by `dt` seconds and rebuild the meshes (call from your animation loop). */
|
|
275
|
+
update(dt) {
|
|
276
|
+
if (!this.paused)
|
|
277
|
+
this.driver.advance(dt);
|
|
278
|
+
this.redraw();
|
|
279
|
+
}
|
|
280
|
+
/** The artboard rectangle in local space (skeleton units, y up): x, y = bottom-left. */
|
|
281
|
+
get artboard() {
|
|
282
|
+
const d = this.asset.doc;
|
|
283
|
+
return { x: -d.originX, y: d.originY - d.height, width: d.width, height: d.height };
|
|
284
|
+
}
|
|
285
|
+
material(texture, blend, k) {
|
|
286
|
+
const dark = k.kind === "draw" && !!k.dark;
|
|
287
|
+
const key = `${texture.uuid}|${blend}|${k.kind}|${k.stencil}${dark ? "|dark" : ""}`;
|
|
288
|
+
let m = this.materials.get(key);
|
|
289
|
+
if (m) {
|
|
290
|
+
m.uniforms.opacity.value = this.opacity;
|
|
291
|
+
return m;
|
|
292
|
+
}
|
|
293
|
+
const [src, dst] = BLEND_FACTORS[blend] ?? BLEND_FACTORS.normal;
|
|
294
|
+
m = new THREE.ShaderMaterial({
|
|
295
|
+
uniforms: { map: { value: texture }, opacity: { value: this.opacity } },
|
|
296
|
+
vertexShader: VERTEX,
|
|
297
|
+
fragmentShader: FRAGMENT,
|
|
298
|
+
...(dark ? { defines: { DARK: "" } } : {}),
|
|
299
|
+
transparent: true,
|
|
300
|
+
premultipliedAlpha: true,
|
|
301
|
+
depthWrite: false,
|
|
302
|
+
depthTest: this.depthTest,
|
|
303
|
+
side: THREE.DoubleSide,
|
|
304
|
+
blending: THREE.CustomBlending,
|
|
305
|
+
blendEquation: THREE.AddEquation,
|
|
306
|
+
blendSrc: src,
|
|
307
|
+
blendDst: dst,
|
|
308
|
+
});
|
|
309
|
+
if (k.kind === "mask") {
|
|
310
|
+
m.colorWrite = false;
|
|
311
|
+
m.stencilWrite = true;
|
|
312
|
+
m.stencilRef = k.stencil;
|
|
313
|
+
m.stencilFunc = THREE.AlwaysStencilFunc;
|
|
314
|
+
m.stencilZPass = THREE.ReplaceStencilOp;
|
|
315
|
+
}
|
|
316
|
+
else if (k.stencil) {
|
|
317
|
+
m.stencilWrite = true;
|
|
318
|
+
m.stencilWriteMask = 0;
|
|
319
|
+
m.stencilRef = k.stencil;
|
|
320
|
+
m.stencilFunc = THREE.EqualStencilFunc;
|
|
321
|
+
m.stencilFail = m.stencilZFail = m.stencilZPass = THREE.KeepStencilOp;
|
|
322
|
+
}
|
|
323
|
+
this.materials.set(key, m);
|
|
324
|
+
return m;
|
|
325
|
+
}
|
|
326
|
+
textureFor(b) {
|
|
327
|
+
if (b.text) {
|
|
328
|
+
const r = this.text.get(b.text.id, b.text.draw, this.textResolution);
|
|
329
|
+
if (!r)
|
|
330
|
+
return this.white;
|
|
331
|
+
let e = this.textTextures.get(b.text.id);
|
|
332
|
+
if (!e || e.version !== r.version) {
|
|
333
|
+
if (e)
|
|
334
|
+
this.dropTexture(e.tex);
|
|
335
|
+
e = { tex: prepareTexture(new THREE.CanvasTexture(r.canvas), false), version: r.version };
|
|
336
|
+
this.textTextures.set(b.text.id, e);
|
|
337
|
+
}
|
|
338
|
+
return e.tex;
|
|
339
|
+
}
|
|
340
|
+
if (!b.texture)
|
|
341
|
+
return this.white;
|
|
342
|
+
if (b.texture === PARTICLE_DOT_TEXTURE) {
|
|
343
|
+
this.dot ??= prepareTexture(new THREE.DataTexture(new Uint8Array(particleDotPixels(true).buffer), PARTICLE_DOT_SIZE, PARTICLE_DOT_SIZE), false);
|
|
344
|
+
// Already premultiplied.
|
|
345
|
+
this.dot.premultiplyAlpha = false;
|
|
346
|
+
return this.dot;
|
|
347
|
+
}
|
|
348
|
+
return this.asset.textures.get(b.texture) ?? this.white;
|
|
349
|
+
}
|
|
350
|
+
dropTexture(t) {
|
|
351
|
+
for (const [k, m] of this.materials)
|
|
352
|
+
if (m.uniforms.map.value === t) {
|
|
353
|
+
m.dispose();
|
|
354
|
+
this.materials.delete(k);
|
|
355
|
+
}
|
|
356
|
+
t.dispose();
|
|
357
|
+
}
|
|
358
|
+
/** Rebuild meshes from the current pose (call after changing the pose by hand). */
|
|
359
|
+
redraw() {
|
|
360
|
+
const tex = this.asset.textures;
|
|
361
|
+
const batches = buildBatches(this.driver.instance.drawList(), { hasTexture: (id) => id === PARTICLE_DOT_TEXTURE || tex.has(id) });
|
|
362
|
+
for (const id of this.text.nextFrame()) {
|
|
363
|
+
const e = this.textTextures.get(id);
|
|
364
|
+
if (e)
|
|
365
|
+
this.dropTexture(e.tex);
|
|
366
|
+
this.textTextures.delete(id);
|
|
367
|
+
}
|
|
368
|
+
let order = 0;
|
|
369
|
+
let maskCount = 0;
|
|
370
|
+
let clip;
|
|
371
|
+
let ref = 0;
|
|
372
|
+
this.clear();
|
|
373
|
+
batches.forEach((b, i) => {
|
|
374
|
+
if (b.clip !== clip) {
|
|
375
|
+
clip = b.clip;
|
|
376
|
+
ref = 0;
|
|
377
|
+
if (clip) {
|
|
378
|
+
// Each clip run keeps its reference across frames, so its materials are reused.
|
|
379
|
+
ref = this.stencilRefs[maskCount] ??= nextStencilRef();
|
|
380
|
+
const mask = (this.masks[maskCount++] ??= new BatchMesh());
|
|
381
|
+
mask.fill(clip.polygon, clip.indices);
|
|
382
|
+
mask.material = this.material(this.white, "normal", { kind: "mask", stencil: ref });
|
|
383
|
+
mask.renderOrder = order++;
|
|
384
|
+
mask.onBeforeRender = warnWithoutStencil;
|
|
385
|
+
this.add(mask);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const mesh = (this.meshes[i] ??= new BatchMesh());
|
|
389
|
+
mesh.fill(b.vertices, b.indices, b.uvs, b.colors, b.dark);
|
|
390
|
+
mesh.material = this.material(this.textureFor(b), b.blend, { kind: "draw", stencil: ref, dark: !!b.dark });
|
|
391
|
+
mesh.renderOrder = order++;
|
|
392
|
+
this.add(mesh);
|
|
393
|
+
});
|
|
394
|
+
for (const m of this.meshes.splice(batches.length))
|
|
395
|
+
m.geometry.dispose();
|
|
396
|
+
for (const m of this.masks.splice(maskCount))
|
|
397
|
+
m.geometry.dispose();
|
|
398
|
+
this.drawCalls = batches.length;
|
|
399
|
+
}
|
|
400
|
+
/** The drawn meshes in order, with `mask` set for clipping-mask (stencil) meshes. */
|
|
401
|
+
drawnMeshes() {
|
|
402
|
+
return this.children.map((m) => ({ mask: !m.material.colorWrite, vertices: m.drawnVertices(), material: m.material }));
|
|
403
|
+
}
|
|
404
|
+
/** Where a ray hits the object's plane, in skeleton space (y up); null when parallel or behind. */
|
|
405
|
+
rayToSkeleton(ray) {
|
|
406
|
+
this.updateWorldMatrix(true, false);
|
|
407
|
+
const inv = new THREE.Matrix4().copy(this.matrixWorld).invert();
|
|
408
|
+
const local = ray.clone().applyMatrix4(inv);
|
|
409
|
+
const hit = local.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), new THREE.Vector3());
|
|
410
|
+
return hit ? [hit.x, hit.y] : null;
|
|
411
|
+
}
|
|
412
|
+
/** Skeleton space (y up) to a world-space point on the object's plane. */
|
|
413
|
+
skeletonToWorld(x, y, target = new THREE.Vector3()) {
|
|
414
|
+
this.updateWorldMatrix(true, false);
|
|
415
|
+
return target.set(x, y, 0).applyMatrix4(this.matrixWorld);
|
|
416
|
+
}
|
|
417
|
+
/** The active bounding boxes (skeleton space): `const p = obj.rayToSkeleton(ray); p && obj.boundingBoxes().containsPoint(...p)`. */
|
|
418
|
+
boundingBoxes() {
|
|
419
|
+
return this.driver.boundingBoxes();
|
|
420
|
+
}
|
|
421
|
+
/** Send a pointer event along a ray (e.g. raycaster.ray) to the state machine; outside the artboard ends hovers. */
|
|
422
|
+
pointer(type, ray) {
|
|
423
|
+
const p = this.rayToSkeleton(ray);
|
|
424
|
+
const a = this.artboard;
|
|
425
|
+
if (!p || p[0] < a.x || p[0] > a.x + a.width || p[1] < a.y || p[1] > a.y + a.height) {
|
|
426
|
+
if (type === "move")
|
|
427
|
+
this.driver.pointerLeave();
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
this.driver.pointer(type, p[0], p[1]);
|
|
431
|
+
}
|
|
432
|
+
/** Route a canvas's pointer events (raycast through `camera`) to the state machine. Returns an unbind function. */
|
|
433
|
+
bindPointer(dom, camera) {
|
|
434
|
+
const raycaster = new THREE.Raycaster();
|
|
435
|
+
const ndc = new THREE.Vector2();
|
|
436
|
+
const send = (type) => (e) => {
|
|
437
|
+
const r = dom.getBoundingClientRect();
|
|
438
|
+
ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
|
|
439
|
+
raycaster.setFromCamera(ndc, camera);
|
|
440
|
+
this.pointer(type, raycaster.ray);
|
|
441
|
+
};
|
|
442
|
+
const down = send("down");
|
|
443
|
+
const up = send("up");
|
|
444
|
+
const move = send("move");
|
|
445
|
+
const leave = () => this.driver.pointerLeave();
|
|
446
|
+
dom.addEventListener("pointerdown", down);
|
|
447
|
+
dom.addEventListener("pointerup", up);
|
|
448
|
+
dom.addEventListener("pointermove", move);
|
|
449
|
+
dom.addEventListener("pointerleave", leave);
|
|
450
|
+
return () => {
|
|
451
|
+
dom.removeEventListener("pointerdown", down);
|
|
452
|
+
dom.removeEventListener("pointerup", up);
|
|
453
|
+
dom.removeEventListener("pointermove", move);
|
|
454
|
+
dom.removeEventListener("pointerleave", leave);
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/** Free GPU resources (textures of the asset are kept: they may be shared). */
|
|
458
|
+
dispose() {
|
|
459
|
+
this.driver.dispose();
|
|
460
|
+
for (const m of [...this.meshes, ...this.masks])
|
|
461
|
+
m.geometry.dispose();
|
|
462
|
+
for (const m of this.materials.values())
|
|
463
|
+
m.dispose();
|
|
464
|
+
for (const e of this.textTextures.values())
|
|
465
|
+
e.tex.dispose();
|
|
466
|
+
this.dot?.dispose();
|
|
467
|
+
this.white.dispose();
|
|
468
|
+
this.materials.clear();
|
|
469
|
+
this.clear();
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function isAsset(x) {
|
|
473
|
+
return !!x && typeof x === "object" && "textures" in x && "doc" in x;
|
|
474
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openbone/three",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "OpenBone runtime for Three.js: an Object3D with one material per atlas page",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"openbone",
|
|
7
|
+
"skeletal-animation",
|
|
8
|
+
"2d-animation",
|
|
9
|
+
"animation",
|
|
10
|
+
"three",
|
|
11
|
+
"threejs"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/UXCentury/open-bone/tree/main/packages/three#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/UXCentury/open-bone/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/UXCentury/open-bone.git",
|
|
20
|
+
"directory": "packages/three"
|
|
21
|
+
},
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@openbone/runtime": "0.3.0",
|
|
39
|
+
"@openbone/core": "0.3.0",
|
|
40
|
+
"@openbone/engine-kit": "0.3.0"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"three": ">=0.160.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"esbuild": "^0.28.2",
|
|
47
|
+
"three": "^0.187.0",
|
|
48
|
+
"@types/three": "^0.187.0",
|
|
49
|
+
"@openbone/render-webgl": "0.3.0"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "node ../build.mjs"
|
|
53
|
+
},
|
|
54
|
+
"main": "./dist/index.js",
|
|
55
|
+
"types": "./dist/index.d.ts"
|
|
6
56
|
}
|