@hackbuild/live2d 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 +130 -2
- package/dist/core.d.ts +102 -0
- package/dist/core.js +56 -0
- package/dist/files.d.ts +72 -0
- package/dist/files.js +186 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/live2d.iife.js +903 -0
- package/dist/model.d.ts +56 -0
- package/dist/model.js +269 -0
- package/dist/motion.d.ts +90 -0
- package/dist/motion.js +168 -0
- package/dist/render.d.ts +48 -0
- package/dist/render.js +204 -0
- package/dist/single.d.ts +1 -0
- package/dist/single.js +2 -0
- package/how.ts +25 -0
- package/llms.md +367 -0
- package/package.json +34 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Moheeb Zara
|
|
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,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hackbuild/live2d
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Show a Live2D Cubism model in a canvas and drive its expressions, motions, gaze and mouth.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@hackbuild/live2d) [](../../LICENSE)  
|
|
6
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
9
|
+
- Opens a Cubism 3 or later model from a zip, a dropped folder or the URL of its `.model3.json`, and lists the files it names that are missing instead of failing.
|
|
10
|
+
- Draws it with a WebGL renderer written for this package: render order, opacity, multiply and screen colours, the normal, additive and multiplicative blend modes, and clipping masks through the stencil buffer.
|
|
11
|
+
- Plays `.motion3.json` motions (linear, bezier, stepped and inverse stepped segments, fades, loops, part opacity and pose groups) and `.exp3.json` expressions (add, multiply, overwrite).
|
|
12
|
+
- Blinks, breathes and plays the idle group on its own; turns toward a point; opens the mouth from a level you pass, such as a lip sync output.
|
|
13
|
+
- Leaves Live2D's own runtime, the Cubism Core, outside the package: it loads from cubism.live2d.com when a model opens, under Live2D's licence.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @hackbuild/live2d
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
It has no dependencies. The Cubism Core is Live2D's and ships outside npm: `loadCubismCore` adds Live2D's script to the page from `https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js` the first time a model opens, and `onLicence` receives the line to show. Pass `url` to load it from your own copy, or `core` when it is already on the page.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createLive2D, filesFrom, modelFromFiles } from "@hackbuild/live2d";
|
|
27
|
+
|
|
28
|
+
const canvas = document.querySelector<HTMLCanvasElement>("canvas")!;
|
|
29
|
+
const input = document.querySelector<HTMLInputElement>("input[type=file]")!;
|
|
30
|
+
|
|
31
|
+
// a .zip of a cubism 3 or later model, or its folder (input webkitdirectory)
|
|
32
|
+
input.addEventListener("change", async () => {
|
|
33
|
+
const source = await modelFromFiles(await filesFrom(input.files ?? []));
|
|
34
|
+
const model = await createLive2D(canvas, source, { frame: "bust", onLicence: (line) => console.info(line) });
|
|
35
|
+
model.expression(model.expressions[0] ?? null);
|
|
36
|
+
model.look(0.3, 0.1);
|
|
37
|
+
let t = 0;
|
|
38
|
+
setInterval(() => model.mouth(0.5 + 0.5 * Math.sin((t += 0.4))), 60);
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Live example
|
|
43
|
+
|
|
44
|
+
The demo page opens a model you drop or link, with its expressions, motions, framing and mouth: [hackbuild-motion/live2d](https://hackbuild.github.io/hackbuild-motion/live2d/). No model ships with it, since Live2D's sample models carry Live2D's own licence.
|
|
45
|
+
|
|
46
|
+
## Concepts
|
|
47
|
+
|
|
48
|
+
### the files
|
|
49
|
+
|
|
50
|
+
`filesFrom(fileList)` unpacks a single zip (stored and deflated entries, deflate through the browser's `DecompressionStream`) or keeps a folder's relative paths. `findModel` picks the `.model3.json` nearest the root and names a Cubism 2 model (`.moc`) or a lone `.moc3` plainly. `modelFromFiles` and `modelFromUrl` resolve every reference against the settings file's folder; a missing moc or texture is an error, a missing motion or expression goes into `missing`.
|
|
51
|
+
|
|
52
|
+
### one frame
|
|
53
|
+
|
|
54
|
+
Each frame starts from every parameter's default, then the playing motions (the old one fading out under the new), the expression, the blink on the model's `EyeBlink` group, a slow breath on the standard angle and breath parameters, the look target, the mouth on the `LipSync` group, and values held with `set`, each clamped to its range. The Cubism Core then updates the meshes and the renderer draws them.
|
|
55
|
+
|
|
56
|
+
### the renderer
|
|
57
|
+
|
|
58
|
+
Drawables are drawn in render order on premultiplied alpha. A drawable with masks first writes its mask meshes into the stencil where their alpha passes one half, then draws where the stencil is set, or where it is not for an inverted mask. `frame("bust")` fits the top half of the model's bounds; `frame("full")` fits all of it.
|
|
59
|
+
|
|
60
|
+
## API overview
|
|
61
|
+
|
|
62
|
+
| export | what it does |
|
|
63
|
+
|---|---|
|
|
64
|
+
| [`createLive2D`](../../docs/api/live2d/README.md#createlive2d) | open a model source on a canvas and start it |
|
|
65
|
+
| [`Live2DModel`](../../docs/api/live2d/README.md#live2dmodel) | expression, motion, mouth, look, set, frame, resize, update, dispose |
|
|
66
|
+
| [`modelFromFiles`](../../docs/api/live2d/README.md#modelfromfiles) | a model source from dropped files |
|
|
67
|
+
| [`modelFromUrl`](../../docs/api/live2d/README.md#modelfromurl) | a model source from a `.model3.json` URL |
|
|
68
|
+
| [`filesFrom`](../../docs/api/live2d/README.md#filesfrom) | a zip or a folder's files, by path |
|
|
69
|
+
| [`readZip`](../../docs/api/live2d/README.md#readzip) | stored and deflated zip entries |
|
|
70
|
+
| [`loadCubismCore`](../../docs/api/live2d/README.md#loadcubismcore) | add Live2D's Cubism Core to the page once |
|
|
71
|
+
| [`parseMotion`](../../docs/api/live2d/README.md#parsemotion) | a `.motion3.json` as curves |
|
|
72
|
+
| [`sampleMotion`](../../docs/api/live2d/README.md#samplemotion) | a motion's values and weights at a moment |
|
|
73
|
+
| [`parseExpression`](../../docs/api/live2d/README.md#parseexpression) | a `.exp3.json` |
|
|
74
|
+
| [`Live2DError`](../../docs/api/live2d/README.md#live2derror) | a model this package cannot open, with the reason |
|
|
75
|
+
|
|
76
|
+
The full reference is in [docs/api/live2d](../../docs/api/live2d/README.md).
|
|
77
|
+
|
|
78
|
+
## Browser support
|
|
79
|
+
|
|
80
|
+
| feature | needs | notes |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| drawing | WebGL 1 with a stencil buffer | 60 frames a second for a 42 parameter model in headless Chrome on an Apple M1 (measured) |
|
|
83
|
+
| deflated zips | `DecompressionStream("deflate-raw")` | Chrome, Edge, Firefox and Safari 16.4 and later (vendor); otherwise drop the folder |
|
|
84
|
+
| the Cubism Core | a network fetch from cubism.live2d.com | or pass `url` or `core` |
|
|
85
|
+
| single file build | `dist/live2d.iife.js` | `HackbuildLive2d` global, runs from file://, the core still loads from Live2D |
|
|
86
|
+
|
|
87
|
+
## Errors and troubleshooting
|
|
88
|
+
|
|
89
|
+
| message | cause | what to do |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| `this is a cubism 2 model (.moc)` | the model is from Cubism 2 | export it from a Cubism 3 or later editor, or use a .moc3 model |
|
|
92
|
+
| `no live2d model here` | the drop holds no `.model3.json` | drop the zip or the whole folder |
|
|
93
|
+
| `the moc ... that the settings name is missing` | the `.moc3` is not where the settings say | keep the folder structure the model came in |
|
|
94
|
+
| `could not read ...moc3: it may be newer than the core` | the model needs a newer Cubism Core | load a newer core with `url` |
|
|
95
|
+
| `the cubism core did not load from cubism.live2d.com` | offline, or the site is blocked | serve the core yourself and pass `url` |
|
|
96
|
+
|
|
97
|
+
## Works with
|
|
98
|
+
|
|
99
|
+
- [@hackbuild/lipsync](../lipsync/README.md) gives the mouth level `mouth()` takes.
|
|
100
|
+
- [@hackbuild/motion-views](../motion-views/README.md) holds the character stage a Live2D model can stand in for.
|
|
101
|
+
|
|
102
|
+
## Changelog and licences
|
|
103
|
+
|
|
104
|
+
Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LICENSE](../../LICENSE)); this README is CC-BY-4.0 with its code samples also MIT. The renderer, file reader, motion and expression players are written for this package from the published file formats; no Live2D framework code is used. The Cubism Core is Live2D's, under the Live2D Proprietary Software License Agreement, and loads from Live2D at run time; models carry their own licences.
|
|
105
|
+
|
|
106
|
+
## What is verified, and what is not
|
|
107
|
+
|
|
108
|
+
### Verified on this machine
|
|
109
|
+
|
|
110
|
+
| check | result |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `npx vitest run packages/live2d` | 12 of 12 tests pass: paths, a model by a relative url, a stored zip with a macOS folder skipped, model finding and its errors, a missing texture, each segment type, a free bezier, fades, loops, the three expression blends, the blink, the fit (counted) |
|
|
113
|
+
| Live2D's sample model haru (Cubism 3, 42 parameters) from its URL and from a zip, Cubism Core 5.1.0 from cubism.live2d.com, headless Chrome on an Apple M1 | opens in 496 ms on the demo page, lists 8 files the copy lacks, draws clean edges and clipped eyes, expression f04 and the mouth show, the bust frame and the Tap motion play, 4,744 to 11,830 pixels change between frames 250 ms apart, 60 frames a second (measured) |
|
|
114
|
+
|
|
115
|
+
### Not verified by anything
|
|
116
|
+
|
|
117
|
+
- Physics (`.physics3.json`) is not run, so hair and cloth do not swing; pose groups switch on motion part opacity only.
|
|
118
|
+
- Only one model has been opened; Cubism 4 and 5 features beyond multiply and screen colours (offscreen blending, newer mask modes) are untested.
|
|
119
|
+
- Nobody has watched it at real frame rate in a visible browser; the checks are headless shots and pixel counts.
|
|
120
|
+
- Motion sound files and user data files are ignored.
|
|
121
|
+
|
|
122
|
+
## Size budget
|
|
123
|
+
|
|
124
|
+
| file | gzip (measured) | ceiling |
|
|
125
|
+
|---|---|---|
|
|
126
|
+
| `dist/index.js` (main entry, imports external) | 11,026 bytes | 11,577 bytes |
|
|
127
|
+
| `dist/live2d.iife.js` (single file build) | 10,844 bytes | 11,386 bytes |
|
|
128
|
+
|
|
129
|
+
Measured 2026-11-30 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
|
|
130
|
+
tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
|
|
131
|
+
5 percent from its row.
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Live2D Cubism Core: Live2D's own runtime for .moc3 models, under the
|
|
3
|
+
* Live2D Proprietary Software License. This library never bundles or copies
|
|
4
|
+
* it; {@link loadCubismCore} adds Live2D's script from cubism.live2d.com to
|
|
5
|
+
* the page when a model is opened, and says whose licence applies. The types
|
|
6
|
+
* here cover the part of its JavaScript surface the renderer reads.
|
|
7
|
+
*/
|
|
8
|
+
/** Where Live2D serves the Cubism Core for the web. */
|
|
9
|
+
export declare const CUBISM_CORE_URL = "https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js";
|
|
10
|
+
/** The line a page shows the first time the core loads. */
|
|
11
|
+
export declare const CUBISM_CORE_LICENCE = "live2d cubism core, under the live2d proprietary software license agreement (https://www.live2d.com/eula/live2d-proprietary-software-license-agreement_en.html). it loads from cubism.live2d.com and is not part of this library.";
|
|
12
|
+
/** A model's parameters: ids and live values, with their ranges and defaults. */
|
|
13
|
+
export interface CoreParameters {
|
|
14
|
+
count: number;
|
|
15
|
+
ids: string[];
|
|
16
|
+
values: Float32Array;
|
|
17
|
+
minimumValues: Float32Array;
|
|
18
|
+
maximumValues: Float32Array;
|
|
19
|
+
defaultValues: Float32Array;
|
|
20
|
+
}
|
|
21
|
+
/** A model's parts: ids and live opacities. */
|
|
22
|
+
export interface CoreParts {
|
|
23
|
+
count: number;
|
|
24
|
+
ids: string[];
|
|
25
|
+
opacities: Float32Array;
|
|
26
|
+
}
|
|
27
|
+
/** A model's drawables, the meshes the renderer draws, refreshed by `update()`. */
|
|
28
|
+
export interface CoreDrawables {
|
|
29
|
+
count: number;
|
|
30
|
+
ids: string[];
|
|
31
|
+
constantFlags: Uint8Array;
|
|
32
|
+
dynamicFlags: Uint8Array;
|
|
33
|
+
textureIndices: Int32Array;
|
|
34
|
+
renderOrders: Int32Array;
|
|
35
|
+
opacities: Float32Array;
|
|
36
|
+
maskCounts: Int32Array;
|
|
37
|
+
masks: Int32Array[];
|
|
38
|
+
vertexCounts: Int32Array;
|
|
39
|
+
vertexPositions: Float32Array[];
|
|
40
|
+
vertexUvs: Float32Array[];
|
|
41
|
+
indexCounts: Int32Array;
|
|
42
|
+
indices: Uint16Array[];
|
|
43
|
+
/** Cubism 4.2 and later: four floats per drawable. */
|
|
44
|
+
multiplyColors?: Float32Array;
|
|
45
|
+
screenColors?: Float32Array;
|
|
46
|
+
resetDynamicFlags(): void;
|
|
47
|
+
}
|
|
48
|
+
/** One model instance from a moc. */
|
|
49
|
+
export interface CoreModel {
|
|
50
|
+
parameters: CoreParameters;
|
|
51
|
+
parts: CoreParts;
|
|
52
|
+
drawables: CoreDrawables;
|
|
53
|
+
canvasinfo: {
|
|
54
|
+
CanvasWidth: number;
|
|
55
|
+
CanvasHeight: number;
|
|
56
|
+
CanvasOriginX: number;
|
|
57
|
+
CanvasOriginY: number;
|
|
58
|
+
PixelsPerUnit: number;
|
|
59
|
+
};
|
|
60
|
+
update(): void;
|
|
61
|
+
release(): void;
|
|
62
|
+
}
|
|
63
|
+
/** A loaded .moc3. */
|
|
64
|
+
export interface CoreMoc {
|
|
65
|
+
_release?(): void;
|
|
66
|
+
}
|
|
67
|
+
/** The `Live2DCubismCore` global the core script defines. */
|
|
68
|
+
export interface CubismCore {
|
|
69
|
+
Version: {
|
|
70
|
+
csmGetVersion(): number;
|
|
71
|
+
};
|
|
72
|
+
Moc: {
|
|
73
|
+
fromArrayBuffer(buffer: ArrayBuffer): CoreMoc | null;
|
|
74
|
+
prototype: unknown;
|
|
75
|
+
} & {
|
|
76
|
+
hasMocConsistency?(buffer: ArrayBuffer): boolean;
|
|
77
|
+
};
|
|
78
|
+
Model: {
|
|
79
|
+
fromMoc(moc: CoreMoc): CoreModel | null;
|
|
80
|
+
};
|
|
81
|
+
Utils: {
|
|
82
|
+
hasBlendAdditiveBit(flags: number): boolean;
|
|
83
|
+
hasBlendMultiplicativeBit(flags: number): boolean;
|
|
84
|
+
hasIsInvertedMaskBit(flags: number): boolean;
|
|
85
|
+
hasIsVisibleBit(flags: number): boolean;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Options for {@link loadCubismCore}. */
|
|
89
|
+
export interface CoreOptions {
|
|
90
|
+
/** Where to load the core from. Default {@link CUBISM_CORE_URL}. */
|
|
91
|
+
url?: string;
|
|
92
|
+
/** Called once with {@link CUBISM_CORE_LICENCE} when the core is added to the page. */
|
|
93
|
+
onLicence?: (text: string) => void;
|
|
94
|
+
}
|
|
95
|
+
/** A Live2D model the library cannot open, with the reason in words a page can show. */
|
|
96
|
+
export declare class Live2DError extends Error {
|
|
97
|
+
constructor(message: string);
|
|
98
|
+
}
|
|
99
|
+
/** Adds Live2D's Cubism Core to the page once and resolves to it; a core already on the page is used as is. */
|
|
100
|
+
export declare function loadCubismCore(o?: CoreOptions): Promise<CubismCore>;
|
|
101
|
+
/** The core's version as major.minor.patch, from its packed number. */
|
|
102
|
+
export declare function coreVersion(core: CubismCore): string;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Live2D Cubism Core: Live2D's own runtime for .moc3 models, under the
|
|
3
|
+
* Live2D Proprietary Software License. This library never bundles or copies
|
|
4
|
+
* it; {@link loadCubismCore} adds Live2D's script from cubism.live2d.com to
|
|
5
|
+
* the page when a model is opened, and says whose licence applies. The types
|
|
6
|
+
* here cover the part of its JavaScript surface the renderer reads.
|
|
7
|
+
*/
|
|
8
|
+
/** Where Live2D serves the Cubism Core for the web. */
|
|
9
|
+
export const CUBISM_CORE_URL = "https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js";
|
|
10
|
+
/** The line a page shows the first time the core loads. */
|
|
11
|
+
export const CUBISM_CORE_LICENCE = "live2d cubism core, under the live2d proprietary software license agreement (https://www.live2d.com/eula/live2d-proprietary-software-license-agreement_en.html). it loads from cubism.live2d.com and is not part of this library.";
|
|
12
|
+
/** A Live2D model the library cannot open, with the reason in words a page can show. */
|
|
13
|
+
export class Live2DError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "Live2DError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
let loading = null;
|
|
20
|
+
const coreOf = () => globalThis.Live2DCubismCore;
|
|
21
|
+
/** Adds Live2D's Cubism Core to the page once and resolves to it; a core already on the page is used as is. */
|
|
22
|
+
export function loadCubismCore(o = {}) {
|
|
23
|
+
const have = coreOf();
|
|
24
|
+
if (have)
|
|
25
|
+
return Promise.resolve(have);
|
|
26
|
+
if (loading)
|
|
27
|
+
return loading;
|
|
28
|
+
if (typeof document === "undefined")
|
|
29
|
+
return Promise.reject(new Live2DError("the cubism core loads into a page; there is no document here."));
|
|
30
|
+
loading = new Promise((resolve, reject) => {
|
|
31
|
+
const s = document.createElement("script");
|
|
32
|
+
s.src = o.url ?? CUBISM_CORE_URL;
|
|
33
|
+
s.async = true;
|
|
34
|
+
s.onload = () => {
|
|
35
|
+
const core = coreOf();
|
|
36
|
+
if (core) {
|
|
37
|
+
o.onLicence?.(CUBISM_CORE_LICENCE);
|
|
38
|
+
resolve(core);
|
|
39
|
+
}
|
|
40
|
+
else
|
|
41
|
+
reject(new Live2DError("the cubism core script loaded but defined nothing."));
|
|
42
|
+
};
|
|
43
|
+
s.onerror = () => {
|
|
44
|
+
loading = null;
|
|
45
|
+
s.remove();
|
|
46
|
+
reject(new Live2DError("the cubism core did not load from cubism.live2d.com. check the connection; live2d models need it."));
|
|
47
|
+
};
|
|
48
|
+
document.head.append(s);
|
|
49
|
+
});
|
|
50
|
+
return loading;
|
|
51
|
+
}
|
|
52
|
+
/** The core's version as major.minor.patch, from its packed number. */
|
|
53
|
+
export function coreVersion(core) {
|
|
54
|
+
const v = core.Version.csmGetVersion();
|
|
55
|
+
return `${(v >>> 24) & 0xff}.${(v >>> 16) & 0xff}.${v & 0xffff}`;
|
|
56
|
+
}
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Live2D model as files: a .model3.json and what it names (the .moc3,
|
|
3
|
+
* textures, motions, expressions, physics, pose), from a zip, a folder or a
|
|
4
|
+
* file list the user dropped, or from a URL. The zip reader is written from
|
|
5
|
+
* the published ZIP format: stored and deflated entries, deflate through the
|
|
6
|
+
* browser's DecompressionStream. A reference the files do not hold is listed
|
|
7
|
+
* in `missing`, and the model still opens.
|
|
8
|
+
*/
|
|
9
|
+
/** A model's files by path, relative to the archive or folder root, with forward slashes. */
|
|
10
|
+
export type ModelFiles = Map<string, Blob>;
|
|
11
|
+
/** The parts of a .model3.json this library reads. */
|
|
12
|
+
export interface Model3 {
|
|
13
|
+
Version?: number;
|
|
14
|
+
FileReferences: {
|
|
15
|
+
Moc: string;
|
|
16
|
+
Textures: string[];
|
|
17
|
+
Physics?: string;
|
|
18
|
+
Pose?: string;
|
|
19
|
+
Expressions?: {
|
|
20
|
+
Name: string;
|
|
21
|
+
File: string;
|
|
22
|
+
}[];
|
|
23
|
+
Motions?: Record<string, {
|
|
24
|
+
File: string;
|
|
25
|
+
FadeInTime?: number;
|
|
26
|
+
FadeOutTime?: number;
|
|
27
|
+
Sound?: string;
|
|
28
|
+
}[]>;
|
|
29
|
+
};
|
|
30
|
+
Groups?: {
|
|
31
|
+
Target: string;
|
|
32
|
+
Name: string;
|
|
33
|
+
Ids: string[];
|
|
34
|
+
}[];
|
|
35
|
+
}
|
|
36
|
+
/** One motion as the model names it, with its parsed file or null when it is missing. */
|
|
37
|
+
export interface MotionRef {
|
|
38
|
+
group: string;
|
|
39
|
+
index: number;
|
|
40
|
+
file: string;
|
|
41
|
+
json: unknown | null;
|
|
42
|
+
fadeIn?: number;
|
|
43
|
+
fadeOut?: number;
|
|
44
|
+
}
|
|
45
|
+
/** A model ready to open: the settings, the moc bytes, textures, motions, expressions and what was missing. */
|
|
46
|
+
export interface ModelSource {
|
|
47
|
+
name: string;
|
|
48
|
+
settings: Model3;
|
|
49
|
+
moc: ArrayBuffer;
|
|
50
|
+
textures: Blob[];
|
|
51
|
+
motions: MotionRef[];
|
|
52
|
+
expressions: {
|
|
53
|
+
name: string;
|
|
54
|
+
json: unknown;
|
|
55
|
+
}[];
|
|
56
|
+
pose: unknown | null;
|
|
57
|
+
physics: unknown | null;
|
|
58
|
+
/** Referenced files the source does not hold. */
|
|
59
|
+
missing: string[];
|
|
60
|
+
}
|
|
61
|
+
/** Joins a reference onto the folder of the file that names it, resolving `..` and `.`. */
|
|
62
|
+
export declare function joinPath(base: string, ref: string): string;
|
|
63
|
+
/** Reads a zip into files: stored and deflated entries, by its central directory. */
|
|
64
|
+
export declare function readZip(buffer: ArrayBuffer): Promise<ModelFiles>;
|
|
65
|
+
/** Files from a drop or a picker: a zip is unpacked, a folder keeps its relative paths. */
|
|
66
|
+
export declare function filesFrom(list: Iterable<File>): Promise<ModelFiles>;
|
|
67
|
+
/** The model settings file among the files: the .model3.json nearest the root. */
|
|
68
|
+
export declare function findModel(files: ModelFiles): string;
|
|
69
|
+
/** A model from dropped files: the settings, every file it names that is present, and the rest in `missing`. */
|
|
70
|
+
export declare function modelFromFiles(files: ModelFiles, path?: string): Promise<ModelSource>;
|
|
71
|
+
/** A model by the URL of its .model3.json; every file it names is fetched beside it. */
|
|
72
|
+
export declare function modelFromUrl(url: string, f?: typeof fetch): Promise<ModelSource>;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Live2D model as files: a .model3.json and what it names (the .moc3,
|
|
3
|
+
* textures, motions, expressions, physics, pose), from a zip, a folder or a
|
|
4
|
+
* file list the user dropped, or from a URL. The zip reader is written from
|
|
5
|
+
* the published ZIP format: stored and deflated entries, deflate through the
|
|
6
|
+
* browser's DecompressionStream. A reference the files do not hold is listed
|
|
7
|
+
* in `missing`, and the model still opens.
|
|
8
|
+
*/
|
|
9
|
+
import { Live2DError } from "./core.js";
|
|
10
|
+
const norm = (p) => p.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
|
|
11
|
+
/** Joins a reference onto the folder of the file that names it, resolving `..` and `.`. */
|
|
12
|
+
export function joinPath(base, ref) {
|
|
13
|
+
const out = norm(base).split("/").slice(0, -1);
|
|
14
|
+
for (const part of norm(ref).split("/")) {
|
|
15
|
+
if (part === "..")
|
|
16
|
+
out.pop();
|
|
17
|
+
else if (part && part !== ".")
|
|
18
|
+
out.push(part);
|
|
19
|
+
}
|
|
20
|
+
return out.join("/");
|
|
21
|
+
}
|
|
22
|
+
/** Reads a zip into files: stored and deflated entries, by its central directory. */
|
|
23
|
+
export async function readZip(buffer) {
|
|
24
|
+
const v = new DataView(buffer);
|
|
25
|
+
let eocd = -1;
|
|
26
|
+
for (let i = buffer.byteLength - 22; i >= Math.max(0, buffer.byteLength - 65557); i--) {
|
|
27
|
+
if (v.getUint32(i, true) === 0x06054b50) {
|
|
28
|
+
eocd = i;
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (eocd < 0)
|
|
33
|
+
throw new Live2DError("this file is not a zip.");
|
|
34
|
+
const count = v.getUint16(eocd + 10, true);
|
|
35
|
+
let p = v.getUint32(eocd + 16, true);
|
|
36
|
+
const out = new Map();
|
|
37
|
+
const dec = new TextDecoder();
|
|
38
|
+
for (let n = 0; n < count; n++) {
|
|
39
|
+
if (v.getUint32(p, true) !== 0x02014b50)
|
|
40
|
+
throw new Live2DError("the zip's directory is damaged.");
|
|
41
|
+
const method = v.getUint16(p + 10, true);
|
|
42
|
+
const size = v.getUint32(p + 20, true);
|
|
43
|
+
const nameLen = v.getUint16(p + 28, true);
|
|
44
|
+
const extraLen = v.getUint16(p + 30, true);
|
|
45
|
+
const commentLen = v.getUint16(p + 32, true);
|
|
46
|
+
const local = v.getUint32(p + 42, true);
|
|
47
|
+
const name = norm(dec.decode(new Uint8Array(buffer, p + 46, nameLen)));
|
|
48
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
49
|
+
if (name.endsWith("/") || name.startsWith("__MACOSX/"))
|
|
50
|
+
continue;
|
|
51
|
+
const dataAt = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true);
|
|
52
|
+
const raw = new Uint8Array(buffer.slice(dataAt, dataAt + size));
|
|
53
|
+
if (method === 0)
|
|
54
|
+
out.set(name, new Blob([raw]));
|
|
55
|
+
else if (method === 8) {
|
|
56
|
+
if (typeof DecompressionStream === "undefined")
|
|
57
|
+
throw new Live2DError("this browser cannot unpack a deflated zip. unzip it and drop the folder.");
|
|
58
|
+
const stream = new Blob([raw]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
|
|
59
|
+
out.set(name, await new Response(stream).blob());
|
|
60
|
+
}
|
|
61
|
+
else
|
|
62
|
+
throw new Live2DError(`the zip uses compression method ${method}, which this reader does not unpack. unzip it and drop the folder.`);
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/** Files from a drop or a picker: a zip is unpacked, a folder keeps its relative paths. */
|
|
67
|
+
export async function filesFrom(list) {
|
|
68
|
+
const files = [...list];
|
|
69
|
+
if (files.length === 1 && /\.zip$/i.test(files[0].name))
|
|
70
|
+
return readZip(await files[0].arrayBuffer());
|
|
71
|
+
const out = new Map();
|
|
72
|
+
for (const f of files)
|
|
73
|
+
out.set(norm(f.webkitRelativePath || f.name), f);
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
/** The model settings file among the files: the .model3.json nearest the root. */
|
|
77
|
+
export function findModel(files) {
|
|
78
|
+
const paths = [...files.keys()];
|
|
79
|
+
const m3 = paths.filter((p) => /\.model3\.json$/i.test(p)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length);
|
|
80
|
+
if (m3[0])
|
|
81
|
+
return m3[0];
|
|
82
|
+
if (paths.some((p) => /\.moc$/i.test(p)) || paths.some((p) => /(^|\/)[^/]*\.model\.json$/i.test(p)))
|
|
83
|
+
throw new Live2DError("this is a cubism 2 model (.moc). this library opens cubism 3 and later models (.moc3).");
|
|
84
|
+
if (paths.some((p) => /\.moc3$/i.test(p)))
|
|
85
|
+
throw new Live2DError("there is a .moc3 but no .model3.json that names its textures. add the .model3.json.");
|
|
86
|
+
throw new Live2DError("no live2d model here: drop a zip or a folder holding a .model3.json.");
|
|
87
|
+
}
|
|
88
|
+
async function json(b) {
|
|
89
|
+
if (!b)
|
|
90
|
+
return null;
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(await b.text());
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** A model from dropped files: the settings, every file it names that is present, and the rest in `missing`. */
|
|
99
|
+
export async function modelFromFiles(files, path = findModel(files)) {
|
|
100
|
+
const settings = (await json(files.get(path)));
|
|
101
|
+
if (!settings?.FileReferences?.Moc)
|
|
102
|
+
throw new Live2DError(`${path} is not a model3 settings file: it names no moc.`);
|
|
103
|
+
return assemble(settings, path, (ref) => files.get(joinPath(path, ref)));
|
|
104
|
+
}
|
|
105
|
+
/** A model by the URL of its .model3.json; every file it names is fetched beside it. */
|
|
106
|
+
export async function modelFromUrl(url, f = globalThis.fetch.bind(globalThis)) {
|
|
107
|
+
// a relative url resolves against the page, as fetch would
|
|
108
|
+
const here = globalThis.location?.href;
|
|
109
|
+
let abs;
|
|
110
|
+
try {
|
|
111
|
+
abs = new URL(url, here).href;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
throw new Live2DError(`${url} is not a url this page can resolve.`);
|
|
115
|
+
}
|
|
116
|
+
url = abs;
|
|
117
|
+
const res = await f(url);
|
|
118
|
+
if (!res.ok)
|
|
119
|
+
throw new Live2DError(`the model settings at ${url} answered ${res.status}.`);
|
|
120
|
+
const settings = (await res.json());
|
|
121
|
+
if (!settings?.FileReferences?.Moc)
|
|
122
|
+
throw new Live2DError(`${url} is not a model3 settings file: it names no moc.`);
|
|
123
|
+
const blobs = new Map();
|
|
124
|
+
const refs = refsOf(settings);
|
|
125
|
+
await Promise.all(refs.map(async (ref) => {
|
|
126
|
+
try {
|
|
127
|
+
const r = await f(new URL(ref, url).href);
|
|
128
|
+
blobs.set(ref, r.ok ? await r.blob() : undefined);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
blobs.set(ref, undefined);
|
|
132
|
+
}
|
|
133
|
+
}));
|
|
134
|
+
return assemble(settings, new URL(url).pathname, (ref) => blobs.get(ref));
|
|
135
|
+
}
|
|
136
|
+
function refsOf(s) {
|
|
137
|
+
const r = s.FileReferences;
|
|
138
|
+
return [r.Moc, ...r.Textures, ...(r.Physics ? [r.Physics] : []), ...(r.Pose ? [r.Pose] : []), ...(r.Expressions ?? []).map((e) => e.File), ...Object.values(r.Motions ?? {}).flat().map((m) => m.File)];
|
|
139
|
+
}
|
|
140
|
+
async function assemble(settings, path, get) {
|
|
141
|
+
const r = settings.FileReferences;
|
|
142
|
+
const missing = [];
|
|
143
|
+
const need = (ref) => {
|
|
144
|
+
const b = get(ref);
|
|
145
|
+
if (!b)
|
|
146
|
+
missing.push(ref);
|
|
147
|
+
return b;
|
|
148
|
+
};
|
|
149
|
+
const moc = need(r.Moc);
|
|
150
|
+
if (!moc)
|
|
151
|
+
throw new Live2DError(`the moc ${r.Moc} that the settings name is missing.`);
|
|
152
|
+
const textures = [];
|
|
153
|
+
for (const t of r.Textures) {
|
|
154
|
+
const b = need(t);
|
|
155
|
+
if (!b)
|
|
156
|
+
throw new Live2DError(`the texture ${t} that the settings name is missing.`);
|
|
157
|
+
textures.push(b);
|
|
158
|
+
}
|
|
159
|
+
const motions = [];
|
|
160
|
+
for (const [group, list] of Object.entries(r.Motions ?? {}))
|
|
161
|
+
for (const [index, m] of list.entries()) {
|
|
162
|
+
const ref = { group, index, file: m.File, json: await json(need(m.File)) };
|
|
163
|
+
if (m.FadeInTime !== undefined)
|
|
164
|
+
ref.fadeIn = m.FadeInTime;
|
|
165
|
+
if (m.FadeOutTime !== undefined)
|
|
166
|
+
ref.fadeOut = m.FadeOutTime;
|
|
167
|
+
motions.push(ref);
|
|
168
|
+
}
|
|
169
|
+
const expressions = [];
|
|
170
|
+
for (const e of r.Expressions ?? []) {
|
|
171
|
+
const j = await json(need(e.File));
|
|
172
|
+
if (j)
|
|
173
|
+
expressions.push({ name: e.Name, json: j });
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
name: norm(path).split("/").pop().replace(/\.model3\.json$/i, ""),
|
|
177
|
+
settings,
|
|
178
|
+
moc: await moc.arrayBuffer(),
|
|
179
|
+
textures,
|
|
180
|
+
motions,
|
|
181
|
+
expressions,
|
|
182
|
+
pose: r.Pose ? await json(need(r.Pose)) : null,
|
|
183
|
+
physics: r.Physics ? await json(need(r.Physics)) : null,
|
|
184
|
+
missing,
|
|
185
|
+
};
|
|
186
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CUBISM_CORE_URL, CUBISM_CORE_LICENCE, Live2DError, loadCubismCore, coreVersion, type CubismCore, type CoreModel, type CoreOptions } from "./core.js";
|
|
2
|
+
export { readZip, filesFrom, findModel, modelFromFiles, modelFromUrl, joinPath, type ModelFiles, type ModelSource, type Model3, type MotionRef } from "./files.js";
|
|
3
|
+
export { parseMotion, curveValue, sampleMotion, parseExpression, blendExpression, ease, Blinker, type Motion, type Curve, type MotionFrame, type Expression, type ExpressionBlend } from "./motion.js";
|
|
4
|
+
export { createLive2D, type Live2DModel, type Live2DOptions, type Live2DFrame } from "./model.js";
|
|
5
|
+
export { fitMatrix, modelBounds } from "./render.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CUBISM_CORE_URL, CUBISM_CORE_LICENCE, Live2DError, loadCubismCore, coreVersion } from "./core.js";
|
|
2
|
+
export { readZip, filesFrom, findModel, modelFromFiles, modelFromUrl, joinPath } from "./files.js";
|
|
3
|
+
export { parseMotion, curveValue, sampleMotion, parseExpression, blendExpression, ease, Blinker } from "./motion.js";
|
|
4
|
+
export { createLive2D } from "./model.js";
|
|
5
|
+
export { fitMatrix, modelBounds } from "./render.js";
|