@jgengine/core 0.35.0 → 0.37.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/CHANGELOG.md +116 -0
- package/dist/agents/system.d.ts +135 -0
- package/dist/agents/system.js +195 -0
- package/dist/combat/projectiles.d.ts +6 -2
- package/dist/combat/projectiles.js +55 -52
- package/dist/combat/shotSpec.d.ts +239 -0
- package/dist/combat/shotSpec.js +216 -0
- package/dist/combat/weaponSystem.js +26 -21
- package/dist/combat.d.ts +1 -0
- package/dist/combat.js +1 -0
- package/dist/game/playableGame.d.ts +9 -0
- package/dist/meta/changelog.d.ts +1 -1
- package/dist/meta/changelog.js +77 -1
- package/dist/movement/characterController.d.ts +5 -0
- package/dist/movement/characterController.js +8 -1
- package/dist/movement/movementModel.js +4 -1
- package/dist/movement/playerMovement.js +4 -0
- package/dist/physics/physicsBackendConformance.js +17 -0
- package/dist/physics/physicsWorld.d.ts +7 -0
- package/dist/physics/physicsWorld.js +27 -6
- package/dist/run/runLoop.d.ts +44 -1
- package/dist/run/runLoop.js +66 -5
- package/dist/world/features.d.ts +15 -1
- package/dist/world/features.js +51 -2
- package/dist/world/lod.d.ts +8 -0
- package/dist/world/lod.js +13 -5
- package/dist/world/modelLod.d.ts +44 -0
- package/dist/world/modelLod.js +75 -0
- package/dist/world.d.ts +2 -1
- package/dist/world.js +2 -1
- package/package.json +1 -1
- package/skills/jgengine/api.md +2 -2
- package/skills/jgengine-combat/SKILL.md +7 -0
- package/skills/jgengine-combat/api.md +61 -1
- package/skills/jgengine-combat/capabilities.md +4 -0
- package/skills/jgengine-combat/reference.md +1 -0
- package/skills/jgengine-gameplay/api.md +35 -0
- package/skills/jgengine-gameplay/capabilities.md +2 -0
- package/skills/jgengine-world/api.md +17 -0
package/CHANGELOG.md
CHANGED
|
@@ -26,6 +26,122 @@ At publish, rename this heading to the new version and mirror the entries into
|
|
|
26
26
|
`packages/core/src/meta/changelog.ts` (the typed `CHANGELOG` export).
|
|
27
27
|
-->
|
|
28
28
|
|
|
29
|
+
## 0.37.0
|
|
30
|
+
|
|
31
|
+
### Migrate
|
|
32
|
+
|
|
33
|
+
- **Bump lockstep SDK packages to `^0.37.0`:** `@jgengine/{core,rapier,react,ws,node,sql,convex,shell,editor,assets,navbake}`. CLI `jgengine` is `0.34.0`; `@jgengine/github` is `0.24.0`.
|
|
34
|
+
|
|
35
|
+
### Added
|
|
36
|
+
|
|
37
|
+
- `bun run check:script-help` walks every `package.json` script that points into `scripts/`, runs each with `--help`, and fails when one errors, hangs over its own timeout, prints nothing, or when a script names a file the repo does not have. Script files that predate `--help` are listed in `scripts/script-help-baseline.json` and reported, so a new one cannot arrive undocumented.
|
|
38
|
+
- `land`, `lane:close`, `lane:audit`, `ci-status` and `verify:fast` answer `--help` with their purpose, the flags they actually accept, one example and their exit codes, through one shared `scripts/script-help.ts`. No install, network or browser needed.
|
|
39
|
+
- `RunLoop.present(count)` and `RunLoop.choose(id)` (`@jgengine/core/run/runLoop`) draw several next-run changes for a choice screen and adopt the pick, so a game that offers three relics does not compose `game/runDraft` beside the loop. `present` honours the same `after` gates and weights as the single draw and never repeats the change just played while alternatives remain; `choose` opens the next run around the pick and refuses an id the loop's table does not carry.
|
|
40
|
+
- `installRunProbe` (`@jgengine/core/run/runLoop`) publishes `window.__jgengineRun` with the run in progress, what it carries, what it banked or lost, its best bank and the change it offers, so a capture or devtools read proves the loop is live instead of only imported.
|
|
41
|
+
- `bun run find <pattern> [--in <dir>] [--kind ts,tsx] [--files]` answers a repository-wide search in about a second: ripgrep reads the tree once, honours `.gitignore` and never enters `node_modules`, `.git`, `.claude/worktrees` or build output. `--files` lists names by `--glob`, which is what a tree listing was for. Eight of the ten hard timeouts in three hours of lane transcripts were a recursive directory listing over this checkout (160 s, 3.0M files) against a 120 s limit, while every other call's p90 was 10.5 s.
|
|
42
|
+
- `bun run check-recursive-walk` fails a `scripts/**` file or a lane document (`AGENTS.md`, `README.md`, every skill under `.claude/skills`) that ships a recursive directory listing, a `find` walk from a root, or `git ls-files` piped into per-file work; a required one carries `// walk-ok: <reason>`. It runs in CI through the scripts test shard.
|
|
43
|
+
- `ModelConfig.variants` (`levels: [{ url, maxDistance? }]`, `hysteresis?`) declares ordered mesh detail levels for a model. The instanced prop path switches level per instance by distance to the camera, so near and far placements of one species keep their own mesh inside one batch cell. A model without `variants` draws exactly as before.
|
|
44
|
+
- `createModelVariantSelector` (`@jgengine/core/world/modelLod`) returns the level index for an id at a distance, carrying hysteresis across each boundary (`DEFAULT_VARIANT_HYSTERESIS`, 6 m). `lodBandIndex` is now exported from `@jgengine/core/world/lod` and both the LOD scheduler and the selector read distances through it, so simulation throttling and mesh detail cannot disagree.
|
|
45
|
+
- `syncStaticObjectSource` takes an optional `accept` predicate so one batch can split its instances between two instanced draws.
|
|
46
|
+
- `InstancedScatter` now honours `ModelConfig.variants`: each species-chunk batch asks the same `createModelVariantSelector` the static prop path uses for every placement's level, and each level draws its own instanced meshes claiming only its placements. A chunk that holds near and far palms of one species draws both levels from the one batch; a model without `variants` draws exactly as before.
|
|
47
|
+
- `writeScatterVariantLevel` (`@jgengine/shell` internal, `scatter/scatterVariants`) is the per-frame pass: it writes one level's composed matrices into a reserved slot array and returns `count`, allocating nothing per frame, and takes an optional `keep` predicate so a tier-distance or occlusion cull composes with level selection in one loop.
|
|
48
|
+
- `terrain({ cellSize })` states ground density as world units per quad instead of a segment count, and derives the per-axis grid from `bounds` — the same `cellSize` on a bigger world spends more cells rather than stretching one count across it. `segments` still works and also takes `[x, z]` for a non-square grid. Setting both fails naming `cellSize`; a cell size over the 1,000,000-vertex ceiling fails with the cell/vertex numbers and the smallest `cellSize` that fits.
|
|
49
|
+
- `shoot`, `drive` and `perf` take `--quality <low|medium|high|ultra>` and pin that graphics tier on the game page (`?quality=<tier>`). Each run reads the tier back from the shell (`data-jg-quality`) and fails when it is missing or different, so a capture or perf record always names the tier it measured. Every capture summary prints `tier <tier>`; `perf` echoes `perf: tier <tier>` and records it in `quality`.
|
|
50
|
+
- The old `--quality draft|full` iteration mode is now the `--draft` switch (low tier, half viewport, `-draft` file names), on `shoot`, `drive` and `perf`; `perf:gate` takes `--draft` too. An unknown `--quality` value fails naming all four tiers.
|
|
51
|
+
- `attributeTriangles` (`@jgengine/shell/render/triangleAttribution`) sums a scene's triangles by model and geometry with instance counts, and the devtools render probe publishes it as `probes["render/triangles"]` and the `render/triangles` system probe, so `debug_snapshot` names the object behind a heavy frame instead of only counting it. Harbor Heat read 1,021,671 triangles from 840 objects: the 640 m terrain at 300 segments (180,000), the `TwistedTree_2` foliage species (137,010 over 15 trees) and 93 instances of a 1,280-triangle NPC model.
|
|
52
|
+
- `ShotSpec` and `resolveShotSpec` (`@jgengine/core/combat/shotSpec`) describe how a shot travels and what it does on contact as plain data: an instant trace or a travelling body with speed, gravity, drag, fuse, lifetime, radius and homing, plus contact damage, falloff, penetration, splash, ricochet and statuses. Every field but `delivery.kind` is optional with a documented default, so a plain gun is three lines and a grenade, mortar, arrow or hitscan explosive is the same shape with different numbers. `shotArc`, `shotFalloffAt` and `shotHitOutcome` are the one place trajectory, falloff and penetration are solved; `shotSpecFromStats` and `shotSpecFromWeapon` adapt existing item stats and weapon definitions once, and a splash radius or damage number never decides that a shot travels.
|
|
53
|
+
- `ProjectileShotInput.spec` lets a caller state the spec directly; the projectile and weapon systems read the resolved spec at spawn, fuse, hitscan settle and damage application instead of classifying a shot.
|
|
54
|
+
- A trace that carries splash now resolves its area damage at the contact point on the same tick, which is the #2272 hitscan-explosive configuration.
|
|
55
|
+
- `bun run check:path-portability` fails a test that asserts one platform's path separator: a `\\` literal under `toContain`/`toEqual`/`toBe`/`includes`/`endsWith`, a bare `toContain("/")`, a POSIX root handed to `join`/`resolve`, or a literal compared with an OS path result. It reports the file, the line and the `join(...)` that replaces it. A genuinely single-platform assertion is named in `scripts/path-portability-allow.json` with a reason, printed on every run. This is the class behind #2301 (`toContain("proofs\\flows")`) and the `agent-worktree.test.ts` assertions that only pass on one OS.
|
|
56
|
+
|
|
57
|
+
Verification:
|
|
58
|
+
- `bun test scripts/check-path-portability.test.ts` - pass, including the pre-fix `proofs\\flows` line failing through the gate and the fixed one passing
|
|
59
|
+
- `bun run check:path-portability` - ok, 3 allowlisted with reasons
|
|
60
|
+
- `bun test scripts/agent-worktree.test.ts scripts/shot-metrics.test.ts scripts/lane-audit.test.ts` - pass
|
|
61
|
+
|
|
62
|
+
### Changed
|
|
63
|
+
|
|
64
|
+
- Merge pull request #2309 from Noisemaker111/agent/lane-path-portability
|
|
65
|
+
- `bun run land` hands the PR over instead of waiting for it: it pushes, opens or updates the PR, runs `--verify`, arms auto-merge and exits in seconds, printing the PR URL and `bun run ci:status --pr <n>`. A trivial change spent 5m09s inside `land`'s own poll loop, and one night's lanes spent 449 minutes watching CI. `--watch` still lands the old way and says it is deprecated.
|
|
66
|
+
- `bun run land:queue` is the only process that waits for CI. It lands ready PRs into `beta` in readiness order (auto-merge armed, else the `land:queue` label), rebases a branch whose base moved in a throwaway worktree so a moved base costs one CI run instead of two, waits once per PR and prints one line per PR with its wait time and run id. A lane hands off by running `bun run land`; it never rebases, labels or waits.
|
|
67
|
+
- `bun run lane:close` ends a lane in one command. It stages the worktree's tracked and new files (ignored ones such as `.scratch/` stay out), takes the commit message from the branch's own `changes/` fragment, writes that fragment from the commit summary when the diff has none, pushes, opens or updates the PR with the fragment as the body, arms auto-merge, and prints the PR URL and `bun run ci:status --pr <n>`. One lane's last 20 calls were 13 of commit, push, rebase and PR choreography; this replaces them with one. `bun run land --commit` does the same for a lane that skips `lane:close`, and a clean tree lands as it did before.
|
|
68
|
+
- `bun run bg:run -- <cmd>` starts a long command and returns its id at once; `bun run bg:await <id>` blocks on that task's exit file as an event, then prints its whole output and its exit code. It replaces waiting out a `.out` file with guessed intervals — one lane spent 10 minutes of `Start-Sleep` calls watching a capture it had already started. A runner that dies is answered rather than waited on forever.
|
|
69
|
+
- `--commit` prints every path it will commit before committing, and refuses the ones a lane did not author: a scratch artifact, a path git ignores, a lockfile staged without its `package.json` manifest, and a new `changes/` fragment whose name is not part of the branch's name. `--allow <path>` keeps one refused file on purpose. The first replay committed a test-written `changes/agent-lane-x.md` and this checkout's shared-install `bun.lock` drift; both are refused now, with the file list printed either way.
|
|
70
|
+
- A capture at a non-default tier writes its tier into the file name (`-low`, `-medium`, `-ultra`), so an ultra shot cannot overwrite the high one it was compared against.
|
|
71
|
+
|
|
72
|
+
Root cause: `--quality` carried the iteration preset, not the graphics tier, so a culling lane that asked for ultra got the game's default `high` on both sides of its comparison and could not prove a tier claim.
|
|
73
|
+
|
|
74
|
+
### Fixed
|
|
75
|
+
|
|
76
|
+
- `verify:fast`, `land` and `lane:close` refuse a checkout with no `node_modules` up front: they print the missing marker, the exact fix (`bun install` in this checkout, or `bun run agent:bootstrap`) and exit 78, instead of a `command not found` or a module error from a test file. A genuine failure still exits on its own code.
|
|
77
|
+
- `lane:audit --cwd` finds the lane whose own tool calls name that worktree, and prints `attributed ses_… (N references to …)`. Ambiguous ties name their candidates and pick the worst-waiting one; no candidate at all exits non-zero naming the path it searched, so `--fail-on-waiting` has a lane to judge instead of an empty table.
|
|
78
|
+
- `land` builds the PR body only from `changes/` fragments its own `git diff origin/beta...HEAD` adds, prints a line for every fragment it ignores, and falls back to the branch's commit subjects.
|
|
79
|
+
|
|
80
|
+
Root cause: a subagent session stores the directory of the agent that spawned it, so a lane was invisible to its own audit; `changes/` is shared by every lane on the branch, so "newest fragment" was free to be a stranger's note.
|
|
81
|
+
|
|
82
|
+
Before: `lane:audit --cwd …\lane-wait-audit` exited 1 with "no child sessions", and a body built from a stray `changes/` fragment claimed work the diff did not contain.
|
|
83
|
+
After: `lane:audit: attributed ses_e94f3aeedffe2CCMsTlrzgvez5 (136 references to …\lane-wait-audit)`, and `land: ignoring changes/scratch-leftover.md: this branch's diff against origin/beta does not add it`.
|
|
84
|
+
|
|
85
|
+
Verification:
|
|
86
|
+
- `bun test scripts/lane-audit.test.ts scripts/lane-close.test.ts scripts/land.test.ts` — pass
|
|
87
|
+
- `bun run verify:fast` — pass
|
|
88
|
+
- `bun run lane:audit --cwd <the real lane worktree> --hours 6` — attributed that lane by 136 references
|
|
89
|
+
- `lane:audit` classifies a call by what it runs, not by the text inside its arguments: `rg`, `grep`, `Select-String`, `findstr`, `Get-Content`, `cat`, `echo`, `Write-Output` and `git` (any subcommand) never count as a sleep or a CI watch, and quoted arguments are stripped before matching. A lane that greps for `Start-Sleep` or writes a PR body about `gh run watch` no longer records waiting it never did.
|
|
90
|
+
- Catches the waits it used to miss: `Start-Sleep` under `powershell -Command`/`pwsh -c`/`bash -lc`, `cmd /c "timeout /t"`, `Thread.sleep`, `Atomics.wait`, `Bun.sleep`, and `gh pr checks` inside a `for`/`while` loop.
|
|
91
|
+
|
|
92
|
+
Over the last 40 hours (209 lanes): sleep 1066.6 -> 1068.7 minutes, CI watch 421.8 -> 421.3 minutes. 15 calls stopped counting as waits, one real `Start-Sleep -Seconds 150` started counting.
|
|
93
|
+
|
|
94
|
+
Verification:
|
|
95
|
+
- `bun test scripts/lane-audit.test.ts scripts/lane-close.test.ts scripts/land.test.ts` — pass
|
|
96
|
+
- `bun run lane:audit --json --hours 40` before and after, compared per command
|
|
97
|
+
- `lane:close` reads `calls` as the count it is, takes waits from a new `waits` list in `lane:audit --json`, and refuses an unfamiliar audit shape with `the audit output shape changed: <field> is <type>, expected <type> (keys seen: …)` instead of a TypeError. Exit codes unchanged: a sleep or CI watch is 2, `--waive` records the reason, no percentage thresholds.
|
|
98
|
+
|
|
99
|
+
Root cause: `lane:audit --json` had always reported `calls` as a number, while `lane:close` held it as a list of call objects; nothing read the real document until lane attribution started returning a lane, so the gate that judges a finishing lane crashed on the first lane that had one.
|
|
100
|
+
|
|
101
|
+
Before: `lane:close` landed the PR, then died with `source.filter is not a function` at `waitingGate`.
|
|
102
|
+
After: the same captured output is judged, the waits are listed, and the lane gets exit 2 with a report skeleton.
|
|
103
|
+
|
|
104
|
+
Verification:
|
|
105
|
+
- `bun test scripts/lane-audit.test.ts scripts/lane-close.test.ts` — pass, including the captured-output fixture
|
|
106
|
+
- `bun run verify:fast` — pass
|
|
107
|
+
- `shoot --url ... --look` now sends the aim to the page it captures, so a lane can measure a branch on a dev runner it started itself. The read-back stays: a page that reports no applied aim still fails the capture instead of returning a plausible wrong view, and a page that applies `--param look=` itself can report it on `data-jg-look` or `window.__jgLook`. `--site --look` is refused at the command line, naming the `--url` form that works.
|
|
108
|
+
- `check:no-blocking-wait` judges code that waits, not prose that describes waiting. In `packages/<pkg>/src/meta` (the changelog mirror and its neighbours) single- and double-quoted text and comments are masked before matching, so a release note reading "one lane spent 10 minutes of `Start-Sleep`" no longer fails the gate; a command in a template literal still fails, and every other `scripts/**` path keeps the strict rule where a quoted command is a real finding. The 0.37.0 release cut failed `types` on `packages/core/src/meta/changelog.ts:46,55,56` with exactly that false positive.
|
|
109
|
+
- `@jgengine/rapier` now accumulates `step(dt)` into its fixed substeps instead of stepping once per call with `fixedDt` as the timestep. A 1 s move covered 0.5 s of simulated time at 30 fps and 2.4 s at 144 fps; it now covers 1 s at either rate, matching `PhysicsWorld` and the `PhysicsBackend` contract.
|
|
110
|
+
- `PhysicsWorld` bounds-floor friction is Coulomb (`friction × g × dt`) like contact friction, not a 60 Hz multiplicative brake: a crate sliding at 4 m/s travelled 0.165 m on the world floor and 0.970 m on a floor collider, and now travels 0.967 m on both.
|
|
111
|
+
- Player and character-controller gravity integrate trapezoidally, so a jump reaches `v²/2g` at any frame rate: the default jump peaked at 0.933 m at 30 fps and 1.026 m at 144 fps, and now at 1.050 m for both.
|
|
112
|
+
|
|
113
|
+
## 0.36.0
|
|
114
|
+
|
|
115
|
+
### Migrate
|
|
116
|
+
|
|
117
|
+
- **Bump lockstep SDK packages to `^0.36.0`:** `@jgengine/{core,rapier,react,ws,node,sql,convex,shell,editor,assets,navbake}`. CLI `jgengine` is `0.33.0`; `@jgengine/github` is `0.23.0`.
|
|
118
|
+
|
|
119
|
+
### Added
|
|
120
|
+
|
|
121
|
+
- `createAgentSystem` (`@jgengine/core/agents/system`) takes a game's needs, options, mood weights, members and
|
|
122
|
+
schedules once and returns a running cast: one `tick(dt)` for everyone, one target selector for the whole system,
|
|
123
|
+
a fallback declared once, and a plain-JSON `save()`/`load()` that rides the game's own save.
|
|
124
|
+
- `--quick` on `bun run shoot` and `bun run drive` is the 960x540 iteration preset: one settled frame (a 2s settle window in drive), no video, no perf pass, written as `<name>-quick.png` and timed on its own line. It refuses a 1600x900 pixel claim, a frame-time claim, a non-desktop device and a recording flag by name instead of producing weaker evidence; full stays the default for PR shots. On a warm daemon a two-shot `drive` of ember-command went 9.3s to 8.2s and 4316KB to 1383KB of PNG.
|
|
125
|
+
- `createPlayScript` / `runPlayScript` (`@jgengine/shell/play`) play a real `PlayableGame` headlessly from a tick-based script: `move`, `aim`, `fire`, `use`, `wait` and `command` steps plus `setup`/`onTick` hooks, `expect` assertions read after setup and on their own tick, a tick timeline, and an FNV digest for replay comparison. It replays the shell's own frame pipeline — held movement through the walk controller, a bound action resolving to its command on press and repeat, interact prompts, hotbar — so a script proves the same code path a player's hands do. No browser, no wall clock, fixed `dt`.
|
|
126
|
+
- `bun run simulate <game> <script>` runs a committed `<game>/scripts/*.play.ts` against a game under `./Games`, prints the timeline, names a failed assertion and exits 1. It merges the game's own tsconfig `paths` with this checkout's source packages, so the game imports and the engine under test are one module graph.
|
|
127
|
+
- `HeadlessRunner.aim()` steers the walk controller mid-run; `HeadlessRunnerOptions` gains `seed` (deterministic `ctx.rng`) and `collision` (the shell's voxel config, previously dropped on the headless path).
|
|
128
|
+
|
|
129
|
+
Play scripts prove play in seconds instead of minutes of browser play, and the three proofs land beside their games: Scrap Signal (an enemy takes damage and closes in), Beacon Bastion (a composed wave is reached, its bounty scales, a boss phase flips) and Harbor Heat (heat is witness-gated, the search area is set, a courier is swept).
|
|
130
|
+
|
|
131
|
+
### Changed
|
|
132
|
+
|
|
133
|
+
- The graphics quality tier now costs what it claims on the render path. A tier's post chain renders at its own resolution scale (`low` 0.7, `medium` 0.85, `high`/`ultra` native) instead of always at the canvas size, and a game's authored `shadowMapSize` and `cascades` are a ceiling the tier caps rather than a value it ignored — every reference game authored 3 cascades and 1024/2048, so no tier changed a shadow before this. `low` and `medium` also stretch the far cascades' refresh interval, and the smallest caster worth a depth draw grows as the map shrinks. `high` and `ultra` keep native resolution, the authored shadow sizes and the measured cadence, so their frames are unchanged.
|
|
134
|
+
- Measured uncapped at 1600x900: whole-frame draws at `low` fell 53% in harbor-heat (515 → 242) and 63% in drift-foundry (1,098 → 408), with the shadow pass there down from 911 ms to 344 ms over a 6 s window; `high` and `ultra` held their draw counts.
|
|
135
|
+
|
|
136
|
+
### Fixed
|
|
137
|
+
|
|
138
|
+
- Terrain build no longer scans every road and path segment for every vertex. A baked path corridor, a draped road and a painted polyline region each answer "how far is this point?" from a precomputed segment grid, so Scrap Signal's world build drops from 16.6 s to 0.51 s on the same machine and its longest boot stall from 11.6–18.4 s to 1.2 s. Sampled heights and palettes are bit-identical to the previous full scan, and `withPathProfiles` still composes profiles in order.
|
|
139
|
+
- Load-time shader warmup compiles against the render state the first frame actually draws with. A scene whose post chain renders into its own buffer was linking two programs per material, one linear untone-mapped set the frame draws and one canvas set nothing ever drew; the cover no longer waits for the second set. Harbor Heat links 84 programs to 58 and Scrap Signal 124 to 83 before the cover lifts, with no visual change.
|
|
140
|
+
|
|
141
|
+
### Performance
|
|
142
|
+
|
|
143
|
+
- `createTerrainPaletteSampler` (`@jgengine/core/world/terrain`) tests only the material regions whose painted core or blend ring covers a sample, so a world with hundreds of authored regions no longer pays for all of them at every vertex.
|
|
144
|
+
|
|
29
145
|
## 0.35.0
|
|
30
146
|
|
|
31
147
|
### Migrate
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { UtilityInterrupt, UtilityOption, UtilityTunables } from "../ai/utilityBrain.js";
|
|
2
|
+
import type { NeedDefinition } from "../sim/needs.js";
|
|
3
|
+
import type { Vec3 } from "../world/geometry.js";
|
|
4
|
+
import { type Agent, type AgentFallback, type AgentFrame, type AgentSnapshot, type AgentTarget } from "./agent.js";
|
|
5
|
+
import type { Mood, MoodTier, MoodWeight } from "./mood.js";
|
|
6
|
+
import type { AgentScheduleConfig } from "./schedule.js";
|
|
7
|
+
export type { Agent, AgentAction, AgentFallback, AgentFrame, AgentSnapshot, AgentTarget } from "./agent.js";
|
|
8
|
+
export type { AgentScheduleConfig, AgentScheduleStop, AgentSchedulePhase } from "./schedule.js";
|
|
9
|
+
export type { Mood, MoodTier, MoodWeight } from "./mood.js";
|
|
10
|
+
export type { NeedDefinition } from "../sim/needs.js";
|
|
11
|
+
export type { UtilityInterrupt, UtilityOption, UtilityTunables } from "../ai/utilityBrain.js";
|
|
12
|
+
/** The mood policy a member runs on: which needs matter, and the game's own words for the bands. */
|
|
13
|
+
export interface AgentMoodConfig {
|
|
14
|
+
readonly weights?: readonly MoodWeight[];
|
|
15
|
+
readonly tiers?: readonly MoodTier[];
|
|
16
|
+
}
|
|
17
|
+
/** What a selector is told about the member asking: who it is, its live agent, and where it stands. */
|
|
18
|
+
export interface AgentSelectView {
|
|
19
|
+
readonly id: string;
|
|
20
|
+
/** The live agent, for a selector that reads needs, mood or the held action. */
|
|
21
|
+
readonly agent: Agent;
|
|
22
|
+
/** Body position from the system's `position` reader, or `null` when the game has no body for it. */
|
|
23
|
+
readonly at: Vec3 | null;
|
|
24
|
+
readonly now: number;
|
|
25
|
+
/** True while the member is off camera and takes no utility pass this tick. */
|
|
26
|
+
readonly far: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Everything the member could do right now, as the game's world offers it. Declared once per system. */
|
|
29
|
+
export type AgentSelector = (view: AgentSelectView) => readonly AgentTarget[];
|
|
30
|
+
/** Where a system keeps its save data: a key-value store, a save slot, or a test's map. */
|
|
31
|
+
export interface AgentSystemStorage {
|
|
32
|
+
read(): AgentSystemState | undefined;
|
|
33
|
+
write(next: AgentSystemState): void;
|
|
34
|
+
}
|
|
35
|
+
/** One member's saved state: its agent snapshot plus the off-camera flag the snapshot does not carry. */
|
|
36
|
+
export interface AgentMemberState {
|
|
37
|
+
readonly agent: AgentSnapshot;
|
|
38
|
+
readonly far: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** The whole system as plain JSON - drop it in a save, read it back with {@link AgentSystem.load}. */
|
|
41
|
+
export interface AgentSystemState {
|
|
42
|
+
readonly version: 1;
|
|
43
|
+
readonly members: Readonly<Record<string, AgentMemberState>>;
|
|
44
|
+
}
|
|
45
|
+
/** One member: an id, and only what differs from the system's defaults. */
|
|
46
|
+
export interface AgentMemberSpec extends UtilityTunables {
|
|
47
|
+
readonly id: string;
|
|
48
|
+
/** Needs for this member; defaults to the system's. */
|
|
49
|
+
readonly needs?: readonly NeedDefinition[];
|
|
50
|
+
/** Scored actions for this member; defaults to the system's. */
|
|
51
|
+
readonly options?: readonly UtilityOption[];
|
|
52
|
+
readonly interrupts?: readonly UtilityInterrupt[];
|
|
53
|
+
/** The member's authored day; omit for one that only reacts to targets. */
|
|
54
|
+
readonly schedule?: AgentScheduleConfig;
|
|
55
|
+
readonly mood?: AgentMoodConfig;
|
|
56
|
+
/** Targets for this member instead of the system's selector. */
|
|
57
|
+
readonly select?: AgentSelector;
|
|
58
|
+
/** `[0,1)` source; defaults to the system's `rng`. */
|
|
59
|
+
readonly rng?: () => number;
|
|
60
|
+
readonly devtoolsName?: string;
|
|
61
|
+
/** Start off camera: schedule and needs only, no utility pass, until `setFar(id, false)`. */
|
|
62
|
+
readonly far?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/** The game's data, in one place: what its people need, what they can do, and how they feel. */
|
|
65
|
+
export interface AgentSystemConfig {
|
|
66
|
+
/** Needs every member carries unless it declares its own. */
|
|
67
|
+
readonly needs: readonly NeedDefinition[];
|
|
68
|
+
/** Scored actions every member chooses between unless it declares its own. */
|
|
69
|
+
readonly options: readonly UtilityOption[];
|
|
70
|
+
readonly interrupts?: readonly UtilityInterrupt[];
|
|
71
|
+
readonly mood?: AgentMoodConfig;
|
|
72
|
+
/** Members present at creation; more join later with {@link AgentSystem.add}. */
|
|
73
|
+
readonly members?: readonly AgentMemberSpec[];
|
|
74
|
+
/** Resolve every member's targets. Called once per on-camera member per tick, never per option. */
|
|
75
|
+
readonly select?: AgentSelector;
|
|
76
|
+
/** Fallback given to every target that declares none - one fallback per system, not per target. */
|
|
77
|
+
readonly fallback?: AgentFallback;
|
|
78
|
+
/** The world clock, so `tick(dt)` needs no `now` argument. */
|
|
79
|
+
readonly clock?: {
|
|
80
|
+
now(): number;
|
|
81
|
+
};
|
|
82
|
+
/** Where a member's body is, handed to the selector as `at`. */
|
|
83
|
+
readonly position?: (id: string) => Vec3 | null;
|
|
84
|
+
/** Save storage, hydrated on the first tick and written by {@link AgentSystem.save}. */
|
|
85
|
+
readonly storage?: AgentSystemStorage;
|
|
86
|
+
/** Deterministic source shared by members that do not declare their own. */
|
|
87
|
+
readonly rng?: () => number;
|
|
88
|
+
/** Dials every member starts with; a member may override any of them. */
|
|
89
|
+
readonly defaults?: UtilityTunables;
|
|
90
|
+
/** Devtools prefix: member `x` registers as `<devtoolsName>.x`. */
|
|
91
|
+
readonly devtoolsName?: string;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* A whole cast of agents behind one factory and one tick.
|
|
95
|
+
*
|
|
96
|
+
* Feed it a game's data once - needs, options, mood weights, the members and their schedules - and it
|
|
97
|
+
* owns the parts a game should not write: the roster, lazy creation, one tick for everyone, where a
|
|
98
|
+
* target came from, and a save blob that is plain JSON. Everything an individual {@link Agent} can do
|
|
99
|
+
* stays reachable through {@link get}.
|
|
100
|
+
*/
|
|
101
|
+
export interface AgentSystem {
|
|
102
|
+
/** Create and register one member; a member saved under this id resumes instead of starting fresh. */
|
|
103
|
+
add(spec: AgentMemberSpec): Agent;
|
|
104
|
+
get(id: string): Agent | null;
|
|
105
|
+
has(id: string): boolean;
|
|
106
|
+
remove(id: string): void;
|
|
107
|
+
/** Member ids in creation order. */
|
|
108
|
+
ids(): readonly string[];
|
|
109
|
+
size(): number;
|
|
110
|
+
/** One call per game tick: decay, day plan and decision for every member, near or far. */
|
|
111
|
+
tick(dt: number, now?: number): void;
|
|
112
|
+
/** What the last tick produced for a member, or `null` before it has ticked. */
|
|
113
|
+
frame(id: string): AgentFrame | null;
|
|
114
|
+
/** A member's mood, readable before its first tick. */
|
|
115
|
+
mood(id: string): Mood | null;
|
|
116
|
+
/** Mean mood across members, or `null` for an empty system. */
|
|
117
|
+
moodMean(): number | null;
|
|
118
|
+
/** Action of a member, `null` before its first tick. */
|
|
119
|
+
action(id: string): AgentFrame["action"] | null;
|
|
120
|
+
setFar(id: string, far: boolean): void;
|
|
121
|
+
isFar(id: string): boolean;
|
|
122
|
+
/** Plain-JSON state, also written to `storage` when one was given. */
|
|
123
|
+
save(): AgentSystemState;
|
|
124
|
+
/** Restore members saved under ids this system knows, and hold the rest until they join. */
|
|
125
|
+
load(next: AgentSystemState | undefined): void;
|
|
126
|
+
dispose(): void;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* One call for a whole cast: a game hands over its needs, options, mood weights, schedules and one
|
|
130
|
+
* target selector, and gets back a running system with a single `tick(dt)` and a save blob that goes
|
|
131
|
+
* into the game's own save.
|
|
132
|
+
*
|
|
133
|
+
* @capability agents a needs, thought, action and mood loop an agent runs on the world clock
|
|
134
|
+
*/
|
|
135
|
+
export declare function createAgentSystem(config: AgentSystemConfig): AgentSystem;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { createAgent, } from "./agent.js";
|
|
2
|
+
/**
|
|
3
|
+
* One call for a whole cast: a game hands over its needs, options, mood weights, schedules and one
|
|
4
|
+
* target selector, and gets back a running system with a single `tick(dt)` and a save blob that goes
|
|
5
|
+
* into the game's own save.
|
|
6
|
+
*
|
|
7
|
+
* @capability agents a needs, thought, action and mood loop an agent runs on the world clock
|
|
8
|
+
*/
|
|
9
|
+
export function createAgentSystem(config) {
|
|
10
|
+
const agents = new Map();
|
|
11
|
+
const frames = new Map();
|
|
12
|
+
const selectors = new Map();
|
|
13
|
+
const saved = new Map();
|
|
14
|
+
const order = [];
|
|
15
|
+
let hydrated = false;
|
|
16
|
+
let lastNow = 0;
|
|
17
|
+
function selectFor(id) {
|
|
18
|
+
return selectors.get(id) ?? config.select;
|
|
19
|
+
}
|
|
20
|
+
function restoreInto(agent, state) {
|
|
21
|
+
agent.restore(state.agent);
|
|
22
|
+
if (state.far)
|
|
23
|
+
agent.setFar(true);
|
|
24
|
+
}
|
|
25
|
+
function hydrate() {
|
|
26
|
+
if (hydrated)
|
|
27
|
+
return;
|
|
28
|
+
const state = config.storage?.read();
|
|
29
|
+
if (state === undefined)
|
|
30
|
+
return;
|
|
31
|
+
hydrated = true;
|
|
32
|
+
loadState(state);
|
|
33
|
+
}
|
|
34
|
+
function loadState(next) {
|
|
35
|
+
if (next === undefined)
|
|
36
|
+
return;
|
|
37
|
+
for (const [id, state] of Object.entries(next.members)) {
|
|
38
|
+
const agent = agents.get(id);
|
|
39
|
+
if (agent === undefined) {
|
|
40
|
+
saved.set(id, state);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
restoreInto(agent, state);
|
|
44
|
+
saved.delete(id);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function create(spec) {
|
|
48
|
+
const defaults = config.defaults;
|
|
49
|
+
const tuned = (key) => spec[key] ?? defaults?.[key];
|
|
50
|
+
const devtoolsName = spec.devtoolsName ?? (config.devtoolsName === undefined ? undefined : `${config.devtoolsName}.${spec.id}`);
|
|
51
|
+
const agent = createAgent({
|
|
52
|
+
id: spec.id,
|
|
53
|
+
needs: spec.needs ?? config.needs,
|
|
54
|
+
options: spec.options ?? config.options,
|
|
55
|
+
...optional("interrupts", spec.interrupts ?? config.interrupts),
|
|
56
|
+
...optional("schedule", spec.schedule),
|
|
57
|
+
mood: {
|
|
58
|
+
...optional("weights", spec.mood?.weights ?? config.mood?.weights),
|
|
59
|
+
...optional("tiers", spec.mood?.tiers ?? config.mood?.tiers),
|
|
60
|
+
},
|
|
61
|
+
...optional("switchMargin", tuned("switchMargin")),
|
|
62
|
+
...optional("minHoldSeconds", tuned("minHoldSeconds")),
|
|
63
|
+
...optional("costWeight", tuned("costWeight")),
|
|
64
|
+
...optional("jitter", tuned("jitter")),
|
|
65
|
+
...optional("rng", spec.rng ?? config.rng),
|
|
66
|
+
...optional("devtoolsName", devtoolsName),
|
|
67
|
+
});
|
|
68
|
+
agents.set(agent.id, agent);
|
|
69
|
+
order.push(agent.id);
|
|
70
|
+
if (spec.select !== undefined)
|
|
71
|
+
selectors.set(agent.id, spec.select);
|
|
72
|
+
if (spec.far === true)
|
|
73
|
+
agent.setFar(true);
|
|
74
|
+
const pending = saved.get(spec.id);
|
|
75
|
+
if (pending !== undefined) {
|
|
76
|
+
restoreInto(agent, pending);
|
|
77
|
+
saved.delete(spec.id);
|
|
78
|
+
}
|
|
79
|
+
return agent;
|
|
80
|
+
}
|
|
81
|
+
const system = {
|
|
82
|
+
add(spec) {
|
|
83
|
+
const existing = agents.get(spec.id);
|
|
84
|
+
if (existing !== undefined)
|
|
85
|
+
return existing;
|
|
86
|
+
return create(spec);
|
|
87
|
+
},
|
|
88
|
+
get: (id) => agents.get(id) ?? null,
|
|
89
|
+
has: (id) => agents.has(id),
|
|
90
|
+
remove(id) {
|
|
91
|
+
const agent = agents.get(id);
|
|
92
|
+
if (agent === undefined)
|
|
93
|
+
return;
|
|
94
|
+
agent.dispose();
|
|
95
|
+
agents.delete(id);
|
|
96
|
+
frames.delete(id);
|
|
97
|
+
selectors.delete(id);
|
|
98
|
+
saved.delete(id);
|
|
99
|
+
const at = order.indexOf(id);
|
|
100
|
+
if (at >= 0)
|
|
101
|
+
order.splice(at, 1);
|
|
102
|
+
},
|
|
103
|
+
ids: () => order,
|
|
104
|
+
size: () => order.length,
|
|
105
|
+
tick(dt, now) {
|
|
106
|
+
hydrate();
|
|
107
|
+
const time = now ?? config.clock?.now() ?? lastNow;
|
|
108
|
+
lastNow = time;
|
|
109
|
+
for (const id of order) {
|
|
110
|
+
const agent = agents.get(id);
|
|
111
|
+
if (agent === undefined)
|
|
112
|
+
continue;
|
|
113
|
+
let targets = [];
|
|
114
|
+
if (!agent.isFar()) {
|
|
115
|
+
const selector = selectFor(id);
|
|
116
|
+
if (selector !== undefined) {
|
|
117
|
+
targets = selector({
|
|
118
|
+
id,
|
|
119
|
+
agent,
|
|
120
|
+
at: config.position?.(id) ?? null,
|
|
121
|
+
now: time,
|
|
122
|
+
far: false,
|
|
123
|
+
});
|
|
124
|
+
if (config.fallback !== undefined)
|
|
125
|
+
targets = withFallback(targets, config.fallback);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
frames.set(id, agent.update({ dt, now: time, targets }));
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
frame: (id) => frames.get(id) ?? null,
|
|
132
|
+
mood: (id) => agents.get(id)?.mood() ?? null,
|
|
133
|
+
moodMean() {
|
|
134
|
+
if (order.length === 0)
|
|
135
|
+
return null;
|
|
136
|
+
let total = 0;
|
|
137
|
+
for (const id of order) {
|
|
138
|
+
const agent = agents.get(id);
|
|
139
|
+
if (agent !== undefined)
|
|
140
|
+
total += agent.mood().score;
|
|
141
|
+
}
|
|
142
|
+
return total / order.length;
|
|
143
|
+
},
|
|
144
|
+
action: (id) => frames.get(id)?.action ?? null,
|
|
145
|
+
setFar(id, far) {
|
|
146
|
+
const agent = agents.get(id);
|
|
147
|
+
if (agent === undefined)
|
|
148
|
+
return;
|
|
149
|
+
agent.setFar(far);
|
|
150
|
+
if (far)
|
|
151
|
+
frames.delete(id);
|
|
152
|
+
},
|
|
153
|
+
isFar: (id) => agents.get(id)?.isFar() ?? false,
|
|
154
|
+
save() {
|
|
155
|
+
hydrate();
|
|
156
|
+
const members = {};
|
|
157
|
+
for (const id of order) {
|
|
158
|
+
const agent = agents.get(id);
|
|
159
|
+
if (agent !== undefined)
|
|
160
|
+
members[id] = { agent: agent.snapshot(), far: agent.isFar() };
|
|
161
|
+
}
|
|
162
|
+
const state = { version: 1, members };
|
|
163
|
+
config.storage?.write(state);
|
|
164
|
+
return state;
|
|
165
|
+
},
|
|
166
|
+
load: loadState,
|
|
167
|
+
dispose() {
|
|
168
|
+
for (const agent of agents.values())
|
|
169
|
+
agent.dispose();
|
|
170
|
+
agents.clear();
|
|
171
|
+
frames.clear();
|
|
172
|
+
saved.clear();
|
|
173
|
+
order.length = 0;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
hydrate();
|
|
177
|
+
for (const spec of config.members ?? [])
|
|
178
|
+
create(spec);
|
|
179
|
+
return system;
|
|
180
|
+
}
|
|
181
|
+
/** Targets keep their own fallback; the rest inherit the system's one. */
|
|
182
|
+
function withFallback(targets, fallback) {
|
|
183
|
+
let changed = false;
|
|
184
|
+
const next = targets.map((target) => {
|
|
185
|
+
if (target.fallback !== undefined)
|
|
186
|
+
return target;
|
|
187
|
+
changed = true;
|
|
188
|
+
return { ...target, fallback };
|
|
189
|
+
});
|
|
190
|
+
return changed ? next : targets;
|
|
191
|
+
}
|
|
192
|
+
/** Spread a config field only when the game set it, so `createAgent`'s own default stands otherwise. */
|
|
193
|
+
function optional(key, value) {
|
|
194
|
+
return value === undefined ? {} : { [key]: value };
|
|
195
|
+
}
|
|
@@ -4,10 +4,13 @@ import type { EntityColliderSet } from "../scene/colliders.js";
|
|
|
4
4
|
import { type SceneRaycastApi } from "../scene/sceneRaycast.js";
|
|
5
5
|
import type { Aim } from "../scene/spatial.js";
|
|
6
6
|
import type { CombatSpatialDeps, EffectResult, EffectSystem, EffectVia } from "./effects.js";
|
|
7
|
+
import { type ShotSpec } from "./shotSpec.js";
|
|
7
8
|
import { type ShotOriginPolicy } from "./shotOrigin.js";
|
|
8
9
|
export interface ProjectileShotInput {
|
|
9
10
|
from: string;
|
|
10
11
|
via: EffectVia;
|
|
12
|
+
/** How this shot travels and what it does on contact. Omitted means the shot's numeric stats are adapted once. */
|
|
13
|
+
spec?: ShotSpec;
|
|
11
14
|
aim: Aim;
|
|
12
15
|
effect: string;
|
|
13
16
|
/** Defaults to `{ kind: "converge" }` — explicit rays pass through; angular aim converges from the muzzle to the sightline. */
|
|
@@ -121,8 +124,9 @@ export interface ProjectileSettleReport {
|
|
|
121
124
|
effect: string;
|
|
122
125
|
hit: boolean;
|
|
123
126
|
/**
|
|
124
|
-
* True for lobbed
|
|
125
|
-
* false for direct-fire shots (bullets, bolts) that travel muzzle→impact in a straight line
|
|
127
|
+
* True for lobbed fused rounds (grenades, launchers, rockets) whose real path is an arc,
|
|
128
|
+
* false for direct-fire shots (bullets, bolts) that travel muzzle→impact in a straight line,
|
|
129
|
+
* including direct-fire shots that carry an explosion.
|
|
126
130
|
* Presentation uses it to keep straight-line tracers off arced projectiles.
|
|
127
131
|
*/
|
|
128
132
|
ballistic: boolean;
|