@margoengine/armies 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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/armies
2
+
3
+ Armies of hundreds of soldiers and horses, drawn at every distance. A `@margoengine/navmesh/formations` `Army` moves
4
+ the men and horses in line, column, square, wedge or skirmish order, on the march or in a charge; `addArmy` draws them:
5
+ every foot soldier and rider as one crowd of a baked person (skinned on the GPU when big on screen, a vertex animation
6
+ of a simplified mesh when small, culled when off screen or too small to see, all inside a budget), every horse in one
7
+ `@margoengine/horses/crowd` herd, each rider seated on the saddle its horse is drawn with. Clips follow each man's
8
+ ground speed (stand, walk, run) at the phase the ground he covered gives, so feet never slide; soldiers keep step;
9
+ each has his own height and outfit. Every frame is a pure function of the army's film time and the camera, so a film
10
+ seeks exactly.
11
+
12
+ Any person plugs in: a Character Creator export loaded through `@margoengine/fbx` and dressed by
13
+ `@margoengine/humans` `addPerson`, a glTF, or a body built in code. Bake it once with `bakePerson`.
14
+
15
+ ```ts
16
+ import {Engine} from 'margoengine';
17
+ import {loadGLTF} from 'margoengine/gltf/pbr';
18
+ import {Animation} from 'margoengine/animation';
19
+ import {Army} from 'margoengine/navmesh/formations';
20
+ import {addArmy, bakePerson} from 'margoengine/armies';
21
+ const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 6, -40], target: [0, 1, 10], fov: 35}});
22
+ const model = await loadGLTF(engine, '/examples/assets/khronos/RiggedFigure/RiggedFigure.glb');
23
+ const person = await bakePerson(new Animation(model));
24
+ model.dispose();
25
+ const army = new Army();
26
+ army.add({count: 200, shape: 'line', ranks: 2}).march();
27
+ army.add({count: 30, kind: 'cavalry', shape: 'line', ranks: 2, position: [0, -25]}).charge({goal: [0, 150]});
28
+ const drawn = await addArmy(engine, army, {person});
29
+ army.advanceTime(4);
30
+ drawn.update(engine.camera);
31
+ console.log(drawn.persons.length, drawn.horses?.count, drawn.people.counts); // 230 people (200 on foot, 30 riders), 30 horses
32
+ ```
33
+
34
+ | Option of `addArmy` | Default |
35
+ | --- | --- |
36
+ | `person` | needed: a `bakePerson` bake |
37
+ | `clips` | `{stand: 'stand', walk: 'walk', run: 'run', ride: 'ride'}` by name or index; a missing run walks, a missing stand holds the walk, a missing ride stands |
38
+ | `strides` | ground one clip cycle covers at scale 1: walk 1.524 m (two 30 inch steps, quick time), run 1.829 m (two 36 inch steps, double time), Infantry Drill Regulations 1911 |
39
+ | `runAbove`, `blendBand`, `standBelow` | 2 m/s (the walk-run change), 0.4 m/s, 0.1 m/s |
40
+ | `step` | `'cadence'`: the men keep step; `'route'`: each his own phase |
41
+ | `stature` | 0.04: one standard deviation of height as a fraction of the mean (about 7 cm on 1.75 m), cut at 2.5 |
42
+ | `variants` | outfits as atlas regions (`castVariants` of `@margoengine/humans/cast` fits), handed out by a seeded hash |
43
+ | `facing` | 0: the model faces +Z (glTF) |
44
+ | `horses` | `addHorseCrowd` options for cavalry; `false` draws no horses (and no riders) |
45
+ | `rider` | `{height, hipHeight, seatHip, pitchShare}` as `riderMatrix` |
46
+ | `near`, `far`, `vertices`, `nearScreen`, `cullScreen`, `hysteresis` | the crowd budget: see Levels |
47
+ | `map`, `color`, `roughness`, `metalness` | the person's look, as `VATCrowd` |
48
+ | `seed` | 1 |
49
+
50
+ `drawn.update(view, aspect?)` reads `army.members` and `army.time`: call it after `army.advanceTime(dt)` or
51
+ `army.seek(t)` and after placing the camera, with the engine's camera. A core Camera only refreshes its frustum as it
52
+ renders, so `update` brings it up to date first (at `aspect`, default the canvas's): the plan follows where the camera
53
+ is now, on the first frame and on a seek alike. `drawn.people.near` and `drawn.people.far` are the two draws and `drawn.horses.crowd` the
54
+ herd, for `shadows.add(...)` and `lighting.add(...)`.
55
+
56
+ ## Baking a person (`./bake`)
57
+
58
+ `bakePerson(animation, {fps, clips, farTriangles})` bakes the person's clips into a bone texture (the near level,
59
+ `@margoengine/animation/instanced-skin` `bakeBones`), simplifies the mesh to at most `farTriangles` (3000) by quadric
60
+ collapses (`@margoengine/lod/auto`; every kept vertex is one of the source's, with its own position, normal, UV and skin
61
+ weights; vertices that follow different bones are never welded), and poses the simplified mesh on the CPU from the same
62
+ bone rows into a vertex animation texture (the far level, `@margoengine/animation/vat`). Skinning is linear in the bone
63
+ matrices, so posing the rows and interpolating them gives what the shader gets by interpolating the matrices: a member
64
+ handed from one level to the other stands where it stood, within 1e-5 m. The far texture of four one-second clips at
65
+ 30 a second and 3000 triangles is about 12 MB; past 8192 texture rows `bakePerson` throws and names the fix.
66
+
67
+ ```ts
68
+ import {Engine} from 'margoengine';
69
+ import {loadGLTF} from 'margoengine/gltf/pbr';
70
+ import {Animation} from 'margoengine/animation';
71
+ import {bakePerson} from 'margoengine/armies/bake';
72
+ const engine = await Engine.create(document.querySelector('canvas')!);
73
+ const model = await loadGLTF(engine, '/examples/assets/khronos/RiggedFigure/RiggedFigure.glb');
74
+ const bake = await bakePerson(new Animation(model), {farTriangles: 500});
75
+ console.log(bake.near.vertexCount, bake.far.vertexCount, bake.height.toFixed(2)); // near and far vertices, the bind pose height
76
+ ```
77
+
78
+ `reduceBones(bake, ratio)` and `vatFromBones(bake)` are the two steps on their own; `personHeight(bake)` the bind pose
79
+ height.
80
+
81
+ ## Levels (`./lod`)
82
+
83
+ `PersonCrowd.attach(engine, bake, options)` draws a person crowd in two draws and `update(people, view)` plans each
84
+ member's level from its size on screen, the biggest first: skinned near while at least `nearScreen` (0.08) of the
85
+ view tall and inside the `near` (128) and `vertices` (8,000,000 a frame) budgets, otherwise far inside the `far`
86
+ (16,384) and vertex budgets, otherwise not drawn; members smaller than `cullScreen` (0.002, two pixels of a 1080 line
87
+ view) or outside the camera's frustum planes are not drawn. `hysteresis` (0) keeps a near member near down to
88
+ `nearScreen * (1 - hysteresis)` in an interactive view; at 0 every frame depends on nothing but the members and the
89
+ camera. The near level blends two clips; the far one plays the clip with more weight. `planCrowd` is the plan alone,
90
+ pure.
91
+
92
+ ```ts
93
+ import {planCrowd, NEAR, FAR} from 'margoengine/armies/lod';
94
+ const members = Array.from({length: 100}, (_, i) => ({x: 0, y: 0.9, z: 5 + i * 3, radius: 0.96}));
95
+ const levels = planCrowd(members, {position: [0, 1.7, 0], fov: 35}, {near: 20}, {near: 12000, far: 1500});
96
+ console.log(levels.filter((l) => l === NEAR).length, levels.filter((l) => l === FAR).length); // 12 near (to 38 m), 88 far
97
+ ```
98
+
99
+ ## Riders (`./riders`)
100
+
101
+ `riderMatrix(saddles, at, scale, placement)` places a rider's root from a horse's seat frame (`herd.saddles` of
102
+ `@margoengine/horses/crowd`, read back from the bone texture the horse is drawn with): the rider's hip joint 0.055 of
103
+ his height above the seat point (`@margoengine/horses/seat` riderSeat), his root `hipHeight` (0.53 of his height) below
104
+ it, facing the horse's way with `pitchShare` (0.4) of the trunk's pitch. A crowd rider follows the saddle rigidly, so
105
+ frames seek exactly; `mountRider` adds the damped spring for a single close-up rider. The rider plays the `ride` clip
106
+ one cycle a horse stride.
107
+
108
+ ```ts
109
+ import {riderMatrix} from 'margoengine/armies/riders';
110
+ const seat = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 1.55, 5, 1]); // a seat frame at 1.55 m
111
+ const root = riderMatrix(seat, 0, 1, {height: 1.75});
112
+ console.log(root[13].toFixed(2)); // 0.72: the hip 0.096 m above the seat, the root 0.928 m below the hip
113
+ ```
114
+
115
+ ## Settings (`./settings`)
116
+
117
+ `ARMY_SETTINGS` holds every option above as slider rows on the shared shape (`@margoengine/sky/settings` is the
118
+ model): the budget and level rows, the gait rows, step, stature, facing, seed and the rider rows are live (the next
119
+ `update` takes them); `fps` and `farTriangles` rebake. No row follows the weather. The formation has its own rows in
120
+ `@margoengine/navmesh/formation-settings`.
121
+
122
+ ```ts
123
+ import {armyOptionsFromSettings} from 'margoengine/armies/settings';
124
+ const {options, bake} = armyOptionsFromSettings({near: 64, step: 'route', farTriangles: 2000});
125
+ console.log(options.near, options.step, bake.farTriangles); // 64 route 2000
126
+ ```
127
+
128
+ ## Limits
129
+
130
+ People need a person source that passes the bar: the package draws whoever it is given, and the period cast kit's
131
+ garments are not yet skinned to a rig. The far level plays one clip (no walk-run blend) and a simplified mesh; at 0.08 of
132
+ the view the difference is a few pixels. One person bake a crowd (variety comes from heights, outfits and phases);
133
+ several bakes need several crowds. Riders follow the saddle rigidly. Members are culled by bounding sphere only, not
134
+ by occlusion. See [docs/limits.md](../../docs/limits.md).
135
+
136
+ ## Sources
137
+
138
+ C. W. Reynolds, "Flocks, herds and schools: a distributed behavioral model", SIGGRAPH 1987; J. van den Berg, S. J.
139
+ Guy, M. Lin and D. Manocha, "Reciprocal n-body collision avoidance", ISRR 2009 (Springer STAR 70, 2011); A. Treuille,
140
+ S. Cooper and Z. Popovic, "Continuum crowds", SIGGRAPH 2006 (the formations and flow fields this package draws);
141
+ B. Dudash, "Animated crowd rendering", GPU Gems 3, chapter 2, 2007; A. Beacco, N. Pelechano and C. Andujar, "A survey
142
+ of real-time crowd rendering", Computer Graphics Forum 35(8):32-50, 2016; M. Garland and P. S. Heckbert, "Surface
143
+ simplification using quadric error metrics", SIGGRAPH 1997; A. Thorstensson and H. Roberthson, "Adaptations to
144
+ changing speed in human locomotion: speed of transition between walking and running", Acta Physiologica Scandinavica
145
+ 131:211-214, 1987; P. M. Visscher, "Sizing up human height variation", Nature Genetics 40:489-490, 2008; G. E. P. Box
146
+ and M. E. Muller, "A note on the generation of random normal deviates", Annals of Mathematical Statistics 29:610, 1958;
147
+ U.S. War Department, Infantry Drill Regulations, 1911.
package/dist/bake.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { BoneBake } from '@margoengine/animation/instanced-skin';
2
+ import type { VATClip, VATData, VATBakeOptions } from '@margoengine/animation/vat';
3
+ import type { Animation } from '@margoengine/animation';
4
+ /** A person baked for a crowd. */
5
+ export interface PersonBake {
6
+ /** Bone texture and the full mesh: near members, skinned on the GPU. */
7
+ readonly near: BoneBake;
8
+ /** The simplified mesh with the same bones (its own vertices, weights and UVs). */
9
+ readonly farBones: BoneBake;
10
+ /** Vertex animation of the simplified mesh, posed from the same bone rows: far members. */
11
+ readonly far: VATData;
12
+ /** The clips, the same rows in every bake. */
13
+ readonly clips: readonly VATClip[];
14
+ /** Standing height of the bind pose, model units (metres for glTF). */
15
+ readonly height: number;
16
+ }
17
+ /** Options of {@link bakePerson}. */
18
+ export interface PersonBakeOptions extends VATBakeOptions {
19
+ /**
20
+ * Triangles the far mesh keeps, at most. Default 3000: a body a few dozen pixels tall shows no difference, and the
21
+ * far texture of four one-second clips at 30 a second stays near 12 MB.
22
+ */
23
+ farTriangles?: number;
24
+ /** Stops the simplifier. */
25
+ signal?: AbortSignal;
26
+ }
27
+ /**
28
+ * Bakes a person for {@link import('./lod.js').PersonCrowd}: bones for the near members, a simplified vertex animation
29
+ * for the far ones, posed from the same rows. Takes any `@margoengine/animation` Animation: a glTF, an FBX (a Character
30
+ * Creator export through `@margoengine/humans` `addPerson`), or a body built in code. Loads the bone baker
31
+ * (`@margoengine/animation/instanced-skin`) and the simplifier on first use.
32
+ * @example
33
+ * const bake = await bakePerson(new Animation(model), {clips: ['stand', 'walk', 'run', 'ride']});
34
+ * @throws RangeError for bad options, or when the far texture would pass 8192 rows (fewer clips, a lower fps or fewer
35
+ * far triangles).
36
+ */
37
+ export declare function bakePerson(animation: Animation, options?: PersonBakeOptions): Promise<PersonBake>;
38
+ /** Height of a bake's bind pose: its highest vertex less its lowest, model units. */
39
+ export declare function personHeight(bake: Pick<BoneBake, 'vertices' | 'vertexCount'>): number;
40
+ /**
41
+ * The same bake on a simplified mesh: about `ratio` of the triangles, every kept vertex one of the source's with its
42
+ * own position, normal, UV and skin weights, so it shares the bone rows. Vertices at one place that follow different
43
+ * bones (closed lips, a cuff on a wrist) stay apart. Loads `@margoengine/lod/auto` on first use.
44
+ * @throws RangeError for a ratio outside (0, 1], or a mesh over the simplifier's 200,000 vertices.
45
+ */
46
+ export declare function reduceBones(bake: BoneBake, ratio: number, signal?: AbortSignal): Promise<BoneBake>;
47
+ /**
48
+ * A vertex animation texture of a bone bake: every row of every clip posed on the CPU exactly as the instanced-skin
49
+ * shader poses it (position: the weighted bone matrices times the bind position; normal: their cofactors times the
50
+ * bind normal), so a `VATCrowd` member and a `SkinnedCrowd` member with the same clip and time stand in the same place.
51
+ * @throws RangeError when the texture would pass 8192 rows of 2048 texels.
52
+ */
53
+ export declare function vatFromBones(bake: BoneBake): VATData;
package/dist/bake.js ADDED
@@ -0,0 +1,92 @@
1
+ //#region src/bake.ts
2
+ var e = 2048;
3
+ async function t(e, t = {}) {
4
+ let a = t.farTriangles ?? 3e3;
5
+ if (!(Number.isInteger(a) && a >= 12 && a <= 1e6)) throw RangeError("bakePerson farTriangles must be a whole number from 12 to 1000000; pass about 3000");
6
+ t.signal?.throwIfAborted();
7
+ let { bakeBones: o } = await import("@margoengine/animation/instanced-skin");
8
+ t.signal?.throwIfAborted();
9
+ let s = o(e, {
10
+ fps: t.fps,
11
+ clips: t.clips
12
+ }), c = s.indices.length / 3, l = c > a ? await r(s, a / c, t.signal) : s;
13
+ return {
14
+ near: s,
15
+ farBones: l,
16
+ far: i(l),
17
+ clips: s.clips,
18
+ height: n(s)
19
+ };
20
+ }
21
+ function n(e) {
22
+ let t = Infinity, n = -Infinity;
23
+ for (let r = 0; r < e.vertexCount; r++) {
24
+ let i = e.vertices[r * 6 + 1];
25
+ t = Math.min(t, i), n = Math.max(n, i);
26
+ }
27
+ return e.vertexCount ? n - t : 0;
28
+ }
29
+ async function r(e, t, n) {
30
+ if (!(t > 0 && t <= 1)) throw RangeError("reduceBones ratio must be above 0 and at most 1");
31
+ if (t === 1) return e;
32
+ let { simplifyAttributes: r } = await import("@margoengine/lod/auto"), i = e.vertexCount, a = new Float32Array(i * 20);
33
+ for (let t = 0; t < i; t++) {
34
+ let n = t * 20;
35
+ a.set(e.vertices.subarray(t * 6, t * 6 + 3), n), a.set(e.vertices.subarray(t * 6 + 3, t * 6 + 6), n + 4), a[n + 12] = e.uvs[t * 2], a[n + 13] = 1 - e.uvs[t * 2 + 1], a.fill(1, n + 16, n + 20);
36
+ }
37
+ let [o] = await r({
38
+ vertices: a,
39
+ indices: e.indices
40
+ }, [t], {
41
+ signal: n,
42
+ apart: (t) => {
43
+ let n = "";
44
+ for (let r = 0; r < 8; r++) {
45
+ let i = e.weights[t * 8 + r];
46
+ i > 0 && (n += `${e.joints[t * 8 + r]}:${i.toFixed(3)} `);
47
+ }
48
+ return n;
49
+ }
50
+ }), s = o.sources ?? Uint32Array.from({ length: i }, (e, t) => t), c = s.length, l = new Float32Array(c * 6), u = new Uint32Array(c * 8), d = new Float32Array(c * 8), f = new Float32Array(c * 2);
51
+ return s.forEach((t, n) => {
52
+ l.set(e.vertices.subarray(t * 6, t * 6 + 6), n * 6), u.set(e.joints.subarray(t * 8, t * 8 + 8), n * 8), d.set(e.weights.subarray(t * 8, t * 8 + 8), n * 8), f.set(e.uvs.subarray(t * 2, t * 2 + 2), n * 2);
53
+ }), {
54
+ ...e,
55
+ vertexCount: c,
56
+ vertices: l,
57
+ joints: u,
58
+ weights: d,
59
+ uvs: f,
60
+ indices: Uint32Array.from(o.indices)
61
+ };
62
+ }
63
+ function i(t) {
64
+ let n = t.vertexCount, r = t.rows * n * 2, i = Math.max(1, Math.ceil(r / e));
65
+ if (i > 8192) throw RangeError(`A far texture of ${n} vertices and ${t.rows} rows needs ${i} texture rows, over 8192; bake fewer clips, a lower fps or fewer far triangles`);
66
+ let a = new Float32Array(e * i * 4), o = /* @__PURE__ */ new Float64Array(12), s = t.bones, c = t.texels, l = t.width;
67
+ for (let e = 0; e < t.rows; e++) for (let r = 0; r < n; r++) {
68
+ o.fill(0);
69
+ for (let n = 0; n < 8; n++) {
70
+ let i = t.weights[r * 8 + n];
71
+ if (!i) continue;
72
+ let a = (e * s + t.joints[r * 8 + n]) * 3;
73
+ for (let e = 0; e < 3; e++) {
74
+ let t = (a + e) % l, n = (Math.floor((a + e) / l) * l + t) * 4;
75
+ for (let t = 0; t < 4; t++) o[e * 4 + t] += i * c[n + t];
76
+ }
77
+ }
78
+ let i = t.vertices[r * 6], u = t.vertices[r * 6 + 1], d = t.vertices[r * 6 + 2], f = t.vertices[r * 6 + 3], p = t.vertices[r * 6 + 4], m = t.vertices[r * 6 + 5], h = o[0], g = o[1], _ = o[2], v = o[4], y = o[5], b = o[6], x = y * o[10] - b * o[9], S = b * o[8] - v * o[10], C = v * o[9] - y * o[8], w = h * x + g * S + _ * C < 0 ? -1 : 1, T = o[9] * _ - o[10] * g, E = o[10] * h - o[8] * _, D = o[8] * g - o[9] * h, O = g * b - _ * y, k = _ * v - h * b, A = h * y - g * v, j = (e * n + r) * 8;
79
+ a[j] = h * i + g * u + _ * d + o[3], a[j + 1] = v * i + y * u + b * d + o[7], a[j + 2] = o[8] * i + o[9] * u + o[10] * d + o[11], a[j + 3] = 1, a[j + 4] = w * (x * f + S * p + C * m), a[j + 5] = w * (T * f + E * p + D * m), a[j + 6] = w * (O * f + k * p + A * m), a[j + 7] = 0;
80
+ }
81
+ return {
82
+ vertexCount: n,
83
+ rows: t.rows,
84
+ width: e,
85
+ texels: a,
86
+ indices: t.indices,
87
+ uvs: t.uvs,
88
+ clips: t.clips.map((e) => ({ ...e }))
89
+ };
90
+ }
91
+ //#endregion
92
+ export { t as bakePerson, n as personHeight, r as reduceBones, i as vatFromBones };
@@ -0,0 +1,141 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { VATCrowdOptions } from '@margoengine/animation/vat';
4
+ import type { HorseCrowd, HorseCrowdOptions } from '@margoengine/horses/crowd';
5
+ import type { PersonBake } from './bake.js';
6
+ import { PersonCrowd, type CrowdBudget, type CrowdPerson, type CrowdView } from './lod.js';
7
+ import { type RiderPlacement } from './riders.js';
8
+ /** One member as a `@margoengine/navmesh/formations` Army keeps it. */
9
+ export interface ArmyMember {
10
+ readonly formation: number;
11
+ readonly x: number;
12
+ readonly z: number;
13
+ readonly heading: number;
14
+ readonly speed: number;
15
+ readonly distance: number;
16
+ }
17
+ /** The parts of a formations Army that addArmy reads. */
18
+ export interface MarchingArmy {
19
+ readonly time: number;
20
+ readonly members: readonly ArmyMember[];
21
+ readonly formations: readonly {
22
+ readonly kind: 'infantry' | 'cavalry';
23
+ }[];
24
+ heightAt(x: number, z: number): number;
25
+ }
26
+ /** Clip names or indices in the person bake. A clip left out falls back as noted. */
27
+ export interface ArmyClips {
28
+ /** Standing. Default `'stand'`, else the walk held still. */
29
+ stand?: string | number;
30
+ /** Walking (quick time). Default `'walk'`, else clip 0. */
31
+ walk?: string | number;
32
+ /** Running (double time, a charge). Default `'run'`, else the walk. */
33
+ run?: string | number;
34
+ /** Sitting a horse. Default `'ride'`, else the stand. */
35
+ ride?: string | number;
36
+ }
37
+ /** Options of {@link addArmy}. */
38
+ export interface AddArmyOptions extends CrowdBudget, VATCrowdOptions {
39
+ /** The person every soldier and rider is drawn as, from `bakePerson`. */
40
+ person: PersonBake;
41
+ clips?: ArmyClips;
42
+ /** Ground a clip's cycle covers at scale 1, m: walk 1.524 (two 30 inch steps), run 1.829 (two 36 inch steps). */
43
+ strides?: {
44
+ walk?: number;
45
+ run?: number;
46
+ };
47
+ /** Speed of the walk-run change, m/s. Default 2. */
48
+ runAbove?: number;
49
+ /** Speed band the two clips blend across, m/s. Default 0.4. */
50
+ blendBand?: number;
51
+ /** Below this a man stands, m/s. Default 0.1. */
52
+ standBelow?: number;
53
+ /** `'cadence'`: the men keep step; `'route'`: each his own (route step). Default `'cadence'`. */
54
+ step?: 'cadence' | 'route';
55
+ /** Spread of heights, a fraction of the mean (one standard deviation; cut at 2.5). Default 0.04. */
56
+ stature?: number;
57
+ /** Outfits: atlas regions handed out by a seeded hash (`castVariants` fits). Default the whole map. */
58
+ variants?: readonly {
59
+ readonly offset: readonly number[];
60
+ readonly scale: readonly number[];
61
+ }[];
62
+ /** The person model's facing, radians about +Y from +Z. Default 0. */
63
+ facing?: number;
64
+ /** The horses of cavalry formations, `addHorseCrowd` options; false draws none. Default `{}` when there is cavalry. */
65
+ horses?: HorseCrowdOptions | false;
66
+ /** How riders sit. Defaults as `riderMatrix`, with the person's own height. */
67
+ rider?: Omit<RiderPlacement, 'facing'>;
68
+ /** Seed of heights, outfits and route-step phases. Default 1. */
69
+ seed?: number;
70
+ }
71
+ /** What {@link addArmy} returns. */
72
+ export interface ArmyCrowd {
73
+ readonly army: MarchingArmy;
74
+ /** The foot soldiers, then the riders, as drawn. */
75
+ readonly people: PersonCrowd;
76
+ readonly horses: HorseCrowd | null;
77
+ /** This frame's people (soldiers then riders), as `update` wrote them. */
78
+ readonly persons: readonly CrowdPerson[];
79
+ /**
80
+ * Places everyone for the army's film time and plans the levels for `view` (a core Camera fits, brought up to date at
81
+ * `aspect`, default the canvas's). Call after the army and the camera move.
82
+ */
83
+ update(view: CrowdView, aspect?: number): this;
84
+ dispose(): void;
85
+ [Symbol.dispose](): void;
86
+ }
87
+ /** A seeded number in [0, 1). */
88
+ export declare const armyHash: (n: number) => number;
89
+ /** A seeded standard normal number, cut at 2.5 (Box and Muller 1958). */
90
+ export declare function armyNormal(n: number): number;
91
+ /** The clips a person plays at a speed, as {@link CrowdPerson} fields. */
92
+ export interface StepPose {
93
+ clip: number;
94
+ offset: number;
95
+ blendClip: number;
96
+ blendOffset: number;
97
+ blend: number;
98
+ }
99
+ /** Resolved clip indices and strides: what {@link stepPose} reads. */
100
+ export interface Gaits {
101
+ readonly stand: number;
102
+ readonly walk: number;
103
+ readonly run: number;
104
+ readonly ride: number;
105
+ readonly durations: readonly number[];
106
+ readonly walkStride: number;
107
+ readonly runStride: number;
108
+ readonly runAbove: number;
109
+ readonly blendBand: number;
110
+ readonly standBelow: number;
111
+ }
112
+ /**
113
+ * Resolves the clip names of `options` against the bake's clips and checks the gait numbers.
114
+ * @throws RangeError for a clip the bake lacks (by index) or numbers out of range.
115
+ */
116
+ export declare function armyGaits(bake: Pick<PersonBake, 'clips'>, options?: Pick<AddArmyOptions, 'clips' | 'strides' | 'runAbove' | 'blendBand' | 'standBelow'>): Gaits;
117
+ /**
118
+ * The clips a man on foot plays: standing below `standBelow`, the walk, the run above `runAbove`, the two blended
119
+ * across `blendBand`, each at the phase the ground covered gives (`distance / (stride * scale)` cycles), shifted by
120
+ * `phase` (0 in step). Standing plays the stand clip on the film clock from `idle` (a fraction of it), so a halted line
121
+ does not sway as one.
122
+ */
123
+ export declare function stepPose(g: Gaits, speed: number, distance: number, scale: number, phase: number, time: number, idle?: number): StepPose;
124
+ /**
125
+ * Draws an army: every foot soldier and rider as one person crowd at every distance, every horse in one herd with its
126
+ * rider in the saddle, all following the army's members. Loads the crowd draws and the horse model on first use.
127
+ * @example
128
+ * const army = new Army();
129
+ * army.add({count: 200, shape: 'line', ranks: 2}).march();
130
+ * army.add({count: 40, kind: 'cavalry', shape: 'line', position: [0, -30]}).charge({goal: [0, 120]});
131
+ * const drawn = await addArmy(engine, army, {person: await bakePerson(new Animation(model))});
132
+ * engine.onUpdate((dt) => { army.advanceTime(dt); drawn.update(engine.camera); });
133
+ * @throws TypeError for a missing army or person; RangeError for options out of range.
134
+ */
135
+ export declare function addArmy(engine: EngineKernel, army: MarchingArmy, options: AddArmyOptions): Promise<ArmyCrowd>;
136
+ export type { PersonBake, PersonBakeOptions } from './bake.js';
137
+ export { bakePerson } from './bake.js';
138
+ export { PersonCrowd, planCrowd, crowdBudget, NEAR, FAR, HIDDEN } from './lod.js';
139
+ export type { CrowdBudget, CrowdPerson, CrowdView, PersonCrowdOptions } from './lod.js';
140
+ export { riderMatrix } from './riders.js';
141
+ export type { RiderPlacement } from './riders.js';