Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2792f0a32 | ||
|
|
8c359d4aeb | ||
|
|
e7a7dfea8b | ||
|
|
96b997ddb2 | ||
|
|
e9d53f059e | ||
|
|
d211f0c301 | ||
|
|
e58345f7c4 | ||
|
|
09ebead9f0 | ||
|
|
6b31607ff2 | ||
|
|
00a5e474b8 | ||
|
|
99ad8cd41d | ||
|
|
e5b6dbb94f | ||
|
|
10e6db5600 | ||
|
|
4ede193ca0 | ||
|
|
267c16d547 | ||
|
|
3ae7f03231 | ||
|
|
9c75c9d52a | ||
|
|
ed781c0f72 | ||
|
|
7416d15dd0 | ||
|
|
53b14bd272 | ||
|
|
8c4eb92806 | ||
|
|
a61611d7ce | ||
|
|
f28c11a108 | ||
|
|
407319b601 | ||
|
|
2af6e85924 | ||
|
|
3f0a0592b3 | ||
|
|
5a683ccc70 | ||
|
|
b1e1c213fc | ||
|
|
1302e24893 | ||
|
|
e940b2fd4b | ||
|
|
f26ec57b90 | ||
|
|
bb75bc07c7 | ||
|
|
c55770f048 | ||
|
|
0f4b3a03a8 | ||
|
|
9d21d81156 | ||
|
|
a30c0a04ff | ||
|
|
3d6e735a47 | ||
|
|
135f8d8ad9 | ||
|
|
cb8bcac964 | ||
|
|
3f0d360e28 | ||
|
|
61f5478bd8 | ||
|
|
21fb7bd37b | ||
|
|
20c2ed73ae | ||
|
|
350e137066 | ||
|
|
b6c77737a9 | ||
|
|
46d70811e1 | ||
|
|
cf0ef3a602 | ||
|
|
6ad5b97bc8 | ||
|
|
357610d37f | ||
|
|
721507f01a | ||
|
|
ee052832dc | ||
|
|
c4fb8d79cf | ||
|
|
5a75043d63 | ||
|
|
28a69549db | ||
|
|
b7305edd04 | ||
|
|
21ed762d35 | ||
|
|
9c9fa8db15 | ||
|
|
35d789553e | ||
|
|
e789efacac | ||
|
|
1d60ed6087 | ||
|
|
2bfb26b75b | ||
|
|
36d5d0b18b | ||
|
|
de5928f9af | ||
|
|
116cfa28eb | ||
|
|
791096939a | ||
|
|
acc79fb13f | ||
|
|
23fa1ca1b8 | ||
|
|
4cabc7f920 | ||
|
|
3286418df3 | ||
|
|
0425ffa108 | ||
|
|
cc9dcaf582 | ||
|
|
bd01101e97 | ||
|
|
79ddc1c82c | ||
|
|
8186d4b859 | ||
|
|
46b9e978f4 | ||
|
|
461a4e8a51 | ||
|
|
a49ffa0f27 | ||
|
|
1305c8cc64 | ||
|
|
bbde113198 | ||
|
|
25cae809e1 | ||
|
|
097fa569b0 | ||
|
|
56a5a53c35 | ||
|
|
746bccdc27 | ||
|
|
378b69dbc5 | ||
|
|
35fe28c2f3 | ||
|
|
814e2435cd | ||
|
|
619d4a8665 | ||
|
|
316e58ddbb | ||
|
|
f4e25a15bd | ||
|
|
ae02a4755d | ||
|
|
4a9861e7d0 | ||
|
|
15ef80a188 | ||
|
|
d217729dbe | ||
|
|
2a8790bc2a | ||
|
|
109bb784bb | ||
|
|
f98f3f9cf1 | ||
|
|
1b7dea0d06 | ||
|
|
fa29d1256f | ||
|
|
154f333fc7 | ||
|
|
7ce8213f64 | ||
|
|
15a34896dc | ||
|
|
dbfbaaa4b8 | ||
|
|
ed85d9e6a6 | ||
|
|
eb9d02cad6 | ||
|
|
324043ab30 | ||
|
|
fa4610ffe5 | ||
|
|
b6d4495abc | ||
|
|
a862844a33 | ||
|
|
ab544a3f02 | ||
|
|
3c5b214f4a | ||
|
|
b5cf844499 | ||
|
|
81a04b2e3a | ||
|
|
acd25f8256 | ||
|
|
73433e8256 | ||
|
|
b4fa1907fe | ||
|
|
06774227a6 | ||
|
|
ddfef49b83 | ||
|
|
e316bcb8e5 | ||
|
|
14b140953e | ||
|
|
4f1686e096 | ||
|
|
e4b1b4e1a3 | ||
|
|
39281ddc78 | ||
|
|
dd081e9408 | ||
|
|
34547b6514 | ||
|
|
b4db734b7e | ||
|
|
faab825994 | ||
|
|
2f4841a95e | ||
|
|
dc104334ff | ||
|
|
4ed6649480 | ||
|
|
ff955f8b1d | ||
|
|
82c85f96c0 | ||
|
|
fd275300f9 | ||
|
|
f600f57259 | ||
|
|
2ea2f4e92c | ||
|
|
d5a456707f | ||
|
|
a218c55090 | ||
|
|
0e9e1ee837 | ||
|
|
92d1478229 | ||
|
|
2cc271d78f | ||
|
|
72a830d62f | ||
|
|
917825cd52 | ||
| 9f597647a6 | |||
|
|
f8f957b17d | ||
|
|
bd275e1bde | ||
| ed89ebd704 | |||
|
|
40f592d087 | ||
| f0b80400ec |
66 changed files with 87016 additions and 199 deletions
2
.gitattributes
vendored
Normal file
2
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
tools/FellaMesh/input/* -text
|
||||
*.glb binary
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
|||
bin/
|
||||
obj/
|
||||
client/.godot/
|
||||
|
|
|
|||
7
Directory.Build.props
Normal file
7
Directory.Build.props
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<!-- Sibling Lodur checkout (main, from the nervous-layers merge on): the nervous model BDS consumes. Set LODUR_ROOT to override. -->
|
||||
<LodurRoot Condition="'$(LodurRoot)' == '' and '$(LODUR_ROOT)' != ''">$(LODUR_ROOT)</LodurRoot>
|
||||
<LodurRoot Condition="'$(LodurRoot)' == ''">$(MSBuildThisFileDirectory)..\Lodur</LodurRoot>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
219
README.md
219
README.md
|
|
@ -6,7 +6,7 @@ feel what happens to them, flinch, writhe, and sometimes crawl on toward
|
|||
whatever they wanted, because they are driven by
|
||||
[Lodur](https://eureka.gamecult.org/forge/GameCult/Lodur).
|
||||
|
||||
**Status: first slice only (the pain box). The 3D sandbox does not exist yet.** The design is Lodur's target,
|
||||
**Status: two scenarios (the pain box and the office stress arc), headless, on the Ymir ragdoll and in a Godot client. The 3D sandbox does not exist yet.** The design is Lodur's target,
|
||||
[`docs/lodur-target.md`](https://eureka.gamecult.org/forge/GameCult/Lodur/src/branch/main/docs/lodur-target.md)
|
||||
in the Lodur repo; this game is its first consumer and its proving ground.
|
||||
|
||||
|
|
@ -20,34 +20,130 @@ impairment) in one place where a player can poke at all of it.
|
|||
Canonical: `https://eureka.gamecult.org/forge/GameCult/BadDaySimulator`.
|
||||
GitHub `GameCult/BadDaySimulator` is a push mirror.
|
||||
|
||||
## What runs today: the pain box
|
||||
## What runs today: the Synaptic Induction Chamber (the pain box)
|
||||
|
||||
A headless, deterministic simulation of one virtual human with a hand in a
|
||||
pain box. Question it answers: **how long until the will breaks, or the box is
|
||||
disabled first?** Entry points:
|
||||
A deterministic simulation of one virtual human with a hand in the Synaptic
|
||||
Induction Chamber (the pain box), run headless or on a Ymir ragdoll. Question it answers: **how long until the
|
||||
will breaks, or the box is disabled first?** The nervous model is Lodur's
|
||||
(`Lodur.Actor`); this game holds the box, the seed, the restraint and the
|
||||
recorder. It needs sibling checkouts of Lodur and Ymir (`LODUR_ROOT`, else
|
||||
`..\Lodur`, built against Lodur `c324570` (`nibu/lodur-dead-flows`: a dead physiology's flows read zero); Lodur finds `..\Ymir`, or `YMIR_ROOT`). Entry points:
|
||||
|
||||
- `src/BadDay.Core/PainBoxSimulation.cs`: the model and the tick loop.
|
||||
- `src/BadDay.Core/PainBoxParameters.cs`: every tunable, with defaults.
|
||||
- `src/BadDay.Core/PainBoxSimulation.cs`: the headless run over Lodur's Actor.
|
||||
- `src/BadDay.Core/ChamberBrain.cs`: the volunteer's Brain, authored as data: his goals, and the payment's pull.
|
||||
- `src/BadDay.Core/PainBoxSession.cs`: the run's seed, traits, box and recorder; both runs drive it.
|
||||
- `src/BadDay.Core/PainBox.cs`: the box schedule (ramp, jitter, disable time).
|
||||
- `src/BadDay.Core/PainBoxParameters.cs`: the box and clock tunables, plus Lodur's parameter records as members.
|
||||
- `src/BadDay.Core/Sweep.cs`: consecutive seeds, break-time min/median/max.
|
||||
- `src/BadDay.Cli`: `baddaysim`.
|
||||
- `tests/BadDay.Tests`: determinism, break-time and monotonicity tests.
|
||||
- `src/BadDay.Ymir/BodyPainBox.cs`: the same run on the Ymir ragdoll, with the hand-out time.
|
||||
- `src/BadDay.Ymir/SeatedPuppet.cs`: the stool, ground and ragdoll every body is built from (`SeatedBody` holds the world).
|
||||
- `src/BadDay.Cli`: `baddaysim` (`baddaysim plan` prints the seated puppet's body plan as JSON: the skeleton `tools/FellaMesh` builds Fella's skin on).
|
||||
- `tests/BadDay.Tests`: determinism, break-time, monotonicity and body tests.
|
||||
- `tools/PainSweep`: the intensity x suppression table.
|
||||
|
||||
```
|
||||
dotnet run --project src/BadDay.Cli -- run --seed 1
|
||||
dotnet run --project src/BadDay.Cli -- sweep --seed 1 --count 50 --pull 0.3
|
||||
dotnet run --project src/BadDay.Cli -- sweep --seed 1 --count 50 --pay 40
|
||||
dotnet run --project src/BadDay.Cli -- run --seed 1 --disable-at 5
|
||||
dotnet run --project src/BadDay.Cli -- run --seed 1 --body
|
||||
dotnet run --project tools/PainSweep
|
||||
dotnet run --project tests/BadDay.Tests # exits non-zero on failure
|
||||
```
|
||||
|
||||
`run` prints a timeline (samples every second, plus flinch, break and
|
||||
withdrawal events) and a one-line summary. Options: `--intensity`, `--pull`,
|
||||
`--disable-at`, `--max`, `--every`.
|
||||
withdrawal events) and a one-line summary. Options: `--intensity`, `--pay` (what the volunteer is paid, dollars; default 100),
|
||||
`--disable-at`, `--max`, `--every`. `--body` runs it on the ragdoll (1/120 s
|
||||
steps; the native Ymir library builds with cmake and a C compiler on first
|
||||
build) and adds a line with the time the hand left the box. The body run is also a stepping
|
||||
session, `BodyPainBoxSession` (create, `Step`, read `Hand` and the world's lanes, `SetIntensity`,
|
||||
`SwitchOff`, `BoxOn`, `DrainEvents`, dispose), that the Godot client drives and `run --body` steps to the end; `BadDay.Core` and
|
||||
`BadDay.Ymir` target net8.0 for Godot, the executables and tests net10.0. Events queue per tick until drained, so a frame spanning several steps loses none. Stepping past the end keeps the body moving; that free motion is float arithmetic on the platform's math and is not bit-identical across operating systems (the run itself is).
|
||||
|
||||
### Godot client
|
||||
|
||||
`client/` is a Godot 4.7.2 (mono) project that renders the body run and takes the player's commands: the
|
||||
Synaptic Induction Chamber, the dummy strapped to a stool with its right hand in the box. It owns presentation and
|
||||
input only. Godot's physics engine is set to Dummy; each 120 Hz physics frame the client calls
|
||||
`BodyPainBoxSession.Step()` once and draws Ymir's lanes: one pose-carrying node per stable id (`BodyRenderer`). Fella's 19 parts are drawn by one
|
||||
skinned mesh, `FellaSkin`, on those carriers' poses (MakeHuman's androgynous base body fitted to Lodur's plan by `tools/FellaMesh`; the file is
|
||||
`client/fella/fella_skin.glb`, CC0, see `client/fella/ATTRIBUTION.md`); every other body holds its own primitive (a capsule, box or sphere of the lane's
|
||||
size). The look is
|
||||
PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy): every surface is `ps1.gdshader` (vertices snapped to the line grid, affine texture
|
||||
coordinates, unfiltered texels, light, glow and fog per vertex, in raw sRGB arithmetic), and `ps1_post.gdshader` on a full-screen rect under the
|
||||
HUD quantises the frame to one colour per block of a 240-line grid (`Look.Lines`, blocks of round(H / 240) pixels anchored at the screen centre)
|
||||
in 15-bit colour with the 4x4 ordered dither. No `Light3D` exists: the shader lights the scene from the globals `ps1_*` (`project.godot`
|
||||
`[shader_globals]`), which `Look` (constants), `Main` (`ps1_res`) and `Chamber` (the glow light, 0.9 m range) write.
|
||||
Needs the .NET 8+ SDK, cmake and a C compiler (MinGW gcc on Windows), the sibling Lodur and Ymir (with joint origin lanes, ABI 8) checkouts
|
||||
(`..\Lodur`, `..\Ymir`, or `LODUR_ROOT` and `YMIR_ROOT`), and Godot 4.7.2 mono. Nothing in this repository pins or checks the siblings' revisions
|
||||
(BDS's graph references no CultLib project, so Ymir's own revision check never runs here); the client was last verified against Lodur 2359142 (the gravity subtree gate) and
|
||||
Ymir 1d27114 (its `extern/box3d` submodule initialised).
|
||||
|
||||
Fella's skin is generated: `py -3 tools/FellaMesh/build_fella_mesh.py` (Python 3, numpy and Blender 5.3.0 headless for the decimation, pinned in `tools/FellaMesh/input/README.md`; it runs `baddaysim plan` for the skeleton, so the siblings above must build) writes
|
||||
`client/fella/fella_skin.glb` from the pinned MakeHuman files in `tools/FellaMesh/input` (see its README for source, commit, licence and SHA-256 sums), and `--check`
|
||||
rebuilds and compares bytes (only on the pinned Blender; any other version is refused). The file is never edited by hand. The macro arguments (`--gender`, `--age`, `--muscle`, `--weight`, `--height`, `--proportions`) default to MakeHuman's neutral
|
||||
0.5 (the androgynous base, lodur:ruling:default-fella-androgynous-base); other values are refused until the macrodetails targets are pinned (lodur:follow_up:fella-body-variety).
|
||||
|
||||
```
|
||||
dotnet build client/BadDay.Client.csproj # Lodur, Ymir (cmake) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug
|
||||
<godot> --path client # play: Blender's navigation: middle-drag orbits the puppet, Shift+middle-drag pans, Ctrl+middle-drag and the wheel zoom; Alt+left-drag stands for the middle button (OrbitCamera.Emulate3ButtonMouse)
|
||||
<godot> --headless --path client res://tests/Smoke.tscn # the smoke; exit code 0 passes
|
||||
<godot> --path client res://tests/DrownCapture.tscn -- --frames=<dir> # the throat cut, in a window: the clutch, the thrash, the sag and the limp body as PNGs and frames.tsv; exit code 0 passes
|
||||
<godot> --path client res://tests/RenderCheck.tscn # the render check, in a window (not headless); exit code 0 passes; -- --frames=<dir> keeps its frames
|
||||
bash client/tests/render-mutants.sh # breaks the look once per claim; each break must fail its line
|
||||
```
|
||||
|
||||
Or open `client/project.godot` in the Godot editor, Build, Play. The HUD has Reset with a seed, a live intensity
|
||||
slider, Box off and Slow motion. Do not run `godot --import` on a fresh checkout; a plain run creates `.godot`.
|
||||
Exports need export templates (not installed here yet), so the client runs from the editor and headless for now.
|
||||
|
||||
The smoke has no renderer. `RenderCheck.tscn` is the check that does: it renders real frames (gl_compatibility, the client's renderer at 1280x720)
|
||||
of seed 1 stopped at a pinned tick and reads them back, so every reading is the same run to run. It checks that every channel is a multiple of 8 and the odd multiples of 8 appear (15-bit, not 12-bit colour), that the
|
||||
grid is 240 lines (a literal: the blocks are 3 px at 720, whatever `Look.Lines` says), that every block of the grid is one colour, that a flat field's
|
||||
blocks follow ps1.js's 4x4 ordered dither, that a wall at 9 m is fogged to the depth's smoothstep, that a triangle with different vertex normals is lit by
|
||||
the blend of its corners' light (per vertex, not per pixel), that a minified checker that carries mipmaps still draws only black and white (nearest, no
|
||||
mips), that a probe box's drawn blocks are those of its hull with the corners snapped to a coarse grid (the unsnapped hull differs in 8 blocks), that the
|
||||
texel runs of a checker triangle seen at 60 degrees keep equal widths along a scanline (affine), that the chamber at full glow lights the figure by at least
|
||||
1.2 levels over dark, that each dynamic body's lane origin projects within a block of a figure pixel, and that the figure has a neck (its width a centimetre below the neck joint over its width at the head, seen from the front), and that the rest-pose mesh is left-right symmetric (the largest mirror distance of its vertices). The check holds at 1280x720 only: at any other
|
||||
window size it fails "window" before reading a frame (the grid is round(H / 240) px, 216 lines at 1080, and `Camera3D.UnprojectPosition` answers in the
|
||||
stretch base's coordinates). Bounds sit at the midpoint of the shipped worst and the least claimed mutant (`lodur:ruling:deterministic-bound-margin`),
|
||||
each stated in its comment; `client/tests/render-mutants.sh` applies one set of edits per claim (post off, 12-bit post, dither off, per-pixel blocks, 360 and
|
||||
120 lines, snap off, perspective-correct UVs, per-pixel light, fog off, mipmapped and linear textures, glow unwritten, carriers unposed, the primitive torso drawn again beside the skin, the skin drawn unposed, the left half of the rest mesh stretched) and wants that
|
||||
claim's line to fail; with `UNCLAIMED=1` it runs the edits no line separates (per-pixel fog, so far), whose readings it records. It needs a display.
|
||||
|
||||
|
||||
### Who owns what (the map)
|
||||
|
||||
The client's drawing pipeline, one owner per decision (the paragraphs above say how it looks; this says who may write what):
|
||||
|
||||
| Owner | Inputs | Outputs | Derived state | Forbidden writers |
|
||||
|---|---|---|---|---|
|
||||
| Ymir (the session's world, ABI 8) | the session's commands and Lodur's torque lanes | pose, shape, stable-id and joint lanes, including each joint's origin in the world (the joint origin lanes) | none the client keeps | the client writes no lane; Ymir never reads the client |
|
||||
| `BodyRenderer` | the lanes (kind, size, stable id, pose), each physics frame | one carrier per stable id, and one primitive `MeshInstance3D` for each body `SeatedPuppet.PartOf` does not claim; `PoseOf`, `InterpolatedPoseOf`, `PuppetCentre` (the skin's centre), `MeshBuilds` | `MeshBuilds`, the smoke's counter: a Reset with the same ids makes no mesh | geometry derived from anything but the lane's size; a primitive for a body the skin draws
|
||||
| `FellaSkin` (a child of `BodyRenderer`) | `fella_skin.glb` (written only by `tools/FellaMesh`), `SeatedPuppet.Plan` (parts and creation frames), the carriers' interpolated poses | one dynamic skinned surface in world space; `Centre`, `MeshBuilds` (1), `RingGap`, `OwnedVertices` | the per-vertex rest data read from the glb at `_Ready`; the posed vertices, rewritten in place every frame | carriers, lanes or the session; any hand edit of the glb; Lodur reading the mesh |; writing a lane |
|
||||
| `ps1.gdshader` | `Look`'s numbers and the `ps1_*` globals, the mesh's vertices, normals and UVs | every surface's colour: snapped vertices, affine texels, per-vertex light, glow and fog | none | skinning; a second light model; a `Light3D` |
|
||||
| `ps1_post.gdshader` | the frame and `ps1_res` | the framebuffer at the line grid in 15-bit colour with the dither | none | a second resolution owner (viewport scaling, a SubViewport; the project's `canvas_items` stretch, base 1280x720, only scales canvas items and `Camera3D.UnprojectPosition`'s answers, and the pass reads the real pixels, so it owns no resolution) |
|
||||
| `Look`, `Main`, `Chamber` | `Look`: constants and textures; `Main`: the window size; `Chamber`: the box's intensity | `Look`: the constant globals and `Look.Ps1` materials; `Main`: `ps1_res` and the post layer; `Chamber`: `ps1_glow_*` | `ps1_res` is the window over `Look.BlockSize`, never set elsewhere | any other writer of a `ps1_*` global |
|
||||
| `tests/RenderCheck.cs` (the windowed check), `render-mutants.sh`, `Smoke.cs` | the same lanes through the real renderer | an exit code, optional PNGs | none | writing the scene's state beyond pinning a tick and a probe |
|
||||
|
||||
The scenarios, one owner per decision:
|
||||
|
||||
| Owner | Inputs | Outputs | Derived state | Forbidden writers |
|
||||
|---|---|---|---|---|
|
||||
| `ChamberBrain`, `OfficeBrain` | `PainBoxParameters` or `StressParameters`, the poses | a Lodur `Brain`: goals and their rules as data (the office's: keep composure, rage, calm, clutch, thrash), and, for the chamber, the release goal's id (`withdraw`) | none; Lodur's Actor commits each switch | a session choosing a goal; a goal rule outside the Brain |
|
||||
| `PainBoxSession`, `StressSession` | seed, traits, the box or the cause, the player's commands (`Silence`, box off) | the box's or the emitters' intensities each tick; rows read back from the Actor (the stress column is the drive's arousal, the goal column the Actor's goal); for the chamber, the end of the run | the chamber's release goal, looked up by its id at construction (an unknown id refuses the build) | computing load, arousal, resolve or a goal; for the chamber, a goal index hard-coded for the release |
|
||||
| Lodur (`Actor`, the drive, the Brain) | the sessions' stimuli, the body's region points | muscle strengths and targets; the events | resolve, strain, pain, arousal, the breaks, the sensory gain in force | BDS writing any of it |
|
||||
| Lodur's `Physiology` | `Afflict` calls (only from `StressSession.Wound`) and the Actor's step input | blood loss, consciousness, air hunger, death and its cause (`Died` once; a dead body is limp) | tissue integrity, bleed, the motor ceiling | a session or client deciding death, bleed or consciousness; any `Afflict` outside `StressSession.Wound` |
|
||||
| `SeatedBody` | the scenario's strengths and targets each tick | the world's view, the sense points, the `BodyEvent` queue | the ragdoll and its world, built through `SeatedPuppet.Build` | any `Box3DSoaWorld` or world step in BDS outside it |
|
||||
| `BodyPainBoxSession`, `OfficeBodySession` | their scenario's commands (`SetIntensity`, `SwitchOff`; `Silence`, `Wound`) | one `SeatedBody` stepped per `Step`; the chamber's hand and result, the office's read-outs (will, arousal, resolve, consciousness, blood loss, air hunger, death) | none: neither owns a world | creating or stepping a world; deciding death |
|
||||
|
||||
Found stale by Modeling, 2026-11-20, not changed: `docs/scenarios/fella-bad-day-at-the-office.md` is a design document (Status: design, not built) whose ladder rows 3 and 4 are now built; its text outside the ladder is not a map of the code.
|
||||
|
||||
### Modeled
|
||||
|
||||
Fixed 10 ms tick, seeded SplitMix64 (the only randomness; integer arithmetic,
|
||||
so a seed means the same stream anywhere). Following the layers in Lodur's
|
||||
target, flattened to one loop:
|
||||
Fixed 10 ms tick headless (1/120 s on the body), seeded SplitMix64 (the only
|
||||
randomness; integer arithmetic, so a seed means the same stream anywhere). The
|
||||
layers are Lodur's, run by its Actor (see Lodur's target); each timeline row is the
|
||||
Actor's state at the end of its tick:
|
||||
|
||||
- **Perception / nerve:** the box emits an intensity (ramped in, with seeded
|
||||
jitter). A nociceptor applies a threshold and sensitises under sustained
|
||||
|
|
@ -57,25 +153,37 @@ target, flattened to one loop:
|
|||
down accumulates strain (suppression is never free, per
|
||||
`reflex-gain-from-drive`).
|
||||
- **Drive:** pain rises with the signal and decays; resolve drains with pain
|
||||
and strain, scaled by `(1 - ObjectivePull)`, and recovers only when pain is low.
|
||||
and strain, scaled by `(1 - pull)` of the goal in force, and recovers only when pain is low.
|
||||
Two seeded traits (nociceptor gain, resolve drain) make each seed a different person.
|
||||
- **Goals:** `HoldHand` (the objective, with its pull) and `Withdraw`. When
|
||||
resolve reaches zero the goal flips and the hand is out after the withdrawal
|
||||
latency (100 ms).
|
||||
- **Goals:** the volunteer is paid to keep his hand in, and his Brain is data, built in code for now
|
||||
(`ChamberBrain`; it becomes CultCache content with Lodur's Brain content, follow-up `npc-brains-as-content`): `HoldHand` pulls with `Payment / (Payment + DollarsAtHalfPull)` (both
|
||||
100 by default, so $100 pulls 0.5; $0 pulls nothing and $400 pulls 0.8), and `Withdraw`
|
||||
is eligible once the will has broken (`Breaks >= 1`, which never falls, so the withdrawal is one-way: a will that mends does not give the hand back), outranks it and is involuntary for good. Lodur's Actor commits the
|
||||
switch after its deliberate latency (100 ms), so the break row still reads `HoldHand`;
|
||||
the hand is out when `Withdraw` takes over. The sessions never decide a goal: the
|
||||
goal column is read back from the Actor.
|
||||
- **Measure:** `TimeToBreakMs` (resolve hits zero) and the outcome:
|
||||
`WillBroke`, `BoxDisabled` (disabled while the will held), or `Endured`.
|
||||
|
||||
### Not modeled
|
||||
|
||||
No body, physics, balance, joints or ragdoll; no shock, adrenaline or blood
|
||||
loss; no impairment or crawling; no Unity binding; no puppets or objects other
|
||||
than the box; no learning. The reflex never removes the hand by itself: only a
|
||||
The headless run has no body, physics or balance (the body run has a ragdoll
|
||||
held on a stool: it cannot balance); no shock, adrenaline or blood
|
||||
loss; no impairment or crawling; no Unity binding; no puppets, and no objects other
|
||||
than the box and the office's emitters; no learning. The reflex never removes the hand by itself: only a
|
||||
broken will does. All parameter values are **placeholders**, not physiology;
|
||||
the figures in Lodur's target are marked unverified and so are these. Break
|
||||
times in the output are properties of this toy model, not predictions about people.
|
||||
Bit-exact output across CPU architectures is not claimed; same-machine runs
|
||||
are byte-identical (the loop uses only `+ - * /` and comparisons, no
|
||||
transcendental functions).
|
||||
are byte-identical. The headless arithmetic is Lodur's and uses only `+ - * /`
|
||||
and comparisons; the hold behaviour's shake uses `Math.Sin`, and the body run
|
||||
adds native physics, so neither is claimed bit-exact across machines (Windows
|
||||
and Linux x64 agreed on seeds 1-5, the sweep and `run --body` when compared).
|
||||
|
||||
The timeline of a run differs from the pre-Lodur slice only in that each row is the
|
||||
Actor's state at the end of its tick: a Flinch row shows strain and resolve after the
|
||||
tick's update. The goal column is the goal in force, so rows from the break to the
|
||||
withdrawal 100 ms later (the break row, and any sample falling in between) read `HoldHand`.
|
||||
|
||||
Persistent content (puppet definitions, drive parameters, saved levels) will
|
||||
be CultCache per Lodur's `content-is-cultcache`; this slice has none, so it
|
||||
|
|
@ -83,8 +191,61 @@ has no cache layer and no JSON.
|
|||
|
||||
### Build note
|
||||
|
||||
The core has no engine reference (`core-engine-free`). The slice has no
|
||||
package dependencies, so the tests are a plain console program rather than
|
||||
xunit. On the Yggdrasil mind host `dotnet restore` currently fails on a
|
||||
NuGet named mutex (read-only `/dev/shm`); the slice was compiled there with
|
||||
Roslyn's `csc` directly, which is why the `.csproj` files are the unverified part.
|
||||
The core has no engine reference (`core-engine-free`). It references the sibling Lodur checkout
|
||||
(`LODUR_ROOT`, else `..\Lodur`) and nothing else, so `dotnet build` and `dotnet run` work with the
|
||||
.NET SDK alone; the tests are a plain console program rather than xunit. Only `BadDay.Ymir` (and what
|
||||
references it: the CLI and the tests) builds Ymir's native library, which needs cmake and a C compiler
|
||||
(on Windows MinGW: `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`). The projects were built and the tests
|
||||
run on Windows and on Linux.
|
||||
|
||||
## The office stress scenario (rungs 3 and 4)
|
||||
|
||||
The office's stressors raise the stress bar until the will breaks, and then Office Fella snaps, rages, and settles:
|
||||
headless, one tick at a time, or on the seated puppet. The scenario is data in three parts. The **setting** names the emitters (printer, ceiling light, desk
|
||||
phone, desktop notifications) and where they sit. The **cause** holds the stressors that drive them (each with
|
||||
an onset, ramp, period, duration, intensity and jitter), and the job's pull (0.6, the keep-composure goal's). The **character** holds the sense nerve he
|
||||
hears and sees with. Lodur owns what the stimulus does: sensing, load, arousal, and the arousal
|
||||
drain on resolve. `StressSession` only writes the emitters' intensities each tick and logs the Actor's state;
|
||||
the player's lever is `Silence(stressorId)`, from the current tick on. Office Fella's Brain is data too, built in code for now (`OfficeBrain`; content later, as above): `KeepComposure` pulls with the job's pull; `Rage` (eligible once the will has broken, `Breaks >= 1`, outranks it,
|
||||
no pull) loops wind-up and strike with each arm at 0.25 s a key. It refills his will on entry, is involuntary for its first second
|
||||
(`RageOnsetSeconds`) and then costs `RageEffort` (0.05) a second, so the rage drains the will it was given. When that will runs dry
|
||||
and breaks a second time (5-20 s after the snap) `Calm` takes over: his composed pose at normal strength, involuntary since his will is spent,
|
||||
terminal as data among the stress goals (it gates on `Breaks >= 2`, which never falls, and only the two air-hunger goals outrank it): he throws no further fit
|
||||
(ruling `lodur:ruling:fella-calm-after-rage`). Air hunger is physiology, not a fit, so it outranks calm: `Clutch` (priority 3, air hunger at `ClutchAirHunger`, 0.3 [P]; a breath tried and not got reads 0.6) puts both hands at his throat, and `Thrash` (priority 4, the same air hunger and a will that has broken now, `WillBroken`, not `Breaks`) walks four flailing keys at `ThrashKeySeconds` (0.2 s [P]). Both are involuntary throughout, since a will-weighted struggle goes limp (rulings `lodur:ruling:bds-air-hunger-clutch-then-thrash`, `lodur:ruling:bds-thrash-when-will-breaks`). A throat cut at rest clutches at once and thrashes 100 ms after the will breaks; a cut during the rage clutches first and thrashes when the rage runs dry; a Fella cut while his will is still broken (calm, resolve 0) thrashes at once. He weakens as he fades through Lodur's motor ceiling (consciousness), which scales every strength; BDS adds no goal for it. The headless office breathes freely and has neither goal. The Actor commits each switch 100 ms after its break,
|
||||
the session logs a `GoalChanged` row for each. The office has no end of its own (ruling `lodur:ruling:bds-office-is-a-sandbox-preset`): the break is an event in the scene, the body goes on, and a wound may kill it in its own time; whoever steps the session stops when the player ends it (the headless run, the sweep and `OfficeBody.Run` take a horizon in seconds, the CLI's `--max`, 180 by default).
|
||||
`TimeToBreakMs` is the first break, the snap; the second `WillBroke` row is the rage running dry.
|
||||
The chamber's release is declared the same way (`PainBoxParameters.ReleaseGoalId`, `withdraw`), and its withdrawal is one-way: a will that mends does not give the hand back. Who has the day is a `Character` (his senses; `Character.OfficeFella`),
|
||||
apart from the setting and the cause. Each scenario builds its own Brain from its own parameters; one entry point keyed by character id
|
||||
waits for Brains as content. Headless the rage moves nothing; `office --body` runs it on the puppet.
|
||||
|
||||
On the puppet the office is `OfficeBodySession`, stepped by its caller one 1/120 s step at a time like the chamber's session (`OfficeBody.Run` records one for a horizon). It builds a `SeatedBody`, the one owner of every BDS body world, and attaches a Lodur `Physiology` to the Actor (`StressParameters.SlowScale`, default 20 [P]: ruling `lodur:ruling:bds-physiology-clock`; Acute afflictions such as a cut do not move with it). The player's harm is `Wound(part, tool)`: a `WoundTool` is a depth and a severity; the hit point in the part's frame and Lodur's `PartTissuesDef.Reach` pick the layers, and `StressSession.Wound` binds one Cut affliction on each, the only path harm takes into the body. The knife (`WoundTool.Knife`, 0.02 m at 20 [P]: skin, fat and muscle on limbs and trunk, the larynx at the front of the throat) is the click-cut's content until contacts become afflictions. Lodur decides the rest: blood loss, consciousness, air hunger and death (`lodur:ruling:bds-death`). A cut on the left lower arm bleeds the body out in 191 s (seed 1; the carotids and the femoral artery in 29.7 s; a throat cut drowns him in his own blood in 167 s); the Actor reports `Died` once, the body goes limp (it writes no strength from then on), the session logs a `Died` row, `Outcome.Died` and `StressResult`'s `DiedAtMs` and `DeathCause` record it, and the run goes on: the session has no end. An unwounded run is unchanged: nothing in it can die.
|
||||
|
||||
The stress bar is his arousal, how wound up he is right now, and reads **stress (arousal)** (`StressResult.StressBarLabel`; ruling `lodur:ruling:stress-bar-shows-arousal-calm-silences`).
|
||||
It rises with each stressor and falls in quiet; will is not on it. Entering calm fades his arousal and his senses' gain to nothing over `CalmFadeSeconds` (3 s, the aftershock tail of
|
||||
`lodur:ruling:flinch-tail-after-stimulus`; the calm goal's `EntryArousal`, `SensoryGain` and `EntrySeconds`), so the bar drains and stays empty for the rest of the run while the stressor columns
|
||||
keep sounding. Arousal is exactly 0 from `CalmFadeSeconds` on; the load column tails off with the gain and reaches 0 one tick later (`Sense` reads the gain a tick after the Actor sets it).
|
||||
|
||||
- `src/BadDay.Core/Setting.cs`, `Cause.cs`: the office's defaults, in code, not persisted yet.
|
||||
- `src/BadDay.Core/StressSession.cs`: one run, driven per tick by the headless run, the sweep, the CLI and a client.
|
||||
- `src/BadDay.Core/OfficeBrain.cs`: Office Fella's goals, and the poses they write.
|
||||
- `src/BadDay.Ymir/OfficeBody.cs`: the office on the seated puppet, recorded to its end: both hands, the pelvis and the strikes.
|
||||
- `src/BadDay.Ymir/OfficeBodySession.cs`: the office's stepping session on a `SeatedBody` with a Lodur `Physiology`; `Wound`, the read-outs, death.
|
||||
- `src/BadDay.Ymir/SeatedBody.cs`: the one owner of a BDS body world and its step order.
|
||||
- `src/BadDay.Core/WoundTool.cs`: what a wound is made of: a depth and a severity; `Knife`.
|
||||
- `src/BadDay.Core/StressSimulation.cs`: the headless run with scheduled silences, and the seed sweep.
|
||||
|
||||
```
|
||||
dotnet run --project src/BadDay.Cli -- office --seed 1
|
||||
dotnet run --project src/BadDay.Cli -- office --seed 1 --body
|
||||
dotnet run --project src/BadDay.Cli -- office --seed 1 --silence printer@20 --silence desk-phone@30
|
||||
dotnet run --project src/BadDay.Cli -- office-sweep --seed 1 --count 50 --scale 1.5
|
||||
```
|
||||
|
||||
Options: `--silence ID@S` (repeatable; `printer`, `ceiling-light`, `desk-phone`, `desktop-interrupt`), `--scale`
|
||||
(every stressor's intensity), `--pull`, `--max`, `--every`, and `--body` (run the puppet; the summary adds the rage's
|
||||
length and the strikes counted as forward hand-speed peaks). The rows are `time_ms kind audio visual interrupt
|
||||
load arousal resolve stress goal`, with kinds Sample, Silenced, WillBroke, GoalChanged and Died (`Endured` is only the outcome "the will held so far") and goals
|
||||
KeepComposure, Rage, Calm, Clutch and Thrash. The sweep prints the
|
||||
break-time min/median/max and the lowest resolve among runs that endured. The office breaks near 90 s at pull
|
||||
0.6 only with the office's own sense nerve (threshold 0.05, no sensitisation, no conduction delay); Lodur's
|
||||
`NerveParameters` defaults break it near 100 s. **Every number here is a placeholder.**
|
||||
|
|
|
|||
13
client/BadDay.Client.csproj
Normal file
13
client/BadDay.Client.csproj
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<Project Sdk="Godot.NET.Sdk/4.7.2">
|
||||
<!-- The Godot client: presentation and input over BodyPainBoxSession. Building it builds Lodur, Ymir (cmake and a C compiler) and BDS into .godot/mono/temp/bin/Debug. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>BadDay.Client</AssemblyName>
|
||||
<RootNamespace>BadDay.Client</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\src\BadDay.Ymir\BadDay.Ymir.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
103
client/BloodRenderer.cs
Normal file
103
client/BloodRenderer.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
using System;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Draws the body's blood from Ymir's lanes and writes nothing back: one MultiMesh of the live fluid drops (a small box of side 2 x the
|
||||
/// particle's radius) and one of the wet patches (a flat disc of the patch's radius, lying horizontal at the patch's point carried by the body it
|
||||
/// is on, in that body's pose). The drawing is not scaled (lodur:ruling:bds-blood-gain-simulated): the volume the physiology loses is
|
||||
/// scaled where the blood is emitted, and what is shown is what the world holds. Splat decals, painted textures and billboards are a later cut.
|
||||
/// </summary>
|
||||
public partial class BloodRenderer : Node3D
|
||||
{
|
||||
/// <summary>A patch is a disc this thick (m), lifted this far (m) so it does not z-fight the surface it lies on.</summary>
|
||||
public const float PatchThickness = 0.004f, PatchLift = 0.003f;
|
||||
|
||||
private readonly MultiMeshInstance3D _drops = Instances(new BoxMesh { Size = Vector3.One }, "Drops");
|
||||
private readonly MultiMeshInstance3D _patches = Instances(new CylinderMesh { TopRadius = 1f, BottomRadius = 1f, Height = 1f, RadialSegments = 8, Rings = 0 }, "Patches");
|
||||
|
||||
private readonly System.Collections.Generic.List<Transform3D> _dropPoses = new(), _patchPoses = new();
|
||||
|
||||
/// <summary>The transforms the latest Sync gave the drops and the patches, in lane order (a copy of what the MultiMeshes were told, display-only: a headless renderer keeps none).</summary>
|
||||
public System.Collections.Generic.IReadOnlyList<Transform3D> Drops => _dropPoses;
|
||||
public System.Collections.Generic.IReadOnlyList<Transform3D> Patches => _patchPoses;
|
||||
|
||||
/// <summary>Drops and wet patches drawn by the latest <see cref="Sync"/>: the live fluid lanes and the live wet lanes.</summary>
|
||||
public int DropCount { get; private set; }
|
||||
public int PatchCount { get; private set; }
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
var material = Look.Ps1(null, Look.Blood);
|
||||
foreach (var node in new[] { _drops, _patches })
|
||||
{
|
||||
node.MaterialOverride = material;
|
||||
node.Multimesh.CustomAabb = new Aabb(new Vector3(-50, -5, -50), new Vector3(100, 20, 100)); // instances move every frame: never culled on a stale box
|
||||
}
|
||||
AddChild(_drops);
|
||||
AddChild(_patches);
|
||||
}
|
||||
|
||||
public void Sync(in Box3DSoaView view)
|
||||
{
|
||||
var live = view.ParticleLive;
|
||||
var phase = view.ParticlePhase;
|
||||
var radius = view.ParticleRadius;
|
||||
int drops = 0;
|
||||
for (int i = 0; i < live.Length; i++) if (live[i] != 0 && (phase[i] & Box3DSoaPhase.Fluid) != 0) drops++;
|
||||
Reserve(_drops.Multimesh, drops);
|
||||
_dropPoses.Clear();
|
||||
int d = 0;
|
||||
for (int i = 0; i < live.Length && d < drops; i++)
|
||||
{
|
||||
if (live[i] == 0 || (phase[i] & Box3DSoaPhase.Fluid) == 0) continue;
|
||||
var pose = new Transform3D(Basis.FromScale(Vector3.One * 2f * radius[i]), new Vector3(view.ParticleX[i], view.ParticleY[i], view.ParticleZ[i]));
|
||||
_dropPoses.Add(pose);
|
||||
_drops.Multimesh.SetInstanceTransform(d++, pose);
|
||||
}
|
||||
DropCount = drops;
|
||||
_drops.Multimesh.VisibleInstanceCount = drops;
|
||||
|
||||
var wet = view.WetLive;
|
||||
int patches = 0;
|
||||
for (int i = 0; i < wet.Length; i++) if (wet[i] != 0) patches++;
|
||||
Reserve(_patches.Multimesh, patches);
|
||||
_patchPoses.Clear();
|
||||
int p = 0;
|
||||
for (int i = 0; i < wet.Length && p < patches; i++)
|
||||
{
|
||||
if (wet[i] == 0) continue;
|
||||
var local = new Vector3(view.WetX[i], view.WetY[i], view.WetZ[i]);
|
||||
Vector3 at;
|
||||
int body = view.WetBody[i], particle = view.WetParticle[i];
|
||||
if (body >= 0)
|
||||
{
|
||||
var q = new Quaternion(view.RotationX[body], view.RotationY[body], view.RotationZ[body], view.RotationW[body]);
|
||||
at = new Vector3(view.PositionX[body], view.PositionY[body], view.PositionZ[body]) + q * local;
|
||||
}
|
||||
else if (particle >= 0) at = new Vector3(view.ParticleX[particle], view.ParticleY[particle], view.ParticleZ[particle]);
|
||||
else at = local;
|
||||
float r = view.WetRadius[i];
|
||||
var pose = new Transform3D(Basis.FromScale(new Vector3(r, PatchThickness, r)), at + Vector3.Up * PatchLift);
|
||||
_patchPoses.Add(pose);
|
||||
_patches.Multimesh.SetInstanceTransform(p++, pose);
|
||||
}
|
||||
PatchCount = patches;
|
||||
_patches.Multimesh.VisibleInstanceCount = patches;
|
||||
}
|
||||
|
||||
/// <summary>Grows the multimesh's capacity (doubling) so <paramref name="count"/> instances fit; it never shrinks, and only the visible ones are drawn.</summary>
|
||||
private static void Reserve(MultiMesh mm, int count)
|
||||
{
|
||||
if (count <= mm.InstanceCount) return;
|
||||
mm.InstanceCount = Math.Max(count, Math.Max(16, mm.InstanceCount * 2));
|
||||
}
|
||||
|
||||
private static MultiMeshInstance3D Instances(Mesh mesh, string name) => new()
|
||||
{
|
||||
Name = name,
|
||||
Multimesh = new MultiMesh { TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, Mesh = mesh },
|
||||
};
|
||||
}
|
||||
106
client/BodyRenderer.cs
Normal file
106
client/BodyRenderer.cs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Draws Ymir's world from its lanes and writes nothing back: one carrier Node3D per stable id, posed each frame from the lanes so
|
||||
/// physics interpolation has something to interpolate. Fella's parts (the stable ids <see cref="SeatedPuppet.PartOf"/> claims) are drawn
|
||||
/// by <see cref="Skin"/> from their carriers' poses; every other body holds one MeshInstance3D of its own primitive (a capsule, box or sphere
|
||||
/// of the lane's size), and the anchor, which has no shape, draws nothing.
|
||||
/// </summary>
|
||||
public partial class BodyRenderer : Node3D
|
||||
{
|
||||
private readonly Dictionary<ulong, Node3D> _carriers = new();
|
||||
private readonly HashSet<ulong> _seen = new();
|
||||
private readonly ShaderMaterial _figure = Look.Ps1(Look.SkinTexture, Colors.White);
|
||||
private readonly ShaderMaterial _scenery = Look.Ps1(Look.TileTexture, Colors.White, tile: 1f);
|
||||
|
||||
/// <summary>Bodies drawn, static and dynamic.</summary>
|
||||
public int BodyCount => _carriers.Count;
|
||||
|
||||
/// <summary>How many primitive MeshInstance3D this renderer has made (Fella's skin is counted by <see cref="FellaSkin.MeshBuilds"/>): a Reset with the same bodies makes none.</summary>
|
||||
public int MeshBuilds { get; private set; }
|
||||
|
||||
public ShaderMaterial SceneryMaterial => _scenery;
|
||||
|
||||
/// <summary>Fella's drawn surface: the one owner of how the parts of the seated puppet look.</summary>
|
||||
public FellaSkin Skin { get; } = new() { Name = "Skin" };
|
||||
|
||||
/// <summary>The world centre of Fella's drawn bounds as of the last frame, or null before the skin has posed once: where the camera orbits.</summary>
|
||||
public Vector3? PuppetCentre => Skin.Centre;
|
||||
|
||||
public override void _Ready() => AddChild(Skin);
|
||||
|
||||
/// <summary>Where body <paramref name="stableId"/> is drawn now, or null if it is not drawn.</summary>
|
||||
public Transform3D? PoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.Transform : null;
|
||||
|
||||
/// <summary>The same pose as rendered this frame, between the last two ticks (a static body does not move).</summary>
|
||||
public Transform3D? InterpolatedPoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.GetGlobalTransformInterpolated() : null;
|
||||
|
||||
/// <summary>Makes the carriers match the lanes (creates the missing, frees the gone, poses every one). <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
|
||||
public void Sync(in Box3DSoaView view, bool teleport = false)
|
||||
{
|
||||
var ids = view.StableId;
|
||||
if (ids.Length != _carriers.Count || !AllPresent(ids))
|
||||
{
|
||||
_seen.Clear();
|
||||
for (int i = 0; i < ids.Length; i++) _seen.Add(ids[i]);
|
||||
foreach (var id in new List<ulong>(_carriers.Keys))
|
||||
{
|
||||
if (_seen.Contains(id)) continue;
|
||||
_carriers[id].QueueFree();
|
||||
_carriers.Remove(id);
|
||||
}
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
if (_carriers.ContainsKey(ids[i])) continue;
|
||||
var node = new Node3D { Name = $"Body{ids[i]}" };
|
||||
var kind = (Box3DSoaKind)view.Kind[i];
|
||||
if (SeatedPuppet.PartOf(ids[i]) is null && PrimitiveOf(kind, view.Size0[i], view.Size1[i], view.Size2[i]) is { } primitive)
|
||||
{
|
||||
var material = kind != Box3DSoaKind.StaticBox ? _figure : _scenery;
|
||||
node.AddChild(new MeshInstance3D { Name = "Mesh", Mesh = primitive, MaterialOverride = material });
|
||||
MeshBuilds++;
|
||||
}
|
||||
AddChild(node);
|
||||
_carriers[ids[i]] = node;
|
||||
teleport = true;
|
||||
}
|
||||
}
|
||||
|
||||
var px = view.PositionX; var py = view.PositionY; var pz = view.PositionZ;
|
||||
var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW;
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
var node = _carriers[ids[i]];
|
||||
node.Transform = new Transform3D(new Basis(new Quaternion(rx[i], ry[i], rz[i], rw[i])), new Vector3(px[i], py[i], pz[i]));
|
||||
if (teleport) node.ResetPhysicsInterpolation();
|
||||
}
|
||||
}
|
||||
|
||||
private bool AllPresent(ReadOnlySpan<ulong> ids)
|
||||
{
|
||||
for (int i = 0; i < ids.Length; i++) if (!_carriers.ContainsKey(ids[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The extra cuts along a box edge of half length <paramref name="half"/>: a cell is at most a metre, so affine texturing on the big floor stays small per cell, as the console's own floors were tiled.</summary>
|
||||
private static int Cells(float half) => Math.Max(0, (int)(2f * half) - 1);
|
||||
|
||||
/// <summary>The body's own primitive, or null for a body with no shape. A capsule's lane is its radius and half-length along Y; a box's its half extents.</summary>
|
||||
private static Mesh? PrimitiveOf(Box3DSoaKind kind, float size0, float size1, float size2) => kind switch
|
||||
{
|
||||
Box3DSoaKind.Capsule => new CapsuleMesh { Radius = size0, Height = 2f * (size1 + size0), RadialSegments = 6, Rings = 1 },
|
||||
Box3DSoaKind.Box or Box3DSoaKind.StaticBox => new BoxMesh
|
||||
{
|
||||
Size = new Vector3(2f * size0, 2f * size1, 2f * size2),
|
||||
SubdivideWidth = Cells(size0), SubdivideHeight = Cells(size1), SubdivideDepth = Cells(size2),
|
||||
},
|
||||
Box3DSoaKind.Sphere => new SphereMesh { Radius = size0, Height = 2f * size0, RadialSegments = 6, Rings = 4 },
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
50
client/Chamber.cs
Normal file
50
client/Chamber.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using System;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>The Synaptic Induction Chamber: the stimulus volume drawn as a translucent box, its glow following the box's intensity, and the light it casts: the shader globals ps1_glow_*, which every surface reads per vertex.</summary>
|
||||
public partial class Chamber : Node3D
|
||||
{
|
||||
private readonly MeshInstance3D _volume = new() { Mesh = new BoxMesh { Size = Vector3.One } };
|
||||
private readonly ShaderMaterial _material = Look.Ps1(null, Look.Glow, 0.06f, emissive: true);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
_volume.MaterialOverride = _material;
|
||||
AddChild(_volume);
|
||||
}
|
||||
|
||||
/// <summary>The translucent box.</summary>
|
||||
public MeshInstance3D Volume => _volume;
|
||||
|
||||
/// <summary>The material of the volume.</summary>
|
||||
public ShaderMaterial Material => _material;
|
||||
|
||||
/// <summary>The glow last drawn, 0 (dark) to 1.</summary>
|
||||
public float Glow { get; private set; }
|
||||
|
||||
/// <summary>The office has no chamber: hidden, and the glow light it casts off.</summary>
|
||||
public new void Hide()
|
||||
{
|
||||
Visible = false;
|
||||
Glow = 0f;
|
||||
Look.Set("ps1_glow_energy", 0f);
|
||||
}
|
||||
|
||||
public void Sync(BodyPainBoxSession session)
|
||||
{
|
||||
Visible = true;
|
||||
double intensity = session.BoxIntensity; // 0 once the box is off
|
||||
var box = session.Chamber;
|
||||
Position = new Vector3(box.CenterX, box.CenterY, box.CenterZ);
|
||||
_volume.Scale = new Vector3(2f * box.HalfX, 2f * box.HalfY, 2f * box.HalfZ);
|
||||
float glow = (float)Math.Min(1.0, intensity / 1.5);
|
||||
Glow = glow;
|
||||
_material.SetShaderParameter("alpha", 0.06f + 0.3f * glow);
|
||||
Look.Set("ps1_glow_pos", new Vector3(box.CenterX, box.CenterY, box.CenterZ));
|
||||
Look.Set("ps1_glow_color", Look.Rgb(Look.Glow));
|
||||
Look.Set("ps1_glow_energy", Look.GlowLightEnergy * glow);
|
||||
}
|
||||
}
|
||||
231
client/FellaSkin.cs
Normal file
231
client/FellaSkin.cs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Fella's drawn surface: one skinned mesh, MakeHuman's base body fitted to Lodur's plan by tools/FellaMesh (client/fella/fella_skin.glb), drawn on
|
||||
/// the bones. It owns which vertices exist, where each is drawn every frame, and the drawn bounds; the plan owns the parts and their creation frames
|
||||
/// (<see cref="SeatedPuppet.Plan"/>), and the carriers of <see cref="BodyRenderer"/> own where each part is. Each vertex has one part, or two at a
|
||||
/// joint ring (a vertex on faces of two parts, one copy per part with the same two weights, so the copies coincide while the parts are joined).
|
||||
/// Every frame the vertices are rebuilt from the carriers' interpolated poses in one pass and written into one dynamic surface in place; the pass
|
||||
/// allocates nothing. The file is read as bytes (no import step decides vertex data) and is never edited: rerun the build.
|
||||
/// </summary>
|
||||
public partial class FellaSkin : Node3D
|
||||
{
|
||||
public const string AssetPath = "res://fella/fella_skin.glb";
|
||||
|
||||
private const int PositionBytes = 12; // three floats
|
||||
private const int NormalBytes = 8; // octahedral normal and tangent, four 16-bit values each vertex; the tangent is never written
|
||||
|
||||
private Vector3[] _rest = Array.Empty<Vector3>();
|
||||
private Vector3[] _restNormal = Array.Empty<Vector3>();
|
||||
private Vector3[] _drawn = Array.Empty<Vector3>();
|
||||
private int[] _partA = Array.Empty<int>(), _partB = Array.Empty<int>();
|
||||
private float[] _weightA = Array.Empty<float>(), _weightB = Array.Empty<float>();
|
||||
private int[][] _rings = Array.Empty<int[]>();
|
||||
private int[] _owned = Array.Empty<int>();
|
||||
private Transform3D[] _inverseCreation = Array.Empty<Transform3D>();
|
||||
private Transform3D[] _skin = Array.Empty<Transform3D>();
|
||||
private byte[] _data = Array.Empty<byte>();
|
||||
private ArrayMesh _mesh = null!;
|
||||
private Rid _rid;
|
||||
private Aabb? _bounds;
|
||||
|
||||
/// <summary>The surfaces made for the session's life: 1.</summary>
|
||||
public int MeshBuilds { get; private set; }
|
||||
|
||||
/// <summary>Vertices drawn, joint-ring copies counted once each.</summary>
|
||||
public int VertexCount => _rest.Length;
|
||||
|
||||
/// <summary>The world centre of the drawn bounds as of the last pose, or null before the first: where the camera orbits.</summary>
|
||||
public Vector3? Centre => _bounds is { } b ? b.Position + b.Size / 2 : null;
|
||||
|
||||
/// <summary>How many vertices part <paramref name="part"/> owns (the copies of joint-ring vertices count for the part each is emitted for).</summary>
|
||||
public int OwnedVertices(int part) => _owned[part];
|
||||
|
||||
/// <summary>The largest distance between the drawn copies of any joint-ring vertex, in metres, as of the last pose: 0 while the parts are joined.</summary>
|
||||
public float RingGap()
|
||||
{
|
||||
float worst = 0f;
|
||||
foreach (var ring in _rings)
|
||||
for (int i = 0; i < ring.Length; i++)
|
||||
for (int j = i + 1; j < ring.Length; j++)
|
||||
worst = Math.Max(worst, _drawn[ring[i]].DistanceTo(_drawn[ring[j]]));
|
||||
return worst;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How far the rest pose is from left-right symmetric, in metres: the largest distance from any rest vertex mirrored across x = 0 to the nearest rest vertex.
|
||||
/// The plan is symmetric about x = 0, so a lopsided build shows here whatever the pose.
|
||||
/// </summary>
|
||||
public float MirrorGap()
|
||||
{
|
||||
float worst = 0f;
|
||||
foreach (var v in _rest)
|
||||
{
|
||||
float nearest = float.MaxValue;
|
||||
var mirrored = new Vector3(-v.X, v.Y, v.Z);
|
||||
foreach (var u in _rest) nearest = Math.Min(nearest, mirrored.DistanceTo(u));
|
||||
worst = Math.Max(worst, nearest);
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
var plan = SeatedPuppet.Plan;
|
||||
var state = new GltfState();
|
||||
var bytes = Godot.FileAccess.GetFileAsBytes(AssetPath);
|
||||
if (bytes.Length == 0 || new GltfDocument().AppendFromBuffer(bytes, "", state) != Error.Ok) throw new InvalidOperationException($"{AssetPath} cannot be read as glTF");
|
||||
var skin = state.GetSkins()[0];
|
||||
var nodes = state.GetNodes();
|
||||
var joints = skin.Joints;
|
||||
if (joints.Length != plan.Parts.Count) throw new InvalidOperationException($"{AssetPath} has {joints.Length} joints for the plan's {plan.Parts.Count} parts");
|
||||
var partOfJoint = new int[joints.Length];
|
||||
var seen = new HashSet<int>();
|
||||
for (int j = 0; j < joints.Length; j++)
|
||||
{
|
||||
var name = nodes[joints[j]].ResourceName; // "Label" for a Center part, else "Label.Left" or "Label.Right"
|
||||
var dot = name.IndexOf('.');
|
||||
var side = dot < 0 ? Lodur.Side.Center : Enum.Parse<Lodur.Side>(name[(dot + 1)..]);
|
||||
partOfJoint[j] = plan.PartIndex(dot < 0 ? name : name[..dot], side); // throws for a name the plan has no part for
|
||||
if (!seen.Add(partOfJoint[j])) throw new InvalidOperationException($"{AssetPath} names part {name} twice");
|
||||
}
|
||||
|
||||
var surfaces = state.GetMeshes()[0].Mesh;
|
||||
if (surfaces.GetSurfaceCount() != plan.Parts.Count) throw new InvalidOperationException($"{AssetPath} has {surfaces.GetSurfaceCount()} primitives for the plan's {plan.Parts.Count} parts");
|
||||
var positions = new List<Vector3>(); var normals = new List<Vector3>(); var uvs = new List<Vector2>(); var indices = new List<int>();
|
||||
var partA = new List<int>(); var partB = new List<int>(); var weightA = new List<float>(); var weightB = new List<float>();
|
||||
_owned = new int[plan.Parts.Count];
|
||||
for (int s = 0; s < surfaces.GetSurfaceCount(); s++) // the build emits one primitive per part, in the plan's order
|
||||
{
|
||||
var arrays = surfaces.GetSurfaceArrays(s);
|
||||
var v = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
||||
var n = arrays[(int)Mesh.ArrayType.Normal].AsVector3Array();
|
||||
var uv = arrays[(int)Mesh.ArrayType.TexUV].AsVector2Array();
|
||||
var bones = arrays[(int)Mesh.ArrayType.Bones].AsInt32Array();
|
||||
var weights = arrays[(int)Mesh.ArrayType.Weights].AsFloat32Array();
|
||||
var first = positions.Count;
|
||||
bool owned = false;
|
||||
for (int i = 0; i < v.Length; i++)
|
||||
{
|
||||
int a = partOfJoint[bones[4 * i]], b = partOfJoint[bones[4 * i + 1]];
|
||||
float wa = weights[4 * i], wb = weights[4 * i + 1];
|
||||
if (wb == 0f) b = a;
|
||||
owned |= a == s || b == s;
|
||||
positions.Add(v[i]); normals.Add(n[i]); uvs.Add(uv[i]);
|
||||
partA.Add(a); partB.Add(b); weightA.Add(wa); weightB.Add(wb);
|
||||
}
|
||||
if (!owned) throw new InvalidOperationException($"{AssetPath}: primitive {s} has no vertex weighted to its part");
|
||||
foreach (var index in arrays[(int)Mesh.ArrayType.Index].AsInt32Array()) indices.Add(first + index);
|
||||
_owned[s] = v.Length;
|
||||
}
|
||||
_rest = positions.ToArray(); _restNormal = normals.ToArray(); _drawn = positions.ToArray();
|
||||
_partA = partA.ToArray(); _partB = partB.ToArray(); _weightA = weightA.ToArray(); _weightB = weightB.ToArray();
|
||||
|
||||
var byPosition = new Dictionary<Vector3, List<int>>(); // the copies of one ring vertex have the same rest position
|
||||
for (int i = 0; i < _rest.Length; i++)
|
||||
{
|
||||
if (!byPosition.TryGetValue(_rest[i], out var list)) byPosition[_rest[i]] = list = new List<int>();
|
||||
list.Add(i);
|
||||
}
|
||||
var rings = new List<int[]>();
|
||||
foreach (var list in byPosition.Values) if (list.Count > 1) rings.Add(list.ToArray());
|
||||
_rings = rings.ToArray();
|
||||
|
||||
_inverseCreation = new Transform3D[plan.Parts.Count];
|
||||
_skin = new Transform3D[plan.Parts.Count];
|
||||
for (int p = 0; p < plan.Parts.Count; p++)
|
||||
{
|
||||
var def = plan.Parts[p];
|
||||
var frame = new Transform3D(new Basis(new Quaternion(def.Rotation.X, def.Rotation.Y, def.Rotation.Z, def.Rotation.W)), new Vector3(def.Position.X, def.Position.Y, def.Position.Z));
|
||||
_inverseCreation[p] = frame.AffineInverse();
|
||||
_skin[p] = Transform3D.Identity;
|
||||
}
|
||||
|
||||
var surface = new Godot.Collections.Array();
|
||||
surface.Resize((int)Mesh.ArrayType.Max);
|
||||
surface[(int)Mesh.ArrayType.Vertex] = _rest;
|
||||
surface[(int)Mesh.ArrayType.Normal] = _restNormal;
|
||||
surface[(int)Mesh.ArrayType.TexUV] = uvs.ToArray();
|
||||
surface[(int)Mesh.ArrayType.Index] = indices.ToArray();
|
||||
_mesh = new ArrayMesh();
|
||||
_mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surface, flags: Mesh.ArrayFormat.FlagUseDynamicUpdate);
|
||||
_rid = _mesh.GetRid();
|
||||
_data = RenderingServer.MeshGetSurface(_rid, 0)["vertex_data"].AsByteArray(); // positions, then normals and tangents: the layout this class rewrites in place
|
||||
if (_data.Length != _rest.Length * (PositionBytes + NormalBytes)) throw new InvalidOperationException($"the dynamic surface holds {_data.Length} vertex bytes, not {_rest.Length * (PositionBytes + NormalBytes)}");
|
||||
AddChild(new MeshInstance3D { Name = "Mesh", Mesh = _mesh, MaterialOverride = Look.Ps1(Look.SkinTexture, Colors.White) });
|
||||
MeshBuilds = 1;
|
||||
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off; // the vertices are already placed from interpolated poses
|
||||
}
|
||||
|
||||
public override void _Process(double delta) => Deform();
|
||||
|
||||
/// <summary>Redraws every vertex from the carriers' interpolated poses: p = sum of w (pose * creation frame inverse) p_rest, normals by the same rotation.</summary>
|
||||
public void Deform()
|
||||
{
|
||||
var bodies = GetParent<BodyRenderer>();
|
||||
for (int p = 0; p < _skin.Length; p++)
|
||||
if (bodies.InterpolatedPoseOf(SeatedPuppet.FirstStableId + (ulong)p) is { } pose) _skin[p] = pose * _inverseCreation[p];
|
||||
var low = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
|
||||
var high = new Vector3(float.MinValue, float.MinValue, float.MinValue);
|
||||
int normalBase = _rest.Length * PositionBytes;
|
||||
for (int i = 0; i < _rest.Length; i++)
|
||||
{
|
||||
var ma = _skin[_partA[i]];
|
||||
var p = ma * _rest[i];
|
||||
var n = ma.Basis * _restNormal[i];
|
||||
if (_weightB[i] > 0f)
|
||||
{
|
||||
var mb = _skin[_partB[i]];
|
||||
p = p * _weightA[i] + mb * _rest[i] * _weightB[i];
|
||||
n = n * _weightA[i] + mb.Basis * _restNormal[i] * _weightB[i];
|
||||
}
|
||||
_drawn[i] = p;
|
||||
low = new Vector3(Math.Min(low.X, p.X), Math.Min(low.Y, p.Y), Math.Min(low.Z, p.Z));
|
||||
high = new Vector3(Math.Max(high.X, p.X), Math.Max(high.Y, p.Y), Math.Max(high.Z, p.Z));
|
||||
var at = _data.AsSpan(i * PositionBytes);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(at, p.X);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(at[4..], p.Y);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(at[8..], p.Z);
|
||||
Octahedral(n, _data.AsSpan(normalBase + i * NormalBytes));
|
||||
}
|
||||
RenderingServer.MeshSurfaceUpdateVertexRegion(_rid, 0, 0, _data);
|
||||
_bounds = new Aabb(low, high - low);
|
||||
_mesh.CustomAabb = _bounds.Value;
|
||||
}
|
||||
|
||||
/// <summary>The median time of <paramref name="frames"/> deforms, in microseconds: the cost line the smoke prints.</summary>
|
||||
public double MedianDeformMicroseconds(int frames)
|
||||
{
|
||||
var ticks = new long[frames];
|
||||
for (int f = 0; f < frames; f++)
|
||||
{
|
||||
long start = Stopwatch.GetTimestamp();
|
||||
Deform();
|
||||
ticks[f] = Stopwatch.GetTimestamp() - start;
|
||||
}
|
||||
Array.Sort(ticks);
|
||||
return ticks[frames / 2] * 1e6 / Stopwatch.Frequency;
|
||||
}
|
||||
|
||||
/// <summary>Godot's surface normal encoding: the octahedral map of the unit normal, two 16-bit values.</summary>
|
||||
private static void Octahedral(Vector3 normal, Span<byte> into)
|
||||
{
|
||||
normal /= Math.Abs(normal.X) + Math.Abs(normal.Y) + Math.Abs(normal.Z);
|
||||
float x = normal.X, y = normal.Y;
|
||||
if (normal.Z < 0f)
|
||||
{
|
||||
x = (1f - Math.Abs(normal.Y)) * (normal.X >= 0f ? 1f : -1f);
|
||||
y = (1f - Math.Abs(normal.X)) * (normal.Y >= 0f ? 1f : -1f);
|
||||
}
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(into, (ushort)Math.Clamp((x * 0.5f + 0.5f) * 65535f, 0f, 65535f));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(into[2..], (ushort)Math.Clamp((y * 0.5f + 0.5f) * 65535f, 0f, 65535f));
|
||||
}
|
||||
}
|
||||
165
client/Hud.cs
Normal file
165
client/Hud.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>Readout and controls. Every number comes from the session; every control calls a Main method that calls it.</summary>
|
||||
public partial class Hud : CanvasLayer
|
||||
{
|
||||
private const int LogLines = 6;
|
||||
private static readonly Color Ink = new(0.92f, 0.92f, 0.9f);
|
||||
|
||||
private readonly Main _main;
|
||||
private readonly Label _readout = new();
|
||||
private readonly StringBuilder _text = new();
|
||||
|
||||
public Hud(Main main) => _main = main;
|
||||
|
||||
private readonly VBoxContainer _chamberControls = new();
|
||||
private readonly VBoxContainer _officeControls = new();
|
||||
private readonly Dictionary<string, Button> _silence = new();
|
||||
|
||||
public OptionButton ScenarioPicker { get; } = new();
|
||||
/// <summary>His will, 0 to 1 (lodur:ruling:bds-will-visible).</summary>
|
||||
public ProgressBar WillBar { get; } = Bar(Color.Color8(0x4c, 0x9a, 0xd8));
|
||||
/// <summary>His arousal, 0 to 1 (lodur:ruling:stress-bar-shows-arousal-calm-silences).</summary>
|
||||
public ProgressBar StressBar { get; } = Bar(Color.Color8(0xd8, 0x8a, 0x2c));
|
||||
|
||||
/// <summary>A 0 to 1 bar with a visible track (dark, outlined), so an empty bar reads as empty, and a fill in <paramref name="fill"/>.</summary>
|
||||
private static ProgressBar Bar(Color fill)
|
||||
{
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0, ShowPercentage = false, CustomMinimumSize = new Vector2(220, 18) };
|
||||
bar.AddThemeStyleboxOverride("background", new StyleBoxFlat { BgColor = Color.Color8(0x1c, 0x1c, 0x20), BorderColor = Ink, BorderWidthLeft = 1, BorderWidthTop = 1, BorderWidthRight = 1, BorderWidthBottom = 1 });
|
||||
bar.AddThemeStyleboxOverride("fill", new StyleBoxFlat { BgColor = fill });
|
||||
return bar;
|
||||
}
|
||||
/// <summary>One button per stressor of the office's cause, by id.</summary>
|
||||
public IReadOnlyDictionary<string, Button> SilenceButtons => _silence;
|
||||
public SpinBox SeedBox { get; } = new() { MinValue = 0, MaxValue = 999999999, Step = 1, Value = 1 };
|
||||
public Button ResetButton { get; } = new() { Text = "Reset" };
|
||||
public HSlider IntensitySlider { get; } = new() { MinValue = 0, MaxValue = PainBox.MaxLevel, Step = 0.05, CustomMinimumSize = new Vector2(220, 24) };
|
||||
public Button BoxOffButton { get; } = new() { Text = "Box off" };
|
||||
public CheckButton SlowToggle { get; } = new() { Text = "Slow motion", Modulate = Ink };
|
||||
|
||||
/// <summary>The readout as drawn.</summary>
|
||||
public string Readout => _readout.Text;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
var margin = new MarginContainer();
|
||||
margin.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.FullRect);
|
||||
foreach (var side in new[] { "left", "top", "right", "bottom" }) margin.AddThemeConstantOverride($"margin_{side}", 16);
|
||||
margin.MouseFilter = Control.MouseFilterEnum.Ignore;
|
||||
AddChild(margin);
|
||||
|
||||
var row = new HBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
|
||||
margin.AddChild(row);
|
||||
|
||||
_readout.AddThemeColorOverride("font_color", Ink);
|
||||
_readout.AddThemeFontSizeOverride("font_size", 16);
|
||||
_readout.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
|
||||
_readout.MouseFilter = Control.MouseFilterEnum.Ignore;
|
||||
row.AddChild(_readout);
|
||||
|
||||
var controls = new VBoxContainer { SizeFlagsVertical = Control.SizeFlags.ShrinkBegin };
|
||||
row.AddChild(controls);
|
||||
|
||||
var seedRow = new HBoxContainer();
|
||||
seedRow.AddChild(new Label { Text = "Seed", Modulate = Ink });
|
||||
seedRow.AddChild(SeedBox);
|
||||
controls.AddChild(seedRow);
|
||||
ResetButton.Pressed += () => _main.Reset((ulong)SeedBox.Value);
|
||||
controls.AddChild(ResetButton);
|
||||
|
||||
foreach (var scenario in System.Enum.GetValues<Scenario>()) ScenarioPicker.AddItem(scenario.ToString(), (int)scenario);
|
||||
ScenarioPicker.Selected = (int)_main.Scenario;
|
||||
ScenarioPicker.ItemSelected += i => _main.SetScenario((Scenario)ScenarioPicker.GetItemId((int)i));
|
||||
controls.AddChild(ScenarioPicker);
|
||||
|
||||
controls.AddChild(_officeControls);
|
||||
_officeControls.AddChild(new Label { Text = "Will", Modulate = Ink });
|
||||
_officeControls.AddChild(WillBar);
|
||||
_officeControls.AddChild(new Label { Text = "Stress", Modulate = Ink });
|
||||
_officeControls.AddChild(StressBar);
|
||||
_officeControls.AddChild(new Label { Text = "Silence", Modulate = Ink });
|
||||
foreach (var stressor in Main.OfficeParameters.Cause.Stressors)
|
||||
{
|
||||
var id = stressor.Id;
|
||||
var button = new Button { Text = id };
|
||||
button.Pressed += () => _main.Silence(id);
|
||||
_silence[id] = button;
|
||||
_officeControls.AddChild(button);
|
||||
}
|
||||
|
||||
controls.AddChild(_chamberControls);
|
||||
_chamberControls.AddChild(new Label { Text = "Intensity", Modulate = Ink });
|
||||
IntensitySlider.Value = _main.Intensity;
|
||||
IntensitySlider.ValueChanged += v => _main.SetIntensity(v);
|
||||
_chamberControls.AddChild(IntensitySlider);
|
||||
|
||||
BoxOffButton.Pressed += () => _main.SwitchOff();
|
||||
_chamberControls.AddChild(BoxOffButton);
|
||||
SlowToggle.Toggled += on => _main.SetSlowMotion(on);
|
||||
controls.AddChild(SlowToggle);
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_main.Failure is { } failure)
|
||||
{
|
||||
_readout.Text = $"Cannot run: {failure}\nReset tries again.";
|
||||
return;
|
||||
}
|
||||
|
||||
_chamberControls.Visible = _main.Scenario == Scenario.Chamber;
|
||||
_officeControls.Visible = _main.Scenario == Scenario.Office;
|
||||
_text.Clear();
|
||||
if (_main.Scenario == Scenario.Office)
|
||||
{
|
||||
OfficeReadout(_main.Office);
|
||||
return;
|
||||
}
|
||||
|
||||
var s = _main.PainBox;
|
||||
var r = s.Result();
|
||||
_text.Append($"seed {_main.Seed} t {s.TickIndex * BodyPainBox.TickSeconds:F2} s (tick {s.TickIndex})\n");
|
||||
_text.Append($"box intensity {s.BoxIntensity:F2}{(s.BoxOn ? "" : " off")} (set {_main.Intensity:F2})\n");
|
||||
_text.Append($"pain {s.Pain:F2} strain {s.Strain:F2} resolve {s.Resolve:F2}\n");
|
||||
_text.Append($"goal {s.Goal} flinches {r.Flinches}\n");
|
||||
_text.Append($"will broke at {Ms(r.TimeToBreakMs)} withdrew {(s.Goal == Goal.Withdraw ? "yes" : "no")}\n");
|
||||
_text.Append($"hand {(s.Hand.InBox ? "in box" : "out of box")} hand out at {Ms(s.HandOutMs)}\n");
|
||||
_text.Append(s.Finished ? $"outcome {r.Outcome}\n" : "running\n");
|
||||
var events = _main.Events;
|
||||
for (int i = System.Math.Max(0, events.Count - LogLines); i < events.Count; i++)
|
||||
{
|
||||
_text.Append($"{events[i].Tick * BodyPainBox.TickSeconds,6:F2} s {events[i].Events}\n");
|
||||
}
|
||||
_readout.Text = _text.ToString();
|
||||
}
|
||||
|
||||
private void OfficeReadout(OfficeBodySession o)
|
||||
{
|
||||
WillBar.Value = o.Will;
|
||||
StressBar.Value = o.Arousal;
|
||||
_text.Append($"office seed {_main.Seed} t {o.TickIndex * OfficeBody.TickSeconds:F2} s (tick {o.TickIndex})\n");
|
||||
_text.Append($"will {o.Will:F2} stress {o.Arousal:F2} goal {o.Goal}\n");
|
||||
_text.Append($"blood loss {o.BloodLoss * 100:F0} % of lethal blood spilled {o.BloodEmitted * 1000:F2} L\n");
|
||||
_text.Append($"consciousness {o.Consciousness:F2} air hunger {o.AirHunger:F2}\n");
|
||||
_text.Append($"airway {o.AirwayLiquid * 1e6:F0} mL ({o.Occlusion * 100:F0} % full)\n");
|
||||
_text.Append($"airway bleed {o.AirwayBleed * 1e6:F2} mL/s drawn {o.AirwayDrawnLive * 1e6:F3} mL this step\n");
|
||||
if (o.Dead) _text.Append($"DEAD: {o.DeathCause}\n");
|
||||
else _text.Append("running\n");
|
||||
_text.Append(_main.Cuts.Count > 0 ? $"last cut: {_main.Cuts[^1].Part} at tick {_main.Cuts[^1].Tick}\n" : "no cuts yet\n");
|
||||
var events = _main.Events;
|
||||
for (int i = System.Math.Max(0, events.Count - LogLines); i < events.Count; i++)
|
||||
{
|
||||
_text.Append($"{events[i].Tick * OfficeBody.TickSeconds,6:F2} s {events[i].Events}\n");
|
||||
}
|
||||
_readout.Text = _text.ToString();
|
||||
}
|
||||
|
||||
private static string Ms(long? ms) => ms is { } v ? $"{v / 1000.0:F2} s" : "-";
|
||||
}
|
||||
130
client/Look.cs
Normal file
130
client/Look.cs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
using System;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// The scene's look: PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy). Every number the look has is here. ps1.gdshader draws every
|
||||
/// surface (vertices snapped to the line grid, affine texture, unfiltered texels, Gouraud light and fog, all per vertex) and ps1_post.gdshader
|
||||
/// the framebuffer (15-bit colour, ordered dither, one colour per block of the grid). Colours are raw sRGB values: the console's arithmetic
|
||||
/// had no colour management and neither does the shader.
|
||||
/// </summary>
|
||||
public static class Look
|
||||
{
|
||||
/// <summary>The framebuffer's height in lines (lodur:question:bds-render-lines): the window is divided into blocks of round(H / Lines) pixels.</summary>
|
||||
public const int Lines = 240;
|
||||
|
||||
public static readonly Color Background = new(0.10f, 0.10f, 0.11f);
|
||||
/// <summary>The floor's tile: noise on this colour, grouted with <see cref="Grout"/>.</summary>
|
||||
public static readonly Color Scenery = Color.Color8(0x1b, 0x26, 0x32);
|
||||
public static readonly Color Grout = Color.Color8(0x0d, 0x15, 0x1d);
|
||||
public static readonly Color Skin = Color.Color8(196, 146, 120);
|
||||
public static readonly Color Glow = new(0.85f, 0.95f, 1f);
|
||||
/// <summary>Blood: a saturated red, a placeholder tuned by eye later.</summary>
|
||||
public static readonly Color Blood = new(0.78f, 0.04f, 0.05f);
|
||||
|
||||
/// <summary>The key light's direction (where it comes from, in the world), its colour and the ambient: ps1.js's.</summary>
|
||||
public static readonly Vector3 KeyDirection = new Vector3(-0.4f, 0.8f, 0.45f).Normalized();
|
||||
public static readonly Color KeyColor = new(0.95f, 0.90f, 0.82f);
|
||||
public static readonly Color AmbientColor = new(0.30f, 0.34f, 0.42f);
|
||||
|
||||
/// <summary>Fog toward <see cref="Background"/>, by view depth in metres.</summary>
|
||||
public const float FogNear = 4f, FogFar = 14f;
|
||||
|
||||
/// <summary>The chamber's light at full glow (it reaches 0.9 m): added per vertex to the key and the ambient.</summary>
|
||||
public const float GlowLightEnergy = 4f;
|
||||
|
||||
/// <summary>Pixels per block of the line grid for a window <paramref name="height"/> pixels high: never less than 1.</summary>
|
||||
public static int BlockSize(int height) => Math.Max(1, (int)Math.Round(height / (double)Lines, MidpointRounding.AwayFromZero));
|
||||
|
||||
private static ImageTexture? _skinTexture, _tileTexture;
|
||||
|
||||
/// <summary>The skin: 8 x 8 texels of <see cref="Skin"/> with a little noise.</summary>
|
||||
public static ImageTexture SkinTexture => _skinTexture ??= Noise(8, 8, Skin, 0.035f, 7);
|
||||
|
||||
/// <summary>The floor's tile: 32 x 32 texels of <see cref="Scenery"/> with noise and a texel of grout on two edges.</summary>
|
||||
public static ImageTexture TileTexture => _tileTexture ??= Noise(32, 32, Scenery, 0.02f, 11, (x, y) => x == 0 || y == 0, Grout);
|
||||
|
||||
/// <summary>The scene's environment: a colour background, linear, no sky and no glow. Every surface is unshaded, so it lights nothing.</summary>
|
||||
public static WorldEnvironment World() => new()
|
||||
{
|
||||
Environment = new Godot.Environment
|
||||
{
|
||||
BackgroundMode = Godot.Environment.BGMode.Color,
|
||||
BackgroundColor = Background,
|
||||
TonemapMode = Godot.Environment.ToneMapper.Linear,
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>Sets the look's constant shader globals, once. Main sets ps1_res, Chamber the glow.</summary>
|
||||
public static void Apply()
|
||||
{
|
||||
Set("ps1_key_dir", KeyDirection);
|
||||
Set("ps1_key_color", Rgb(KeyColor));
|
||||
Set("ps1_ambient", Rgb(AmbientColor));
|
||||
Set("ps1_fog_color", Rgb(Background));
|
||||
Set("ps1_fog_near", FogNear);
|
||||
Set("ps1_fog_far", FogFar);
|
||||
}
|
||||
|
||||
public static void Set(string name, Variant value) => RenderingServer.GlobalShaderParameterSet(name, value);
|
||||
|
||||
public static Vector3 Rgb(Color c) => new(c.R, c.G, c.B);
|
||||
|
||||
/// <summary>
|
||||
/// The PS1 material: <paramref name="texture"/> (white if null) times <paramref name="tint"/>, lit and fogged per vertex. Below alpha 1 it is
|
||||
/// the translucent variant of the same shader. <paramref name="tile"/> is the world's metres per texture repeat (0: the mesh's UV).
|
||||
/// </summary>
|
||||
public static ShaderMaterial Ps1(Texture2D? texture, Color tint, float alpha = 1f, bool emissive = false, float tile = 0f)
|
||||
{
|
||||
var source = GD.Load<Shader>("res://ps1.gdshader");
|
||||
var shader = alpha < 1f ? new Shader { Code = "#define TRANSLUCENT\n" + source.Code } : source;
|
||||
var material = new ShaderMaterial { Shader = shader };
|
||||
material.SetShaderParameter("albedo_tex", texture);
|
||||
material.SetShaderParameter("tint", Rgb(tint));
|
||||
material.SetShaderParameter("alpha", alpha);
|
||||
material.SetShaderParameter("emissive", emissive);
|
||||
material.SetShaderParameter("tile", tile);
|
||||
return material;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The office's mouse cursor: a knife, tip at the top left corner (the hotspot), blade running down to the right into a handle, 32 x 32,
|
||||
/// drawn pixel by pixel here so the client carries no art file. The blade is steel with a dark edge; the handle is brown.
|
||||
/// </summary>
|
||||
public static Image KnifeCursor()
|
||||
{
|
||||
const int size = 32;
|
||||
var image = Image.CreateEmpty(size, size, false, Image.Format.Rgba8);
|
||||
image.Fill(new Color(0, 0, 0, 0));
|
||||
var steel = Color.Color8(0xc8, 0xd0, 0xd8);
|
||||
var edge = Color.Color8(0x20, 0x24, 0x2a);
|
||||
var grip = Color.Color8(0x5a, 0x34, 0x1c);
|
||||
for (int y = 0; y < size; y++)
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
// Distance from the pixel to the knife's axis, the diagonal x = y, and the position along it.
|
||||
float along = (x + y) / 2f, across = Math.Abs(x - y) / 1.4142135f;
|
||||
if (along > 29f) continue;
|
||||
bool handle = along > 17f;
|
||||
float half = handle ? 3f : 4.2f * (1f - 0.2f * along / 17f) * Math.Min(1f, along / 3f + 0.15f);
|
||||
if (across > half) continue;
|
||||
image.SetPixel(x, y, handle ? grip : across > half - 1f || along < 1f ? edge : steel);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private static ImageTexture Noise(int w, int h, Color baseColour, float spread, ulong seed, Func<int, int, bool>? grouted = null, Color? groutColour = null)
|
||||
{
|
||||
var rng = new RandomNumberGenerator { Seed = seed };
|
||||
var image = Image.CreateEmpty(w, h, false, Image.Format.Rgb8);
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
var c = grouted?.Invoke(x, y) == true ? groutColour ?? baseColour : baseColour;
|
||||
float k = rng.RandfRange(-spread, spread);
|
||||
image.SetPixel(x, y, new Color(Math.Clamp(c.R + k, 0, 1), Math.Clamp(c.G + k, 0, 1), Math.Clamp(c.B + k, 0, 1)));
|
||||
}
|
||||
return ImageTexture.CreateFromImage(image);
|
||||
}
|
||||
}
|
||||
235
client/Main.cs
Normal file
235
client/Main.cs
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BadDay.Core;
|
||||
using Lodur;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>The runs the client hosts: the Synaptic Induction Chamber's pain box, or the office with its knife.</summary>
|
||||
public enum Scenario { Chamber, Office }
|
||||
|
||||
/// <summary>
|
||||
/// The client's root. Godot's physics frame decides when a tick happens (physics interpolation on, Godot's own
|
||||
/// physics engine Dummy); the live <see cref="IBodyRun"/> (the pain box or the office, one at a time) decides everything a tick does.
|
||||
/// This node only steps whichever is live, draws it and forwards the player's commands to it. A session that cannot start (the native library is missing, say)
|
||||
/// is reported once in <see cref="Failure"/> and the log, and nothing ticks until a Reset succeeds.
|
||||
/// </summary>
|
||||
public partial class Main : Node3D
|
||||
{
|
||||
/// <summary>Slow motion runs this fraction of the session steps per real second.</summary>
|
||||
private const double SlowFactor = 0.25;
|
||||
|
||||
private readonly List<BodyEvent> _events = new();
|
||||
private BodyRenderer _bodies = null!;
|
||||
private Chamber _chamber = null!;
|
||||
private OrbitCamera _camera = null!;
|
||||
private Hud _hud = null!;
|
||||
private BloodRenderer _blood = null!;
|
||||
private IBodyRun? _run;
|
||||
private double _intensity = new PainBoxParameters().BoxIntensity;
|
||||
|
||||
public BloodRenderer Blood => _blood;
|
||||
|
||||
public Scenario Scenario { get; private set; } = Scenario.Chamber;
|
||||
|
||||
/// <summary>The live run, whichever scenario.</summary>
|
||||
public IBodyRun Run => _run ?? throw new InvalidOperationException($"Main has no session ({Failure ?? "before _Ready"}).");
|
||||
|
||||
/// <summary>The live run as the pain box; throws in the office.</summary>
|
||||
public BodyPainBoxSession PainBox => Run as BodyPainBoxSession ?? throw new InvalidOperationException("The live run is not the pain box.");
|
||||
|
||||
/// <summary>The live run as the office; throws in the chamber.</summary>
|
||||
public OfficeBodySession Office => Run as OfficeBodySession ?? throw new InvalidOperationException("The live run is not the office.");
|
||||
public BodyRenderer Bodies => _bodies;
|
||||
public Chamber Chamber => _chamber;
|
||||
public Hud Hud => _hud;
|
||||
public ulong Seed { get; private set; } = 1;
|
||||
|
||||
/// <summary>Why the session could not start, or null. Cleared by the next successful Reset.</summary>
|
||||
public string? Failure { get; private set; }
|
||||
|
||||
/// <summary>The intensity the box is set to; the next Reset starts with it.</summary>
|
||||
public double Intensity => _intensity;
|
||||
|
||||
/// <summary>The parameters of an office run: every default except the 1/120 s tick the body needs.</summary>
|
||||
public static StressParameters OfficeParameters { get; } = new() { TickSeconds = OfficeBody.TickSeconds };
|
||||
|
||||
/// <summary>A cut the knife opened: the part's label and the tick.</summary>
|
||||
public readonly record struct Cut(string Part, long Tick);
|
||||
|
||||
private readonly List<Cut> _cuts = new();
|
||||
|
||||
/// <summary>Every cut opened since the last Reset, oldest first: a log for the HUD.</summary>
|
||||
public IReadOnlyList<Cut> Cuts => _cuts;
|
||||
|
||||
public bool SlowMotion { get; private set; }
|
||||
|
||||
/// <summary>Every event the session has reported since the last Reset, oldest first.</summary>
|
||||
public IReadOnlyList<BodyEvent> Events => _events;
|
||||
|
||||
/// <summary>The parameters of a run at the given box intensity: every default except the 1/120 s tick the body needs.</summary>
|
||||
public static PainBoxParameters ParametersFor(double intensity) =>
|
||||
new() { TickSeconds = BodyPainBox.TickSeconds, BoxIntensity = intensity };
|
||||
|
||||
private static int StepsPerSecond(double speed) => (int)Math.Round(speed / BodyPainBox.TickSeconds);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
Look.Apply();
|
||||
_bodies = new BodyRenderer { Name = "Bodies" };
|
||||
AddChild(_bodies);
|
||||
_blood = new BloodRenderer { Name = "Blood" };
|
||||
AddChild(_blood);
|
||||
_chamber = new Chamber { Name = "Chamber" };
|
||||
AddChild(_chamber);
|
||||
_camera = new OrbitCamera { Name = "Camera", Pivot = () => _bodies.PuppetCentre };
|
||||
AddChild(_camera);
|
||||
AddChild(Look.World());
|
||||
_hud = new Hud(this) { Name = "Hud" };
|
||||
AddChild(_hud);
|
||||
AddChild(Post());
|
||||
SetLines();
|
||||
GetWindow().SizeChanged += SetLines;
|
||||
Reset(Seed);
|
||||
}
|
||||
|
||||
/// <summary>The line grid: the window's size over its block size, the one value ps1_res ever holds.</summary>
|
||||
public Vector2 Ps1Res { get; private set; }
|
||||
|
||||
private void SetLines()
|
||||
{
|
||||
var size = GetWindow().Size;
|
||||
float block = Look.BlockSize(size.Y);
|
||||
Ps1Res = new Vector2(size.X / block, size.Y / block);
|
||||
Look.Set("ps1_res", Ps1Res);
|
||||
}
|
||||
|
||||
/// <summary>The framebuffer pass: a full-screen rect under the HUD (its layer is above this one) that quantises what the 3D drew.</summary>
|
||||
private static CanvasLayer Post()
|
||||
{
|
||||
var layer = new CanvasLayer { Name = "Post", Layer = -1 };
|
||||
layer.AddChild(new ColorRect
|
||||
{
|
||||
Name = "Quantise",
|
||||
Material = new ShaderMaterial { Shader = GD.Load<Shader>("res://ps1_post.gdshader") },
|
||||
MouseFilter = Control.MouseFilterEnum.Ignore,
|
||||
AnchorRight = 1,
|
||||
AnchorBottom = 1,
|
||||
});
|
||||
return layer;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (IsInstanceValid(GetWindow())) GetWindow().SizeChanged -= SetLines;
|
||||
Engine.PhysicsTicksPerSecond = StepsPerSecond(1.0);
|
||||
Input.SetCustomMouseCursor(null);
|
||||
_run?.Dispose();
|
||||
_run = null;
|
||||
}
|
||||
|
||||
public override void _PhysicsProcess(double delta)
|
||||
{
|
||||
if (_run is null) return;
|
||||
_run.Step(); // one step of 1/120 s per physics frame; never Godot's delta, whatever the frame rate
|
||||
Present(teleport: false);
|
||||
}
|
||||
|
||||
/// <summary>Switches to <paramref name="scenario"/> and starts it at the current seed.</summary>
|
||||
public void SetScenario(Scenario scenario)
|
||||
{
|
||||
Scenario = scenario;
|
||||
if (scenario == Scenario.Office) Input.SetCustomMouseCursor(ImageTexture.CreateFromImage(Look.KnifeCursor()), Input.CursorShape.Arrow, Vector2.Zero);
|
||||
else Input.SetCustomMouseCursor(null);
|
||||
Reset(Seed);
|
||||
}
|
||||
|
||||
public override void _UnhandledInput(InputEvent e)
|
||||
{
|
||||
// The knife takes a left press the camera's binding table does not (Alt+left is its emulated middle button, whatever its mode).
|
||||
if (Scenario == Scenario.Office && e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } press && !OrbitCamera.Binds(press))
|
||||
{
|
||||
CutAt(press.Position);
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The knife at a screen point: the camera's ray through it (20 m), the office's pick, and a cut where it hit. True when a cut opened;
|
||||
/// then the part and the tick are appended to <see cref="Cuts"/>. A miss, a refusal and any other scenario do nothing.
|
||||
/// </summary>
|
||||
public bool CutAt(Vector2 screenPoint)
|
||||
{
|
||||
if (Scenario != Scenario.Office || _run is not OfficeBodySession office) return false;
|
||||
var origin = _camera.ProjectRayOrigin(screenPoint);
|
||||
var translation = _camera.ProjectRayNormal(screenPoint) * 20f;
|
||||
if (office.Pick(new BodyPoint(origin.X, origin.Y, origin.Z), new BodyPoint(translation.X, translation.Y, translation.Z)) is not { } hit) return false;
|
||||
if (!office.Wound(hit, WoundTool.Knife)) return false;
|
||||
var part = SeatedPuppet.Plan.Parts[hit.Part];
|
||||
_cuts.Add(new Cut(part.Side switch { Lodur.Side.Left => part.Label + " L", Lodur.Side.Right => part.Label + " R", _ => part.Label }, office.TickIndex));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Starts a new run of the current scenario from <paramref name="seed"/> (the box at the current intensity), replacing the live run.</summary>
|
||||
public void Reset(ulong seed)
|
||||
{
|
||||
_run?.Dispose();
|
||||
_run = null;
|
||||
Failure = null;
|
||||
_events.Clear();
|
||||
_cuts.Clear();
|
||||
Seed = seed;
|
||||
try
|
||||
{
|
||||
_run = Scenario == Scenario.Office
|
||||
? new OfficeBodySession(OfficeParameters, seed)
|
||||
: new BodyPainBoxSession(ParametersFor(_intensity), seed);
|
||||
}
|
||||
catch (Exception e) // the session's start can fail in native code (library missing, ABI mismatch): report once, tick nothing
|
||||
{
|
||||
Failure = $"{e.GetType().Name}: {e.Message}";
|
||||
GD.PushError($"BadDay: cannot start a run: {e}");
|
||||
return;
|
||||
}
|
||||
Present(teleport: true);
|
||||
}
|
||||
|
||||
/// <summary>Sets the box intensity now and for the next Reset.</summary>
|
||||
public void SetIntensity(double level)
|
||||
{
|
||||
(_run as BodyPainBoxSession)?.SetIntensity(level);
|
||||
_intensity = level;
|
||||
}
|
||||
|
||||
/// <summary>The player silences a stressor of the office.</summary>
|
||||
public void Silence(string stressorId) => Office.Silence(stressorId);
|
||||
|
||||
public void SwitchOff() => (_run as BodyPainBoxSession)?.SwitchOff();
|
||||
|
||||
/// <summary>
|
||||
/// Slow motion is fewer session steps per real second: Godot runs its physics frames at a quarter of the rate and each
|
||||
/// frame still steps the session 1/120 s, so the run is the same run, slower, and interpolation smooths the pose
|
||||
/// between ticks. (Engine.TimeScale would only scale the delta, which the session never uses.)
|
||||
/// </summary>
|
||||
public void SetSlowMotion(bool on)
|
||||
{
|
||||
SlowMotion = on;
|
||||
Engine.PhysicsTicksPerSecond = StepsPerSecond(on ? SlowFactor : 1.0);
|
||||
}
|
||||
|
||||
private void Present(bool teleport)
|
||||
{
|
||||
var s = Run;
|
||||
_bodies.Sync(s.View, teleport);
|
||||
_blood.Sync(s.View);
|
||||
if (s is BodyPainBoxSession box) _chamber.Sync(box); else _chamber.Hide();
|
||||
Span<BodyEvent> events = stackalloc BodyEvent[8];
|
||||
int n;
|
||||
while ((n = s.DrainEvents(events)) > 0)
|
||||
{
|
||||
for (int i = 0; i < n; i++) _events.Add(events[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
6
client/Main.tscn
Normal file
6
client/Main.tscn
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://Main.cs" id="1"]
|
||||
|
||||
[node name="Main" type="Node3D"]
|
||||
script = ExtResource("1")
|
||||
43
client/NativeLibraries.cs
Normal file
43
client/NativeLibraries.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the
|
||||
/// default probing does not look beside them. A run from the editor or <c>--path</c> loads the library from the
|
||||
/// project's build directory; an exported run from the data folder Godot puts beside the executable.
|
||||
/// </summary>
|
||||
internal static class NativeLibraries
|
||||
{
|
||||
private const string Library = "ymir_box3d";
|
||||
|
||||
#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport
|
||||
[ModuleInitializer]
|
||||
internal static void Register() =>
|
||||
NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve);
|
||||
|
||||
private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
|
||||
{
|
||||
if (name != Library) return IntPtr.Zero;
|
||||
string dir = OS.HasFeature("template")
|
||||
? Path.Combine(Path.GetDirectoryName(OS.GetExecutablePath())!, $"data_BadDay.Client_{Platform()}_{Arch()}")
|
||||
: ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug");
|
||||
string path = Path.Combine(dir, FileName());
|
||||
return File.Exists(path) && NativeLibrary.TryLoad(path, out var handle) ? handle : IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static string FileName() =>
|
||||
OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so";
|
||||
|
||||
private static string Platform() =>
|
||||
OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd";
|
||||
|
||||
private static string Arch() =>
|
||||
RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Arm64 ? "arm64" : "x86_64";
|
||||
}
|
||||
153
client/OrbitCamera.cs
Normal file
153
client/OrbitCamera.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// A camera that navigates as Blender's viewport does: middle-drag orbits (turntable, 0.4 degrees per pixel, about the puppet), Shift+middle-drag
|
||||
/// pans, Ctrl+middle-drag and the wheel zoom. With <see cref="Emulate3ButtonMouse"/> (on by default) Alt+left-drag stands for the middle button
|
||||
/// in each combination. Plain left, right and every other combination pass through unhandled. The camera's own transform is the state: the orientation is
|
||||
/// its basis, the view centre lies <see cref="Distance"/> ahead of it, and every gesture writes the transform once, on input.
|
||||
/// </summary>
|
||||
public partial class OrbitCamera : Camera3D
|
||||
{
|
||||
private enum Gesture { Orbit, Pan, Zoom }
|
||||
|
||||
private readonly record struct Binding(MouseButton Button, bool Alt, bool Shift, bool Ctrl, Gesture Gesture, bool Emulated);
|
||||
|
||||
/// <summary>The gesture the drag in progress runs, fixed at the press: the button that holds it, where an orbit turns and which way up the view started.</summary>
|
||||
private readonly record struct Drag(Gesture Gesture, MouseButton Button, Vector3 Pivot, float Reverse);
|
||||
|
||||
private static readonly Binding[] Bindings =
|
||||
{
|
||||
new(MouseButton.Middle, false, false, false, Gesture.Orbit, false),
|
||||
new(MouseButton.Middle, false, true, false, Gesture.Pan, false),
|
||||
new(MouseButton.Middle, false, false, true, Gesture.Zoom, false),
|
||||
new(MouseButton.Left, true, false, false, Gesture.Orbit, true),
|
||||
new(MouseButton.Left, true, true, false, Gesture.Pan, true),
|
||||
new(MouseButton.Left, true, false, true, Gesture.Zoom, true),
|
||||
};
|
||||
|
||||
/// <summary>Blender's default turntable sensitivity.</summary>
|
||||
private const float DegreesPerPixel = 0.4f;
|
||||
/// <summary>One wheel notch, or 16 pixels of zoom drag, scales the distance by this.</summary>
|
||||
private const float ZoomStep = 1.2f;
|
||||
private const float ZoomDragPixels = 16f;
|
||||
private const float MinDistance = 0.6f;
|
||||
private const float MaxDistance = 12f;
|
||||
|
||||
private float _distance = 2.4f;
|
||||
private Drag? _drag;
|
||||
|
||||
/// <summary>Alt+left-drag stands for the middle button (Blender's Emulate 3 Button Mouse).</summary>
|
||||
public bool Emulate3ButtonMouse { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="press"/> is one of the camera's gestures: a button and modifier combination in its binding table. The knife leaves
|
||||
/// every such press alone, in every camera mode (emulation off, a drag in progress): the camera's table is the one owner of what a press means to it.
|
||||
/// </summary>
|
||||
public static bool Binds(InputEventMouseButton press)
|
||||
{
|
||||
foreach (var row in Bindings)
|
||||
if (row.Button == press.ButtonIndex && row.Alt == press.AltPressed && row.Shift == press.ShiftPressed && row.Ctrl == press.CtrlPressed) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Where an orbit turns, read once at each orbit press; null, or a null result, means the view centre.</summary>
|
||||
public Func<Vector3?>? Pivot { get; set; }
|
||||
|
||||
/// <summary>How far the view centre lies ahead of the camera, in metres. Setting it zooms about the view centre, within the clamp.</summary>
|
||||
public float Distance
|
||||
{
|
||||
get => _distance;
|
||||
set => Commit(Basis, ViewCentre, Math.Clamp(value, MinDistance, MaxDistance));
|
||||
}
|
||||
|
||||
/// <summary>The point the camera looks at and the view pans and zooms about.</summary>
|
||||
public Vector3 ViewCentre => Position - Basis.Z * _distance;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
Fov = 55f;
|
||||
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off; // moved on input, not on the physics tick
|
||||
Current = true;
|
||||
// The startup view: yaw 0.35, pitch 0.2, 2.4 m from the hold point.
|
||||
var centre = new Vector3(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z);
|
||||
const float yaw = 0.35f, pitch = 0.2f;
|
||||
var offset = new Vector3(MathF.Sin(yaw) * MathF.Cos(pitch), MathF.Sin(pitch), MathF.Cos(yaw) * MathF.Cos(pitch));
|
||||
Commit(Basis.LookingAt(-offset, Vector3.Up), centre, _distance);
|
||||
}
|
||||
|
||||
public override void _UnhandledInput(InputEvent e)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.WheelUp or MouseButton.WheelDown } wheel:
|
||||
if (wheel.AltPressed || wheel.ShiftPressed || wheel.CtrlPressed) return;
|
||||
Distance = wheel.ButtonIndex == MouseButton.WheelUp ? _distance / MathF.Pow(ZoomStep, wheel.Factor) : _distance * MathF.Pow(ZoomStep, wheel.Factor);
|
||||
Handle();
|
||||
break;
|
||||
case InputEventMouseButton { Pressed: true } press when _drag is null || StaleDrag(press.ButtonMask):
|
||||
foreach (var row in Bindings)
|
||||
{
|
||||
if (row.Button != press.ButtonIndex || row.Alt != press.AltPressed || row.Shift != press.ShiftPressed || row.Ctrl != press.CtrlPressed) continue;
|
||||
if (row.Emulated && !Emulate3ButtonMouse) continue;
|
||||
var pivot = row.Gesture == Gesture.Orbit ? Pivot?.Invoke() ?? ViewCentre : ViewCentre;
|
||||
_drag = new Drag(row.Gesture, row.Button, pivot, Basis.Y.Dot(Vector3.Up) < 0 ? -1f : 1f);
|
||||
Handle();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case InputEventMouseButton { Pressed: false } release when _drag is { } drag && drag.Button == release.ButtonIndex:
|
||||
_drag = null;
|
||||
Handle();
|
||||
break;
|
||||
case InputEventMouseMotion motion when _drag is { } drag:
|
||||
if ((motion.ButtonMask & Held(drag.Button)) == 0) { _drag = null; return; } // the release was lost, to a focus change say
|
||||
Apply(drag, motion.Relative);
|
||||
Handle();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static MouseButtonMask Held(MouseButton button) => button == MouseButton.Left ? MouseButtonMask.Left : MouseButtonMask.Middle;
|
||||
|
||||
/// <summary>A drag is under way, so a second press is ignored as Blender's modal operator ignores it, unless the drag's own button is no longer held (its release was lost): then the drag ends and the press is new.</summary>
|
||||
private bool StaleDrag(MouseButtonMask held)
|
||||
{
|
||||
if (_drag is { } drag && (held & Held(drag.Button)) == 0) _drag = null;
|
||||
return _drag is null;
|
||||
}
|
||||
|
||||
private void Handle() => GetViewport().SetInputAsHandled();
|
||||
|
||||
private void Apply(Drag drag, Vector2 move)
|
||||
{
|
||||
switch (drag.Gesture)
|
||||
{
|
||||
case Gesture.Orbit:
|
||||
// Turntable: yaw about the world's up, pitch about the view's right, both about the pivot, unclamped.
|
||||
float step = Mathf.DegToRad(DegreesPerPixel);
|
||||
var turn = new Basis(Vector3.Up, -move.X * step * drag.Reverse) * new Basis(Basis.X, -move.Y * step);
|
||||
Commit(turn * Basis, drag.Pivot + turn * (ViewCentre - drag.Pivot), _distance);
|
||||
break;
|
||||
case Gesture.Pan:
|
||||
// The view-centre plane follows the cursor.
|
||||
float perPixel = 2f * _distance * MathF.Tan(Mathf.DegToRad(Fov) / 2f) / GetViewport().GetVisibleRect().Size.Y;
|
||||
Commit(Basis, ViewCentre + (-move.X * Basis.X + move.Y * Basis.Y) * perPixel, _distance);
|
||||
break;
|
||||
case Gesture.Zoom:
|
||||
Distance = _distance * MathF.Pow(ZoomStep, move.Y / ZoomDragPixels);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The one writer of the camera's transform: <paramref name="basis"/> looking at <paramref name="centre"/> from <paramref name="distance"/> away.</summary>
|
||||
private void Commit(Basis basis, Vector3 centre, float distance)
|
||||
{
|
||||
_distance = distance;
|
||||
basis = basis.Orthonormalized();
|
||||
Transform = new Transform3D(basis, centre + basis.Z * distance);
|
||||
}
|
||||
}
|
||||
7
client/fella/ATTRIBUTION.md
Normal file
7
client/fella/ATTRIBUTION.md
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# Fella's skin: attribution
|
||||
|
||||
`fella_skin.glb` is built by `tools/FellaMesh/build_fella_mesh.py` from three MakeHuman files, never edited by hand.
|
||||
|
||||
- Source: MakeHuman (https://github.com/makehumancommunity/makehuman), commit `a8bc2d54ff0ac92e78ff71431b1023eda42bf482`: the base mesh (`base.obj`), the default skeleton (`default.mhskel`) and its skin weights (`default_weights.mhw`). Pinned copies and SHA-256 sums: `tools/FellaMesh/input/README.md`.
|
||||
- Licence: CC0 1.0 Universal. MakeHuman released these assets to the public domain in September 2020; copyright holders at that point: Data Collection AB, Joel Palmius, Jonas Hauquier. No attribution is required; it is given here because the file's shape is theirs.
|
||||
- What the build does to them: keeps the body group (drops the helper, joint, eye, teeth and tongue groups), scales it to the plan's height, poses it into Lodur's 19-part creation pose with MakeHuman's own weights, stretches each part's segment to the plan's length, decimates the whole body to about 450 vertices with Blender's Decimate modifier (Blender 5.3.0, GPL, used as a tool: no Blender code or data is in the file), splits it into one primitive per part with shared two-part joint rings, and writes glTF. Vertices, normals and weights are the build's; UVs are MakeHuman's, one per vertex.
|
||||
BIN
client/fella/fella_skin.glb
Normal file
BIN
client/fella/fella_skin.glb
Normal file
Binary file not shown.
76
client/project.godot
Normal file
76
client/project.godot
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
; Engine configuration file.
|
||||
; It's best edited using the editor UI and not directly,
|
||||
; since the parameters that go here are not all obvious.
|
||||
|
||||
config_version=5
|
||||
|
||||
[application]
|
||||
|
||||
config/name="Bad Day Simulator"
|
||||
run/main_scene="res://Main.tscn"
|
||||
config/features=PackedStringArray("4.7", "C#")
|
||||
|
||||
[display]
|
||||
|
||||
window/size/viewport_width=1280
|
||||
window/size/viewport_height=720
|
||||
window/stretch/mode="canvas_items"
|
||||
|
||||
[dotnet]
|
||||
|
||||
project/assembly_name="BadDay.Client"
|
||||
|
||||
[physics]
|
||||
|
||||
; Godot's physics is switched off: Ymir is the only physics world. The client ticks BodyPainBoxSession at 120 Hz.
|
||||
3d/physics_engine="Dummy"
|
||||
common/physics_ticks_per_second=120
|
||||
common/physics_interpolation=true
|
||||
|
||||
[rendering]
|
||||
|
||||
renderer/rendering_method="gl_compatibility"
|
||||
renderer/rendering_method.mobile="gl_compatibility"
|
||||
|
||||
[shader_globals]
|
||||
|
||||
ps1_res={
|
||||
"type": "vec2",
|
||||
"value": Vector2(426.667, 240)
|
||||
}
|
||||
ps1_key_dir={
|
||||
"type": "vec3",
|
||||
"value": Vector3(-0.4, 0.8, 0.45)
|
||||
}
|
||||
ps1_key_color={
|
||||
"type": "vec3",
|
||||
"value": Vector3(0.95, 0.9, 0.82)
|
||||
}
|
||||
ps1_ambient={
|
||||
"type": "vec3",
|
||||
"value": Vector3(0.3, 0.34, 0.42)
|
||||
}
|
||||
ps1_fog_color={
|
||||
"type": "vec3",
|
||||
"value": Vector3(0.1, 0.1, 0.11)
|
||||
}
|
||||
ps1_fog_near={
|
||||
"type": "float",
|
||||
"value": 4.0
|
||||
}
|
||||
ps1_fog_far={
|
||||
"type": "float",
|
||||
"value": 14.0
|
||||
}
|
||||
ps1_glow_pos={
|
||||
"type": "vec3",
|
||||
"value": Vector3(0, 0, 0)
|
||||
}
|
||||
ps1_glow_color={
|
||||
"type": "vec3",
|
||||
"value": Vector3(0.85, 0.95, 1)
|
||||
}
|
||||
ps1_glow_energy={
|
||||
"type": "float",
|
||||
"value": 0.0
|
||||
}
|
||||
66
client/ps1.gdshader
Normal file
66
client/ps1.gdshader
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// The PS1 look, a port of eureka-site prototype/ps1.js (MIT): every vertex snapped to the low-res grid, affine texture coordinates,
|
||||
// unfiltered texels, per-vertex (Gouraud) light and fog. The arithmetic is the console's, in raw sRGB values with no colour management:
|
||||
// the compatibility renderer writes ALBEDO to the screen as it is, so nothing converts. The framebuffer's colour depth and dither are ps1_post.gdshader. Look owns every number.
|
||||
// Look.Ps1 makes the translucent variant by defining TRANSLUCENT ahead of this source: blended, no depth write, both faces.
|
||||
shader_type spatial;
|
||||
#ifdef TRANSLUCENT
|
||||
render_mode unshaded, blend_mix, depth_draw_never, cull_disabled;
|
||||
#else
|
||||
render_mode unshaded, cull_back;
|
||||
#endif
|
||||
|
||||
global uniform vec2 ps1_res;
|
||||
global uniform vec3 ps1_key_dir;
|
||||
global uniform vec3 ps1_key_color;
|
||||
global uniform vec3 ps1_ambient;
|
||||
global uniform vec3 ps1_fog_color;
|
||||
global uniform float ps1_fog_near;
|
||||
global uniform float ps1_fog_far;
|
||||
global uniform vec3 ps1_glow_pos;
|
||||
global uniform vec3 ps1_glow_color;
|
||||
global uniform float ps1_glow_energy;
|
||||
|
||||
uniform sampler2D albedo_tex : hint_default_white, filter_nearest, repeat_enable;
|
||||
uniform vec3 tint = vec3(1.0);
|
||||
uniform float alpha = 1.0;
|
||||
uniform bool emissive = false;
|
||||
uniform float tile = 0.0; // metres per texture repeat on the world's axes; 0 takes the mesh's own UV
|
||||
|
||||
varying vec3 auv;
|
||||
varying vec3 light;
|
||||
varying float fog;
|
||||
|
||||
void vertex() {
|
||||
vec4 mv = MODELVIEW_MATRIX * vec4(VERTEX, 1.0);
|
||||
vec4 clip = PROJECTION_MATRIX * mv;
|
||||
if (clip.w > 0.05) {
|
||||
vec2 h = ps1_res * 0.5;
|
||||
clip.xy = floor(clip.xy / clip.w * h + 0.5) / h * clip.w; // the GTE had no sub-pixel precision
|
||||
}
|
||||
POSITION = clip;
|
||||
|
||||
vec3 p = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
|
||||
vec3 n = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
|
||||
vec2 uv = UV;
|
||||
if (tile > 0.0) {
|
||||
vec3 a = abs(n);
|
||||
uv = (a.y >= a.x && a.y >= a.z ? p.xz : (a.x >= a.z ? p.zy : p.xy)) / tile;
|
||||
}
|
||||
auv = vec3(uv * clip.w, clip.w); // pre-multiplied by w: the GPU's perspective division cancels, the texture is affine
|
||||
|
||||
vec3 to_glow = ps1_glow_pos - p;
|
||||
float d = length(to_glow);
|
||||
float near = clamp(1.0 - d / 0.9, 0.0, 1.0);
|
||||
vec3 glow = ps1_glow_color * ps1_glow_energy * max(dot(n, to_glow / max(d, 1e-4)), 0.0) * near * near;
|
||||
light = emissive ? vec3(1.0) : ps1_ambient + ps1_key_color * max(dot(n, ps1_key_dir), 0.0) + glow;
|
||||
fog = smoothstep(ps1_fog_near, ps1_fog_far, -mv.z);
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
vec3 c = texture(albedo_tex, auv.xy / auv.z).rgb * tint * light;
|
||||
c = mix(c, ps1_fog_color, fog);
|
||||
ALBEDO = c;
|
||||
#ifdef TRANSLUCENT
|
||||
ALPHA = alpha;
|
||||
#endif
|
||||
}
|
||||
18
client/ps1_post.gdshader
Normal file
18
client/ps1_post.gdshader
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// The PS1 framebuffer: one colour per block of the line grid, 15-bit colour with the console's 4x4 ordered dither. The block grid is
|
||||
// anchored at the screen centre, as the vertex snap is. A full-screen ColorRect under the HUD runs it.
|
||||
shader_type canvas_item;
|
||||
|
||||
uniform sampler2D screen_tex : hint_screen_texture, filter_nearest;
|
||||
global uniform vec2 ps1_res;
|
||||
|
||||
const mat4 D = mat4(vec4(-4., 0., -3., 1.), vec4(2., -2., 3., -1.), vec4(-3., 1., -4., 0.), vec4(3., -1., 2., -2.));
|
||||
|
||||
void fragment() {
|
||||
vec2 size = 1.0 / SCREEN_PIXEL_SIZE;
|
||||
float s = size.y / ps1_res.y;
|
||||
vec2 b = floor((FRAGCOORD.xy - size * 0.5) / s);
|
||||
vec3 c = textureLod(screen_tex, (size * 0.5 + (b + 0.5) * s) / size, 0.0).rgb * 255.0;
|
||||
ivec2 q = ivec2(mod(b, 4.0));
|
||||
c = clamp(c + D[q.x][q.y], 0.0, 255.0);
|
||||
COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0);
|
||||
}
|
||||
243
client/tests/CameraChecks.cs
Normal file
243
client/tests/CameraChecks.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>Records the unhandled input that reaches it: what the camera let through.</summary>
|
||||
public partial class UnhandledListener : Node
|
||||
{
|
||||
public readonly List<InputEvent> Seen = new();
|
||||
public override void _UnhandledInput(InputEvent e) => Seen.Add(e);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The orbit camera's navigation, run by the smoke on the real Main: events pushed through the viewport reach the camera as the player's mouse would, and a listener
|
||||
/// behind it sees what the camera did not consume. Synchronous; the camera's transform and distance are restored at the end. Each check reports what broke through <c>fail</c>.
|
||||
/// </summary>
|
||||
public static class CameraChecks
|
||||
{
|
||||
private const float Degrees = 0.4f;
|
||||
|
||||
public static void Run(Action<string> fail, Main main)
|
||||
{
|
||||
void Check(bool ok, string what) { if (!ok) fail(what); }
|
||||
var camera = main.GetNode<OrbitCamera>("Camera");
|
||||
var viewport = main.GetViewport();
|
||||
// Events go in local (canvas) coordinates: the headless window is 64 px wide under a stretch to 1280, which would scale a window-space drag by 20.
|
||||
var cursor = viewport.GetVisibleRect().Size * new Vector2(0.1f, 0.9f); // clear of the HUD's controls, which sit at the top right
|
||||
var listener = new UnhandledListener();
|
||||
main.AddChild(listener);
|
||||
main.MoveChild(listener, 0); // the first child gets unhandled input last
|
||||
var home = camera.Transform;
|
||||
float homeDistance = camera.Distance;
|
||||
|
||||
// The startup view: the hold point from yaw 0.35, pitch 0.2, 2.4 m, FOV 55, as the camera was placed before it navigated like Blender's.
|
||||
var centre = new Vector3(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z);
|
||||
var offset = new Vector3(MathF.Sin(0.35f) * MathF.Cos(0.2f), MathF.Sin(0.2f), MathF.Cos(0.35f) * MathF.Cos(0.2f)) * 2.4f;
|
||||
var startup = new Transform3D(Basis.Identity, centre + offset).LookingAt(centre, Vector3.Up);
|
||||
Check(Near(camera.Transform, startup, 1e-5f) && camera.Fov == 55f && camera.Distance == 2.4f, $"the startup view is {camera.Transform} at {camera.Distance} m, FOV {camera.Fov}, not {startup} at 2.4 m, FOV 55");
|
||||
|
||||
void Button(MouseButton button, bool pressed, bool alt = false, bool shift = false, bool ctrl = false, double factor = 1, MouseButtonMask also = 0) =>
|
||||
viewport.PushInput(new InputEventMouseButton
|
||||
{
|
||||
ButtonIndex = button, Pressed = pressed, Position = cursor, GlobalPosition = cursor, AltPressed = alt, ShiftPressed = shift, CtrlPressed = ctrl, Factor = (float)factor,
|
||||
ButtonMask = pressed && button is MouseButton.Left or MouseButton.Middle or MouseButton.Right ? Mask(button) | also : 0,
|
||||
}, true);
|
||||
void Motion(Vector2 move, MouseButtonMask held, bool alt = false, bool shift = false, bool ctrl = false) =>
|
||||
viewport.PushInput(new InputEventMouseMotion { Position = cursor + move, GlobalPosition = cursor + move, Relative = move, ButtonMask = held, AltPressed = alt, ShiftPressed = shift, CtrlPressed = ctrl }, true);
|
||||
void Drag(MouseButton button, Vector2 move, bool alt = false, bool shift = false, bool ctrl = false)
|
||||
{
|
||||
Button(button, true, alt, shift, ctrl);
|
||||
Motion(move, Mask(button), alt, shift, ctrl);
|
||||
Button(button, false, alt, shift, ctrl);
|
||||
}
|
||||
|
||||
// Pan first, so the puppet's centre is off the view centre and an orbit about the wrong point shows.
|
||||
Drag(MouseButton.Middle, new Vector2(60, -30), shift: true);
|
||||
if (main.Bodies.PuppetCentre is not { } puppet) { fail("the puppet has no centre to orbit"); main.RemoveChild(listener); listener.Free(); return; }
|
||||
var afterPan = camera.Transform;
|
||||
float afterPanDistance = camera.Distance;
|
||||
void Back() { camera.Distance = afterPanDistance; camera.Transform = afterPan; listener.Seen.Clear(); }
|
||||
Check(camera.UnprojectPosition(puppet).DistanceTo(camera.UnprojectPosition(camera.ViewCentre)) > 5, "the pan left the puppet at the view centre; the orbit check would not tell the pivots apart");
|
||||
listener.Seen.Clear();
|
||||
|
||||
// Orbit: the turntable turns by 0.4 degrees a pixel about the world's up, and the puppet stays where it is on the screen.
|
||||
var shown = camera.UnprojectPosition(puppet);
|
||||
Drag(MouseButton.Middle, new Vector2(50, 0));
|
||||
var orbited = camera.Transform;
|
||||
float turned = Floor(-afterPan.Basis.Z).SignedAngleTo(Floor(-orbited.Basis.Z), Vector3.Up);
|
||||
Check(MathF.Abs(turned - Mathf.DegToRad(-50 * Degrees)) < Mathf.DegToRad(0.1f), $"a 50 px drag turned the camera {Mathf.RadToDeg(turned):F2} degrees about up, not {-50 * Degrees}");
|
||||
Check(camera.UnprojectPosition(puppet).DistanceTo(shown) < 0.5f, $"the orbit moved the puppet from {shown} to {camera.UnprojectPosition(puppet)} on the screen; it turned about something else");
|
||||
Check(listener.Seen.Count == 0, "the orbit's events were not consumed");
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance) < 1e-6f, "an orbit changed the distance");
|
||||
Back();
|
||||
Drag(MouseButton.Left, new Vector2(50, 0), alt: true);
|
||||
Check(Near(camera.Transform, orbited, 1e-5f), $"Alt+left-drag gave {camera.Transform}, not the middle-drag's {orbited}");
|
||||
Back();
|
||||
|
||||
// Over the top: a drag down of 400 px in 40 motions pitches 160 degrees, past the pole, and the view turns upside down rather than stopping.
|
||||
Button(MouseButton.Middle, true);
|
||||
for (int i = 0; i < 40; i++) Motion(new Vector2(0, 10), MouseButtonMask.Middle); // many small steps: a clamp near the pole would stop here
|
||||
Button(MouseButton.Middle, false);
|
||||
Check(camera.Basis.Y.Dot(Vector3.Up) < 0, "an orbit of 160 degrees over the top did not carry the view over");
|
||||
// Upside down, a drag to the right still turns the scene with the cursor: the yaw reverses (Blender's turntable does).
|
||||
var flipped = camera.Transform;
|
||||
Drag(MouseButton.Middle, new Vector2(50, 0));
|
||||
float flippedTurn = Floor(-flipped.Basis.Z).SignedAngleTo(Floor(-camera.Basis.Z), Vector3.Up);
|
||||
Check(MathF.Abs(flippedTurn - Mathf.DegToRad(50 * Degrees)) < Mathf.DegToRad(0.1f), $"a 50 px drag with the view upside down turned the camera {Mathf.RadToDeg(flippedTurn):F2} degrees about up, not {50 * Degrees}");
|
||||
Back();
|
||||
|
||||
// Emulation off: Alt+left-drag is no gesture, and the press reaches whoever is behind.
|
||||
camera.Emulate3ButtonMouse = false;
|
||||
Drag(MouseButton.Left, new Vector2(50, 20), alt: true);
|
||||
camera.Emulate3ButtonMouse = true;
|
||||
Check(Near(camera.Transform, afterPan, 1e-6f), "Alt+left-drag moved the camera with the emulation off");
|
||||
Check(listener.Seen.OfType<InputEventMouseButton>().Any(b => b.Pressed && b.ButtonIndex == MouseButton.Left), "Alt+left press did not reach the listener with the emulation off");
|
||||
listener.Seen.Clear();
|
||||
|
||||
// Plain left and right drags are free: nothing moves and everything reaches the listener.
|
||||
foreach (var button in new[] { MouseButton.Left, MouseButton.Right })
|
||||
{
|
||||
Drag(button, new Vector2(50, 20));
|
||||
Check(Near(camera.Transform, afterPan, 1e-6f), $"a plain {button} drag moved the camera");
|
||||
Check(listener.Seen.OfType<InputEventMouseButton>().Count(b => b.ButtonIndex == button) == 2, $"the plain {button} press and release did not both reach the listener");
|
||||
listener.Seen.Clear();
|
||||
}
|
||||
|
||||
// Pan: the basis holds and the view centre follows the cursor, 1 px per px.
|
||||
var centreShown = camera.UnprojectPosition(camera.ViewCentre);
|
||||
var centreWas = camera.ViewCentre;
|
||||
Drag(MouseButton.Middle, new Vector2(40, -25), shift: true);
|
||||
Check(SameBasis(camera.Basis, afterPan.Basis, 1e-6f), "a pan changed the view's orientation");
|
||||
Check(camera.UnprojectPosition(centreWas).DistanceTo(centreShown + new Vector2(40, -25)) < 0.5f, $"a pan of (40, -25) moved the view centre on the screen from {centreShown} to {camera.UnprojectPosition(centreWas)}");
|
||||
var panned = camera.Transform;
|
||||
Back();
|
||||
Drag(MouseButton.Left, new Vector2(40, -25), alt: true, shift: true);
|
||||
Check(Near(camera.Transform, panned, 1e-5f), "Alt+Shift+left-drag did not pan as Shift+middle-drag does");
|
||||
Back();
|
||||
|
||||
// Zoom: a notch is a factor 1.2, a drag of 16 px up is a notch in, the clamp holds and the view direction and centre stay.
|
||||
var zoomCentre = camera.ViewCentre;
|
||||
Button(MouseButton.WheelUp, true);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance / 1.2f) < 1e-5f, $"a notch in made the distance {camera.Distance}, not {afterPanDistance / 1.2f}");
|
||||
Button(MouseButton.WheelDown, true);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance) < 1e-5f, $"a notch in and a notch out left the distance {camera.Distance}, not {afterPanDistance}");
|
||||
Button(MouseButton.WheelUp, true, factor: 2);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance / 1.44f) < 1e-5f, $"a notch in of factor 2 made the distance {camera.Distance}, not {afterPanDistance / 1.44f}");
|
||||
camera.Distance = afterPanDistance;
|
||||
Button(MouseButton.WheelUp, true, ctrl: true);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance) < 1e-6f && listener.Seen.Count == 1, "a wheel notch with Ctrl held was consumed or zoomed");
|
||||
listener.Seen.Clear();
|
||||
Drag(MouseButton.Middle, new Vector2(0, -32), ctrl: true);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance / 1.44f) < 1e-5f, $"Ctrl+middle-drag up by 32 px made the distance {camera.Distance}, not {afterPanDistance / 1.44f}");
|
||||
Drag(MouseButton.Left, new Vector2(0, 32), alt: true, ctrl: true);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance) < 1e-4f, $"Ctrl+Alt+left-drag down by 32 px made the distance {camera.Distance}, not back to {afterPanDistance}");
|
||||
for (int i = 0; i < 100; i++) Button(MouseButton.WheelUp, true);
|
||||
Check(MathF.Abs(camera.Distance - 0.6f) < 1e-5f, $"100 notches in left the distance {camera.Distance}, not 0.6");
|
||||
for (int i = 0; i < 100; i++) Button(MouseButton.WheelDown, true);
|
||||
Check(MathF.Abs(camera.Distance - 12f) < 1e-4f, $"100 notches out left the distance {camera.Distance}, not 12");
|
||||
Check(SameBasis(camera.Basis, afterPan.Basis, 1e-6f) && camera.ViewCentre.DistanceTo(zoomCentre) < 1e-4f, "zooming changed the view direction or moved the view centre");
|
||||
Back();
|
||||
|
||||
// The gesture is fixed at the press: Alt released mid-drag still orbits, and a release the viewport never delivered ends the drag.
|
||||
Button(MouseButton.Left, true, alt: true);
|
||||
Motion(new Vector2(10, 0), MouseButtonMask.Left);
|
||||
var midDrag = camera.Transform;
|
||||
Check(!Near(midDrag, afterPan, 1e-4f), "a drag that began with Alt stopped orbiting when Alt was released");
|
||||
Motion(new Vector2(10, 0), 0);
|
||||
Motion(new Vector2(10, 0), MouseButtonMask.Left);
|
||||
Check(Near(camera.Transform, midDrag, 1e-6f), "a motion with no button held, or one after it, still moved the camera; the drag was not ended");
|
||||
Button(MouseButton.Left, false);
|
||||
|
||||
// Pitch turns about the camera's own right axis, not the world's: from a yawed view, a drag down by 50 px is exactly that rotation.
|
||||
Back();
|
||||
Drag(MouseButton.Middle, new Vector2(0, 50));
|
||||
var pitched = new Basis(afterPan.Basis.X, Mathf.DegToRad(-50 * Degrees)) * afterPan.Basis;
|
||||
Check(SameBasis(camera.Basis, pitched, 1e-4f), $"a 50 px drag down from a yawed view gave {camera.Basis}, not a pitch about the camera's own right axis, {pitched}");
|
||||
|
||||
// Thousands of small orbits leave the basis a rotation: no drift into scale or shear.
|
||||
Back();
|
||||
Button(MouseButton.Middle, true);
|
||||
for (int i = 0; i < 20000; i++) Motion(new Vector2(1, 1), MouseButtonMask.Middle);
|
||||
Button(MouseButton.Middle, false);
|
||||
var drifted = camera.Basis;
|
||||
Check(MathF.Abs(drifted.X.Length() - 1) < 1e-6f && MathF.Abs(drifted.Y.Length() - 1) < 1e-6f && MathF.Abs(drifted.Z.Length() - 1) < 1e-6f
|
||||
&& MathF.Abs(drifted.X.Dot(drifted.Y)) < 1e-6f && MathF.Abs(drifted.Y.Dot(drifted.Z)) < 1e-6f && MathF.Abs(drifted.X.Dot(drifted.Z)) < 1e-6f,
|
||||
$"after 20000 small orbits the basis is no longer orthonormal: {drifted}");
|
||||
|
||||
// The pivot is read at the press: one that moves mid-drag does not move the orbit.
|
||||
var livePivot = camera.Pivot;
|
||||
var pivotNow = puppet;
|
||||
camera.Pivot = () => pivotNow;
|
||||
Back();
|
||||
var pinned = camera.UnprojectPosition(puppet);
|
||||
Button(MouseButton.Middle, true);
|
||||
pivotNow = puppet + new Vector3(0.5f, 0, 0);
|
||||
Motion(new Vector2(50, 0), MouseButtonMask.Middle);
|
||||
Button(MouseButton.Middle, false);
|
||||
camera.Pivot = livePivot;
|
||||
Check(camera.UnprojectPosition(puppet).DistanceTo(pinned) < 0.5f, "an orbit followed a pivot that moved after the press");
|
||||
|
||||
// The yaw's direction is fixed at the press as well: turning the view over mid-drag does not reverse it, and turning it back does not restore it.
|
||||
float YawOf(Transform3D from, Transform3D to) => Floor(-from.Basis.Z).SignedAngleTo(Floor(-to.Basis.Z), Vector3.Up);
|
||||
Back();
|
||||
Button(MouseButton.Middle, true);
|
||||
for (int i = 0; i < 40; i++) Motion(new Vector2(0, 10), MouseButtonMask.Middle);
|
||||
var over = camera.Transform;
|
||||
Check(camera.Basis.Y.Dot(Vector3.Up) < 0, "the drag did not turn the view over");
|
||||
Motion(new Vector2(50, 0), MouseButtonMask.Middle);
|
||||
Button(MouseButton.Middle, false);
|
||||
Check(MathF.Abs(YawOf(over, camera.Transform) - Mathf.DegToRad(-50 * Degrees)) < Mathf.DegToRad(0.1f), "a drag begun upright reversed its yaw when the view turned over mid-drag");
|
||||
Button(MouseButton.Middle, true); // upside down at the press, so reversed
|
||||
for (int i = 0; i < 40; i++) Motion(new Vector2(0, -10), MouseButtonMask.Middle);
|
||||
var upright = camera.Transform;
|
||||
Check(camera.Basis.Y.Dot(Vector3.Up) > 0, "the drag did not turn the view back");
|
||||
Motion(new Vector2(50, 0), MouseButtonMask.Middle);
|
||||
Button(MouseButton.Middle, false);
|
||||
Check(MathF.Abs(YawOf(upright, camera.Transform) - Mathf.DegToRad(50 * Degrees)) < Mathf.DegToRad(0.1f), "a drag begun upside down lost its reversed yaw when the view came upright mid-drag");
|
||||
|
||||
// A second press while a drag is under way is ignored: the first gesture runs on, and its own release ends it.
|
||||
Back();
|
||||
Button(MouseButton.Middle, true, ctrl: true); // zoom
|
||||
Button(MouseButton.Left, true, alt: true, also: MouseButtonMask.Middle); // an orbit, ignored
|
||||
Motion(new Vector2(0, -32), MouseButtonMask.Middle | MouseButtonMask.Left);
|
||||
Check(MathF.Abs(camera.Distance - afterPanDistance / 1.44f) < 1e-5f && SameBasis(camera.Basis, afterPan.Basis, 1e-6f), "a second press replaced the drag in progress");
|
||||
listener.Seen.Clear();
|
||||
Button(MouseButton.Middle, false);
|
||||
Check(listener.Seen.Count == 0, "the first button's release was not the drag's end");
|
||||
float ended = camera.Distance;
|
||||
Motion(new Vector2(0, -32), MouseButtonMask.Middle);
|
||||
Check(camera.Distance == ended, "the drag outlived its button's release");
|
||||
Button(MouseButton.Left, false);
|
||||
|
||||
// A drag whose button is no longer held (its release was lost) does not block the next press.
|
||||
Back();
|
||||
Button(MouseButton.Left, true, alt: true);
|
||||
Button(MouseButton.Middle, true); // the mask carries no Left: that drag is stale
|
||||
Motion(new Vector2(50, 0), MouseButtonMask.Middle);
|
||||
Check(MathF.Abs(YawOf(afterPan, camera.Transform) - Mathf.DegToRad(-50 * Degrees)) < Mathf.DegToRad(0.1f), "a press after a lost release was ignored");
|
||||
Button(MouseButton.Middle, false);
|
||||
Back();
|
||||
|
||||
main.RemoveChild(listener);
|
||||
listener.Free();
|
||||
camera.Distance = homeDistance;
|
||||
camera.Transform = home;
|
||||
}
|
||||
|
||||
private static MouseButtonMask Mask(MouseButton button) => button switch
|
||||
{
|
||||
MouseButton.Left => MouseButtonMask.Left,
|
||||
MouseButton.Right => MouseButtonMask.Right,
|
||||
_ => MouseButtonMask.Middle,
|
||||
};
|
||||
|
||||
private static Vector3 Floor(Vector3 v) => new Vector3(v.X, 0, v.Z).Normalized();
|
||||
|
||||
private static bool Near(Transform3D a, Transform3D b, float tolerance) => SameBasis(a.Basis, b.Basis, tolerance) && a.Origin.DistanceTo(b.Origin) < tolerance;
|
||||
|
||||
private static bool SameBasis(Basis a, Basis b, float tolerance) => (a.X - b.X).Length() < tolerance && (a.Y - b.Y).Length() < tolerance && (a.Z - b.Z).Length() < tolerance;
|
||||
}
|
||||
195
client/tests/DrownCapture.cs
Normal file
195
client/tests/DrownCapture.cs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The look of the throat cut, for Deru to tune the clutch and thrash poses and <c>ThrashKeySeconds</c> on: the office at seed 1, the knife at
|
||||
/// the front of the throat at tick 120 through <see cref="Main.CutAt"/>, and a PNG of the window at nine moments (the cut, the clutch, the
|
||||
/// will's first break, the thrash, the sag, the limp body), with <c>frames.tsv</c> naming each one's tick, goal, will and consciousness.
|
||||
/// It writes no scene state but the cut. Windowed, 1280x720, the HUD visible; the frames are of the window this scene opened.
|
||||
/// <c>godot --path client res://tests/DrownCapture.tscn -- --frames=<dir></c> (the directory is required); exit code 0 passes, 1 fails.
|
||||
/// It passes only when the goals went Clutch then Thrash and the thrash came 0.2 s or less after a will break.
|
||||
/// </summary>
|
||||
public partial class DrownCapture : Node
|
||||
{
|
||||
private const int Width = 1280, Height = 720, CutTick = 120, Hz = 120;
|
||||
private const double WatchdogSeconds = 300;
|
||||
private static readonly Vector3 Throat = new(0f, -0.0778f, 0.0778f); // the front of the throat, in the head's frame (the tests' HitAtPoint)
|
||||
|
||||
private readonly List<string> _failures = new();
|
||||
private readonly StringBuilder _tsv = new("name\ttick\tgoal\twill\tconsciousness\n");
|
||||
private Main _main = null!;
|
||||
private string? _frames;
|
||||
private bool _done;
|
||||
private int _taken;
|
||||
|
||||
private Hud Hud => _main.Hud;
|
||||
private OfficeBodySession Office => _main.Office;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
foreach (var arg in OS.GetCmdlineUserArgs())
|
||||
if (arg.StartsWith("--frames=")) _frames = arg["--frames=".Length..];
|
||||
_ = RunAsync();
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000)
|
||||
{
|
||||
Fail($"no result after {WatchdogSeconds} s");
|
||||
Finish();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(_frames)) Fail("--frames=<dir> is required");
|
||||
else
|
||||
{
|
||||
Directory.CreateDirectory(_frames);
|
||||
DisplayServer.WindowSetSize(new Vector2I(Width, Height));
|
||||
_main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
|
||||
AddChild(_main);
|
||||
if (_main.Failure is { } failure) Fail(failure);
|
||||
else await RunCapture();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Fail(e.ToString());
|
||||
}
|
||||
Finish();
|
||||
}
|
||||
|
||||
private async Task RunCapture()
|
||||
{
|
||||
await Frames(3);
|
||||
var window = GetWindow().Size;
|
||||
if (window != new Vector2I(Width, Height)) { Fail($"the window is {window}, not {Width}x{Height}"); return; }
|
||||
Hud.SeedBox.Value = 1;
|
||||
Hud.ScenarioPicker.Select((int)Scenario.Office);
|
||||
Hud.ScenarioPicker.EmitSignal(OptionButton.SignalName.ItemSelected, (long)Scenario.Office); // the HUD's own control, as the smoke picks it
|
||||
Engine.PhysicsTicksPerSecond = 1200; // the session still steps 1/120 s a physics frame
|
||||
|
||||
while (Office.TickIndex < CutTick) await Physics();
|
||||
if (!await Cut()) return;
|
||||
long cutTick = Office.TickIndex;
|
||||
if (_main.Cuts.Count != 1 || _main.Cuts[0].Part != "Head") { Fail($"the cut landed on [{string.Join(", ", _main.Cuts)}], not the head"); return; }
|
||||
|
||||
// Follow the run, noting the goal changes and the will's breaks as they come; each moment is the first tick its condition holds.
|
||||
long clutchTick = -1, thrashTick = -1, firstBreak = -1, thrashBreak = -1, bleedTick = -1, deathTick = -1;
|
||||
var moments = new List<(string Name, Func<bool> When)>
|
||||
{
|
||||
("1-cut-0.5s", () => Office.TickIndex >= cutTick + Hz / 2),
|
||||
("2-clutch-3s", () => clutchTick >= 0 && Office.TickIndex >= clutchTick + 3 * Hz),
|
||||
("3-willbroke", () => firstBreak >= 0),
|
||||
("4-thrash-0.5s", () => thrashTick >= 0 && Office.TickIndex >= thrashTick + Hz / 2),
|
||||
("5-thrash-1.0s", () => thrashTick >= 0 && Office.TickIndex >= thrashTick + Hz),
|
||||
("6-thrash-1.5s", () => thrashTick >= 0 && Office.TickIndex >= thrashTick + 3 * Hz / 2),
|
||||
("7-consciousness-0.3", () => Office.Consciousness <= 0.3),
|
||||
("8-consciousness-0.1", () => Office.Consciousness <= 0.1),
|
||||
("9-death-2s", () => deathTick >= 0 && Office.TickIndex >= deathTick + 2 * Hz),
|
||||
};
|
||||
while (_taken < moments.Count && !_done)
|
||||
{
|
||||
await Physics();
|
||||
long t = Office.TickIndex;
|
||||
if (bleedTick < 0 && Office.AirwayBleed > 0.0) bleedTick = t;
|
||||
if (bleedTick < 0 && t > cutTick + Hz) { Fail("no AirwayBleed within 1 s of the cut"); return; }
|
||||
var goal = Office.Goal;
|
||||
if (goal == OfficeGoal.Clutch && clutchTick < 0) clutchTick = t;
|
||||
if (goal == OfficeGoal.Thrash && thrashTick < 0)
|
||||
{
|
||||
thrashTick = t;
|
||||
thrashBreak = LastBreakAtOrBefore(t);
|
||||
}
|
||||
if (firstBreak < 0) firstBreak = LastBreakAtOrBefore(t);
|
||||
if (Office.Dead && deathTick < 0) deathTick = t;
|
||||
if (moments[_taken].When()) await Capture(moments[_taken].Name);
|
||||
if (deathTick >= 0 && t > deathTick + 4 * Hz) break;
|
||||
}
|
||||
if (_taken < moments.Count) Fail($"the run reached tick {Office.TickIndex} with {moments.Count - _taken} moments not taken (dead {Office.Dead})");
|
||||
if (clutchTick < 0 || thrashTick < 0 || clutchTick >= thrashTick) Fail($"the goals did not go Clutch then Thrash (clutch tick {clutchTick}, thrash tick {thrashTick})");
|
||||
else if (thrashBreak < 0 || thrashTick - thrashBreak > Hz / 5) Fail($"the thrash at tick {thrashTick} did not follow a will break (at {thrashBreak}) within 0.2 s");
|
||||
File.WriteAllText(Path.Combine(_frames!, "frames.tsv"), _tsv.ToString());
|
||||
GD.Print($"CAPTURE cut {cutTick}, clutch {clutchTick}, will broke {firstBreak}, thrash {thrashTick}, died {deathTick}");
|
||||
}
|
||||
|
||||
/// <summary>The tick of the latest WillBroke row at or before <paramref name="tick"/>, or -1.</summary>
|
||||
private long LastBreakAtOrBefore(long tick)
|
||||
{
|
||||
long found = -1;
|
||||
foreach (var e in Office.Result().Timeline)
|
||||
if (e.Kind == StressEntryKind.WillBroke && (long)Math.Round(e.TimeMs * Hz / 1000.0) <= tick) found = (long)Math.Round(e.TimeMs * Hz / 1000.0);
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The knife at the throat's drawn point. If the default view's ray misses, the camera is turned through its input path (a middle drag) and the cut tried again.</summary>
|
||||
private async Task<bool> Cut()
|
||||
{
|
||||
var camera = _main.GetNode<OrbitCamera>("Camera");
|
||||
int part = SeatedPuppet.Plan.PartIndex("Head", Lodur.Side.Center);
|
||||
for (int attempt = 0; attempt < 8; attempt++)
|
||||
{
|
||||
var pose = _main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)part)!.Value;
|
||||
var at = camera.UnprojectPosition(pose * Throat);
|
||||
if (_main.CutAt(at)) return true;
|
||||
var centre = GetViewport().GetVisibleRect().Size / 2f;
|
||||
GetViewport().PushInput(new InputEventMouseButton { ButtonIndex = MouseButton.Middle, Pressed = true, Position = centre, GlobalPosition = centre, ButtonMask = MouseButtonMask.Middle }, true);
|
||||
GetViewport().PushInput(new InputEventMouseMotion { Position = centre + new Vector2(40f, 0f), GlobalPosition = centre + new Vector2(40f, 0f), Relative = new Vector2(40f, 0f), ButtonMask = MouseButtonMask.Middle }, true);
|
||||
GetViewport().PushInput(new InputEventMouseButton { ButtonIndex = MouseButton.Middle, Pressed = false, Position = centre, GlobalPosition = centre }, true);
|
||||
await Frames(2);
|
||||
}
|
||||
Fail("the knife was refused at the throat from every view tried");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Holds the run, lets the scene catch up, saves the window, and lets the run go on.</summary>
|
||||
private async Task Capture(string name)
|
||||
{
|
||||
_main.SetPhysicsProcess(false);
|
||||
await Frames(3);
|
||||
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var image = GetViewport().GetTexture().GetImage();
|
||||
image.Convert(Image.Format.Rgba8);
|
||||
image.SavePng(Path.Combine(_frames!, name + ".png"));
|
||||
var o = Office;
|
||||
_tsv.Append(string.Create(CultureInfo.InvariantCulture, $"{name}\t{o.TickIndex}\t{o.Goal}\t{o.Will:F3}\t{o.Consciousness:F3}\n"));
|
||||
_taken++;
|
||||
_main.SetPhysicsProcess(true);
|
||||
}
|
||||
|
||||
private async Task Physics()
|
||||
{
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
|
||||
if (_main.Failure is { } failure) throw new InvalidOperationException(failure);
|
||||
}
|
||||
|
||||
private async Task Frames(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++) await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
}
|
||||
|
||||
private void Fail(string failure) => _failures.Add(failure);
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
if (_done) return;
|
||||
_done = true;
|
||||
foreach (var f in _failures) GD.PrintErr("CAPTURE FAIL " + f);
|
||||
GD.Print(_failures.Count == 0 ? "CAPTURE PASS" : $"CAPTURE FAILED ({_failures.Count})");
|
||||
GetTree().Quit(_failures.Count == 0 ? 0 : 1);
|
||||
}
|
||||
}
|
||||
6
client/tests/DrownCapture.tscn
Normal file
6
client/tests/DrownCapture.tscn
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://tests/DrownCapture.cs" id="1"]
|
||||
|
||||
[node name="DrownCapture" type="Node"]
|
||||
script = ExtResource("1")
|
||||
600
client/tests/RenderCheck.cs
Normal file
600
client/tests/RenderCheck.cs
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The windowed check of the PS1 look: it renders real frames (gl_compatibility, the client's renderer) and reads them back. Every reading is
|
||||
/// deterministic (seed 1, ticks pinned, physics frozen before a capture, probes drawn with the client's own materials), so a bound
|
||||
/// sits at the geometric midpoint of the shipped worst and the least claimed mutant and needs at least 1.2 between them
|
||||
/// (lodur:ruling:deterministic-bound-margin; a zero reading, shipped or mutant, is counted as lodur:ruling:deterministic-bound-zero-reading says: half a unit shipped, one unit mutant, each bound's comment stating it); tests/render-mutants.sh breaks the shipped code once per claim and wants that claim's line to fail.
|
||||
/// <c>godot --path client res://tests/RenderCheck.tscn [-- --frames=dir]</c>; exit code 0 passes, 1 fails. It needs a window.
|
||||
/// </summary>
|
||||
public partial class RenderCheck : Node
|
||||
{
|
||||
private const int Width = 1280, Height = 720;
|
||||
private const double WatchdogSeconds = 120;
|
||||
// Bounds (shipped worst, least claimed mutant, separation) are in each check's comment.
|
||||
private const int OddLevelFloor = 1245, FigureMisses = 1, DitherBlocks = 160;
|
||||
private const double SymmetryMillimetres = 85, NeckBound = 1.14, FogLevels = 6.6, LightLevels = 11, MipPercent = 6.5;
|
||||
|
||||
private readonly List<string> _failures = new();
|
||||
private Main _main = null!;
|
||||
private OrbitCamera _camera = null!;
|
||||
private string? _frames;
|
||||
private bool _done;
|
||||
|
||||
private BodyPainBoxSession Session => _main.PainBox;
|
||||
private int Block => Look.BlockSize(Height);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
foreach (var arg in OS.GetCmdlineUserArgs())
|
||||
if (arg.StartsWith("--frames=")) _frames = arg["--frames=".Length..];
|
||||
_ = RunAsync();
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000)
|
||||
{
|
||||
Fail("watchdog", $"no result after {WatchdogSeconds} s");
|
||||
Finish();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
DisplayServer.WindowSetSize(new Vector2I(Width, Height));
|
||||
_main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
|
||||
AddChild(_main);
|
||||
_camera = _main.GetNode<OrbitCamera>("Camera");
|
||||
_main.Hud.Visible = false; // the HUD draws above the post pass: it is not the 3D's
|
||||
Engine.PhysicsTicksPerSecond = 1200;
|
||||
if (_main.Failure is { } failure) Fail("start", failure);
|
||||
else await Scenario();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Fail("exception", e.ToString());
|
||||
}
|
||||
Finish();
|
||||
}
|
||||
|
||||
private async Task Scenario()
|
||||
{
|
||||
await Frames(3);
|
||||
var window = GetWindow().Size;
|
||||
if (window != new Vector2I(Width, Height)) { Fail("window", $"the window is {window}, not {Width}x{Height}"); return; }
|
||||
|
||||
// The play view at tick 240 of seed 1.
|
||||
await UntilTick(240);
|
||||
_main.SetPhysicsProcess(false); // the run stops here; the carriers settle on its pose
|
||||
await Frames(3);
|
||||
var play = await Capture("play");
|
||||
|
||||
CheckFifteenBit(play);
|
||||
CheckBlocks(play, Block);
|
||||
CheckLines(play);
|
||||
|
||||
_main.Chamber.Volume.Visible = false; // the translucent box tints the hand bodies inside it
|
||||
CheckFigureWhereLanesAre(await Capture("play-clear"));
|
||||
_main.Chamber.Volume.Visible = true;
|
||||
await CheckNeck();
|
||||
CheckSymmetry();
|
||||
|
||||
var home = _camera.Transform;
|
||||
_camera.Distance = 0.9f;
|
||||
await Frames(2);
|
||||
await Capture("close");
|
||||
_camera.Transform = home;
|
||||
|
||||
await CheckSnapAndAffine();
|
||||
await CheckShading();
|
||||
await CheckGlow();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 15-bit colour: every channel of every pixel is a multiple of 8 (within one level of the 8-bit rounding), and the odd multiples of 8 (8, 24, 40 ...)
|
||||
/// appear, which 12-bit colour (multiples of 16) never draws. Off-grid channels: bound 0; shipped 0, post off 1728141. Channels within one level of an
|
||||
/// odd multiple: floor 1245 = sqrt(1 x 1549038); the least shipped reading is 1549038 (the lines mutants read more), the 12-bit post 0 (counted as 1, lodur:ruling:deterministic-bound-zero-reading),
|
||||
/// so the shipped frame is over the floor by a factor of 1244 and the mutant under it by 1245.
|
||||
/// </summary>
|
||||
private void CheckFifteenBit(Frame f)
|
||||
{
|
||||
int bad = 0, odd = 0;
|
||||
for (int i = 0; i < f.Data.Length; i += 4)
|
||||
for (int c = 0; c < 3; c++)
|
||||
{
|
||||
if (f.Data[i + c] % 8 is not (0 or 1 or 7)) bad++;
|
||||
if (f.Data[i + c] % 16 is 7 or 8 or 9) odd++;
|
||||
}
|
||||
Report("15-bit", bad, 0);
|
||||
Check(bad == 0, "15-bit", $"{bad} channels are not a multiple of 8");
|
||||
Report("15-bit: channels at an odd multiple of 8", odd, OddLevelFloor);
|
||||
Check(odd >= OddLevelFloor, "15-bit", $"only {odd} channels are at an odd multiple of 8 (8, 24, 40 ...), under {OddLevelFloor}: the framebuffer is not 15-bit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line grid is 240 lines, a literal and not Look.Lines: at 1280x720 the blocks are 3 px, so the greatest common divisor of the offsets from the
|
||||
/// screen centre at which any colour changes is 3 along each axis (a coarser grid has a larger divisor, a finer one a smaller). Exact. The harness
|
||||
/// asserts this at 720 only: any other window size fails the "window" check before a frame is read (the grid is round(H / 240) px, 216 lines at 1080,
|
||||
/// and Camera3D.UnprojectPosition answers in the stretch base's coordinates, so the lanes and snap probes read the wrong pixels). Shipped 3 and 3,
|
||||
/// Look.Lines 360 reads 2, Look.Lines 120 reads 6.
|
||||
/// </summary>
|
||||
private void CheckLines(Frame f)
|
||||
{
|
||||
int gx = 0, gy = 0;
|
||||
for (int y = 0; y < f.Height; y++)
|
||||
for (int x = 1; x < f.Width; x++)
|
||||
if (f.Rgb(x, y) != f.Rgb(x - 1, y)) gx = Gcd(gx, Math.Abs(x - f.Width / 2));
|
||||
for (int x = 0; x < f.Width; x++)
|
||||
for (int y = 1; y < f.Height; y++)
|
||||
if (f.Rgb(x, y) != f.Rgb(x, y - 1)) gy = Gcd(gy, Math.Abs(y - f.Height / 2));
|
||||
Report("lines: block width in px", gx, 3);
|
||||
Report("lines: block height in px", gy, 3);
|
||||
Check(gx == 3 && gy == 3, "lines", $"the blocks are {gx} x {gy} px, not 3 x 3: 240 lines at {Height} px");
|
||||
}
|
||||
|
||||
/// <summary>Every block of the line grid, anchored at the screen centre, is one colour. Bound 0 pixels; shipped 0, sampling per pixel 218873.</summary>
|
||||
private void CheckBlocks(Frame f, int s)
|
||||
{
|
||||
var seen = new Dictionary<(int, int), uint>();
|
||||
int bad = 0;
|
||||
for (int y = 0; y < f.Height; y++)
|
||||
for (int x = 0; x < f.Width; x++)
|
||||
{
|
||||
var key = (BlockOf(x, f.Width, s), BlockOf(y, f.Height, s));
|
||||
var colour = f.Rgb(x, y);
|
||||
if (!seen.TryGetValue(key, out var first)) seen[key] = colour;
|
||||
else if (first != colour) bad++;
|
||||
}
|
||||
Report("blocks", bad, 0);
|
||||
Check(bad == 0, "blocks", $"{bad} pixels differ from the first pixel of their block");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Each dynamic body's lane origin, projected through the camera, lands within one block (3 px) of a figure pixel (skin is red over blue; floor,
|
||||
/// background and chamber are blue over red). A single pixel failed under unrelated edits (dither, snap, glow, post off each moved one origin onto a
|
||||
/// dithered or edge pixel), so the neighbourhood is the block. Bound 1 of 19 = sqrt(0.5 x 4) rounded down, a count: shipped 0 (counted as half a body, lodur:ruling:deterministic-bound-zero-reading), the least claimed mutant skin-unposed (the
|
||||
/// skin drawn at its rest pose) 4, carriers left unposed 19, separation 8; post off, 12-bit, dither off, snap off, glow unset, fog off, per-pixel light, mipmapped and linear textures, 360 and 120
|
||||
/// lines, perspective UVs and per-block sampling each read 0, so no collateral edit turns it.
|
||||
/// </summary>
|
||||
private void CheckFigureWhereLanesAre(Frame play)
|
||||
{
|
||||
var view = Session.View;
|
||||
var camera = GetViewport().GetCamera3D();
|
||||
int missed = 0, checkedBodies = 0;
|
||||
for (int i = 0; i < view.Count; i++)
|
||||
{
|
||||
var kind = (Box3DSoaKind)view.Kind[i];
|
||||
if (kind is Box3DSoaKind.StaticBox or Box3DSoaKind.Anchor) continue;
|
||||
var p = camera.UnprojectPosition(new Vector3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]));
|
||||
int x = (int)p.X, y = (int)p.Y;
|
||||
checkedBodies++;
|
||||
bool figure = false;
|
||||
for (int dy = -Block; dy <= Block && !figure; dy++)
|
||||
for (int dx = -Block; dx <= Block && !figure; dx++)
|
||||
{
|
||||
int px = x + dx, py = y + dy;
|
||||
if (px >= 0 && py >= 0 && px < Width && py < Height && (play.Rgb(px, py) >> 16 & 0xff) >= (play.Rgb(px, py) & 0xff) + 16) figure = true;
|
||||
}
|
||||
if (!figure) missed++;
|
||||
}
|
||||
Report("figure at lanes", missed, FigureMisses);
|
||||
Check(checkedBodies > 5 && missed <= FigureMisses, "figure at lanes", $"{missed} of {checkedBodies} dynamic bodies' origins are not within a block of a figure pixel");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A real neck is drawn. The chamber is hidden and the camera put straight in front of the head, 1.2 m away; the reading is the figure pixels on the row
|
||||
/// 1 cm below the projected neck joint (the torso's pose times the joint's local anchor) over the figure pixels on the row through the projected head origin:
|
||||
/// how wide the figure is at the neck against how wide at the head. Bound 1.14 = sqrt(0.73 x 1.79): shipped 0.73 (66 px over 90), the least claimed mutant
|
||||
/// fella-primitives (the primitive box torso, 0.30 m wide, drawn again beside the skin) 1.79 (183 px over 102), separation 2.45; skin-unposed reads 0.72.
|
||||
/// </summary>
|
||||
private async Task CheckNeck()
|
||||
{
|
||||
var plan = SeatedPuppet.Plan;
|
||||
int head = plan.PartIndex("Head"), torso = plan.PartIndex("Torso");
|
||||
var headPose = _main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)head)!.Value;
|
||||
var torsoPose = _main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)torso)!.Value;
|
||||
var torsoDef = plan.Parts[torso];
|
||||
var torsoCreation = new Transform3D(new Basis(new Quaternion(torsoDef.Rotation.X, torsoDef.Rotation.Y, torsoDef.Rotation.Z, torsoDef.Rotation.W)), new Vector3(torsoDef.Position.X, torsoDef.Position.Y, torsoDef.Position.Z));
|
||||
var anchor = plan.Joints[plan.JointIndex("Neck")].Anchor;
|
||||
var neck = torsoPose * (torsoCreation.AffineInverse() * new Vector3(anchor.X, anchor.Y, anchor.Z));
|
||||
|
||||
_main.Chamber.Visible = false;
|
||||
var home = _camera.Transform;
|
||||
_camera.GlobalTransform = new Transform3D(Basis.Identity, headPose.Origin + new Vector3(0, 0, 1.2f));
|
||||
await Frames(3);
|
||||
var frame = await Capture("neck");
|
||||
var camera = GetViewport().GetCamera3D();
|
||||
int neckRow = (int)camera.UnprojectPosition(neck + new Vector3(0, -0.01f, 0)).Y;
|
||||
int headRow = (int)camera.UnprojectPosition(headPose.Origin).Y;
|
||||
int FigureOn(int y)
|
||||
{
|
||||
int n = 0;
|
||||
for (int x = 0; x < Width; x++) if ((frame.Rgb(x, y) >> 16 & 0xff) >= (frame.Rgb(x, y) & 0xff) + 16) n++;
|
||||
return n;
|
||||
}
|
||||
int atNeck = FigureOn(neckRow), atHead = FigureOn(headRow);
|
||||
double ratio = atHead > 0 ? atNeck / (double)atHead : double.PositiveInfinity;
|
||||
Report($"neck: figure width at the neck over at the head ({atNeck} px over {atHead} px)", ratio, NeckBound);
|
||||
Check(atHead > 0 && ratio <= NeckBound, "neck", $"the figure is {atNeck} px wide a centimetre below the neck joint and {atHead} px wide at the head: the ratio {ratio:0.##} is over {NeckBound}");
|
||||
_camera.Transform = home;
|
||||
_main.Chamber.Visible = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest-pose mesh is left-right symmetric: no rendering, a count of the skin's own vertices (<see cref="FellaSkin.MirrorGap"/>, millimetres).
|
||||
/// Bound 85 mm = sqrt(55.9 x 128.9): shipped 55.9 mm, the least claimed mutant skin-lopsided (the left half's vertices stretched 1.5 times in x) 128.9 mm, separation 2.3.
|
||||
/// </summary>
|
||||
private void CheckSymmetry()
|
||||
{
|
||||
double gap = _main.Bodies.Skin.MirrorGap() * 1000.0;
|
||||
Report("symmetry: largest mirror distance of the rest mesh in mm", gap, SymmetryMillimetres);
|
||||
Check(gap <= SymmetryMillimetres, "symmetry", $"the rest mesh is {gap:0.#} mm from its mirror image at worst (bound {SymmetryMillimetres})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The snap and the affine probes: the figure and floor are hidden and a probe is drawn with the client's own material under the client's camera.
|
||||
/// Snap: a box on a 30-line grid (blocks of 24 px), its drawn blocks against the blocks the CPU-projected hull covers with its corners snapped to
|
||||
/// that grid and with them not snapped. Affine: one triangle with a checker texture seen from 60 degrees, one scanline, the widths of its texel runs.
|
||||
/// </summary>
|
||||
private async Task CheckSnapAndAffine()
|
||||
{
|
||||
_main.Bodies.Visible = false;
|
||||
_main.Chamber.Visible = false;
|
||||
var home = _camera.Transform;
|
||||
var res = _main.Ps1Res;
|
||||
var probes = new Node3D();
|
||||
_main.AddChild(probes);
|
||||
|
||||
// Snap. Blocks of 24 px; the pose is chosen so that snapping moves enough of the silhouette to count.
|
||||
const int coarse = 24;
|
||||
Look.Set("ps1_res", new Vector2(Width / (float)coarse, Height / (float)coarse));
|
||||
_camera.GlobalTransform = new Transform3D(Basis.Identity, new Vector3(0, 0, 3f));
|
||||
var box = new MeshInstance3D { Mesh = new BoxMesh { Size = new Vector3(1.2f, 0.8f, 0.6f) }, MaterialOverride = Look.Ps1(null, Colors.White, emissive: true) };
|
||||
box.Transform = new Transform3D(new Basis(Vector3.Up, 0.5f) * new Basis(Vector3.Right, 0.35f), new Vector3(0.13f, -0.07f, 0f));
|
||||
probes.AddChild(box);
|
||||
await Frames(3);
|
||||
var snapFrame = await Capture("snap");
|
||||
var corners = new List<Vector2>();
|
||||
foreach (var sx in new[] { -0.6f, 0.6f }) foreach (var sy in new[] { -0.4f, 0.4f }) foreach (var sz in new[] { -0.3f, 0.3f })
|
||||
corners.Add(_camera.UnprojectPosition(box.GlobalTransform * new Vector3(sx, sy, sz)));
|
||||
var exact = Hull(corners);
|
||||
var snapped = Hull(corners.Select(p => new Vector2(Width / 2f + coarse * MathF.Floor((p.X - Width / 2f) / coarse + 0.5f), Height / 2f - coarse * MathF.Floor(-(p.Y - Height / 2f) / coarse + 0.5f))).ToList());
|
||||
int offSnapped = 0, offExact = 0;
|
||||
for (int by = BlockOf(0, Height, coarse); by <= BlockOf(Height - 1, Height, coarse); by++)
|
||||
for (int bx = BlockOf(0, Width, coarse); bx <= BlockOf(Width - 1, Width, coarse); bx++)
|
||||
{
|
||||
var centre = new Vector2(Width / 2f + (bx + 0.5f) * coarse, Height / 2f + (by + 0.5f) * coarse);
|
||||
bool drawn = snapFrame.Luma((int)centre.X, (int)centre.Y) > 128, wantSnapped = Inside(snapped, centre), wantExact = Inside(exact, centre);
|
||||
if (drawn != wantSnapped) offSnapped++;
|
||||
if (drawn != wantExact) offExact++;
|
||||
}
|
||||
// Bound 2 blocks: shipped worst 0, snap off 9 (a shipped worst of 0 counts as half a block, lodur:ruling:deterministic-bound-zero-reading: sqrt(0.5 x 9) = 2.1, separation 18).
|
||||
Report("snap: blocks off the snapped hull", offSnapped, 2);
|
||||
Report("snap: blocks off the unsnapped hull", offExact, 0);
|
||||
Check(offSnapped <= 2, "snap", $"{offSnapped} blocks differ from the hull of the snapped corners (the unsnapped hull differs in {offExact})");
|
||||
Check(offExact >= 4, "snap", $"the pose does not tell snapping from not: the drawn blocks differ from the unsnapped hull in {offExact}");
|
||||
box.QueueFree();
|
||||
|
||||
// Affine. Full resolution, the camera at the triangle's base height so its base edge is the horizon row: a row 40 px above is a constant-height scanline.
|
||||
Look.Set("ps1_res", new Vector2(Width, Height));
|
||||
_camera.GlobalTransform = new Transform3D(Basis.Identity, new Vector3(0, -0.6f, 3f));
|
||||
var checker = Image.CreateEmpty(2, 2, false, Image.Format.Rgb8);
|
||||
checker.SetPixel(0, 0, Colors.White); checker.SetPixel(1, 1, Colors.White); checker.SetPixel(1, 0, Colors.Black); checker.SetPixel(0, 1, Colors.Black);
|
||||
var mesh = TriangleMesh(new[] { new Vector3(-1.6f, -0.6f, 0), new Vector3(-1.6f, 1.8f, 0), new Vector3(1.6f, -0.6f, 0) }, new[] { Vector3.Back, Vector3.Back, Vector3.Back }, new[] { new Vector2(0, 0), new Vector2(0, 8), new Vector2(8, 0) });
|
||||
var triangle = new MeshInstance3D { Mesh = mesh, MaterialOverride = Look.Ps1(ImageTexture.CreateFromImage(checker), Colors.White, emissive: true) };
|
||||
triangle.Transform = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(60)), Vector3.Zero);
|
||||
probes.AddChild(triangle);
|
||||
await Frames(3);
|
||||
var affineFrame = await Capture("affine");
|
||||
var runs = Runs(affineFrame, Height / 2 - 40);
|
||||
float spread = runs.Count > 3 ? runs.Skip(1).Take(runs.Count - 2).Max() - runs.Skip(1).Take(runs.Count - 2).Min() : float.PositiveInfinity;
|
||||
// Bound 8 px: shipped worst 1, perspective-correct UVs 67 (sqrt(1 x 67) = 8.2, separation 67).
|
||||
Report("affine: spread of texel run widths in px (" + string.Join(" ", runs) + ")", spread, 8);
|
||||
Check(runs.Count >= 6 && spread <= 8, "affine", $"texel runs along a scanline are {string.Join(" ", runs)} px wide (spread {spread}); an affine texture keeps them equal within 8");
|
||||
|
||||
probes.QueueFree();
|
||||
_camera.Transform = home;
|
||||
Look.Set("ps1_res", res);
|
||||
_main.Bodies.Visible = true;
|
||||
_main.Chamber.Visible = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shading probes, each a surface drawn with the client's own material under the client's camera (the figure and chamber hidden, the chamber's
|
||||
/// glow off): ordered dither on a flat field, fog at 9 m, per-vertex light on a triangle whose vertex normals differ, and a minified texture that
|
||||
/// carries mipmaps. Every reading is a deterministic count or mean; each bound's comment gives shipped worst, least mutant and separation.
|
||||
/// </summary>
|
||||
private async Task CheckShading()
|
||||
{
|
||||
_main.Bodies.Visible = false;
|
||||
_main.Chamber.Visible = false;
|
||||
var home = _camera.Transform;
|
||||
var res = _main.Ps1Res;
|
||||
var glow = RenderingServer.GlobalShaderParameterGet("ps1_glow_energy");
|
||||
Look.Set("ps1_glow_energy", 0f);
|
||||
var probes = new Node3D();
|
||||
_main.AddChild(probes);
|
||||
_camera.GlobalTransform = new Transform3D(Basis.Identity, new Vector3(0, 0, 3f));
|
||||
|
||||
// Dither: three flat emissive fields whose channels sit on every threshold of ps1.js's 4x4 matrix. A channel of raw value v is at level
|
||||
// (v + d) / 8 * 8 in a block whose matrix value is d, and the matrix holds the eight values -4 .. 3 (each twice); a channel of v mod 8 = 3, 2, 1, 0, 7, 6, 5
|
||||
// changes level between the matrix values -4|-3, -3|-2, -2|-1, -1|0, 0|1, 1|2, 2|3, and v mod 8 = 4 never does. The fields below hold these seven
|
||||
// thresholds (and three channels at 4), so a block's three channels in the three fields read the matrix value of its cell exactly: a 2x2 matrix, a
|
||||
// transposed one or one cell changed shows in some field. The level a channel must read is the one the matrix value gives, no level below accepted
|
||||
// (the 8-bit readback of v is exact: every n of 0..255 survives n / 255 x 255 in float32), within 1 of the 8-bit rounding.
|
||||
int[][] fields = { new[] { 99, 98, 97 }, new[] { 96, 103, 102 }, new[] { 101, 100, 100 } };
|
||||
int s = Block, offDither = 0;
|
||||
for (int f = 0; f < fields.Length; f++)
|
||||
{
|
||||
int[] raw = fields[f];
|
||||
var field = new MeshInstance3D { Mesh = new QuadMesh { Size = new Vector2(30, 30) }, MaterialOverride = Look.Ps1(null, new Color(raw[0] / 255f, raw[1] / 255f, raw[2] / 255f), emissive: true) };
|
||||
probes.AddChild(field);
|
||||
await Frames(3);
|
||||
var flat = await Capture("dither" + f);
|
||||
for (int by = BlockOf(0, Height, s); by <= BlockOf(Height - 1, Height, s); by++)
|
||||
for (int bx = BlockOf(0, Width, s); bx <= BlockOf(Width - 1, Width, s); bx++)
|
||||
{
|
||||
int x = Width / 2 + bx * s, y = Height / 2 + by * s;
|
||||
if (x < 0 || y < 0 || x >= Width || y >= Height) continue;
|
||||
int d = Bayer[((bx % 4) + 4) % 4][((by % 4) + 4) % 4];
|
||||
bool ok = true;
|
||||
for (int c = 0; c < 3; c++) ok &= Math.Abs(flat.Data[4 * (y * Width + x) + c] - (raw[c] + d) / 8 * 8) <= 1;
|
||||
if (!ok) offDither++;
|
||||
}
|
||||
field.QueueFree();
|
||||
}
|
||||
// Bound 160 block readings of 307440 (three fields of 102480) = sqrt(0.5 x 51240): shipped 0 (counted as half a reading,
|
||||
// lodur:ruling:deterministic-bound-zero-reading), the 2x2 matrix 51240, the transposed one 76860, dither off 140940, round-to-nearest 217740, separation 102480.
|
||||
Report("dither: blocks off ps1.js's matrix, three fields", offDither, DitherBlocks);
|
||||
Check(offDither <= DitherBlocks, "dither", $"{offDither} block readings of three flat fields differ from the 4x4 ordered dither");
|
||||
|
||||
// Fog: a white wall at 6, 9 and 12 m against the literals 4 and 14 m (Look's are not read: a changed FogNear or FogFar must show) and the literal
|
||||
// background (0.10, 0.10, 0.11), the smoothstep 0.104, 0.5 and 0.896 of them; linear fog would read 0.2, 0.5 and 0.8. The wall's colour is the
|
||||
// 8-bit mix toward the background, and the mean of a 300 px square (100 x 100 blocks, 25 periods of the matrix) is that colour's mean level after the
|
||||
// dither and the floor to 8, which round-to-nearest would lift by 4.
|
||||
var wall = new MeshInstance3D { Mesh = new QuadMesh { Size = new Vector2(30, 30) }, MaterialOverride = Look.Ps1(null, Colors.White, emissive: true) };
|
||||
probes.AddChild(wall);
|
||||
double worst = 0;
|
||||
float[] bg = { 0.10f, 0.10f, 0.11f };
|
||||
foreach (float depth in new[] { 6f, 9f, 12f })
|
||||
{
|
||||
wall.Position = new Vector3(0, 0, 3f - depth);
|
||||
await Frames(3);
|
||||
var fogFrame = await Capture("fog" + depth);
|
||||
float t = Math.Clamp((depth - 4f) / (14f - 4f), 0f, 1f), fogged = t * t * (3 - 2 * t);
|
||||
for (int c = 0; c < 3; c++)
|
||||
{
|
||||
double sum = 0; int n = 0;
|
||||
for (int y = Height / 2 - 150; y < Height / 2 + 150; y++)
|
||||
for (int x = Width / 2 - 150; x < Width / 2 + 150; x++) { sum += fogFrame.Data[4 * (y * Width + x) + c]; n++; }
|
||||
int mixed = (int)Math.Round(255 * (1 - fogged * (1 - bg[c])));
|
||||
double want = Bayer.SelectMany(col => col).Average(d => Math.Clamp(mixed + d, 0, 255) / 8 * 8);
|
||||
worst = Math.Max(worst, Math.Abs(sum / n - want));
|
||||
}
|
||||
}
|
||||
// Bound 6.6 levels = sqrt(2 x 22): shipped worst 2, fog centred wide (2 to 16 m) 22, linear fog 23, FogNear 6 42, FogFar 18 67, fog off 203, separation 11.
|
||||
// (Round-to-nearest reads 4 and the 12-bit post 8 here; the first is the dither line's claim.)
|
||||
Report("fog: mean level off the fogged colour at 6, 9 and 12 m", worst, FogLevels);
|
||||
Check(worst <= FogLevels, "fog", $"a wall at 6, 9 or 12 m reads {worst:F1} levels from white fogged by the literal smoothstep of 4 to 14 m toward the background");
|
||||
wall.QueueFree();
|
||||
|
||||
// Light: one grey triangle facing the camera, vertex normals at 0 and -+120 degrees from the key (dots 1, -0.5, -0.5). Light per vertex is the
|
||||
// clamped dot at the corners interpolated across the face; per pixel it would be the dot of the interpolated normal, clamped after. One row
|
||||
// near the base, the red channel against the barycentric blend of the corners' light.
|
||||
Look.Set("ps1_res", new Vector2(Width, Height));
|
||||
var key = Look.KeyDirection;
|
||||
var u = key.Cross(Vector3.Right).Normalized();
|
||||
var normals = new[] { key, key * -0.5f + u * 0.8660254f, key * -0.5f - u * 0.8660254f };
|
||||
var corners = new[] { new Vector3(-1.2f, -0.8f, 0), new Vector3(0, 0.9f, 0), new Vector3(1.2f, -0.8f, 0) };
|
||||
var lit = new MeshInstance3D { Mesh = TriangleMesh(corners, normals, new Vector2[3]), MaterialOverride = Look.Ps1(null, new Color(0.5f, 0.5f, 0.5f)) };
|
||||
probes.AddChild(lit);
|
||||
await Frames(3);
|
||||
var litFrame = await Capture("light");
|
||||
var screen = corners.Select(c => _camera.UnprojectPosition(c)).ToArray();
|
||||
int row = (int)(screen[0].Y + (screen[1].Y - screen[0].Y) * 0.12f);
|
||||
double err = 0; int samples = 0;
|
||||
for (int x = 0; x < Width; x++)
|
||||
{
|
||||
var p = new Vector2(x + 0.5f, row + 0.5f);
|
||||
float den = (screen[1].Y - screen[2].Y) * (screen[0].X - screen[2].X) + (screen[2].X - screen[1].X) * (screen[0].Y - screen[2].Y);
|
||||
float w0 = ((screen[1].Y - screen[2].Y) * (p.X - screen[2].X) + (screen[2].X - screen[1].X) * (p.Y - screen[2].Y)) / den;
|
||||
float w1 = ((screen[2].Y - screen[0].Y) * (p.X - screen[2].X) + (screen[0].X - screen[2].X) * (p.Y - screen[2].Y)) / den;
|
||||
float w2 = 1 - w0 - w1;
|
||||
if (w0 < 0.04f || w1 < 0.04f || w2 < 0.04f) continue;
|
||||
float dots = w0 * Math.Max(normals[0].Dot(key), 0) + w1 * Math.Max(normals[1].Dot(key), 0) + w2 * Math.Max(normals[2].Dot(key), 0);
|
||||
err += Math.Abs(litFrame.Data[4 * (row * Width + x)] - Math.Min(1f, 0.5f * (Look.AmbientColor.R + Look.KeyColor.R * dots)) * 255);
|
||||
samples++;
|
||||
}
|
||||
double lightErr = samples > 100 ? err / samples : double.PositiveInfinity;
|
||||
// Bound 11 levels = sqrt(4.45 x 27.13): shipped worst 4.45, light per pixel 27.13, separation 6.1. (The 12-bit post reads 8.51.)
|
||||
Report($"light: mean red level off the Gouraud blend over {samples} px", lightErr, LightLevels);
|
||||
Check(lightErr <= LightLevels, "light", $"red along a row of a triangle is {lightErr:F1} levels from the blend of its corners' light ({samples} px): the light is not per vertex");
|
||||
lit.QueueFree();
|
||||
|
||||
// Mips: a 2 x 2 checker that carries a generated mip chain, minified (about 1.7 texels a pixel). Nearest without mips draws only black and white;
|
||||
// a sampler that reads the mips or filters draws grey. The share of the central 400 x 300 px with luma between 60 and 190.
|
||||
var image = Image.CreateEmpty(2, 2, true, Image.Format.Rgb8);
|
||||
image.SetPixel(0, 0, Colors.White); image.SetPixel(1, 1, Colors.White); image.SetPixel(1, 0, Colors.Black); image.SetPixel(0, 1, Colors.Black);
|
||||
image.GenerateMipmaps();
|
||||
var sheet = new MeshInstance3D
|
||||
{
|
||||
Mesh = TriangleMesh(new[] { new Vector3(-3, 2, 0), new Vector3(3, 2, 0), new Vector3(3, -2, 0), new Vector3(-3, 2, 0), new Vector3(3, -2, 0), new Vector3(-3, -2, 0) },
|
||||
Enumerable.Repeat(Vector3.Back, 6).ToArray(),
|
||||
new[] { new Vector2(0, 0), new Vector2(2400, 0), new Vector2(2400, 1600), new Vector2(0, 0), new Vector2(2400, 1600), new Vector2(0, 1600) }),
|
||||
MaterialOverride = Look.Ps1(ImageTexture.CreateFromImage(image), Colors.White, emissive: true),
|
||||
};
|
||||
probes.AddChild(sheet);
|
||||
await Frames(3);
|
||||
var sheetFrame = await Capture("mips");
|
||||
int grey = 0, all = 0;
|
||||
for (int y = Height / 2 - 150; y < Height / 2 + 150; y++)
|
||||
for (int x = Width / 2 - 200; x < Width / 2 + 200; x++) { if (sheetFrame.Luma(x, y) is > 60 and < 190) grey++; all++; }
|
||||
double share = 100.0 * grey / all;
|
||||
// Bound 6.5 percent = sqrt(0.5 x 84.44): shipped 0 (counted as half a percent, lodur:ruling:deterministic-bound-zero-reading), linear filter 84.44, nearest with mipmaps 100, separation 169.
|
||||
Report("mips: percent of a minified checker that is neither black nor white", share, MipPercent);
|
||||
Check(share <= MipPercent, "mips", $"{share:F1}% of a minified checker is grey: the sampler reads mipmaps or filters");
|
||||
|
||||
probes.QueueFree();
|
||||
_camera.Transform = home;
|
||||
Look.Set("ps1_res", res);
|
||||
Look.Set("ps1_glow_energy", glow);
|
||||
_main.Bodies.Visible = true;
|
||||
_main.Chamber.Visible = true;
|
||||
}
|
||||
|
||||
private static ArrayMesh TriangleMesh(Vector3[] vertices, Vector3[] normals, Vector2[] uv)
|
||||
{
|
||||
var arrays = new Godot.Collections.Array();
|
||||
arrays.Resize((int)Mesh.ArrayType.Max);
|
||||
arrays[(int)Mesh.ArrayType.Vertex] = vertices;
|
||||
arrays[(int)Mesh.ArrayType.Normal] = normals;
|
||||
arrays[(int)Mesh.ArrayType.TexUV] = uv;
|
||||
var mesh = new ArrayMesh();
|
||||
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
private static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
|
||||
|
||||
/// <summary>ps1.js's 4x4 ordered dither matrix, indexed [block column mod 4][block row mod 4] as ps1_post.gdshader indexes its mat4.</summary>
|
||||
private static readonly int[][] Bayer = { new[] { -4, 0, -3, 1 }, new[] { 2, -2, 3, -1 }, new[] { -3, 1, -4, 0 }, new[] { 3, -1, 2, -2 } };
|
||||
|
||||
/// <summary>
|
||||
/// The chamber's light lights the figure: at tick 1 of seed 1 the chamber at full glow (box intensity 6) and dark (0), the bodies in the same
|
||||
/// pose, the chamber's own volume hidden so only the light differs; the mean luma of the 300 px square about the held hand is higher
|
||||
/// lit. Bound: half the shipped difference; a chamber whose light is not written reads 0.
|
||||
/// </summary>
|
||||
private async Task CheckGlow()
|
||||
{
|
||||
var means = new double[2];
|
||||
var poses = new List<Transform3D?[]>();
|
||||
for (int run = 0; run < 2; run++)
|
||||
{
|
||||
_main.SetPhysicsProcess(true);
|
||||
_main.SetIntensity(run == 0 ? 6 : 0);
|
||||
_main.Reset(1);
|
||||
await UntilTick(1);
|
||||
_main.SetPhysicsProcess(false);
|
||||
await Frames(3);
|
||||
_main.Chamber.Volume.Visible = false;
|
||||
var frame = await Capture(run == 0 ? "glow-full" : "glow-off");
|
||||
_main.Chamber.Volume.Visible = true;
|
||||
var hold = _camera.UnprojectPosition(new Vector3(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z));
|
||||
double sum = 0; int n = 0;
|
||||
for (int y = (int)hold.Y - 150; y < (int)hold.Y + 150; y++)
|
||||
for (int x = (int)hold.X - 150; x < (int)hold.X + 150; x++)
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= Width || y >= Height) continue;
|
||||
sum += frame.Luma(x, y); n++;
|
||||
}
|
||||
means[run] = sum / n;
|
||||
poses.Add(Session.View.StableId.ToArray().Select(id => _main.Bodies.PoseOf(id)).ToArray());
|
||||
}
|
||||
bool samePose = poses[0].Zip(poses[1]).All(p => p.First is { } a && p.Second is { } b && a.Origin.DistanceTo(b.Origin) < 1e-4f);
|
||||
double lift = means[0] - means[1];
|
||||
// Bound 1.2 levels: shipped 2.4, light not written 0 (half the shipped lift: the mutant's reading has no spread to take a midpoint of).
|
||||
Report("glow: luma lift near the hand", lift, 1.2);
|
||||
Check(samePose, "glow", "the bodies are not in the same pose at tick 1 with the box lit and dark; the probe proves nothing");
|
||||
Check(lift >= 1.2, "glow", $"the figure is {lift:F2} levels brighter with the chamber at full glow than dark, under 1.2");
|
||||
}
|
||||
|
||||
private readonly record struct Frame(int Width, int Height, byte[] Data)
|
||||
{
|
||||
public uint Rgb(int x, int y) { int i = 4 * (y * Width + x); return (uint)(Data[i] << 16 | Data[i + 1] << 8 | Data[i + 2]); }
|
||||
public double Luma(int x, int y) { int i = 4 * (y * Width + x); return 0.299 * Data[i] + 0.587 * Data[i + 1] + 0.114 * Data[i + 2]; }
|
||||
}
|
||||
|
||||
private async Task<Frame> Capture(string name)
|
||||
{
|
||||
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var image = GetViewport().GetTexture().GetImage();
|
||||
image.Convert(Image.Format.Rgba8);
|
||||
if (_frames is not null) image.SavePng($"{_frames}/{name}.png");
|
||||
return new Frame(image.GetWidth(), image.GetHeight(), image.GetData());
|
||||
}
|
||||
|
||||
/// <summary>The widths in pixels of the white and black runs along row <paramref name="y"/> inside the lit triangle, edges included.</summary>
|
||||
private static List<int> Runs(Frame f, int y)
|
||||
{
|
||||
var runs = new List<int>();
|
||||
int start = 0; bool? last = null;
|
||||
for (int x = 0; x < f.Width; x++)
|
||||
{
|
||||
if (f.Luma(x, y) is var l && l is > 60 and < 190) { last = null; continue; } // a dithered or blended pixel: not a clean texel
|
||||
bool white = f.Luma(x, y) > 128;
|
||||
if (last is null) { start = x; last = white; }
|
||||
else if (last != white) { runs.Add(x - start); start = x; last = white; }
|
||||
}
|
||||
return runs;
|
||||
}
|
||||
|
||||
/// <summary>The block a pixel belongs to on a grid of <paramref name="s"/>-pixel blocks anchored at the centre of an axis of <paramref name="length"/> pixels.</summary>
|
||||
private static int BlockOf(int pixel, int length, int s) => (int)Math.Floor((pixel - length / 2.0) / s);
|
||||
|
||||
private static List<Vector2> Hull(List<Vector2> points)
|
||||
{
|
||||
var p = points.OrderBy(a => a.X).ThenBy(a => a.Y).ToList();
|
||||
var h = new List<Vector2>();
|
||||
foreach (var pass in new[] { p, Enumerable.Reverse(p).ToList() })
|
||||
{
|
||||
int floor = h.Count;
|
||||
foreach (var q in pass)
|
||||
{
|
||||
while (h.Count >= floor + 2 && Cross(h[^2], h[^1], q) <= 0) h.RemoveAt(h.Count - 1);
|
||||
h.Add(q);
|
||||
}
|
||||
h.RemoveAt(h.Count - 1);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
private static float Cross(Vector2 o, Vector2 a, Vector2 b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X);
|
||||
|
||||
private static bool Inside(List<Vector2> hull, Vector2 q)
|
||||
{
|
||||
for (int i = 0; i < hull.Count; i++) if (Cross(hull[i], hull[(i + 1) % hull.Count], q) < 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task Frames(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++) await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
}
|
||||
|
||||
private async Task UntilTick(long tick)
|
||||
{
|
||||
while (Session.TickIndex < tick && !Session.Finished) await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
|
||||
if (Session.TickIndex != tick) Fail("tick", $"the run stopped at tick {Session.TickIndex}, not {tick}");
|
||||
await Frames(1);
|
||||
}
|
||||
|
||||
private void Report(string name, double reading, double bound) => GD.Print($"RENDER {name}: {reading:0.##} (bound {bound:0.##})");
|
||||
|
||||
private void Check(bool ok, string name, string failure)
|
||||
{
|
||||
if (!ok) Fail(name, failure);
|
||||
}
|
||||
|
||||
private void Fail(string name, string failure) => _failures.Add($"{name}: {failure}");
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
if (_done) return;
|
||||
_done = true;
|
||||
foreach (var f in _failures) GD.PrintErr("RENDER FAIL " + f);
|
||||
GD.Print(_failures.Count == 0 ? "RENDER PASS" : $"RENDER FAILED ({_failures.Count})");
|
||||
GetTree().Quit(_failures.Count == 0 ? 0 : 1);
|
||||
}
|
||||
}
|
||||
6
client/tests/RenderCheck.tscn
Normal file
6
client/tests/RenderCheck.tscn
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://tests/RenderCheck.cs" id="1"]
|
||||
|
||||
[node name="RenderCheck" type="Node"]
|
||||
script = ExtResource("1")
|
||||
458
client/tests/Smoke.cs
Normal file
458
client/tests/Smoke.cs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The headless smoke: runs the real Main scene, drives it through the HUD's own controls and checks what the client
|
||||
/// promises against a headless BDS run in the same process. Exit code 0 passes, 1 fails.
|
||||
/// <c>godot --headless --path client res://tests/Smoke.tscn</c>
|
||||
/// </summary>
|
||||
public partial class Smoke : Node
|
||||
{
|
||||
private const ulong Seed = 1;
|
||||
private const double WatchdogSeconds = 150;
|
||||
// The joint rings' bound, in micrometres (lodur:ruling:deterministic-bound-margin and deterministic-bound-zero-reading): shipped worst 0 (counted as half a micrometre),
|
||||
// the least claimed mutant (split rings: each copy weighted to its own part only) 75768 at tick 240; sqrt(0.5 x 75768) = 195, separation 1.5e5.
|
||||
private const double RingGapMicrometres = 195;
|
||||
|
||||
private readonly List<string> _failures = new();
|
||||
private Main _main = null!;
|
||||
private IBodyRun? _lastSession;
|
||||
private long _lastTick;
|
||||
private bool _done;
|
||||
|
||||
private Hud Hud => _main.Hud;
|
||||
private BodyPainBoxSession Session => _main.PainBox;
|
||||
private OfficeBodySession Office => _main.Office;
|
||||
|
||||
public override void _Ready() => _ = RunAsync();
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000)
|
||||
{
|
||||
Check(false, $"no result after {WatchdogSeconds} s");
|
||||
Finish();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
|
||||
AddChild(_main);
|
||||
if (_main.Failure is { } failure) Check(false, "Main could not start a session: " + failure);
|
||||
else await ChamberScenario();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Check(false, e.ToString());
|
||||
}
|
||||
Finish();
|
||||
}
|
||||
|
||||
private async Task ChamberScenario()
|
||||
{
|
||||
CheckEngineAndScene();
|
||||
if (_failures.Count > 0) return;
|
||||
|
||||
// Slow motion, by wall clock: a quarter of the session steps per real second, the same run.
|
||||
await Frames(10);
|
||||
double normal = await StepsPerSecond(1000);
|
||||
Hud.SlowToggle.ButtonPressed = true; // the real control
|
||||
double slow = await StepsPerSecond(2000);
|
||||
Check(slow > 0.15 * normal && slow < 0.4 * normal, $"slow motion runs {slow:F0} steps per second against {normal:F0}; wanted about a quarter");
|
||||
Hud.SlowToggle.ButtonPressed = false;
|
||||
Check(Engine.PhysicsTicksPerSecond == 120, $"slow motion off leaves {Engine.PhysicsTicksPerSecond} physics ticks per second");
|
||||
|
||||
// The rest runs the physics clock fast; the session still steps 1/120 s per frame.
|
||||
Engine.PhysicsTicksPerSecond = 1200;
|
||||
|
||||
// A Reset is not a new set of bodies: the carriers and meshes made at startup stay. Checked after three resets so a rebuild per
|
||||
// Reset fails here, not after hundreds.
|
||||
for (ulong seed = 1; seed <= 3; seed++) { PressReset(seed); await Frame(); }
|
||||
CheckMeshBuilds("by the third Reset");
|
||||
CameraChecks.Run(failure => Check(false, "camera: " + failure), _main);
|
||||
// The camera writes its transform on input only: one written between frames stays through them.
|
||||
var orbit = _main.GetNode<OrbitCamera>("Camera");
|
||||
var home = orbit.Transform;
|
||||
var moved = new Transform3D(home.Basis.Rotated(Vector3.Up, 1f), home.Origin + new Vector3(0.1f, 0, 0));
|
||||
orbit.Transform = moved;
|
||||
for (int i = 0; i < 3; i++) await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
Check(orbit.Transform == moved, $"the camera moved itself from {moved.Origin} to {orbit.Transform.Origin} between frames");
|
||||
orbit.Transform = home;
|
||||
if (_failures.Count > 0) return;
|
||||
|
||||
// Seed 1 at the default intensity against the headless run: events, and the hand at ticks 240 and 1500.
|
||||
PressReset(1);
|
||||
var reference = Run(new PainBoxParameters().BoxIntensity, 1, 1500);
|
||||
await UntilTick(240);
|
||||
CheckHand(reference.Hand[239], "tick 240");
|
||||
CheckPoses("tick 240");
|
||||
CheckSkin("tick 240");
|
||||
await UntilTick(1500);
|
||||
CheckEvents(reference, "seed 1, default intensity");
|
||||
CheckHand(reference.Hand[^1], "tick 1500");
|
||||
|
||||
// The slider sets the next run's intensity; a high one breaks the will, and the run ends.
|
||||
Hud.IntensitySlider.Value = 6;
|
||||
Check(_main.Intensity == 6, $"the slider set intensity {_main.Intensity}, not 6");
|
||||
PressReset(3);
|
||||
reference = Run(6, 3, 1500);
|
||||
await UntilTick(1500);
|
||||
CheckEvents(reference, "seed 3, intensity 6");
|
||||
Check(Session.Finished && _main.Events.Any(e => (e.Events & Lodur.TickEvents.WillBroke) != 0), "intensity 6 did not break the will");
|
||||
|
||||
// A reset puts every body at its pose now, not on the way from where the last run left it. A reset from the UI
|
||||
// lands between physics frames, and on a slow physics clock the next render frame comes before the next tick.
|
||||
Engine.PhysicsTicksPerSecond = 10;
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
PressReset(4);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
foreach (var id in Session.View.StableId.ToArray())
|
||||
{
|
||||
var shown = _main.Bodies.InterpolatedPoseOf(id);
|
||||
var pose = _main.Bodies.PoseOf(id);
|
||||
Check(shown is { } a && pose is { } b && a.Origin.DistanceTo(b.Origin) < 1e-2f, $"after Reset body {id} is rendered at {shown?.Origin}, not at {pose?.Origin}");
|
||||
}
|
||||
Engine.PhysicsTicksPerSecond = 1200;
|
||||
|
||||
// Every reset honours its seed, whatever it replaces.
|
||||
Hud.IntensitySlider.Value = new PainBoxParameters().BoxIntensity;
|
||||
foreach (ulong seed in new ulong[] { 2, 7, 123456789 })
|
||||
{
|
||||
PressReset(seed);
|
||||
reference = Run(_main.Intensity, seed, 150);
|
||||
await UntilTick(150);
|
||||
Check(Session.Pain == reference.Pain && Session.Strain == reference.Strain, $"seed {seed}: pain {Session.Pain} differs from the headless run's {reference.Pain}");
|
||||
CheckHand(reference.Hand[^1], $"seed {seed} tick 150");
|
||||
}
|
||||
|
||||
// Many resets without leaking native worlds (the native library caps them near 128).
|
||||
for (int i = 0; i < 400; i++)
|
||||
{
|
||||
PressReset(1000 + (ulong)i);
|
||||
await Frame();
|
||||
}
|
||||
Check(_main.Seed == 1399, $"after 400 resets the seed is {_main.Seed}");
|
||||
CheckMeshBuilds("after 400 Resets");
|
||||
|
||||
// Box off, through the HUD button, at tick 600: the run ends with the will intact and the screen shows the box off.
|
||||
PressReset(Seed);
|
||||
await UntilTick(600);
|
||||
Check(!Session.Finished, "the run was over before tick 600; the box-off probe needs the will intact");
|
||||
Hud.BoxOffButton.EmitSignal(BaseButton.SignalName.Pressed);
|
||||
await Frame();
|
||||
Check(Session.Finished && Session.Result().Outcome == Outcome.BoxDisabled, "Box off did not end the run as BoxDisabled within one tick");
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); // the HUD draws in _Process, after this frame's signal
|
||||
Check(_main.Chamber.Glow == 0f, $"the chamber still glows ({_main.Chamber.Glow}) with the box off");
|
||||
Check(Hud.Readout.Contains("box intensity 0.00"), "the readout does not show the box off: " + Hud.Readout.Split('\n')[1]);
|
||||
|
||||
// Box off after the will has broken: the run is over, and the box the player switches off still goes dark.
|
||||
PressReset(Seed);
|
||||
while (!Session.Finished) await Frame();
|
||||
Check(Session.Result().Outcome == Outcome.WillBroke && Session.BoxOn, $"the run ended {Session.Result().Outcome} with the box on: expected WillBroke");
|
||||
await Frame();
|
||||
Check(_main.Chamber.Glow > 0.1f, $"the chamber is dark ({_main.Chamber.Glow}) after the will broke, so the probe proves nothing");
|
||||
Hud.BoxOffButton.EmitSignal(BaseButton.SignalName.Pressed);
|
||||
await Frame();
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
Check(!Session.BoxOn && _main.Chamber.Glow == 0f && Hud.Readout.Contains("box intensity 0.00 off"), $"after Box off on a finished run: on {Session.BoxOn}, glow {_main.Chamber.Glow}");
|
||||
|
||||
await OfficeScenario();
|
||||
}
|
||||
|
||||
/// <summary>The office, chosen through the HUD's picker: the bars, Silence, and the way back to the chamber.</summary>
|
||||
private async Task OfficeScenario()
|
||||
{
|
||||
Hud.SeedBox.Value = Seed;
|
||||
Hud.ScenarioPicker.Select((int)Scenario.Office);
|
||||
Hud.ScenarioPicker.EmitSignal(OptionButton.SignalName.ItemSelected, (long)Scenario.Office);
|
||||
Check(_main.Scenario == Scenario.Office && _main.Seed == Seed, $"the picker left Main in {_main.Scenario}, seed {_main.Seed}");
|
||||
var office = Office;
|
||||
Check(!_main.Chamber.Visible && _main.Chamber.Glow == 0f, "the chamber is drawn in the office");
|
||||
await UntilTick(120);
|
||||
|
||||
// The knife: where the player clicks. An Alt+left press is the camera's emulated middle button and cuts nothing; a plain left press on
|
||||
// LowerArm L's drawn centre opens one cut there, through the same CutAt a direct call takes.
|
||||
int arm = SeatedPuppet.Plan.PartIndex("LowerArm", Lodur.Side.Left);
|
||||
var camera = _main.GetNode<OrbitCamera>("Camera");
|
||||
Vector2 at = camera.UnprojectPosition(_main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)arm)!.Value.Origin);
|
||||
Click(at, alt: true);
|
||||
Check(_main.Cuts.Count == 0, "an Alt+left press cut");
|
||||
Click(at, alt: false);
|
||||
Check(_main.Cuts.Count == 1 && _main.Cuts[0].Part == "LowerArm L", $"a left press on LowerArm L's centre left cuts [{string.Join(", ", _main.Cuts)}]");
|
||||
Check(office.Result().Timeline.Count > 0, "no timeline after a cut");
|
||||
Check(Hud.Readout.Contains("airway "), "the readout has no airway line");
|
||||
await CheckAltGuard(at);
|
||||
await UntilTick(600);
|
||||
|
||||
// The blood drawn is the blood the world holds: a drop per live fluid lane, a disc per live wet lane, counted from the lanes here.
|
||||
var view = office.View;
|
||||
int liveDrops = 0, livePatches = 0;
|
||||
for (int i = 0; i < view.ParticleCount; i++) if (view.ParticleLive[i] != 0 && (view.ParticlePhase[i] & Box3DSoaPhase.Fluid) != 0) liveDrops++;
|
||||
for (int i = 0; i < view.WetCount; i++) if (view.WetLive[i] != 0) livePatches++;
|
||||
Check(liveDrops + livePatches > 0, "no blood in the world 480 ticks after the cut");
|
||||
Check(_main.Blood.DropCount == liveDrops && _main.Blood.PatchCount == livePatches,
|
||||
$"blood draws {_main.Blood.DropCount} drops and {_main.Blood.PatchCount} patches; the lanes hold {liveDrops} and {livePatches}");
|
||||
|
||||
CheckBloodPlaced(view);
|
||||
|
||||
// The bars are the session's will and arousal, to the bit, once a frame has drawn them (stepping paused so the session holds still).
|
||||
// Run on until the cut has cost his will, so a bar bound to resolve instead shows a different number.
|
||||
// The knife is severity 20 (the arm bleeds for 191 s), so the will falls behind resolve later than tick 1800: run to the first tick it has, within the break.
|
||||
while (office.Will >= office.Resolve - 0.1 && office.TickIndex < 12000) await Frame();
|
||||
Check(office.Will < office.Resolve - 0.1, $"will {office.Will} and resolve {office.Resolve} are too close at tick {office.TickIndex} for the bars to tell them apart");
|
||||
_main.SetPhysicsProcess(false);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
Check(Hud.WillBar.Value == office.Will && Hud.StressBar.Value == office.Arousal,
|
||||
$"bars show will {Hud.WillBar.Value} and stress {Hud.StressBar.Value}; the session has {office.Will} and {office.Arousal}");
|
||||
_main.SetPhysicsProcess(true);
|
||||
_lastSession = null;
|
||||
|
||||
// Silence is the HUD's button for the stressor, and the session logs it.
|
||||
Check(Hud.SilenceButtons.Count == Main.OfficeParameters.Cause.Stressors.Count, $"{Hud.SilenceButtons.Count} Silence buttons for {Main.OfficeParameters.Cause.Stressors.Count} stressors");
|
||||
int silenced = office.Result().Timeline.Count(e => e.Kind == StressEntryKind.Silenced);
|
||||
Hud.SilenceButtons["printer"].EmitSignal(BaseButton.SignalName.Pressed);
|
||||
Check(office.Result().Timeline.Count(e => e.Kind == StressEntryKind.Silenced) == silenced + 1, "Silence did not put a Silenced row in the result");
|
||||
await Frame();
|
||||
|
||||
// Back to the chamber: the office run is gone and the chamber is drawn.
|
||||
Hud.ScenarioPicker.Select((int)Scenario.Chamber);
|
||||
Hud.ScenarioPicker.EmitSignal(OptionButton.SignalName.ItemSelected, (long)Scenario.Chamber);
|
||||
await Frame();
|
||||
Check(_main.Scenario == Scenario.Chamber && _main.Run is BodyPainBoxSession, "switching back did not make the pain box the live run");
|
||||
Check(_main.Chamber.Visible, "the chamber is hidden after switching back");
|
||||
Check(Throws(() => _ = office.TickIndex), "the office run was not disposed by the switch");
|
||||
}
|
||||
|
||||
/// <summary>Each drop is drawn at its lane's point and 2 x its radius wide; each disc at its body's pose applied to its point, lifted, and as wide as its radius (both in lane order).</summary>
|
||||
private void CheckBloodPlaced(Box3DSoaView view)
|
||||
{
|
||||
int d = 0;
|
||||
for (int i = 0; i < view.ParticleCount; i++)
|
||||
{
|
||||
if (view.ParticleLive[i] == 0 || (view.ParticlePhase[i] & Box3DSoaPhase.Fluid) == 0) continue;
|
||||
var t = _main.Blood.Drops[d++];
|
||||
Check(t.Origin == new Vector3(view.ParticleX[i], view.ParticleY[i], view.ParticleZ[i]) && Math.Abs(t.Basis.Scale.X - 2f * view.ParticleRadius[i]) < 1e-6f,
|
||||
$"drop {d - 1} is drawn at {t.Origin} size {t.Basis.Scale.X}; lane {i} is at ({view.ParticleX[i]}, {view.ParticleY[i]}, {view.ParticleZ[i]}), radius {view.ParticleRadius[i]}");
|
||||
}
|
||||
int p = 0;
|
||||
for (int i = 0; i < view.WetCount; i++)
|
||||
{
|
||||
if (view.WetLive[i] == 0) continue;
|
||||
int b = view.WetBody[i];
|
||||
if (b < 0) { p++; continue; }
|
||||
var q = new Quaternion(view.RotationX[b], view.RotationY[b], view.RotationZ[b], view.RotationW[b]);
|
||||
var want = new Vector3(view.PositionX[b], view.PositionY[b], view.PositionZ[b]) + q * new Vector3(view.WetX[i], view.WetY[i], view.WetZ[i]) + Vector3.Up * BloodRenderer.PatchLift;
|
||||
var t = _main.Blood.Patches[p++];
|
||||
Check(t.Origin.DistanceTo(want) < 1e-5f && Math.Abs(t.Basis.Scale.X - view.WetRadius[i]) < 1e-6f,
|
||||
$"patch {p - 1} is drawn at {t.Origin} radius {t.Basis.Scale.X}; lane {i} puts it at {want}, radius {view.WetRadius[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The knife leaves the camera's presses alone in every mode: with emulation off, and while a middle drag is under way, an Alt+left press cuts nothing.</summary>
|
||||
private async Task CheckAltGuard(Vector2 at)
|
||||
{
|
||||
var camera = _main.GetNode<OrbitCamera>("Camera");
|
||||
int cuts = _main.Cuts.Count;
|
||||
camera.Emulate3ButtonMouse = false;
|
||||
Click(at, alt: true);
|
||||
camera.Emulate3ButtonMouse = true;
|
||||
Check(_main.Cuts.Count == cuts, "an Alt+left press cut with camera emulation off");
|
||||
GetViewport().PushInput(new InputEventMouseButton { ButtonIndex = MouseButton.Middle, Pressed = true, Position = at, GlobalPosition = at, ButtonMask = MouseButtonMask.Middle }, true);
|
||||
Click(at, alt: true);
|
||||
Check(_main.Cuts.Count == cuts, "an Alt+left press cut during a middle drag");
|
||||
GetViewport().PushInput(new InputEventMouseButton { ButtonIndex = MouseButton.Middle, Pressed = false, Position = at, GlobalPosition = at }, true);
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>A left press and release at <paramref name="at"/> (viewport coordinates), pushed through the viewport like the mouse's.</summary>
|
||||
private void Click(Vector2 at, bool alt)
|
||||
{
|
||||
foreach (bool pressed in new[] { true, false })
|
||||
GetViewport().PushInput(new InputEventMouseButton { ButtonIndex = MouseButton.Left, Pressed = pressed, Position = at, GlobalPosition = at, AltPressed = alt, ButtonMask = pressed ? MouseButtonMask.Left : 0 }, inLocalCoords: true);
|
||||
}
|
||||
|
||||
private static bool Throws(Action a)
|
||||
{
|
||||
try { a(); return false; }
|
||||
catch (ObjectDisposedException) { return true; }
|
||||
}
|
||||
|
||||
private void CheckEngineAndScene()
|
||||
{
|
||||
Check(Engine.PhysicsTicksPerSecond == 120, $"physics ticks per second is {Engine.PhysicsTicksPerSecond}, not 120");
|
||||
Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot's 3D physics engine is not Dummy");
|
||||
Check(!_main.GetWorld3D().Space.IsValid, "Godot has a physics space");
|
||||
Check(Count(_main, n => n is CollisionObject3D || n.GetClass().StartsWith("Collision")) == 0, "Godot physics nodes are in the scene");
|
||||
Check(_main.IsPhysicsInterpolatedAndEnabled() && (bool)ProjectSettings.GetSetting("physics/common/physics_interpolation"), "physics interpolation is off");
|
||||
Check(_main.Seed == Seed, "Main did not start from the smoke's seed");
|
||||
|
||||
// The look: PS1. Every surface is the PS1 shader and the shader lights it (no Light3D), the quantising pass sits below the HUD, the
|
||||
// 3D has no MSAA, and ps1_res is the window over its block size.
|
||||
var ps1 = GD.Load<Shader>("res://ps1.gdshader");
|
||||
var meshes = _main.FindChildren("*", "MeshInstance3D", true, false).Cast<MeshInstance3D>().ToArray();
|
||||
Check(meshes.Length > 0 && meshes.All(m => m.MaterialOverride is ShaderMaterial sm && (sm.Shader == ps1 || sm.Shader.Code.EndsWith(ps1.Code))), "a mesh is not drawn with res://ps1.gdshader");
|
||||
Check(Count(_main, n => n is Light3D) == 0, "the scene has a Light3D; the shader lights it");
|
||||
Check(_main.GetNode<CanvasLayer>("Post").Layer < Hud.Layer, "the post pass does not sit below the HUD");
|
||||
Check((int)ProjectSettings.GetSetting("rendering/anti_aliasing/quality/msaa_3d", 0) == 0, "msaa_3d is on");
|
||||
int height = GetWindow().Size.Y, block = Math.Max(1, (int)Math.Round(height / (double)Look.Lines, MidpointRounding.AwayFromZero));
|
||||
Check(Math.Abs(_main.Ps1Res.Y - height / (float)block) < 1e-4f, $"ps1_res.y is {_main.Ps1Res.Y}, not {height} / {block}");
|
||||
Check(Look.Scenery.Luminance < 0.3f, "the floor is not dark");
|
||||
var glow = (Vector3)_main.Chamber.Material.GetShaderParameter("tint");
|
||||
Check(Math.Max(glow.X, Math.Max(glow.Y, glow.Z)) > 0.7f, $"the chamber is {glow}, not light");
|
||||
var environment = _main.GetChildren().OfType<WorldEnvironment>().Single().Environment;
|
||||
Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey");
|
||||
Check(environment.Sky is null && environment.TonemapMode == Godot.Environment.ToneMapper.Linear && !environment.GlowEnabled, "the environment is not a linear colour environment with no sky and no glow");
|
||||
}
|
||||
|
||||
/// <summary>Every body with a shape that Fella's skin does not draw has one primitive mesh, made once (the anchor has none); the skin is one surface, made once.</summary>
|
||||
private void CheckMeshBuilds(string when)
|
||||
{
|
||||
var view = Session.View;
|
||||
int shaped = 0;
|
||||
for (int i = 0; i < view.Count; i++) if ((Box3DSoaKind)view.Kind[i] != Box3DSoaKind.Anchor && SeatedPuppet.PartOf(view.StableId[i]) is null) shaped++;
|
||||
Check(_main.Bodies.MeshBuilds == shaped, $"{when}: {_main.Bodies.MeshBuilds} body meshes were made for {shaped} bodies with a shape the skin does not draw; a Reset makes none");
|
||||
Check(_main.Bodies.Skin.MeshBuilds == 1, $"{when}: the skin was built {_main.Bodies.Skin.MeshBuilds} times, not once");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fella's skin: every part of the plan owns vertices, and the copies of every joint-ring vertex are drawn together while the parts are joined.
|
||||
/// The ring-gap bound is in micrometres (lodur:ruling:deterministic-bound-zero-reading: a shipped zero counts as half a micrometre).
|
||||
/// </summary>
|
||||
private void CheckSkin(string when)
|
||||
{
|
||||
var skin = _main.Bodies.Skin;
|
||||
for (int part = 0; part < SeatedPuppet.Plan.Parts.Count; part++)
|
||||
Check(skin.OwnedVertices(part) > 0, $"{when}: part {part} ({SeatedPuppet.Plan.Parts[part].Label}) owns no skin vertices");
|
||||
double gap = skin.RingGap() * 1e6;
|
||||
Check(gap < RingGapMicrometres, $"{when}: joint-ring copies are drawn {gap:F1} micrometres apart (bound {RingGapMicrometres})");
|
||||
GD.Print($"SKIN {skin.VertexCount} vertices, ring gap {gap:F1} um, deform {skin.MedianDeformMicroseconds(1000):F1} us per frame (median of 1000, headless)");
|
||||
}
|
||||
|
||||
private void CheckPoses(string when)
|
||||
{
|
||||
var view = Session.View;
|
||||
Check(_main.Bodies.BodyCount == view.Count, $"{when}: {_main.Bodies.BodyCount} bodies drawn for {view.Count} lanes");
|
||||
for (int i = 0; i < view.Count; i++)
|
||||
{
|
||||
var id = view.StableId[i];
|
||||
if (_main.Bodies.PoseOf(id) is not { } pose) { Check(false, $"{when}: no body drawn for stable id {id}"); continue; }
|
||||
var want = new Vector3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]);
|
||||
Check(pose.Origin == want, $"{when}: body {id} at {pose.Origin}, lanes say {want}");
|
||||
var q = new Quaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i]);
|
||||
Check(Math.Abs(pose.Basis.GetRotationQuaternion().Dot(q)) > 0.99999, $"{when}: body {id} is rotated differently from its lane");
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckEvents(HeadlessRun reference, string what)
|
||||
{
|
||||
var got = _main.Events.Select(e => (e.Tick, e.Events)).ToList();
|
||||
var want = reference.Events.Select(e => (e.Tick, e.Events)).ToList();
|
||||
Check(want.Count > 0, $"{what}: the headless run reported no events");
|
||||
Check(got.SequenceEqual(want), $"{what}: events {Format(got)} differ from the headless run's {Format(want)}");
|
||||
}
|
||||
|
||||
private void CheckHand(HandSample want, string when)
|
||||
{
|
||||
var h = Session.Hand;
|
||||
Check(Bits(h.X) == Bits(want.X) && Bits(h.Y) == Bits(want.Y) && Bits(h.Z) == Bits(want.Z),
|
||||
$"hand at {when} ({h.X}, {h.Y}, {h.Z}) differs from the headless run ({want.X}, {want.Y}, {want.Z})");
|
||||
}
|
||||
|
||||
/// <summary>Presses the HUD's Reset with the seed typed in its seed box.</summary>
|
||||
private void PressReset(ulong seed)
|
||||
{
|
||||
Hud.SeedBox.Value = seed;
|
||||
Hud.ResetButton.EmitSignal(BaseButton.SignalName.Pressed);
|
||||
Check(_main.Seed == seed, $"Reset started seed {_main.Seed}, not {seed}");
|
||||
_lastSession = null;
|
||||
}
|
||||
|
||||
/// <summary>Waits one physics frame, and checks the session took exactly one step in the frame before it.</summary>
|
||||
private async Task Frame()
|
||||
{
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
|
||||
if (_main.Failure is { } failure) throw new InvalidOperationException(failure);
|
||||
var s = _main.Run;
|
||||
if (ReferenceEquals(s, _lastSession) && !s.Finished) Check(s.TickIndex == _lastTick + 1, $"{s.TickIndex - _lastTick} steps in one physics frame");
|
||||
_lastSession = s;
|
||||
_lastTick = s.TickIndex;
|
||||
}
|
||||
|
||||
private async Task Frames(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++) await Frame();
|
||||
}
|
||||
|
||||
private async Task UntilTick(long tick)
|
||||
{
|
||||
while (_main.Run.TickIndex < tick && !_main.Run.Finished) await Frame();
|
||||
}
|
||||
|
||||
/// <summary>Session steps per real second over the next <paramref name="milliseconds"/>.</summary>
|
||||
private async Task<double> StepsPerSecond(ulong milliseconds)
|
||||
{
|
||||
ulong t0 = Time.GetTicksMsec();
|
||||
long tick0 = Session.TickIndex;
|
||||
while (Time.GetTicksMsec() - t0 < milliseconds) await Frame();
|
||||
return (Session.TickIndex - tick0) * 1000.0 / (Time.GetTicksMsec() - t0);
|
||||
}
|
||||
|
||||
private readonly record struct HeadlessRun(List<BodyEvent> Events, List<HandSample> Hand, double Pain, double Strain);
|
||||
|
||||
/// <summary>The same run without Godot: stepped until <paramref name="ticks"/> or the end, events drained as the client does.</summary>
|
||||
private static HeadlessRun Run(double intensity, ulong seed, long ticks)
|
||||
{
|
||||
using var s = new BodyPainBoxSession(Main.ParametersFor(intensity), seed);
|
||||
var events = new List<BodyEvent>();
|
||||
var hand = new List<HandSample>();
|
||||
var buffer = new BodyEvent[8];
|
||||
while (s.TickIndex < ticks && !s.Finished)
|
||||
{
|
||||
s.Step();
|
||||
hand.Add(s.Hand);
|
||||
int n;
|
||||
while ((n = s.DrainEvents(buffer)) > 0) events.AddRange(buffer.Take(n));
|
||||
}
|
||||
return new HeadlessRun(events, hand, s.Pain, s.Strain);
|
||||
}
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
if (_done) return;
|
||||
_done = true;
|
||||
foreach (var f in _failures) GD.PrintErr("SMOKE FAIL: " + f);
|
||||
GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})");
|
||||
GetTree().Quit(_failures.Count == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
private void Check(bool ok, string failure)
|
||||
{
|
||||
if (!ok) _failures.Add(failure);
|
||||
}
|
||||
|
||||
private static string Format(List<(long Tick, Lodur.TickEvents Events)> events) =>
|
||||
string.Join(",", events.Select(e => $"{e.Tick}:{e.Events}"));
|
||||
|
||||
private static uint Bits(float f) => BitConverter.SingleToUInt32Bits(f);
|
||||
|
||||
private static int Count(Node root, Func<Node, bool> match)
|
||||
{
|
||||
int n = match(root) ? 1 : 0;
|
||||
foreach (var child in root.GetChildren()) n += Count(child, match);
|
||||
return n;
|
||||
}
|
||||
}
|
||||
6
client/tests/Smoke.tscn
Normal file
6
client/tests/Smoke.tscn
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://tests/Smoke.cs" id="1"]
|
||||
|
||||
[node name="Smoke" type="Node"]
|
||||
script = ExtResource("1")
|
||||
101
client/tests/render-mutants.sh
Normal file
101
client/tests/render-mutants.sh
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
#!/usr/bin/env bash
|
||||
# Breaks the shipped look once per claim of RenderCheck and wants that claim's line to fail. Each mutant is one set of edits, each of which must
|
||||
# apply exactly once; the file is restored whatever happens (the end, a failed edit or build, an interrupt: a trap restores it once the build or check in flight returns, and a leftover .orig
|
||||
# from a run that died harder is refused at the start). Needs a window (RenderCheck draws). Run from anywhere:
|
||||
# GODOT=<godot console exe> bash client/tests/render-mutants.sh # every claimed mutant must fail its own line
|
||||
# GODOT=<godot console exe> UNCLAIMED=1 bash client/tests/render-mutants.sh # the unclaimed ones below must still pass (their readings are the record)
|
||||
# ONLY="name name" bash client/tests/render-mutants.sh # just those mutants
|
||||
# A mutant's edits are old@@old|new@@new pairs in one file; the line it must fail is the RenderCheck check named in its last field.
|
||||
#
|
||||
# Readings (shipped / mutant) of the claims, from RenderCheck's bounds, which sit at the geometric midpoint of shipped worst and least mutant
|
||||
# (lodur:ruling:deterministic-bound-margin); a zero reading is counted as lodur:ruling:deterministic-bound-zero-reading says (shipped 0 as half a unit, mutant 0 as one, then the geometric mean).
|
||||
# The dither line reads three flat fields that hold every threshold of the 4x4 matrix, so the 2x2 matrix and the transposed one fail it; the fog line probes
|
||||
# 6, 9 and 12 m against the literals 4 and 14 m, so a linear ramp and changed FogNear or FogFar fail it. Round-to-nearest in the post pass fails the dither line.
|
||||
#
|
||||
# UNCLAIMED, recorded as the ruling requires (no RenderCheck line separates them; the mutants are in UNCLAIMED below):
|
||||
# fog-per-pixel: fog from the interpolated view depth, in the fragment, instead of per vertex. The fog probe is a quad at one depth, where the
|
||||
# two agree to the bit; a surface spanning FogNear to FogFar would separate them (smoothstep of the depth against the blend of the corners'
|
||||
# smoothsteps, about 20 levels at the quarter point), but ps1.js's per-vertex fog is not among the claims the cut was ordered to guard.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
GODOT="${GODOT:-F:/Applications/Godot_v4.7.2-stable_mono_win64/Godot_v4.7.2-stable_mono_win64_console.exe}"
|
||||
|
||||
# name | file | old@@old | new@@new | the RenderCheck line it must fail
|
||||
MUTANTS=(
|
||||
'post-off|ps1_post.gdshader|COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0);|COLOR = vec4(c / 255.0, 1.0);|15-bit'
|
||||
'twelve-bit|ps1_post.gdshader|COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0);|COLOR = vec4(floor(c / 16.0) * 16.0 / 255.0, 1.0);|15-bit'
|
||||
'dither-off|ps1_post.gdshader|c = clamp(c + D[q.x][q.y], 0.0, 255.0);|c = clamp(c, 0.0, 255.0);|dither'
|
||||
'dither-bayer2|ps1_post.gdshader|const mat4 D = mat4(vec4(-4., 0., -3., 1.), vec4(2., -2., 3., -1.), vec4(-3., 1., -4., 0.), vec4(3., -1., 2., -2.));|const mat4 D = mat4(vec4(-4., 0., -4., 0.), vec4(2., -2., 2., -2.), vec4(-4., 0., -4., 0.), vec4(2., -2., 2., -2.));|dither'
|
||||
'dither-transposed|ps1_post.gdshader|c = clamp(c + D[q.x][q.y], 0.0, 255.0);|c = clamp(c + D[q.y][q.x], 0.0, 255.0);|dither'
|
||||
'post-rounds|ps1_post.gdshader|COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0);|COLOR = vec4(floor(c / 8.0 + 0.5) * 8.0 / 255.0, 1.0);|dither'
|
||||
'block-off|ps1_post.gdshader|textureLod(screen_tex, (size * 0.5 + (b + 0.5) * s) / size, 0.0)|textureLod(screen_tex, SCREEN_UV, 0.0)|blocks'
|
||||
'lines-360|Look.cs|public const int Lines = 240;|public const int Lines = 360;|lines'
|
||||
'lines-120|Look.cs|public const int Lines = 240;|public const int Lines = 120;|lines'
|
||||
'snap-off|ps1.gdshader|if (clip.w > 0.05) {|if (false) {|snap'
|
||||
'perspective-uv|ps1.gdshader|auv = vec3(uv * clip.w, clip.w);|auv = vec3(uv, 1.0);|affine'
|
||||
'per-pixel-light|ps1.gdshader|varying vec3 light;@@light = emissive ? vec3(1.0) : ps1_ambient + ps1_key_color * max(dot(n, ps1_key_dir), 0.0) + glow;@@vec3 c = texture(albedo_tex, auv.xy / auv.z).rgb * tint * light;|varying vec3 light; varying vec3 nrm;@@nrm = n; light = vec3(1.0);@@vec3 c = texture(albedo_tex, auv.xy / auv.z).rgb * tint * (emissive ? vec3(1.0) : ps1_ambient + ps1_key_color * max(dot(normalize(nrm), ps1_key_dir), 0.0));|light'
|
||||
'fog-off|ps1.gdshader|fog = smoothstep(ps1_fog_near, ps1_fog_far, -mv.z);|fog = 0.0;|fog'
|
||||
'fog-linear|ps1.gdshader|fog = smoothstep(ps1_fog_near, ps1_fog_far, -mv.z);|fog = clamp((-mv.z - ps1_fog_near) / (ps1_fog_far - ps1_fog_near), 0.0, 1.0);|fog'
|
||||
'fog-far-18|Look.cs|FogNear = 4f, FogFar = 14f;|FogNear = 4f, FogFar = 18f;|fog'
|
||||
'fog-near-6|Look.cs|FogNear = 4f, FogFar = 14f;|FogNear = 6f, FogFar = 14f;|fog'
|
||||
'fog-centred-wide|Look.cs|FogNear = 4f, FogFar = 14f;|FogNear = 2f, FogFar = 16f;|fog'
|
||||
'mipmapped|ps1.gdshader|filter_nearest, repeat_enable|filter_nearest_mipmap, repeat_enable|mips'
|
||||
'linear-filter|ps1.gdshader|filter_nearest, repeat_enable|filter_linear, repeat_enable|mips'
|
||||
'glow-unset|Chamber.cs|Look.GlowLightEnergy * glow|0f|glow'
|
||||
'carrier-unposed|BodyRenderer.cs|node.Transform = new Transform3D(new Basis(new Quaternion(rx[i]|_ = new Transform3D(new Basis(new Quaternion(rx[i]|figure at lanes'
|
||||
'fella-primitives|BodyRenderer.cs|SeatedPuppet.PartOf(ids[i]) is null && PrimitiveOf(|PrimitiveOf(|neck'
|
||||
'skin-lopsided|FellaSkin.cs|positions.Add(v[i]);|positions.Add(v[i].X > 0f ? new Vector3(1.5f * v[i].X, v[i].Y, v[i].Z) : v[i]);|symmetry'
|
||||
'skin-unposed|FellaSkin.cs|is { } pose) _skin[p] = pose * _inverseCreation[p];|is { } pose) _skin[p] = Transform3D.Identity;|figure at lanes'
|
||||
)
|
||||
|
||||
UNCLAIMED_MUTANTS=(
|
||||
'fog-per-pixel|ps1.gdshader|fog = smoothstep(ps1_fog_near, ps1_fog_far, -mv.z);@@c = mix(c, ps1_fog_color, fog);|fog = -mv.z;@@c = mix(c, ps1_fog_color, smoothstep(ps1_fog_near, ps1_fog_far, fog));|'
|
||||
)
|
||||
|
||||
ACTIVE=""
|
||||
restore() {
|
||||
if [ -n "$ACTIVE" ] && [ -f "$ACTIVE.orig" ]; then mv -f "$ACTIVE.orig" "$ACTIVE"; touch "$ACTIVE"; fi
|
||||
ACTIVE=""
|
||||
}
|
||||
trap restore EXIT
|
||||
trap 'restore; exit 130' INT TERM
|
||||
|
||||
left="$(find . -maxdepth 1 -name '*.orig')"
|
||||
if [ -n "$left" ]; then echo "an earlier run died with its edit in place: restore these from their .orig first: $left"; exit 2; fi
|
||||
|
||||
status=0
|
||||
if [ "${UNCLAIMED:-}" = 1 ]; then LIST=("${UNCLAIMED_MUTANTS[@]}"); else LIST=("${MUTANTS[@]}"); fi
|
||||
for m in "${LIST[@]}"; do
|
||||
IFS='|' read -r name file old new want <<<"$m"
|
||||
if [ -n "${ONLY:-}" ] && [[ " $ONLY " != *" $name "* ]]; then continue; fi # ONLY="name name": just those
|
||||
cp "$file" "$file.orig"
|
||||
ACTIVE="$file"
|
||||
if ! python - "$file" "$old" "$new" <<'PY'
|
||||
import sys
|
||||
path, old, new = sys.argv[1:4]
|
||||
raw = open(path, newline='').read()
|
||||
text = raw.replace('\r\n', '\n')
|
||||
olds, news = old.split('@@'), new.split('@@')
|
||||
if len(olds) != len(news):
|
||||
sys.exit("old and new have different numbers of edits")
|
||||
for o, n in zip(olds, news):
|
||||
if text.count(o) != 1:
|
||||
sys.exit(f"{path}: the edit {o!r} applies {text.count(o)} times, not once")
|
||||
text = text.replace(o, n)
|
||||
open(path, 'w', newline='').write(text.replace('\n', '\r\n') if '\r\n' in raw else text)
|
||||
PY
|
||||
then restore; echo "MUTANT $name: edit did not apply once; aborting"; exit 2; fi
|
||||
build="$(dotnet build BadDay.Client.csproj 2>&1)"
|
||||
if ! grep -q "Build succeeded" <<<"$build"; then restore; echo "MUTANT $name: does not build; aborting"; exit 2; fi
|
||||
out="$("$GODOT" --path . res://tests/RenderCheck.tscn 2>&1)"
|
||||
restore
|
||||
readings="$(grep '^RENDER ' <<<"$out" | grep -v 'FAIL\|PASS\|FAILED' | sed 's/^RENDER //' | tr '\n' ';')"
|
||||
if [ "${UNCLAIMED:-}" = 1 ]; then
|
||||
if grep -q "^RENDER PASS" <<<"$out"; then echo "UNCLAIMED $name: RENDER PASS as recorded [$readings]"
|
||||
else echo "UNCLAIMED $name: something fails now, so it is claimed by that line; move it [$(grep '^RENDER FAIL' <<<"$out" | tr '\n' ';')]"; status=1; fi
|
||||
elif grep -q "^RENDER FAIL $want:" <<<"$out"; then echo "MUTANT $name: fails '$want' as wanted [$readings]"
|
||||
else echo "MUTANT $name: DOES NOT FAIL '$want' [$readings]"; status=1; fi
|
||||
done
|
||||
build="$(dotnet build BadDay.Client.csproj 2>&1)"
|
||||
grep -q "Build succeeded" <<<"$build" || { echo "the shipped code does not build after the run"; status=1; }
|
||||
exit $status
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Pain sweep: time to break over intensity and suppression
|
||||
|
||||
`tools/PainSweep/Program.cs` runs the pain box puppet over a grid of box
|
||||
`tools/PainSweep/Program.cs` runs the Synaptic Induction Chamber (the pain box) puppet over a grid of box
|
||||
intensity (rows) and withdrawal-reflex suppression strength (columns,
|
||||
`PainBoxParameters.MaxSuppression`: the largest fraction of the reflex the will
|
||||
`PainBoxParameters.Reflex.MaxSuppression`: the largest fraction of the reflex the will
|
||||
can hold down). It is engine-free and deterministic; the same build prints the
|
||||
same table.
|
||||
|
||||
|
|
@ -10,7 +10,7 @@ same table.
|
|||
|
||||
Each cell is the median time-to-break in seconds over 9 consecutive seeds (1..9;
|
||||
seeds vary nociceptor gain, resolve drain and stimulus jitter). Everything else
|
||||
is at its default, including objective pull 0.5 and a 120 s limit.
|
||||
is at its default, including the volunteer's $100 payment (pull 0.5) and a 120 s limit.
|
||||
|
||||
- `never`: no seed's will broke within 120 s. This is a result, not an error.
|
||||
- `95.4(8/9)`: only 8 of 9 seeds broke; the median is over those 8, so it
|
||||
|
|
@ -39,16 +39,13 @@ Is time-to-break the right measure? It collapses a whole run to one number and
|
|||
treats "never" as an outcome of equal weight to "late". Candidates: time to
|
||||
first flinch, flinch count, area under the pain curve before the hand leaves,
|
||||
peak strain, or the fraction of seeds that break by a deadline. Which one says
|
||||
what a player should feel?
|
||||
what a player should feel? The open question is `lodur:question:pain-sweep-measure`.
|
||||
|
||||
## Build and run (no `dotnet restore`)
|
||||
## Build and run
|
||||
|
||||
```
|
||||
D=/opt/commons/opt/dotnet; REF=$D/packs/Microsoft.NETCore.App.Ref/10.0.14/ref/net10.0
|
||||
dotnet $D/sdk/10.0.403/Roslyn/bincore/csc.dll -nologo -nullable:enable -target:exe \
|
||||
-out:$TMPDIR/painsweep/PainSweep.dll -noconfig -nostdlib+ $(for f in $REF/*.dll; do echo -n "-r:$f "; done) \
|
||||
src/BadDay.Core/*.cs tools/PainSweep/Program.cs
|
||||
printf '{"runtimeOptions":{"tfm":"net10.0","framework":{"name":"Microsoft.NETCore.App","version":"10.0.14"}}}' \
|
||||
> $TMPDIR/painsweep/PainSweep.runtimeconfig.json
|
||||
dotnet $TMPDIR/painsweep/PainSweep.dll
|
||||
dotnet run --project tools/PainSweep
|
||||
```
|
||||
|
||||
The project references `BadDay.Core` and through it the sibling Lodur checkout (`LODUR_ROOT`, else
|
||||
`..\Lodur`); it needs no Ymir and no native build.
|
||||
|
|
|
|||
278
docs/scenarios/fella-bad-day-at-the-office.md
Normal file
278
docs/scenarios/fella-bad-day-at-the-office.md
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
# Scenario: Fella's bad day at the office
|
||||
|
||||
Status: **design, not built.** Every number below is a **placeholder** (marked `[P]`) chosen so the shape is
|
||||
readable; none is measured physiology or tuned play. Nothing here is canon until the designer rules.
|
||||
|
||||
Concept: Meta, 2026-11-06. The protagonist's name, **Fella**, is by **Deru**.
|
||||
|
||||
Built on the first slice: the Synaptic Induction Chamber (the pain box) (`PainBoxSimulation`, merged in
|
||||
[GameCult/BadDaySimulator#1](https://eureka.gamecult.org/forge/GameCult/BadDaySimulator/pulls/1)) and its sweep,
|
||||
[`docs/pain-sweep.md`](https://eureka.gamecult.org/forge/GameCult/BadDaySimulator/src/branch/main/docs/pain-sweep.md).
|
||||
Layer and invariant names (`drive-is-state`,
|
||||
`reflex-gain-from-drive`, `body-one-interface`, `content-is-cultcache`) are Lodur's
|
||||
([`docs/lodur-target.md`](https://eureka.gamecult.org/forge/GameCult/Lodur/src/branch/main/docs/lodur-target.md)).
|
||||
|
||||
## The ladder
|
||||
|
||||
Meta's build order (2026-11-06): one system at a time, then connect, then full fat. Fella's whole bad day is the
|
||||
top rung, not the first thing built. Each rung is demonstrable alone and measured before the next starts.
|
||||
|
||||
| Rung | What runs | Status |
|
||||
|---|---|---|
|
||||
| 1 | A Ymir body stands, falls and rests deterministically, read through the SoA view | merged (Ymir #2, Lodur #2) |
|
||||
| 2 | One withdrawal reflex; time-to-break may be the main metric | built as the pain box, on Lodur's Actor; connected to rung 1: the pain box runs on the Ymir ragdoll (`baddaysim run --body`) |
|
||||
| 3 | Sensory load drives the stress bar | built headless: `baddaysim office` and `office-sweep` (README, the office stress scenario) |
|
||||
| 4 | The goal flip, alone: the Brain authors the goals, the Actor commits the switch | built: the chamber's volunteer is paid and withdraws (`baddaysim run --pay`, pull = pay / (pay + $100), $100 pulls 0.5), and Office Fella snaps, rages on a refilled will, drains, and settles calm for good (`baddaysim office --body`); the rage is a geyser, not the design below |
|
||||
| 5 | Fatigue and limb failure (jelly), alone | not built |
|
||||
| 6 | One coworker, one personality axis | not built |
|
||||
| 7 | Fella's whole bad day (this document) | design only |
|
||||
|
||||
A rung may use only what lower rungs built. Black Knight is an idea after rung 5, not a rung.
|
||||
|
||||
## Setting and cause
|
||||
|
||||
BDS is the whole space of bad days, not the office (Meta, 2026-11-06): the park, a factory, driving, resting at
|
||||
home with a medical condition, and more. So a scenario is three things that vary independently, and neither the
|
||||
engine nor the scenario schema may hard-code any of them:
|
||||
|
||||
- **Setting**: where and with what. Place and geometry, objects and fixtures, ambient conditions, who else is
|
||||
present, and the *emitters* in that place (a printer, a ceiling light, a phone) by stable id. A setting knows
|
||||
nothing about why the day is bad.
|
||||
- **Cause**: why it is a bad day. The time-varying drivers that act on the actor (stressors, injuries, threats,
|
||||
symptoms, deadlines), the break condition, and the goal flip it triggers. A cause refers to the setting's
|
||||
emitters by id and to the actor's drive by name; it knows nothing about the room.
|
||||
- **Fella** is a role filled by an actor document (traits, drive parameters, rig), not a hard-coded character:
|
||||
any actor can be Fella, and the engine never tests for the name.
|
||||
|
||||
| Setting | Cause | Reads as |
|
||||
|---|---|---|
|
||||
| office | accumulating sensory load | this document |
|
||||
| factory floor | a machine fault and an injury | pain and impairment drive, no stress bar |
|
||||
| car | a deadline and traffic | threat and time pressure |
|
||||
| home, resting | a medical condition flaring | symptoms, fatigue; no coworkers needed |
|
||||
|
||||
The rest of this document is one pairing: the office setting with the sensory-load cause. Where a later section
|
||||
says "stressor", "stress bar" or "Smash", that is this cause's content, authored as data in the cause document,
|
||||
not engine behaviour.
|
||||
|
||||
## The story in two phases
|
||||
|
||||
1. **Composure.** Fella is at work, holding it together while the office keeps adding sensory load: noise,
|
||||
flicker, interruptions, crowding. The player (or a schedule) is the source of stress; Fella's job is to
|
||||
not break. The stress bar fills.
|
||||
2. **Full ape mode.** When the bar breaks, Fella's goals do not drift, they **flip entirely**: composure no longer
|
||||
matters, nothing matters except smashing everything within reach with fists. The question phase 2 asks:
|
||||
**how long does the smashing hold while the limbs turn to jelly?** Coworkers react throughout, each by
|
||||
personality.
|
||||
|
||||
The pain box already has this shape in miniature: a will drains under a stimulus, and when resolve reaches zero
|
||||
the goal flips (`HoldHand` to `Withdraw`). Fella reuses that mechanism instead of adding a second one. Her
|
||||
composure **is** the drive's resolve; her sensory load **is** stimulus into the nerve layer, with the same
|
||||
sensitisation (a loaded Fella notices more, which is what "overload" means mechanically).
|
||||
|
||||
## 1. The scenario as authored data
|
||||
|
||||
Scenario content is CultCache documents (`content-is-cultcache`). The tables below name the fields; they are
|
||||
the shape of the documents, not a JSON format. A scenario document references setting, cause and actor
|
||||
documents by stable id; it contains no behaviour.
|
||||
|
||||
**Scenario** (one document): `id`, `seed` (the only randomness, SplitMix64 as in the pain box), `setting`
|
||||
(reference), `cause` (reference), `actor` (reference; the Fella role), `endConditions`, `testHooks`.
|
||||
|
||||
**Setting** (one document): `id`, `place` (geometry and fixtures), `emitters` (id, kind, position: the printer,
|
||||
the ceiling light, the phone), `ambient`, `present` (coworker references). No schedule, no thresholds.
|
||||
|
||||
**Cause** (one document): `id`, `drivers` (here the stressor schedule below, each referring to a setting emitter
|
||||
or a coworker by id), `breakCondition`, `flip` (the actor state change), `driveMapping` (which actor drive state
|
||||
each driver feeds: for sensory load, `resolve`). Swap the cause and the same setting gives a different day; swap
|
||||
the setting and the same cause plays somewhere else.
|
||||
|
||||
**Phases** are derived from actor state, not from a clock: phase 1 is "goal is KeepComposure", phase 2 is "goal
|
||||
is Smash". There is no phase variable to desync.
|
||||
|
||||
| Field | Phase 1: Composure | Phase 2: Ape |
|
||||
|---|---|---|
|
||||
| Actor goal | `KeepComposure` (objective pull `[P] 0.6`) | `Smash` (pull 1.0) |
|
||||
| Reflex gain | startle and flinch suppressed by resolve, strain accrues | suppression released; startle becomes strike |
|
||||
| Muscle strength | 1.0 | `[P] 1.4` at the flip, then jelly decay (below) |
|
||||
| Stress bar | fills from stressors | frozen; irrelevant |
|
||||
| Ends when | break, or end of schedule (outcome `Endured`) | nothing smashable in reach, or strength below the effective floor |
|
||||
|
||||
### Stressor schedule
|
||||
|
||||
These rows are the cause document's `drivers`; the sources named are the setting's emitters.
|
||||
|
||||
A stressor is a document: `id`, `channel` (`audio`, `visual`, `interrupt`, `proximity`), `source` (an object or a
|
||||
coworker id), `region` (ears, eyes, torso), `onsetSeconds`, `rampSeconds`, `intensity` (0..1), `durationSeconds`,
|
||||
`repeat` (period, or none), `jitter` (seeded fraction). Channels are summed with a saturating curve so the
|
||||
tenth beep matters less than the first but a second channel still adds (`[P]` shape: `1 - prod(1 - i_c)`).
|
||||
|
||||
| id | channel | source | onset | intensity | note (all `[P]`) |
|
||||
|---|---|---|---|---|---|
|
||||
| `printer-jam-beep` | audio | printer | 5 s, repeats 8 s | 0.25 | thin, regular, can be silenced by the player |
|
||||
| `fluorescent-flicker` | visual | ceiling | 15 s, repeats 11 s | 0.2 | |
|
||||
| `desk-phone` | audio | phone | 25 s, repeats 14 s | 0.35 | stops if answered (Fella can pick it up) |
|
||||
| `chatty-neighbour` | interrupt | coworker `gossip` | 30 s | 0.3 | emitted by that coworker's behaviour, not a timer |
|
||||
| `standup-crowd` | proximity | 4 coworkers | 60 s | 0.4 | scales with coworkers in range |
|
||||
| `boss-email-ping` | interrupt | desktop | 75 s, repeats 20 s | 0.3 | |
|
||||
|
||||
The schedule is data: add, remove or retime a row and the scenario changes. Sources that are coworkers emit by
|
||||
behaviour, so a stressor can start or stop because of what a coworker decides.
|
||||
|
||||
### Break condition
|
||||
|
||||
`resolve <= 0`, the drive's own value. Pain-box rule, unchanged: resolve drains with sensory load and strain
|
||||
(holding startle down), scaled by `(1 - objectivePull)`, and recovers only when load is low. So quiet gaps
|
||||
matter, and a player can silence stressors to extend phase 1. No separate "stress bar" state exists; the bar the
|
||||
player sees is arousal, not resolve (ruling `lodur:ruling:stress-bar-shows-arousal-calm-silences`).
|
||||
|
||||
If the schedule ends with resolve above zero the outcome is `Endured` and phase 2 never runs. For testing
|
||||
phase 2 alone, `testHooks.forceBreakAtSeconds` flips Fella at a fixed time (a test hook, not a game feature).
|
||||
|
||||
### The goal flip as an actor state change
|
||||
|
||||
The flip is one typed state transition, emitted as one event, `GoalFlipped { actor, from, to, tick }`. Nothing
|
||||
else in the engine special-cases the break: everything downstream reads actor state.
|
||||
|
||||
| State | Before | After |
|
||||
|---|---|---|
|
||||
| `goal` | `KeepComposure` | `Smash` |
|
||||
| goal weights | composure `[P] 1.0`, others per author | every weight 0 except `Smash`; a survival floor `[P] 0.1` keeps Fella from stepping off a ledge |
|
||||
| objective pull | `[P] 0.6` | 1.0 |
|
||||
| reflex gain from drive | suppression by resolve | suppression 0 (`reflex-gain-from-drive`: drive sets the gain) |
|
||||
| adrenaline | baseline | spike `[P] 1.0`, decaying |
|
||||
| target selector | off | on: nearest breakable object or fixture in reach, re-picked as things are destroyed |
|
||||
| behaviour set | work, fidget, flinch | `Strike`, `Advance`, `Stagger` (limbs failing) |
|
||||
|
||||
Because the transition is drive state and not an authored cutscene, other scenarios can reuse it (a different
|
||||
actor, a different trigger).
|
||||
|
||||
### Jelly limbs
|
||||
|
||||
The body layer takes per-muscle strength (`body-one-interface`), so jelly is strength, not damage. Each limb
|
||||
group has `strength` in 0..1, scaled by adrenaline and drained by effort: `strength -= effortDrain * work(strike
|
||||
impulse)` per strike, with slow recovery in lulls, plus an adrenaline-crash term that bites after the spike
|
||||
decays (`[P]` rates). Fine control goes first: forearm and wrist strength fall before shoulders, so punches
|
||||
land late, wide, then weakly. At `strength < [P] 0.25` a strike no longer breaks an object (the effective floor);
|
||||
below `[P] 0.1` the arm will not lift. The scenario ends phase 2 at no smashable target left or all arms below
|
||||
the floor, and records which one ended it.
|
||||
|
||||
## 2. Measurable outputs per phase
|
||||
|
||||
Deru's open question (`docs/pain-sweep.md`) is whether time-to-break is the right measure. Our answer: it is one
|
||||
number from a run, and "never" is censored data, not a value. So report a **distribution and a margin**, plus
|
||||
per-phase quantities that say what a player would feel. Recommendation, not a ruling, with low confidence until
|
||||
a player has felt both candidate sets.
|
||||
|
||||
Outputs are computed from the timeline and the contact facts; none is a state the simulation reads.
|
||||
|
||||
**Phase 1 (composure)**
|
||||
- `timeToFirstFlinch`, `flinchCount`, `flinchRate` over the last 30 s before the break.
|
||||
- `sensoryLoadIntegral`: area under the combined load before the break or the end.
|
||||
- `peakStrain` and `strainIntegral` (the cost of holding it together).
|
||||
- `composureMargin`: minimum resolve reached when the run did not break; how close it came.
|
||||
- `drainShare` per stressor channel and source: which stressor cost the most resolve.
|
||||
- `silenceUsed`: stressors the player or Fella removed, and the resolve regained in lulls.
|
||||
- `timeToBreak`, with the outcome (`WillBroke`, `Endured`), reported as a survival curve over a seed batch
|
||||
(fraction broken by 30, 60, 90 s), never a bare median.
|
||||
|
||||
**Phase 2 (ape)**
|
||||
- `timeToFirstStrike` (flip to first impact) and `strikesLanded`.
|
||||
- `objectsDestroyed` and `impulseDelivered` (sum of impact impulse, from contact facts).
|
||||
- `effectivenessCurve`: fraction of strikes that break their target, by 5 s windows.
|
||||
- `jellyOnsetSeconds`: time until the first limb group is under `[P] 0.5` strength.
|
||||
- `holdingTimeSeconds`: flip to the last effective blow; the headline phase-2 number.
|
||||
- `endReason`: `NoTargets`, `StrengthFloor`, or `Interrupted` (coworker restrained Fella). This one matters:
|
||||
holding time that ends for lack of targets says nothing about jelly.
|
||||
- `collateral`: coworkers struck, and objects broken that were not the nearest.
|
||||
|
||||
**Both**: `coworkerOutcomes` per coworker (see section 3): reaction taken, first-reaction latency, distance
|
||||
kept, whether it changed the phase-1 stress load or phase-2 end reason.
|
||||
|
||||
## 3. Coworker personality as data
|
||||
|
||||
A coworker is a document: `id`, `body` (same rig as any puppet), `axes` (below), `stressorsEmitted`, and
|
||||
behaviour weights. As elsewhere in Lodur (`drive-is-state`), a coworker does not run a per-personality lookup of
|
||||
"if X then Y": the axes set the weights of one shared behaviour selection over the coworker's own drive and
|
||||
what it perceives of Fella.
|
||||
|
||||
Axes, each 0..1 (`[P]` set; add or drop as play teaches):
|
||||
|
||||
| Axis | Low | High |
|
||||
|---|---|---|
|
||||
| `courage` | freezes, flees | steps toward the threat |
|
||||
| `empathy` | indifferent | tries to help or comfort |
|
||||
| `assertiveness` | defers, silent | commands, de-escalates, restrains |
|
||||
| `reactivity` | slow to register Fella | notices the first flinch and spreads it |
|
||||
| `contagion` | own composure unaffected | own resolve drains with Fella's visible strain |
|
||||
|
||||
Reaction catalogue (behaviours, selected by weight; weights are per-document `[P]`): `ignore`, `freeze`, `flee`,
|
||||
`hide`, `film` (a stressor, see below), `soothe`, `command`, `intervene`, `restrain`, `join_in` (contagion
|
||||
break). Example weights for the five authored archetypes in this scenario (`[P]`):
|
||||
|
||||
| Coworker | courage | empathy | assertiveness | reactivity | contagion | likely reaction |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `gossip` | 0.3 | 0.4 | 0.2 | 0.9 | 0.5 | films, spreads it, emits `chatty-neighbour` |
|
||||
| `manager` | 0.6 | 0.3 | 0.9 | 0.5 | 0.2 | commands; stays near in phase 1 (extra load), restrains in 2 |
|
||||
| `intern` | 0.1 | 0.6 | 0.1 | 0.6 | 0.8 | freezes, then flees; may break too |
|
||||
| `friend` | 0.7 | 0.9 | 0.4 | 0.8 | 0.3 | soothes in phase 1; intervenes in phase 2 |
|
||||
| `bystander` | 0.2 | 0.2 | 0.2 | 0.2 | 0.1 | ignores until a thing flies at them |
|
||||
|
||||
Coworkers feed the scenario through three authored paths only: stressors they emit, perceived-load changes
|
||||
(proximity), and phase-2 `restrain` or `intervene`. Anything else they do is visible but must not alter Fella's
|
||||
resolve, so the personality effect can be isolated in testing.
|
||||
|
||||
## 4. What Lodur and Ymir must expose
|
||||
|
||||
Lodur (all under Lodur's layer rules; the nervous layers and the hold stand-in exist, and none of what follows is built):
|
||||
- Actor drive state readable and writable per tick: `resolve`, `adrenaline`, per-limb-group `strength`, `goal`,
|
||||
goal weights, objective pull. The goal as first-class state with a typed `GoalFlipped` event.
|
||||
- Perception of non-contact stimuli by channel and region (audio, visual, interrupt, proximity), feeding the same
|
||||
nerve and sensitisation layer as the pain box's contact stimulus.
|
||||
- Reflex gain set from drive, including a mapping from startle to strike when suppression is released.
|
||||
- A strike behaviour with a target selector over breakables in reach, emitting body targets and per-muscle
|
||||
strength (`body-one-interface`), never joints or forces.
|
||||
- A fatigue model for per-muscle strength (effort drain, recovery, adrenaline crash), deterministic and
|
||||
allocation-free per tick (`bounded-tick`).
|
||||
- Coworker perception of another actor's visible state (strain, flinch, goal) and the shared behaviour
|
||||
selection weighted by axes.
|
||||
|
||||
Ymir (the pinned-Box3D boundary, `GameCult/Ymir`). The SoA world is merged (Ymir #2) with capsule and box
|
||||
bodies, spheres, joints with state lanes (angle, speed, rotation), per-body force and torque write lanes, an
|
||||
in-place state view and same-input same-bits stepping; Lodur's ragdoll and the pain box on it run on that.
|
||||
Still missing:
|
||||
- Contact facts per body pair with relative speed (the planar session has Begin/Hit/End; the 3D SoA world has
|
||||
none) to compute impact impulse for `impulseDelivered` and breaking.
|
||||
- Breakable objects: a break threshold on a joint or weld, or removal of a body on a destroy call. The SoA
|
||||
world has a fixed capacity and no removal.
|
||||
- Joint springs, for stiff limbs without explicit PD torques.
|
||||
- An id convention for actors and objects: the SoA world carries a StableId lane, so ids exist; scenario
|
||||
documents still need BDS to allocate and name them.
|
||||
|
||||
## 5. Three tuning checks
|
||||
|
||||
Each can run headless in the style of the pain-sweep and fails loudly.
|
||||
|
||||
1. **Phase 1 is monotone and seeded.** For seeds 1..50, raising a stressor's intensity or adding a stressor never
|
||||
lengthens the median time-to-break, and removing all stressors never breaks. The default scenario breaks for
|
||||
at least 80% of seeds within the schedule (`[P]`: window 90 s) and the 50-seed survival curve is not a step
|
||||
(the 10th and 90th percentile of break time differ by more than `[P] 20%`), or the scenario cannot
|
||||
discriminate players. The same seed reproduces the timeline byte for byte.
|
||||
2. **Phase 2 ends for the stated reason.** Force the break at fixed times over a grid of jelly drain rate and
|
||||
target supply (few, many). With plenty of targets, `holdingTimeSeconds` falls monotonically as drain rises
|
||||
and `endReason` is `StrengthFloor`; with few targets and slow drain, `endReason` is `NoTargets` and holding
|
||||
time does not move with drain. If holding time is insensitive to the drain at plentiful targets, the jelly
|
||||
model does nothing and the check fails.
|
||||
3. **Personality separates and stays isolated.** With the schedule fixed, set each coworker axis to 0 and to 1
|
||||
in turn: each setting changes that coworker's reaction mix in a stated direction (courage up, fewer `flee`;
|
||||
assertiveness up, more `command` and `restrain`), and across the five archetypes at least four distinct
|
||||
first reactions occur. Separately, with coworker behaviour outside the three authored paths disabled, the
|
||||
phase 1 distribution from check 1 does not change; if it does, a coworker is leaking into the stress bar
|
||||
by an unauthored route.
|
||||
|
||||
## Not decided
|
||||
|
||||
- Whether phase 2 can be interrupted back into phase 1 (a restrained Fella recovering), or is one-way.
|
||||
- Whether coworkers can also break, which makes this a cascade scenario.
|
||||
- Rig, level geometry and what counts as "breakable"; those belong to the sandbox, not this document.
|
||||
- Whether the player controls Fella in phase 1 or only the stressors.
|
||||
|
|
@ -8,5 +8,6 @@
|
|||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BadDay.Core\BadDay.Core.csproj" />
|
||||
<ProjectReference Include="..\BadDay.Ymir\BadDay.Ymir.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,24 +1,45 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
|
||||
namespace BadDay.Cli;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
private const string Usage = """
|
||||
baddaysim: the Synaptic Induction Chamber (the pain box)
|
||||
|
||||
baddaysim plan the seated puppet's body plan as JSON: parts and joints in their creation pose (the mesh build's skeleton)
|
||||
baddaysim run --seed N [options] one run, full timeline
|
||||
baddaysim run --seed N --body [options] the same run on the Ymir ragdoll, with the hand-out time
|
||||
baddaysim sweep --seed N --count M [options] seeds N..N+M-1, break-time summary
|
||||
|
||||
baddaysim office --seed N [office options] the office: stressors fill the stress bar, the will breaks, the rage follows
|
||||
baddaysim office --seed N --body [office options] the same run on the Ymir ragdoll: rage time and strikes
|
||||
baddaysim office-sweep --seed N --count M [office options]
|
||||
|
||||
options (all numbers, seconds unless noted):
|
||||
--intensity X box intensity 0..1 (default 0.8)
|
||||
--pull X objective pull 0..1 (default 0.5)
|
||||
--pay DOLLARS what the volunteer is paid: the pull is pay / (pay + 100) (default 100, pull 0.5)
|
||||
--disable-at S box switches off at S (default never)
|
||||
--max S give up after S (default 120)
|
||||
--every S timeline sample interval (default 1)
|
||||
|
||||
office options:
|
||||
--silence ID@S silence stressor ID from S seconds (repeatable; ids: printer, ceiling-light, desk-phone, desktop-interrupt)
|
||||
--scale X every stressor's intensity times X (default 1)
|
||||
--pull X the job's pull 0..1 (default 0.6)
|
||||
--max S give up after S (default 180)
|
||||
--every S timeline sample interval (default 1)
|
||||
""";
|
||||
|
||||
private const string Title = "Synaptic Induction Chamber (the pain box)";
|
||||
|
||||
private static readonly string OfficeTitle = $"Bad day at the office, rung 4 (stress = arousal, \"{StressResult.StressBarLabel}\")";
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
try { return Execute(args, Console.Out); }
|
||||
|
|
@ -32,22 +53,40 @@ public static class Program
|
|||
|
||||
public static int Execute(string[] args, System.IO.TextWriter output)
|
||||
{
|
||||
if (args.Length == 0 || (args[0] != "run" && args[0] != "sweep")) throw new ArgumentException("expected 'run' or 'sweep'");
|
||||
if (args.Length == 1 && args[0] == "plan") { output.Write(PlanJson()); return 0; }
|
||||
if (args.Length == 0 || (args[0] != "run" && args[0] != "sweep" && args[0] != "office" && args[0] != "office-sweep"))
|
||||
throw new ArgumentException("expected 'run', 'sweep', 'office' or 'office-sweep'");
|
||||
var opts = ParseOptions(args);
|
||||
ulong seed = opts.TryGetValue("seed", out var s) ? ulong.Parse(s, CultureInfo.InvariantCulture)
|
||||
: throw new ArgumentException("--seed is required");
|
||||
if (args[0].StartsWith("office")) return ExecuteOffice(args[0] == "office-sweep", seed, opts, output);
|
||||
if (opts.ContainsKey("pull")) throw new ArgumentException("--pull applies to office; the chamber takes --pay");
|
||||
var p = new PainBoxParameters
|
||||
{
|
||||
BoxIntensity = Num(opts, "intensity", 0.8),
|
||||
ObjectivePull = Num(opts, "pull", 0.5),
|
||||
Payment = Num(opts, "pay", 100),
|
||||
BoxDisableAtSeconds = opts.ContainsKey("disable-at") ? Num(opts, "disable-at", 0) : null,
|
||||
MaxSeconds = Num(opts, "max", 120),
|
||||
SampleEverySeconds = Num(opts, "every", 1),
|
||||
};
|
||||
|
||||
if (args[0] == "run" && opts.ContainsKey("body"))
|
||||
{
|
||||
var b = BodyPainBox.Run(p with { TickSeconds = BodyPainBox.TickSeconds }, seed);
|
||||
output.WriteLine(Title);
|
||||
output.Write(b.Run.Render());
|
||||
output.WriteLine(b.Run.Summary());
|
||||
output.WriteLine(b.Run.HandOutMs is { } out_
|
||||
? $"hand out at {out_} ms, {out_ - b.Run.TimeToBreakMs} ms after the will broke; {b.Excursions} excursions from the box before the break"
|
||||
: $"hand not out for good by {b.Run.EndMs} ms; {b.Excursions} excursions from the box before the break");
|
||||
return 0;
|
||||
}
|
||||
if (opts.ContainsKey("body")) throw new ArgumentException("--body applies to run");
|
||||
|
||||
if (args[0] == "run")
|
||||
{
|
||||
var r = PainBoxSimulation.Run(p, seed);
|
||||
output.WriteLine(Title);
|
||||
output.Write(r.Render());
|
||||
output.WriteLine(r.Summary());
|
||||
return 0;
|
||||
|
|
@ -61,6 +100,81 @@ public static class Program
|
|||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>SeatedPuppet.Plan as JSON, floats in round-trip form: per part label, side, creation position and rotation (x, y, z, w); per joint label, side, parent and child part ordinals and anchor.</summary>
|
||||
private static string PlanJson()
|
||||
{
|
||||
string F(float v) => v.ToString("R", CultureInfo.InvariantCulture);
|
||||
string V((float X, float Y, float Z) v) => $"[{F(v.X)}, {F(v.Y)}, {F(v.Z)}]";
|
||||
var plan = SeatedPuppet.Plan;
|
||||
var parts = plan.Parts.Select(p => $" {{\"label\": \"{p.Label}\", \"side\": \"{p.Side}\", \"position\": {V(p.Position)}, \"rotation\": [{F(p.Rotation.X)}, {F(p.Rotation.Y)}, {F(p.Rotation.Z)}, {F(p.Rotation.W)}]}}");
|
||||
var joints = plan.Joints.Select(j => $" {{\"label\": \"{j.Label}\", \"side\": \"{j.Side}\", \"parent\": {j.Parent}, \"child\": {j.Child}, \"anchor\": {V(j.Anchor)}}}");
|
||||
return "{\n \"parts\": [\n" + string.Join(",\n", parts) + "\n ],\n \"joints\": [\n" + string.Join(",\n", joints) + "\n ]\n}\n";
|
||||
}
|
||||
|
||||
private static int ExecuteOffice(bool sweep, ulong seed, Dictionary<string, string> opts, System.IO.TextWriter output)
|
||||
{
|
||||
if (opts.ContainsKey("body") && sweep) throw new ArgumentException("--body applies to run and office");
|
||||
if (opts.ContainsKey("pay")) throw new ArgumentException("--pay applies to run and sweep; the office takes --pull");
|
||||
var defaults = new StressParameters();
|
||||
var p = defaults with
|
||||
{
|
||||
Cause = (defaults.Cause with { ObjectivePull = Num(opts, "pull", defaults.Cause.ObjectivePull) }).Scaled(Num(opts, "scale", 1.0)),
|
||||
SampleEverySeconds = Num(opts, "every", defaults.SampleEverySeconds),
|
||||
};
|
||||
double seconds = Num(opts, "max", 180); // the headless run's horizon: the office session has no end of its own
|
||||
if (opts.ContainsKey("body") && opts.ContainsKey("silence")) throw new ArgumentException("--silence does not apply to --body");
|
||||
var silences = new List<SilenceCommand>();
|
||||
if (opts.TryGetValue("silence", out var list))
|
||||
{
|
||||
foreach (var item in list.Split(','))
|
||||
{
|
||||
int at = item.LastIndexOf('@');
|
||||
if (at <= 0) throw new ArgumentException($"--silence wants ID@SECONDS, got '{item}'");
|
||||
silences.Add(new SilenceCommand(item[..at], double.Parse(item[(at + 1)..], CultureInfo.InvariantCulture)));
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.ContainsKey("body"))
|
||||
{
|
||||
var b = OfficeBody.Run(p with { TickSeconds = OfficeBody.TickSeconds }, seed, seconds);
|
||||
output.WriteLine(OfficeTitle);
|
||||
output.Write(b.Run.Render());
|
||||
output.WriteLine(b.Run.Summary());
|
||||
if (b.RageTick is { } rage)
|
||||
{
|
||||
int end = b.HandL.Count;
|
||||
StressEntry? calm = b.Run.Timeline.Any(e => e.Kind == StressEntryKind.GoalChanged && e.Goal == OfficeGoal.Calm)
|
||||
? b.Run.Timeline.First(e => e.Kind == StressEntryKind.GoalChanged && e.Goal == OfficeGoal.Calm) : null;
|
||||
int rageEnd = calm is null ? end : (int)Math.Round(calm.Value.TimeMs * OfficeBody.Hz / 1000.0);
|
||||
string how = calm is null ? "clipped by --max, no calm" : $"to calm at {calm.Value.TimeMs} ms";
|
||||
output.WriteLine($"rage from {b.Run.Timeline.First(e => e.Kind == StressEntryKind.GoalChanged && e.Goal == OfficeGoal.Rage).TimeMs} ms for " +
|
||||
$"{((rageEnd - rage) / (double)OfficeBody.Hz).ToString("F1", CultureInfo.InvariantCulture)} s ({how}); strikes {b.Strikes(rage, end)} " +
|
||||
$"(left {OfficeBody.CountStrikes(b.HandL, rage, end)}, right {OfficeBody.CountStrikes(b.HandR, rage, end)}), " +
|
||||
$"{b.Strikes(0, rage)} before it");
|
||||
}
|
||||
else if (b.Run.Outcome == Outcome.WillBroke) output.WriteLine($"the will broke but --max stopped the run at {b.Run.EndMs} ms, before the rage took over");
|
||||
else output.WriteLine($"no rage: the will held to {b.Run.EndMs} ms");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!sweep)
|
||||
{
|
||||
var r = StressSimulation.Run(p, seed, seconds, silences);
|
||||
output.WriteLine(OfficeTitle);
|
||||
output.Write(r.Render());
|
||||
output.WriteLine(r.Summary());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int count = (int)Num(opts, "count", 20);
|
||||
var summary = StressSweep.Run(p, seed, count, seconds, silences);
|
||||
foreach (var r in summary.Results) output.WriteLine(r.Summary());
|
||||
output.WriteLine($"runs {summary.Runs}: broke {summary.Broke}, endured {summary.Endured}; " +
|
||||
$"time to break min/median/max ms: {Fmt(summary.MinBreakMs)}/{Fmt(summary.MedianBreakMs)}/{Fmt(summary.MaxBreakMs)}; " +
|
||||
$"min resolve of endured runs: {(summary.MinEnduredResolve?.ToString("F3", CultureInfo.InvariantCulture) ?? "-")}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Fmt(long? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "-";
|
||||
|
||||
private static double Num(Dictionary<string, string> o, string key, double fallback) =>
|
||||
|
|
@ -69,10 +183,13 @@ public static class Program
|
|||
private static Dictionary<string, string> ParseOptions(string[] args)
|
||||
{
|
||||
var o = new Dictionary<string, string>();
|
||||
for (int i = 1; i < args.Length; i += 2)
|
||||
for (int i = 1; i < args.Length;)
|
||||
{
|
||||
if (args[i] == "--body") { o["body"] = ""; i++; continue; } // the one flag
|
||||
if (!args[i].StartsWith("--") || i + 1 >= args.Length) throw new ArgumentException($"bad option near '{args[i]}'");
|
||||
o[args[i][2..]] = args[i + 1];
|
||||
// --silence repeats; its values are joined, since a stressor id holds no comma.
|
||||
o[args[i][2..]] = args[i] == "--silence" && o.TryGetValue("silence", out var prior) ? prior + "," + args[i + 1] : args[i + 1];
|
||||
i += 2;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<RootNamespace>BadDay.Core</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="$(LodurRoot)\src\Lodur.Core\Lodur.Core.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
61
src/BadDay.Core/Cause.cs
Normal file
61
src/BadDay.Core/Cause.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// One recurring source of load: when it starts, how it rises, how often it comes back, how long it lasts and how
|
||||
/// hard, on one emitter of the <see cref="Setting"/>. Times are seconds; a null period is a single burst.
|
||||
/// </summary>
|
||||
public sealed record Stressor(
|
||||
string Id, string EmitterId,
|
||||
double OnsetSeconds, double RampSeconds, double? PeriodSeconds, double DurationSeconds,
|
||||
double Intensity, double Jitter)
|
||||
{
|
||||
/// <summary>
|
||||
/// The intensity at <paramref name="tick"/>, in whole ticks so the burst edges never wander with float error:
|
||||
/// zero before the onset and outside a burst, else Intensity rising over the ramp, scaled by (1 + Jitter * draw).
|
||||
/// </summary>
|
||||
public double Value(long tick, double tickSeconds, double draw)
|
||||
{
|
||||
long t = tick - Ticks(OnsetSeconds, tickSeconds);
|
||||
if (t < 0) return 0.0;
|
||||
long phase = PeriodSeconds is { } p ? t % Math.Max(1, Ticks(p, tickSeconds)) : t;
|
||||
if (phase >= Ticks(DurationSeconds, tickSeconds)) return 0.0;
|
||||
long ramp = Ticks(RampSeconds, tickSeconds);
|
||||
double rise = ramp > 0 ? Math.Min(1.0, (double)phase / ramp) : 1.0;
|
||||
return Math.Max(0.0, Intensity * rise * (1.0 + Jitter * draw));
|
||||
}
|
||||
|
||||
private static long Ticks(double seconds, double tickSeconds) => (long)Math.Round(seconds / tickSeconds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What goes wrong: the stressors and the objective's pull (the job). It holds no geometry (the <see cref="Setting"/>'s)
|
||||
/// and no senses (the <see cref="Character"/>'s). Code defaults, not persisted.
|
||||
/// </summary>
|
||||
public sealed record Cause(IReadOnlyList<Stressor> Stressors, double ObjectivePull)
|
||||
{
|
||||
/// <summary>
|
||||
/// The office's sensory-load cause [P]: printer audio 5 s on, every 8 s for 1 s at 0.25; ceiling light 15 s
|
||||
/// every 11 s for 2 s at 0.2; desk phone 25 s every 14 s for 3 s at 0.35; desktop interrupt 75 s every 20 s for
|
||||
/// 1 s at 0.3; pull 0.6. The chatty neighbour and the stand-up crowd wait for coworkers (rung 6).
|
||||
/// </summary>
|
||||
public static Cause Office { get; } = new(new[]
|
||||
{
|
||||
new Stressor("printer", "printer", 5.0, 0.0, 8.0, 1.0, 0.25, 0.1),
|
||||
new Stressor("ceiling-light", "ceiling-light", 15.0, 0.0, 11.0, 2.0, 0.2, 0.1),
|
||||
new Stressor("desk-phone", "desk-phone", 25.0, 0.0, 14.0, 3.0, 0.35, 0.1),
|
||||
new Stressor("desktop-interrupt", "desktop", 75.0, 0.0, 20.0, 1.0, 0.3, 0.1),
|
||||
}, 0.6);
|
||||
|
||||
/// <summary>Every stressor's intensity times <paramref name="factor"/>.</summary>
|
||||
public Cause Scaled(double factor) => this with
|
||||
{
|
||||
Stressors = Stressors.Select(s => s with { Intensity = s.Intensity * factor }).ToArray(),
|
||||
};
|
||||
|
||||
public Cause Without(string stressorId) => this with { Stressors = Stressors.Where(s => s.Id != stressorId).ToArray() };
|
||||
}
|
||||
71
src/BadDay.Core/ChamberBrain.cs
Normal file
71
src/BadDay.Core/ChamberBrain.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The Synaptic Induction Chamber's Brain: what the volunteer wants to be doing, authored as data for Lodur's Actor to
|
||||
/// run. He holds his hand in the box for the payment (the objective, pulling Payment / (Payment + DollarsAtHalfPull))
|
||||
/// until the will breaks, then withdraws. No session decides a switch; the Actor commits the Brain's choice, so the
|
||||
/// goal column of every timeline is read back from <see cref="Actor.GoalIndex"/>.
|
||||
/// </summary>
|
||||
public static class ChamberBrain
|
||||
{
|
||||
public const int HoldIndex = 0;
|
||||
public const int WithdrawIndex = 1;
|
||||
|
||||
/// <summary>The withdraw goal's id: what the pain box's release waits for (<see cref="PainBoxParameters.ReleaseGoalId"/>).</summary>
|
||||
public const string WithdrawId = "withdraw";
|
||||
|
||||
/// <summary>The objective's pull for the payment: 0 for nothing, 0.5 at <see cref="PainBoxParameters.DollarsAtHalfPull"/>, toward 1 for more.</summary>
|
||||
public static double Pull(PainBoxParameters p)
|
||||
{
|
||||
if (!(p.Payment >= 0.0 && double.IsFinite(p.Payment))) throw new ArgumentException($"Payment must be finite and not negative, got {p.Payment}.");
|
||||
if (!(p.DollarsAtHalfPull > 0.0 && double.IsFinite(p.DollarsAtHalfPull))) throw new ArgumentException($"DollarsAtHalfPull must be finite and positive, got {p.DollarsAtHalfPull}.");
|
||||
return p.Payment / (p.Payment + p.DollarsAtHalfPull);
|
||||
}
|
||||
|
||||
/// <summary>The chamber's display name for the goal at <paramref name="index"/> of this Brain.</summary>
|
||||
public static Goal GoalAt(int index) => index == WithdrawIndex ? Goal.Withdraw : Goal.HoldHand;
|
||||
|
||||
/// <summary>
|
||||
/// hold-hand: always eligible, priority 0, the payment's pull, the hold pose with the reflex leak and strain shake
|
||||
/// pulling toward the withdraw pose. withdraw: eligible once the will has broken (<see cref="DriveQuantity.Breaks"/>, which
|
||||
/// never falls, so the goal is one-way: the will mending does not give the hand back), priority 1, no pull, involuntary
|
||||
/// for good (the withdrawal is the body's, it costs no will and does not weaken as the will mends), the withdraw pose
|
||||
/// with no leak or shake.
|
||||
/// </summary>
|
||||
public static Brain Build(PainBoxParameters p, ReadOnlySpan<Quat> hold, ReadOnlySpan<Quat> withdraw)
|
||||
{
|
||||
var holdPose = hold.ToArray();
|
||||
var withdrawPose = withdraw.ToArray();
|
||||
return new Brain
|
||||
{
|
||||
Start = HoldIndex,
|
||||
Goals = new[]
|
||||
{
|
||||
new GoalSpec
|
||||
{
|
||||
Id = "hold-hand",
|
||||
Priority = 0.0,
|
||||
Pull = Pull(p),
|
||||
Behaviour = new PoseBehaviour { Keys = new[] { holdPose }, FlinchPose = withdrawPose, Hold = p.Hold },
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = WithdrawId,
|
||||
Priority = 1.0,
|
||||
Pull = 0.0,
|
||||
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
|
||||
InvoluntarySeconds = double.PositiveInfinity,
|
||||
Behaviour = new PoseBehaviour
|
||||
{
|
||||
Keys = new[] { withdrawPose },
|
||||
FlinchPose = withdrawPose,
|
||||
Hold = p.Hold with { FlinchGain = 0.0, StrainShake = 0.0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
22
src/BadDay.Core/Character.cs
Normal file
22
src/BadDay.Core/Character.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Who has the bad day: the character's own nervous parameters, apart from the <see cref="Setting"/> (where) and the
|
||||
/// <see cref="Cause"/> (why). Today that is the sense nerve he hears and sees with; his goals are <see cref="OfficeBrain"/>'s.
|
||||
/// A character is code for now and becomes content with the Brains (follow-up npc-brains-as-content).
|
||||
/// </summary>
|
||||
public sealed record Character(string Id, NerveParameters Senses)
|
||||
{
|
||||
/// <summary>
|
||||
/// Office Fella: threshold 0.05, no sensitisation, no conduction delay. The office's break near 90 s at pull 0.6
|
||||
/// holds only with these; Lodur's NerveParameters defaults break at about 100 s.
|
||||
/// </summary>
|
||||
public static Character OfficeFella { get; } = new("office-fella", new NerveParameters
|
||||
{
|
||||
Threshold = 0.05,
|
||||
SensitisationGrowth = 0.0,
|
||||
ConductionDelaySeconds = 0.0,
|
||||
});
|
||||
}
|
||||
127
src/BadDay.Core/OfficeBrain.cs
Normal file
127
src/BadDay.Core/OfficeBrain.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
using System;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>What the office timeline's goal column names: the goal in force, by <see cref="OfficeBrain"/>'s index. Display only.</summary>
|
||||
public enum OfficeGoal { KeepComposure, Rage, Calm, Clutch, Thrash }
|
||||
|
||||
/// <summary>
|
||||
/// The poses Office Fella's goals write, one rotation per muscle: the composed pose he holds while he keeps his
|
||||
/// composure (and the pose a leak would pull toward), the keys the rage walks in a loop, the clutch (both hands at the
|
||||
/// throat) and the keys the thrash walks. The body supplies them
|
||||
/// (<c>OfficeBody.Poses</c>); the headless run, which has no body, takes <see cref="Identity"/>.
|
||||
/// </summary>
|
||||
public sealed record OfficePoses(Quat[] Composed, Quat[] Flinch, Quat[][] RageKeys, Quat[] Clutch, Quat[][] ThrashKeys)
|
||||
{
|
||||
/// <summary>One muscle, every pose the identity: the headless run's behaviour has no body to move.</summary>
|
||||
public static OfficePoses Identity { get; } = new(
|
||||
new[] { Quat.Identity }, new[] { Quat.Identity },
|
||||
new[] { new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity } },
|
||||
new[] { Quat.Identity },
|
||||
new[] { new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity } });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Office Fella's Brain: keep-composure (the job, pulling with <see cref="Cause.ObjectivePull"/>) until the will
|
||||
/// breaks, then rage (a geyser: no pull, nothing held down, the rage keys in a loop; it refills his will on entry, is
|
||||
/// involuntary for its first <see cref="StressParameters.RageOnsetSeconds"/> and then costs will at
|
||||
/// <see cref="StressParameters.RageEffort"/> a second), until that will runs dry and breaks a second time, and then calm:
|
||||
/// his composed pose at normal strength, for good (ruling lodur:ruling:fella-calm-after-rage); entering it fades his arousal and his senses' gain to nothing over
|
||||
/// <see cref="StressParameters.CalmFadeSeconds"/> (rulings lodur:ruling:stress-bar-shows-arousal-calm-silences and lodur:ruling:flinch-tail-after-stimulus), so the stress bar
|
||||
/// empties while the office keeps sounding. Calm is terminal as
|
||||
/// data among the stress goals: it gates on Breaks, which never falls, and only the two air-hunger goals outrank it, since air
|
||||
/// hunger is physiology, not a fit (ruling lodur:ruling:fella-calm-after-rage is about the rage). Air hunger, from a breath tried
|
||||
/// and not got (<see cref="StressParameters.ClutchAirHunger"/>), makes him clutch his throat; once his will has broken while it
|
||||
/// holds he thrashes (rulings lodur:ruling:bds-air-hunger-clutch-then-thrash, lodur:ruling:bds-thrash-when-will-breaks). Both are
|
||||
/// involuntary throughout, so a will-weighted struggle never goes limp, and both sag with the Actor's motor ceiling, which
|
||||
/// carries consciousness: BDS adds no sag goal. A Fella cut while his will is still broken thrashes at once. Authored as data; the Actor commits the
|
||||
/// switches, so the timeline's goal column is read back from <see cref="Actor.GoalIndex"/>.
|
||||
/// </summary>
|
||||
public static class OfficeBrain
|
||||
{
|
||||
public const int ComposureIndex = 0;
|
||||
public const int RageIndex = 1;
|
||||
public const int CalmIndex = 2;
|
||||
public const int ClutchIndex = 3;
|
||||
public const int ThrashIndex = 4;
|
||||
|
||||
public const string RageId = "rage";
|
||||
|
||||
/// <summary>The calm goal's id.</summary>
|
||||
public const string CalmId = "calm";
|
||||
|
||||
/// <summary>The clutch goal's id.</summary>
|
||||
public const string ClutchId = "clutch";
|
||||
|
||||
/// <summary>The thrash goal's id.</summary>
|
||||
public const string ThrashId = "thrash";
|
||||
|
||||
public static OfficeGoal GoalAt(int index) => index switch { RageIndex => OfficeGoal.Rage, CalmIndex => OfficeGoal.Calm, ClutchIndex => OfficeGoal.Clutch, ThrashIndex => OfficeGoal.Thrash, _ => OfficeGoal.KeepComposure };
|
||||
|
||||
public static Brain Build(StressParameters p, OfficePoses poses) => new()
|
||||
{
|
||||
Start = ComposureIndex,
|
||||
Goals = new[]
|
||||
{
|
||||
new GoalSpec
|
||||
{
|
||||
Id = "keep-composure",
|
||||
Priority = 0.0,
|
||||
Pull = p.Cause.ObjectivePull,
|
||||
Behaviour = new PoseBehaviour { Keys = new[] { poses.Composed }, FlinchPose = poses.Flinch, Hold = p.Hold },
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = RageId,
|
||||
Priority = 1.0,
|
||||
Pull = 0.0,
|
||||
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
|
||||
EntryResolve = 1.0,
|
||||
Effort = p.RageEffort,
|
||||
InvoluntarySeconds = p.RageOnsetSeconds,
|
||||
Behaviour = new PoseBehaviour
|
||||
{
|
||||
Keys = poses.RageKeys,
|
||||
SecondsPerKey = p.RageKeySeconds,
|
||||
FlinchPose = poses.RageKeys[0],
|
||||
Hold = p.Hold with { HoldStrength = 1f, FlinchGain = 0.0, StrainShake = 0.0 },
|
||||
},
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = CalmId,
|
||||
Priority = 2.0,
|
||||
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 2.0) },
|
||||
InvoluntarySeconds = double.PositiveInfinity,
|
||||
EntryArousal = 0.0,
|
||||
SensoryGain = 0.0,
|
||||
EntrySeconds = p.CalmFadeSeconds,
|
||||
Behaviour = new PoseBehaviour { Keys = new[] { poses.Composed }, FlinchPose = poses.Flinch, Hold = p.Hold },
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = ClutchId,
|
||||
Priority = 3.0,
|
||||
When = new[] { new Condition(DriveQuantity.AirHunger, ConditionOp.AtLeast, p.ClutchAirHunger) },
|
||||
InvoluntarySeconds = double.PositiveInfinity,
|
||||
Pull = 0.0,
|
||||
Behaviour = new PoseBehaviour { Keys = new[] { poses.Clutch }, FlinchPose = poses.Clutch, Hold = p.Hold with { FlinchGain = 0.0 } },
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = ThrashId,
|
||||
Priority = 4.0,
|
||||
When = new[] { new Condition(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0), new Condition(DriveQuantity.AirHunger, ConditionOp.AtLeast, p.ClutchAirHunger) },
|
||||
InvoluntarySeconds = double.PositiveInfinity,
|
||||
Behaviour = new PoseBehaviour
|
||||
{
|
||||
Keys = poses.ThrashKeys,
|
||||
SecondsPerKey = p.ThrashKeySeconds,
|
||||
FlinchPose = poses.ThrashKeys[0],
|
||||
Hold = p.Hold with { HoldStrength = 1f, FlinchGain = 0.0, StrainShake = 0.0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
63
src/BadDay.Core/PainBox.cs
Normal file
63
src/BadDay.Core/PainBox.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The game's box: its schedule. A noxious intensity ramped in with seeded jitter, switched off at the disable
|
||||
/// time. It writes the intensity of a Lodur <see cref="BoxStimulus"/> and nothing else; what the intensity does
|
||||
/// to a character is Lodur's.
|
||||
/// </summary>
|
||||
public sealed class PainBox
|
||||
{
|
||||
private readonly PainBoxParameters _p;
|
||||
private readonly SplitMix64 _rng;
|
||||
|
||||
public PainBox(PainBoxParameters parameters, SplitMix64 rng)
|
||||
{
|
||||
_p = parameters;
|
||||
_rng = rng;
|
||||
Level = parameters.BoxIntensity;
|
||||
DisableTick = long.MaxValue;
|
||||
if (parameters.BoxDisableAtSeconds is { } d) SwitchOff((long)Math.Round(d / parameters.TickSeconds));
|
||||
}
|
||||
|
||||
/// <summary>The first tick the box is off; <see cref="long.MaxValue"/> when it is never disabled.</summary>
|
||||
public long DisableTick { get; private set; }
|
||||
|
||||
/// <summary>The largest intensity the box takes: ten times the strongest the models use, small enough that no product with the ramp and noise can overflow.</summary>
|
||||
public const double MaxLevel = 10.0;
|
||||
|
||||
private double _level;
|
||||
|
||||
/// <summary>
|
||||
/// The intensity the ramp scales: the parameters' <c>BoxIntensity</c> until a caller sets it. The one rule for every
|
||||
/// writer, the constructor included: finite, not negative, at most <see cref="MaxLevel"/>; anything else throws
|
||||
/// <see cref="ArgumentOutOfRangeException"/> and leaves the level as it was.
|
||||
/// </summary>
|
||||
public double Level
|
||||
{
|
||||
get => _level;
|
||||
set
|
||||
{
|
||||
if (!double.IsFinite(value) || value < 0.0 || value > MaxLevel)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value), value, $"The box intensity is finite, from 0 to {MaxLevel}.");
|
||||
}
|
||||
_level = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Switches the box off from <paramref name="tick"/>; an earlier switch-off stands.</summary>
|
||||
public void SwitchOff(long tick) => DisableTick = Math.Min(DisableTick, tick);
|
||||
|
||||
/// <summary>Writes this tick's intensity. Always draws the jitter, so the stream does not depend on state.</summary>
|
||||
public void Write(long tick, ref BoxStimulus box)
|
||||
{
|
||||
double jitter = _rng.NextSigned();
|
||||
double ramp = Math.Min(1.0, tick * _p.TickSeconds / _p.BoxRampSeconds);
|
||||
box.Intensity = tick < DisableTick
|
||||
? Math.Max(0.0, Level * ramp * (1.0 + _p.BoxNoise * jitter))
|
||||
: 0.0;
|
||||
}
|
||||
}
|
||||
|
|
@ -19,34 +19,23 @@ public sealed record PainBoxParameters
|
|||
/// <summary>When set, the box switches off at this time (the game disables it).</summary>
|
||||
public double? BoxDisableAtSeconds { get; init; }
|
||||
|
||||
// Nerve: threshold, sensitisation under sustained stimulus, conduction delay.
|
||||
public double NociceptorThreshold { get; init; } = 0.1;
|
||||
public double SensitisationGrowth { get; init; } = 0.04;
|
||||
public double SensitisationRecovery { get; init; } = 0.02;
|
||||
public double SensitisationCap { get; init; } = 2.0;
|
||||
public double ConductionDelaySeconds { get; init; } = 0.06;
|
||||
// The nervous model is Lodur's: nerve, drive and reflex keep their records and defaults. Hold is the hold goal's pose
|
||||
// behaviour (the body run's; the headless run ignores what it writes). The goals themselves are ChamberBrain's.
|
||||
public Lodur.NerveParameters Nerve { get; init; } = new();
|
||||
public Lodur.DriveParameters Drive { get; init; } = new();
|
||||
public Lodur.WithdrawalParameters Reflex { get; init; } = new();
|
||||
public Lodur.HoldParameters Hold { get; init; } = new();
|
||||
|
||||
// Drive: pain, strain from holding a reflex down, resolve.
|
||||
public double PainRise { get; init; } = 1.0;
|
||||
public double PainDecay { get; init; } = 0.05;
|
||||
public double StrainRecover { get; init; } = 0.1;
|
||||
public double ResolveDrainPain { get; init; } = 0.012;
|
||||
public double ResolveDrainStrain { get; init; } = 0.05;
|
||||
public double ResolveRecovery { get; init; } = 0.02;
|
||||
public double ResolveRecoversBelowPain { get; init; } = 0.1;
|
||||
// The objective: the volunteer is paid, and the payment sets how hard holding the hand in the box pulls
|
||||
// (ChamberBrain.Pull: Payment / (Payment + DollarsAtHalfPull), so DollarsAtHalfPull is the payment that pulls half). [P]
|
||||
public double Payment { get; init; } = 100.0;
|
||||
public double DollarsAtHalfPull { get; init; } = 100.0;
|
||||
|
||||
// Reflex: how much of it will can hold down, and the latencies.
|
||||
public double MaxSuppression { get; init; } = 0.95;
|
||||
public double FlinchLeakThreshold { get; init; } = 0.3;
|
||||
public double FlinchRefractorySeconds { get; init; } = 0.5;
|
||||
public double WithdrawalLatencySeconds { get; init; } = 0.1;
|
||||
|
||||
// Goals: how hard the objective ("keep the hand in the box") pulls, 0..1.
|
||||
// It scales resolve drain by (1 - pull); it is not a second resolve bar.
|
||||
public double ObjectivePull { get; init; } = 0.5;
|
||||
|
||||
// Per-seed trait spread (fraction): nociceptor gain and resolve drain.
|
||||
// Per-seed trait spread (fraction): nociceptor gain and resolve drain. The seed's draw multiplies Nerve.Gain and Drive.DrainTrait.
|
||||
public double TraitJitter { get; init; } = 0.2;
|
||||
|
||||
/// <summary>The id of the Brain goal whose takeover is the withdrawal: the session's Withdrew, its Withdrew row and its WillBroke outcome come from that goal's GoalChanged and no other. The session refuses an id the Brain lacks.</summary>
|
||||
public string ReleaseGoalId { get; init; } = ChamberBrain.WithdrawId;
|
||||
|
||||
public double SampleEverySeconds { get; init; } = 1.0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ public enum Outcome
|
|||
BoxDisabled,
|
||||
/// <summary>MaxSeconds passed with the box on and the will intact.</summary>
|
||||
Endured,
|
||||
/// <summary>A body with a physiology died (an office run; the chamber never produces it).</summary>
|
||||
Died,
|
||||
}
|
||||
|
||||
public enum EntryKind { Sample, Flinch, WillBroke, Withdrew, BoxDisabled, Endured }
|
||||
|
|
@ -29,7 +31,9 @@ public sealed record PainBoxResult(
|
|||
/// <summary>Time resolve hit zero, ms; null unless <see cref="Outcome"/> is WillBroke.</summary>
|
||||
long? TimeToBreakMs,
|
||||
int Flinches,
|
||||
IReadOnlyList<TimelineEntry> Timeline)
|
||||
IReadOnlyList<TimelineEntry> Timeline,
|
||||
/// <summary>Time the hand was out of the box for good, ms; null if it never was. Headless: the deliberate withdrawal. Body: the start of a sustained exit.</summary>
|
||||
long? HandOutMs = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// Deterministic text form (invariant culture, fixed precision). Two runs
|
||||
|
|
@ -54,7 +58,9 @@ public sealed record PainBoxResult(
|
|||
|
||||
public string Summary() => Outcome switch
|
||||
{
|
||||
Outcome.WillBroke => $"seed {Seed}: will broke at {TimeToBreakMs} ms, hand out at {EndMs} ms, {Flinches} flinches",
|
||||
Outcome.WillBroke => HandOutMs is { } out_
|
||||
? $"seed {Seed}: will broke at {TimeToBreakMs} ms, hand out at {out_} ms, {Flinches} flinches"
|
||||
: $"seed {Seed}: will broke at {TimeToBreakMs} ms, hand not out by {EndMs} ms, {Flinches} flinches",
|
||||
Outcome.BoxDisabled => $"seed {Seed}: box disabled at {EndMs} ms, will held, {Flinches} flinches",
|
||||
_ => $"seed {Seed}: endured to {EndMs} ms, will held, {Flinches} flinches",
|
||||
};
|
||||
|
|
|
|||
158
src/BadDay.Core/PainBoxSession.cs
Normal file
158
src/BadDay.Core/PainBoxSession.cs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// One run of the pain box: the seed's traits, the box schedule, a Lodur <see cref="Actor"/>, and the recorder.
|
||||
/// The headless run and the body run both drive it, one <see cref="Tick"/> per step, and differ only in where
|
||||
/// the hand point comes from and what ends the run. The session decides nothing about the character: the
|
||||
/// timeline rows are end-of-tick state read from the Actor, and nothing reads them back.
|
||||
/// </summary>
|
||||
public sealed class PainBoxSession
|
||||
{
|
||||
private readonly PainBoxParameters _p;
|
||||
private readonly PainBox _box;
|
||||
private readonly BoxStimulus[] _sources;
|
||||
private readonly List<TimelineEntry> _timeline = new();
|
||||
private readonly long _maxTick;
|
||||
private readonly long _sampleEvery;
|
||||
private readonly int _handRegion;
|
||||
private readonly int _releaseGoal;
|
||||
private double _stimulus;
|
||||
private long _breakTick = -1;
|
||||
private int _flinches;
|
||||
private Outcome _outcome = Outcome.Endured;
|
||||
private long _endTick;
|
||||
|
||||
/// <param name="box">The stimulus volume the hand is held in; its intensity is the session's to write.</param>
|
||||
/// <param name="handRegion">The region of the hand in the box; the timeline's stimulus column is the stimulus there.</param>
|
||||
public PainBoxSession(PainBoxParameters p, ulong seed, BoxStimulus box, int regionCount,
|
||||
ReadOnlySpan<Quat> holdPose, ReadOnlySpan<Quat> withdrawPose, int handRegion = 0)
|
||||
{
|
||||
_handRegion = handRegion;
|
||||
_p = p;
|
||||
var rng = new SplitMix64(seed);
|
||||
// Per-seed traits, drawn first and in fixed order so the stream never shifts. They multiply the caller's
|
||||
// Nerve.Gain and Drive.DrainTrait (1.0 by default), so a caller's own value is a baseline, never overwritten.
|
||||
double gainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
|
||||
double drainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
|
||||
Seed = seed;
|
||||
Actor = new Actor(p.TickSeconds, regionCount, p.Nerve with { Gain = p.Nerve.Gain * gainTrait }, p.Reflex,
|
||||
p.Drive with { DrainTrait = p.Drive.DrainTrait * drainTrait }, ChamberBrain.Build(p, holdPose, withdrawPose));
|
||||
_releaseGoal = -1;
|
||||
for (int g = 0; g < Actor.Brain.Goals.Count; g++) if (Actor.Brain.Goals[g].Id == p.ReleaseGoalId) _releaseGoal = g;
|
||||
if (_releaseGoal < 0) throw new ArgumentException($"the Brain has no goal '{p.ReleaseGoalId}' to release on");
|
||||
_box = new PainBox(p, rng);
|
||||
_sources = new[] { box };
|
||||
_maxTick = Ticks(p.MaxSeconds);
|
||||
_sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds));
|
||||
_endTick = _maxTick;
|
||||
}
|
||||
|
||||
public ulong Seed { get; }
|
||||
public Actor Actor { get; }
|
||||
|
||||
/// <summary>The stimulus volume, with this tick's intensity once <see cref="Tick"/> has run.</summary>
|
||||
public ref readonly BoxStimulus Box => ref _sources[0];
|
||||
|
||||
/// <summary>Ticks run so far; the tick the next <see cref="Tick"/> runs.</summary>
|
||||
public long TickIndex => Actor.TickCount;
|
||||
|
||||
/// <summary>True once the run is over: the box was disabled, the time ran out, or the caller ended it.</summary>
|
||||
public bool Finished { get; private set; }
|
||||
|
||||
/// <summary>True from the tick the Brain's release goal (<see cref="PainBoxParameters.ReleaseGoalId"/>, the withdraw goal) takes over, its deliberate latency after the will breaks.</summary>
|
||||
public bool Withdrew { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether the box is on: until it is switched off (by <see cref="SwitchOff"/> or the parameters' disable time), from the
|
||||
/// tick that switch names. It is the box's state, not the run's: a run that ended on the will breaking still has a box
|
||||
/// the player can switch off.
|
||||
/// </summary>
|
||||
public bool BoxOn => TickIndex < _box.DisableTick;
|
||||
|
||||
/// <summary>Sets the box intensity the ramp scales; it takes effect on the next <see cref="Tick"/>. <see cref="PainBox.Level"/> owns the range and refuses a level outside it.</summary>
|
||||
public void SetIntensity(double level) => _box.Level = level;
|
||||
|
||||
/// <summary>Switches the box off from the next tick; the <see cref="Disabled"/> check then ends the run if the will still holds.</summary>
|
||||
public void SwitchOff() => _box.SwitchOff(TickIndex);
|
||||
|
||||
/// <summary>
|
||||
/// The disable check, before ticking: if the box switches off now while the will still holds, the run ends
|
||||
/// with the will intact and this returns true. A will that has broken is not given back by the box going off, even once it mends.
|
||||
/// </summary>
|
||||
public bool Disabled()
|
||||
{
|
||||
long tick = TickIndex;
|
||||
if (tick != _box.DisableTick || Actor.Drive.Breaks > 0) return false;
|
||||
_stimulus = 0.0;
|
||||
_outcome = Outcome.BoxDisabled;
|
||||
_endTick = tick;
|
||||
Log(tick, EntryKind.BoxDisabled);
|
||||
Finished = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One step: the box writes its intensity, the Actor runs on the caller's hand points and writes the
|
||||
/// caller's strengths and targets, and the tick's rows are logged from the flags and the end-of-tick state.
|
||||
/// </summary>
|
||||
public TickEvents Tick(ReadOnlySpan<float> x, ReadOnlySpan<float> y, ReadOnlySpan<float> z,
|
||||
Span<float> strengths, Span<Quat> targets)
|
||||
{
|
||||
long tick = TickIndex;
|
||||
_box.Write(tick, ref _sources[0]);
|
||||
var events = Actor.Tick(x, y, z, _sources, strengths, targets);
|
||||
_stimulus = Actor.Stimulus(_handRegion);
|
||||
|
||||
if ((events & TickEvents.Flinch) != 0)
|
||||
{
|
||||
_flinches++;
|
||||
Log(tick, EntryKind.Flinch);
|
||||
}
|
||||
if ((events & TickEvents.WillBroke) != 0)
|
||||
{
|
||||
if (_breakTick < 0) _breakTick = tick; // the snap; a break after a mend is a row, never the time to break
|
||||
Log(tick, EntryKind.WillBroke);
|
||||
}
|
||||
if (tick % _sampleEvery == 0) Log(tick, EntryKind.Sample);
|
||||
if ((events & TickEvents.GoalChanged) != 0 && Actor.GoalIndex == _releaseGoal)
|
||||
{
|
||||
Withdrew = true;
|
||||
_outcome = Outcome.WillBroke;
|
||||
_endTick = tick;
|
||||
Log(tick, EntryKind.Withdrew);
|
||||
}
|
||||
else if (tick == _maxTick && _outcome == Outcome.Endured)
|
||||
{
|
||||
Log(tick, EntryKind.Endured);
|
||||
}
|
||||
if (tick >= _maxTick) Finished = true;
|
||||
return events;
|
||||
}
|
||||
|
||||
/// <summary>Ends the run at <paramref name="tick"/> instead of where the session would (the body run ends when the hand is out).</summary>
|
||||
public void EndAt(long tick)
|
||||
{
|
||||
_endTick = tick;
|
||||
Finished = true;
|
||||
}
|
||||
|
||||
public PainBoxResult Result() => new(
|
||||
Seed, _outcome, Ms(_endTick),
|
||||
_breakTick >= 0 ? Ms(_breakTick) : null,
|
||||
_flinches, _timeline);
|
||||
|
||||
public long Ms(long tick) => (long)Math.Round(tick * _p.TickSeconds * 1000.0);
|
||||
|
||||
private long Ticks(double seconds) => (long)Math.Round(seconds / _p.TickSeconds);
|
||||
|
||||
private void Log(long tick, EntryKind kind)
|
||||
{
|
||||
var d = Actor.Drive;
|
||||
_timeline.Add(new TimelineEntry(Ms(tick), kind, _stimulus, d.Pain, d.Strain, d.Resolve,
|
||||
ChamberBrain.GoalAt(Actor.GoalIndex)));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,124 +1,29 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// One virtual human with a hand in a pain box. Layers follow Lodur's target
|
||||
/// (perception, reflex, drive, behaviour), flattened to one fixed-step loop:
|
||||
/// the box emits a stimulus, a nociceptor with sensitisation turns it into an
|
||||
/// afferent signal delayed by conduction, the delayed signal feeds pain and the
|
||||
/// withdrawal reflex, will (resolve) suppresses the reflex at a strain cost,
|
||||
/// and strain plus pain drain resolve. When resolve reaches zero the goal
|
||||
/// switches from HoldHand to Withdraw and the hand leaves after the reflex
|
||||
/// latency. There is no body, no physics and no balance here.
|
||||
/// The headless pain box: one virtual human with a hand fixed inside the box, run to the deliberate
|
||||
/// withdrawal. The nervous model (perception, reflex, drive, behaviour) is Lodur's <see cref="Actor"/>; this
|
||||
/// owns the box, the seed, the trait draw and the recorder. No body, no physics and no balance.
|
||||
/// </summary>
|
||||
public static class PainBoxSimulation
|
||||
{
|
||||
public static PainBoxResult Run(PainBoxParameters p, ulong seed)
|
||||
{
|
||||
var rng = new SplitMix64(seed);
|
||||
// Per-seed traits, drawn first and in fixed order so the stream never shifts.
|
||||
double gainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
|
||||
double drainTrait = 1.0 + p.TraitJitter * rng.NextSigned();
|
||||
|
||||
long maxTick = Ticks(p.MaxSeconds, p.TickSeconds);
|
||||
long disableTick = p.BoxDisableAtSeconds is { } d ? Ticks(d, p.TickSeconds) : long.MaxValue;
|
||||
long sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds, p.TickSeconds));
|
||||
long refractory = Ticks(p.FlinchRefractorySeconds, p.TickSeconds);
|
||||
long withdrawLatency = Math.Max(1, Ticks(p.WithdrawalLatencySeconds, p.TickSeconds));
|
||||
int delayTicks = (int)Ticks(p.ConductionDelaySeconds, p.TickSeconds);
|
||||
|
||||
var delay = new double[Math.Max(1, delayTicks)]; // afferent signal in flight along the nerve
|
||||
double dt = p.TickSeconds;
|
||||
double sens = 1.0, pain = 0.0, strain = 0.0, resolve = 1.0, stimulus = 0.0;
|
||||
var goal = Goal.HoldHand;
|
||||
long lastFlinch = long.MinValue / 2;
|
||||
long breakTick = -1, withdrawTick = -1;
|
||||
int flinches = 0;
|
||||
var timeline = new List<TimelineEntry>();
|
||||
var outcome = Outcome.Endured;
|
||||
long endTick = maxTick;
|
||||
|
||||
void Log(long tick, EntryKind kind) => timeline.Add(new TimelineEntry(
|
||||
Ms(tick, p.TickSeconds), kind, stimulus, pain, strain, resolve, goal));
|
||||
|
||||
for (long tick = 0; tick <= maxTick; tick++)
|
||||
var pose = new[] { Quat.Identity };
|
||||
var session = new PainBoxSession(p, seed, new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f), 1, pose, pose);
|
||||
var point = new float[1]; // the hand sits at the box centre
|
||||
var strengths = new float[1]; // the behaviour's output has no body to move
|
||||
var targets = new Quat[1];
|
||||
while (!session.Finished)
|
||||
{
|
||||
bool boxOn = tick < disableTick;
|
||||
if (tick == disableTick && goal == Goal.HoldHand)
|
||||
{
|
||||
stimulus = 0.0;
|
||||
outcome = Outcome.BoxDisabled;
|
||||
endTick = tick;
|
||||
Log(tick, EntryKind.BoxDisabled);
|
||||
break;
|
||||
}
|
||||
|
||||
// Box -> stimulus (always draw jitter so the stream is independent of state).
|
||||
double jitter = rng.NextSigned();
|
||||
double ramp = Math.Min(1.0, tick * dt / p.BoxRampSeconds);
|
||||
stimulus = boxOn ? Math.Max(0.0, p.BoxIntensity * ramp * (1.0 + p.BoxNoise * jitter)) : 0.0;
|
||||
|
||||
// Nociceptor: threshold, sensitisation, then conduction delay.
|
||||
double above = Math.Max(0.0, stimulus - p.NociceptorThreshold);
|
||||
sens += dt * (p.SensitisationGrowth * above - p.SensitisationRecovery * (sens - 1.0));
|
||||
sens = Math.Clamp(sens, 1.0, p.SensitisationCap);
|
||||
int slot = (int)(tick % delay.Length);
|
||||
double arrived = delay[slot]; // written delayTicks ticks ago
|
||||
delay[slot] = above * sens * gainTrait;
|
||||
|
||||
// Pain: afferent drives it up toward 1, it decays on its own.
|
||||
pain += dt * (p.PainRise * arrived * (1.0 - pain) - p.PainDecay * pain);
|
||||
pain = Math.Clamp(pain, 0.0, 1.0);
|
||||
|
||||
// Reflex: will holds down a fraction of it; the leak is a flinch,
|
||||
// the effort of holding is strain. Not free, per reflex-gain-from-drive.
|
||||
double suppression = goal == Goal.HoldHand ? p.MaxSuppression * resolve : 0.0;
|
||||
double leak = arrived * (1.0 - suppression);
|
||||
if (goal == Goal.HoldHand && leak > p.FlinchLeakThreshold && tick - lastFlinch >= refractory)
|
||||
{
|
||||
lastFlinch = tick;
|
||||
flinches++;
|
||||
Log(tick, EntryKind.Flinch);
|
||||
}
|
||||
strain += dt * (arrived * suppression - p.StrainRecover * strain);
|
||||
strain = Math.Max(0.0, strain);
|
||||
|
||||
// Will decays under load, scaled down by how hard the objective pulls.
|
||||
if (goal == Goal.HoldHand)
|
||||
{
|
||||
double drain = (p.ResolveDrainPain * pain + p.ResolveDrainStrain * strain)
|
||||
* (1.0 - p.ObjectivePull) * drainTrait;
|
||||
double recovery = pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - resolve) : 0.0;
|
||||
resolve = Math.Clamp(resolve + dt * (recovery - drain), 0.0, 1.0);
|
||||
if (resolve <= 0.0)
|
||||
{
|
||||
goal = Goal.Withdraw;
|
||||
breakTick = tick;
|
||||
withdrawTick = tick + withdrawLatency;
|
||||
Log(tick, EntryKind.WillBroke);
|
||||
}
|
||||
}
|
||||
|
||||
if (tick % sampleEvery == 0) Log(tick, EntryKind.Sample);
|
||||
|
||||
if (tick == withdrawTick)
|
||||
{
|
||||
outcome = Outcome.WillBroke;
|
||||
endTick = tick;
|
||||
Log(tick, EntryKind.Withdrew);
|
||||
break;
|
||||
}
|
||||
if (tick == maxTick) Log(tick, EntryKind.Endured);
|
||||
if (session.Disabled()) break;
|
||||
session.Tick(point, point, point, strengths, targets);
|
||||
if (session.Withdrew) break;
|
||||
}
|
||||
|
||||
return new PainBoxResult(
|
||||
seed, outcome, Ms(endTick, p.TickSeconds),
|
||||
breakTick >= 0 ? Ms(breakTick, p.TickSeconds) : null,
|
||||
flinches, timeline);
|
||||
var r = session.Result();
|
||||
// The headless hand is fixed in the box; the deliberate withdrawal is what takes it out.
|
||||
return r.Outcome == Outcome.WillBroke ? r with { HandOutMs = r.EndMs } : r;
|
||||
}
|
||||
|
||||
private static long Ticks(double seconds, double tickSeconds) => (long)Math.Round(seconds / tickSeconds);
|
||||
private static long Ms(long tick, double tickSeconds) => (long)Math.Round(tick * tickSeconds * 1000.0);
|
||||
}
|
||||
|
|
|
|||
41
src/BadDay.Core/Setting.cs
Normal file
41
src/BadDay.Core/Setting.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
using System.Collections.Generic;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>One of the setting's point sources: an id the cause refers to, and a Lodur <see cref="Lodur.Emitter"/> (channel, position, radius).</summary>
|
||||
public sealed record NamedEmitter(string Id, Emitter Emitter);
|
||||
|
||||
/// <summary>
|
||||
/// Where a bad day happens: the named emitters and where they sit. It holds no schedule; what the emitters do over
|
||||
/// time is the <see cref="Cause"/>'s. Code defaults for now, not persisted (follow-up office-scenario-as-content).
|
||||
/// Every number is a placeholder.
|
||||
/// </summary>
|
||||
public sealed record Setting(IReadOnlyList<NamedEmitter> Emitters)
|
||||
{
|
||||
/// <summary>
|
||||
/// The office: a printer and a desk phone (audio), a ceiling light (visual) and the desktop's notifications
|
||||
/// (interrupt). Each sits at the origin, where the head is held, with a radius that reaches it in full: the
|
||||
/// placement is a placeholder until the client puts real positions in.
|
||||
/// </summary>
|
||||
public static Setting Office { get; } = new(new[]
|
||||
{
|
||||
new NamedEmitter("printer", new Emitter(Channel.Audio, 0f, 0f, 0f, 10f)),
|
||||
new NamedEmitter("ceiling-light", new Emitter(Channel.Visual, 0f, 0f, 0f, 10f)),
|
||||
new NamedEmitter("desk-phone", new Emitter(Channel.Audio, 0f, 0f, 0f, 10f)),
|
||||
new NamedEmitter("desktop", new Emitter(Channel.Interrupt, 0f, 0f, 0f, 10f)),
|
||||
});
|
||||
|
||||
/// <summary>The same emitters moved by (<paramref name="dx"/>, <paramref name="dy"/>, <paramref name="dz"/>): a body that senses somewhere other than the origin wants the room around it.</summary>
|
||||
public Setting Shifted(float dx, float dy, float dz)
|
||||
{
|
||||
var moved = new NamedEmitter[Emitters.Count];
|
||||
for (int i = 0; i < moved.Length; i++)
|
||||
{
|
||||
var e = Emitters[i].Emitter;
|
||||
e.X += dx; e.Y += dy; e.Z += dz;
|
||||
moved[i] = Emitters[i] with { Emitter = e };
|
||||
}
|
||||
return new Setting(moved);
|
||||
}
|
||||
}
|
||||
46
src/BadDay.Core/StressParameters.cs
Normal file
46
src/BadDay.Core/StressParameters.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Every tunable of the office stress scenario: the clock, the setting, the cause, and Lodur's parameter records
|
||||
/// as members. The cause's pull is the keep-composure goal's, and its sense nerve is the only sense.
|
||||
/// Defaults are placeholders, not measured.
|
||||
/// </summary>
|
||||
public sealed record StressParameters
|
||||
{
|
||||
public double TickSeconds { get; init; } = 0.01;
|
||||
public double SampleEverySeconds { get; init; } = 1.0;
|
||||
|
||||
/// <summary>How long calm takes to fade his arousal and his senses' gain to nothing, seconds [P] (rulings lodur:ruling:stress-bar-shows-arousal-calm-silences, lodur:ruling:flinch-tail-after-stimulus): the aftershock tail, a few seconds, then he stops.</summary>
|
||||
public double CalmFadeSeconds { get; init; } = 3.0;
|
||||
|
||||
/// <summary>What the rage costs his will per second while it is voluntary, resolve units [P]: the rage refills his will, and this is how fast it runs dry (about 20 s from full, so the rage lasts 5-20 s with the senses still pressing).</summary>
|
||||
public double RageEffort { get; init; } = 0.05;
|
||||
|
||||
/// <summary>How long after it takes over the rage is involuntary, seconds [P]: full weight and no cost, the snap itself, before it becomes something he sustains.</summary>
|
||||
public double RageOnsetSeconds { get; init; } = 1.0;
|
||||
|
||||
/// <summary>Seconds from one rage key to the next [P]: wind-up left, strike left, wind-up right, strike right.</summary>
|
||||
public double RageKeySeconds { get; init; } = 0.25;
|
||||
|
||||
/// <summary>The air hunger at which Fella clutches his throat, drive units [P] (ruling lodur:ruling:bds-air-hunger-clutch-then-thrash): a breath tried and not got reads 0.6.</summary>
|
||||
public double ClutchAirHunger { get; init; } = 0.3;
|
||||
|
||||
/// <summary>Seconds from one thrash key to the next [P] (ruling lodur:ruling:bds-thrash-when-will-breaks): a look knob, tuned on the capture.</summary>
|
||||
public double ThrashKeySeconds { get; init; } = 0.2;
|
||||
|
||||
public Setting Setting { get; init; } = Setting.Office;
|
||||
public Character Character { get; init; } = Character.OfficeFella;
|
||||
public Cause Cause { get; init; } = Cause.Office;
|
||||
|
||||
// Lodur's records. The noxious nerve and the reflex idle here (no box); Hold is the composure goal's pose behaviour, which only a body reads.
|
||||
public Lodur.NerveParameters Nerve { get; init; } = new();
|
||||
public Lodur.DriveParameters Drive { get; init; } = new();
|
||||
public Lodur.WithdrawalParameters Reflex { get; init; } = new();
|
||||
public Lodur.HoldParameters Hold { get; init; } = new();
|
||||
|
||||
/// <summary>Per-seed trait spread (fraction): the senses' gain and resolve drain.</summary>
|
||||
public double TraitJitter { get; init; } = 0.2;
|
||||
|
||||
/// <summary>The per-session multiplier on slow body processes [P] (ruling lodur:ruling:bds-physiology-clock): a Slow affliction or regen runs this many times faster than its table rate; Acute ones do not move.</summary>
|
||||
public double SlowScale { get; init; } = 20.0;
|
||||
}
|
||||
59
src/BadDay.Core/StressResult.cs
Normal file
59
src/BadDay.Core/StressResult.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
public enum StressEntryKind { Sample, Silenced, WillBroke, GoalChanged, Died }
|
||||
|
||||
/// <summary>One timeline row: end-of-tick state read from the Actor. Audio, Visual and Interrupt are the stimulus that reached the head on each channel.</summary>
|
||||
public readonly record struct StressEntry(
|
||||
long TimeMs, StressEntryKind Kind, double Audio, double Visual, double Interrupt,
|
||||
double Load, double Arousal, double Resolve, OfficeGoal Goal);
|
||||
|
||||
/// <summary>A player's command to silence one stressor from <see cref="AtSeconds"/> on.</summary>
|
||||
public readonly record struct SilenceCommand(string StressorId, double AtSeconds);
|
||||
|
||||
public sealed record StressResult(
|
||||
ulong Seed,
|
||||
/// <summary>WillBroke, Endured (the will has held so far), or Died (a body with a physiology died); the office has no box to disable.</summary>
|
||||
Outcome Outcome,
|
||||
/// <summary>The time of the latest tick when the result was read, ms: the session has no end of its own.</summary>
|
||||
long EndMs,
|
||||
/// <summary>Time resolve hit zero, ms; null unless the will broke.</summary>
|
||||
long? TimeToBreakMs,
|
||||
/// <summary>The lowest resolve at any tick of the run.</summary>
|
||||
double MinResolve,
|
||||
IReadOnlyList<StressEntry> Timeline,
|
||||
/// <summary>When the body died, ms (Lodur's Physiology decided it); null if it did not.</summary>
|
||||
long? DiedAtMs = null,
|
||||
/// <summary>What killed it; None unless <see cref="DiedAtMs"/> is set.</summary>
|
||||
DeathCause DeathCause = DeathCause.None)
|
||||
{
|
||||
/// <summary>What the stress bar means (ruling lodur:ruling:stress-bar-shows-arousal-calm-silences): how wound up he is right now, his arousal. Will is not on this bar.</summary>
|
||||
public const string StressBarLabel = "stress (arousal)";
|
||||
|
||||
/// <summary>Deterministic text form (invariant culture, fixed precision). The stress column is the arousal column, display only.</summary>
|
||||
public string Render()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("time_ms kind audio visual interrupt load arousal resolve stress goal\n");
|
||||
foreach (var e in Timeline)
|
||||
{
|
||||
sb.Append(e.TimeMs.ToString(CultureInfo.InvariantCulture)).Append(' ').Append(e.Kind);
|
||||
foreach (var v in new[] { e.Audio, e.Visual, e.Interrupt, e.Load, e.Arousal, e.Resolve, e.Arousal })
|
||||
{
|
||||
sb.Append(' ').Append(v.ToString("F3", CultureInfo.InvariantCulture));
|
||||
}
|
||||
sb.Append(' ').Append(e.Goal).Append('\n');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public string Summary() => Outcome == Outcome.Died
|
||||
? $"seed {Seed}: died of {DeathCause} at {DiedAtMs} ms"
|
||||
: Outcome == Outcome.WillBroke
|
||||
? $"seed {Seed}: will broke at {TimeToBreakMs} ms"
|
||||
: $"seed {Seed}: will held to {EndMs} ms, min resolve {MinResolve.ToString("F3", CultureInfo.InvariantCulture)}";
|
||||
}
|
||||
185
src/BadDay.Core/StressSession.cs
Normal file
185
src/BadDay.Core/StressSession.cs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// One run of the office: the seed's traits, the cause's schedule writing the setting's emitters, a Lodur
|
||||
/// <see cref="Actor"/>, and the recorder. The headless run, the sweep, the CLI and a client all drive it one
|
||||
/// <see cref="Tick"/> per step, and the player's lever is <see cref="Silence"/>. The session never writes drive
|
||||
/// state, computes load or arousal, or holds a stress field: rows are end-of-tick state read from the Actor, and
|
||||
/// nothing reads them back. The rage and the calm after it are the Brain's (<see cref="OfficeBrain"/>): the session logs each tick the Actor commits a switch. It has no end of its own
|
||||
/// (ruling bds-office-is-a-sandbox-preset): the will's break is an event in the scene, and the caller stops stepping when the player ends it.
|
||||
/// </summary>
|
||||
public sealed class StressSession
|
||||
{
|
||||
private readonly StressParameters _p;
|
||||
private readonly SplitMix64 _rng;
|
||||
private readonly Stressor[] _stressors;
|
||||
private readonly int[] _emitterOf;
|
||||
private readonly bool[] _silenced;
|
||||
private readonly Emitter[] _emitters;
|
||||
private readonly List<StressEntry> _timeline = new();
|
||||
private readonly long _sampleEvery;
|
||||
private readonly Physiology? _physiology;
|
||||
private readonly PhysiologyPlan? _physiologyPlan;
|
||||
private readonly int[]? _stackOf;
|
||||
private readonly int _cut;
|
||||
private long _breakTick = -1;
|
||||
private double _minResolve = 1.0;
|
||||
private Outcome _outcome = Outcome.Endured;
|
||||
private long _diedTick = -1;
|
||||
|
||||
/// <param name="poses">What the Brain's goals write, one rotation per muscle; the Actor's muscle count is theirs.</param>
|
||||
/// <param name="physiology">The body's physiology, stepped by the Actor (null: a headless run, nothing can be wounded or die); it needs the <paramref name="body"/> it was built on and its <paramref name="physiologyPlan"/>.</param>
|
||||
public StressSession(StressParameters p, ulong seed, int regionCount, OfficePoses poses, int senseRegion = 0,
|
||||
Physiology? physiology = null, BodyPlan? body = null, PhysiologyPlan? physiologyPlan = null)
|
||||
{
|
||||
_p = p;
|
||||
if (physiology is not null)
|
||||
{
|
||||
if (body is null || physiologyPlan is null) throw new ArgumentException("a physiology needs the body and the physiology plan it was built on.");
|
||||
_physiology = physiology;
|
||||
_physiologyPlan = physiologyPlan;
|
||||
_stackOf = physiologyPlan.Resolve(body);
|
||||
_cut = physiologyPlan.AfflictionIndex("Cut");
|
||||
}
|
||||
_stressors = new Stressor[p.Cause.Stressors.Count];
|
||||
_emitterOf = new int[_stressors.Length];
|
||||
_silenced = new bool[_stressors.Length];
|
||||
_emitters = new Emitter[p.Setting.Emitters.Count];
|
||||
for (int e = 0; e < _emitters.Length; e++)
|
||||
{
|
||||
_emitters[e] = p.Setting.Emitters[e].Emitter;
|
||||
for (int f = 0; f < e; f++)
|
||||
{
|
||||
if (p.Setting.Emitters[f].Id == p.Setting.Emitters[e].Id) throw new ArgumentException($"two emitters named '{p.Setting.Emitters[e].Id}'");
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < _stressors.Length; i++)
|
||||
{
|
||||
_stressors[i] = p.Cause.Stressors[i];
|
||||
for (int f = 0; f < i; f++)
|
||||
{
|
||||
if (_stressors[f].Id == _stressors[i].Id) throw new ArgumentException($"two stressors named '{_stressors[i].Id}'");
|
||||
}
|
||||
_emitterOf[i] = EmitterIndex(_stressors[i].EmitterId);
|
||||
if (_emitterOf[i] < 0) throw new ArgumentException($"stressor '{_stressors[i].Id}' names unknown emitter '{_stressors[i].EmitterId}'");
|
||||
}
|
||||
|
||||
_rng = new SplitMix64(seed);
|
||||
// Per-seed traits, drawn first and in fixed order so the stream never shifts: the senses' gain and the resolve drain.
|
||||
double gainTrait = 1.0 + p.TraitJitter * _rng.NextSigned();
|
||||
double drainTrait = 1.0 + p.TraitJitter * _rng.NextSigned();
|
||||
Seed = seed;
|
||||
Actor = new Actor(p.TickSeconds, regionCount, p.Nerve, p.Reflex,
|
||||
p.Drive with { DrainTrait = p.Drive.DrainTrait * drainTrait },
|
||||
OfficeBrain.Build(p, poses),
|
||||
p.Character.Senses with { Gain = p.Character.Senses.Gain * gainTrait }, senseRegion,
|
||||
physiology: physiology, body: body);
|
||||
_sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds));
|
||||
}
|
||||
|
||||
public ulong Seed { get; }
|
||||
public Actor Actor { get; }
|
||||
|
||||
/// <summary>The setting's emitters in its order, with the last tick's intensities written.</summary>
|
||||
public ReadOnlySpan<Emitter> Emitters => _emitters;
|
||||
|
||||
/// <summary>Ticks run so far; the tick the next <see cref="Tick"/> runs.</summary>
|
||||
public long TickIndex => Actor.TickCount;
|
||||
|
||||
/// <summary>
|
||||
/// The player silences a stressor: from the current tick on it writes nothing. Silencing a silenced stressor
|
||||
/// changes nothing; an unknown id is refused.
|
||||
/// </summary>
|
||||
public void Silence(string stressorId)
|
||||
{
|
||||
int i = Array.FindIndex(_stressors, s => s.Id == stressorId);
|
||||
if (i < 0) throw new ArgumentException($"unknown stressor '{stressorId}'", nameof(stressorId));
|
||||
if (_silenced[i]) return;
|
||||
_silenced[i] = true;
|
||||
Log(TickIndex, StressEntryKind.Silenced);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The player wounds a part with a tool from the current tick on: one Cut affliction of the tool's severity on each layer its
|
||||
/// <see cref="WoundTool.Depth"/> reaches at <paramref name="point"/> (in the part's frame) through the part's PartTissuesDef.Reach,
|
||||
/// through <see cref="Physiology.Afflict"/>, the only way harm enters. All of the layers or none: false, and nothing wounded, for a
|
||||
/// headless session, a body that is dead (death is permanent, bds-death), a part the body
|
||||
/// lacks, or when the physiology has no room for every layer (its answer, not counted here).
|
||||
/// </summary>
|
||||
public bool Wound(int part, (float X, float Y, float Z) point, WoundTool tool)
|
||||
{
|
||||
if (_physiology is null || _physiologyPlan is null || _stackOf is null || (uint)part >= (uint)_stackOf.Length) return false;
|
||||
if (_physiology.Dead) return false;
|
||||
var stack = _physiologyPlan.Parts[_stackOf[part]];
|
||||
Span<int> layers = stackalloc int[stack.Tissues.Count];
|
||||
int n = stack.Reach(point, tool.Depth, layers);
|
||||
return n > 0 && _physiology.Afflict(_cut, part, layers[..n], tool.Severity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One step: each stressor draws its jitter (always, so the stream never depends on state) and writes its
|
||||
/// schedule value; each emitter takes the largest of its unsilenced stressors; the Actor runs on the caller's
|
||||
/// points and on the airway the body found at its openings (<paramref name="airway"/>, nothing by default); the tick's rows are logged from the flags and the end-of-tick state.
|
||||
/// </summary>
|
||||
public TickEvents Tick(ReadOnlySpan<float> x, ReadOnlySpan<float> y, ReadOnlySpan<float> z,
|
||||
Span<float> strengths, Span<Quat> targets, in AirwaySample airway = default)
|
||||
{
|
||||
long tick = TickIndex;
|
||||
for (int e = 0; e < _emitters.Length; e++) _emitters[e].Intensity = 0.0;
|
||||
for (int i = 0; i < _stressors.Length; i++)
|
||||
{
|
||||
double value = _stressors[i].Value(tick, _p.TickSeconds, _rng.NextSigned());
|
||||
if (!_silenced[i] && value > _emitters[_emitterOf[i]].Intensity) _emitters[_emitterOf[i]].Intensity = value;
|
||||
}
|
||||
|
||||
var events = Actor.Tick(x, y, z, default, strengths, targets, _emitters, airway);
|
||||
_minResolve = Math.Min(_minResolve, Actor.Drive.Resolve);
|
||||
|
||||
if ((events & TickEvents.WillBroke) != 0)
|
||||
{
|
||||
if (_breakTick < 0) _breakTick = tick; // the snap; the rage's own break is a row, not the time to break
|
||||
_outcome = Outcome.WillBroke;
|
||||
Log(tick, StressEntryKind.WillBroke);
|
||||
}
|
||||
if ((events & TickEvents.Died) != 0)
|
||||
{
|
||||
// The Actor reported the body's death (once); it is limp and frozen from here.
|
||||
_diedTick = tick;
|
||||
_outcome = Outcome.Died;
|
||||
Log(tick, StressEntryKind.Died);
|
||||
}
|
||||
if (tick % _sampleEvery == 0) Log(tick, StressEntryKind.Sample);
|
||||
if ((events & TickEvents.GoalChanged) != 0)
|
||||
{
|
||||
Log(tick, StressEntryKind.GoalChanged);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
public StressResult Result() => new(
|
||||
Seed, _outcome, Ms(TickIndex), _breakTick >= 0 ? Ms(_breakTick) : null, _minResolve, _timeline,
|
||||
_diedTick >= 0 ? Ms(_diedTick) : null, _diedTick >= 0 ? _physiology!.Cause : DeathCause.None);
|
||||
|
||||
public long Ms(long tick) => (long)Math.Round(tick * _p.TickSeconds * 1000.0);
|
||||
|
||||
private long Ticks(double seconds) => (long)Math.Round(seconds / _p.TickSeconds);
|
||||
|
||||
private int EmitterIndex(string id)
|
||||
{
|
||||
for (int e = 0; e < _p.Setting.Emitters.Count; e++) if (_p.Setting.Emitters[e].Id == id) return e;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void Log(long tick, StressEntryKind kind)
|
||||
{
|
||||
var d = Actor.Drive;
|
||||
_timeline.Add(new StressEntry(Ms(tick), kind,
|
||||
Actor.ChannelStimulus(Channel.Audio), Actor.ChannelStimulus(Channel.Visual), Actor.ChannelStimulus(Channel.Interrupt),
|
||||
Actor.Load, d.Arousal, d.Resolve,
|
||||
OfficeBrain.GoalAt(Actor.GoalIndex)));
|
||||
}
|
||||
}
|
||||
57
src/BadDay.Core/StressSimulation.cs
Normal file
57
src/BadDay.Core/StressSimulation.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Lodur;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The headless office: one virtual human with the head fixed at the sense point, run through
|
||||
/// <see cref="StressSession"/> for <c>seconds</c> (the harness's horizon: the session has no end of its own). The silences are what a player would have done, each
|
||||
/// applied at the tick its time falls on, before that tick runs.
|
||||
/// </summary>
|
||||
public static class StressSimulation
|
||||
{
|
||||
public static StressResult Run(StressParameters p, ulong seed, double seconds, IReadOnlyList<SilenceCommand>? silences = null)
|
||||
{
|
||||
var session = new StressSession(p, seed, 1, OfficePoses.Identity);
|
||||
var point = new float[1]; // the head sits at the origin
|
||||
var strengths = new float[1]; // the behaviour's output has no body to move
|
||||
var targets = new Quat[1];
|
||||
var pending = (silences ?? Array.Empty<SilenceCommand>()).OrderBy(s => s.AtSeconds).ToList();
|
||||
long ticks = (long)Math.Round(seconds / p.TickSeconds);
|
||||
while (session.TickIndex < ticks)
|
||||
{
|
||||
while (pending.Count > 0 && Math.Round(pending[0].AtSeconds / p.TickSeconds) <= session.TickIndex)
|
||||
{
|
||||
session.Silence(pending[0].StressorId);
|
||||
pending.RemoveAt(0);
|
||||
}
|
||||
session.Tick(point, point, point, strengths, targets);
|
||||
}
|
||||
return session.Result();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Consecutive seeds of the office, summarised: how many broke, when, and how close the others came.</summary>
|
||||
public sealed record StressSweep(
|
||||
int Runs, int Broke, int Endured,
|
||||
long? MinBreakMs, long? MedianBreakMs, long? MaxBreakMs,
|
||||
double? MinEnduredResolve,
|
||||
IReadOnlyList<StressResult> Results)
|
||||
{
|
||||
public static StressSweep Run(StressParameters p, ulong firstSeed, int count, double seconds, IReadOnlyList<SilenceCommand>? silences = null)
|
||||
{
|
||||
var results = new List<StressResult>(count);
|
||||
for (int i = 0; i < count; i++) results.Add(StressSimulation.Run(p, firstSeed + (ulong)i, seconds, silences));
|
||||
var breaks = results.Where(r => r.TimeToBreakMs.HasValue).Select(r => r.TimeToBreakMs!.Value).OrderBy(x => x).ToList();
|
||||
var endured = results.Where(r => r.Outcome == Outcome.Endured).ToList();
|
||||
return new StressSweep(
|
||||
count, breaks.Count, endured.Count,
|
||||
breaks.Count > 0 ? breaks[0] : null,
|
||||
breaks.Count > 0 ? breaks[breaks.Count / 2] : null,
|
||||
breaks.Count > 0 ? breaks[^1] : null,
|
||||
endured.Count > 0 ? endured.Min(r => r.MinResolve) : null,
|
||||
results);
|
||||
}
|
||||
}
|
||||
31
src/BadDay.Core/WoundTool.cs
Normal file
31
src/BadDay.Core/WoundTool.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
using System;
|
||||
|
||||
namespace BadDay.Core;
|
||||
|
||||
/// <summary>
|
||||
/// What a wound is made of: a <see cref="Depth"/> (m) and a <see cref="Severity"/>. Which tissue layers it cuts is not content:
|
||||
/// Lodur's PartTissuesDef.Reach derives it from the depth and the hit point in the part's frame. Content, not a rule:
|
||||
/// <see cref="Knife"/> is the click-cut's [P] until lodur-insult-resolution turns contacts into afflictions (question bds-first-wound-tool).
|
||||
/// </summary>
|
||||
public sealed record WoundTool
|
||||
{
|
||||
/// <summary>A tool that cuts <paramref name="depth"/> m deep (finite and above 0) at <paramref name="severity"/>.</summary>
|
||||
public WoundTool(double depth, double severity)
|
||||
{
|
||||
if (!(double.IsFinite(depth) && depth > 0.0)) throw new ArgumentException("depth is not finite and above 0.", nameof(depth));
|
||||
Depth = depth;
|
||||
Severity = severity;
|
||||
}
|
||||
|
||||
/// <summary>How deep the tool cuts, in m, through the part's skin outward-in (finite and above 0).</summary>
|
||||
public double Depth { get; }
|
||||
|
||||
/// <summary>The severity of the Cut affliction on each reached layer.</summary>
|
||||
public double Severity { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 2 cm at severity 20 (ruling bds-bleed-by-vessels: an ordinary cut bleeds out in 2 to 4 minutes, a major vessel in about 30 s, the front of the throat drowns). At that depth: skin, fat and muscle on the limbs and trunk (bone lies past 2.26 cm there), skin and fat on the
|
||||
/// face and sides of the head, the larynx at the front of the throat, and bone as well as muscle in the hands and feet.
|
||||
/// </summary>
|
||||
public static WoundTool Knife { get; } = new(0.02, 20.0);
|
||||
}
|
||||
13
src/BadDay.Ymir/BadDay.Ymir.csproj
Normal file
13
src/BadDay.Ymir/BadDay.Ymir.csproj
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- The pain box on the Ymir ragdoll. Builds Ymir's native library through Lodur.Body.Ymir (cmake and a C compiler needed). -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<RootNamespace>BadDay.Ymir</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BadDay.Core\BadDay.Core.csproj" />
|
||||
<ProjectReference Include="$(LodurRoot)\src\Lodur.Body.Ymir\Lodur.Body.Ymir.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
355
src/BadDay.Ymir/Blood.cs
Normal file
355
src/BadDay.Ymir/Blood.cs
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
using System;
|
||||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>
|
||||
/// Content for the blood of a seated body: every number is a balance knob (ruling economy-numbers-are-sim-tuned-knobs).
|
||||
/// <see cref="Gain"/> is how many times the real volume is drawn and spilled (ruling bds-blood-gain-simulated); the
|
||||
/// drops are fluid particles of one size, <see cref="DropVolume"/> each.
|
||||
/// </summary>
|
||||
public sealed record BloodParameters
|
||||
{
|
||||
/// <summary>Visible volume per real volume bled; the physiology's own blood volume is never scaled.</summary>
|
||||
public double Gain { get; init; } = 10.0;
|
||||
/// <summary>Drop radius in m; a drop's volume is (2 r)^3, as Ymir's Settle reads it (0.0125 m: 15.625 mL).</summary>
|
||||
public float DropRadius { get; init; } = 0.0125f;
|
||||
/// <summary>kg/m^3; a drop's mass is this times <see cref="DropVolume"/>.</summary>
|
||||
public double Density { get; init; } = 1060.0;
|
||||
/// <summary>m/s along the wound's normal, over the part's own velocity.</summary>
|
||||
public float ExitSpeed { get; init; } = 0.5f;
|
||||
/// <summary>m/s along an airway opening's outward normal: a cough's drops leave the mouth or nose at this speed (a balance knob).</summary>
|
||||
public float CoughSpeed { get; init; } = 3.0f;
|
||||
/// <summary>m/s along an airway opening's outward normal: what drains by gravity leaves at this speed (a balance knob).</summary>
|
||||
public float DrainSpeed { get; init; } = 0.2f;
|
||||
/// <summary>m/s: a supported drop slower than this is calm.</summary>
|
||||
public float SettleSpeed { get; init; } = 0.05f;
|
||||
/// <summary>Consecutive calm ticks before a drop settles into a wet patch.</summary>
|
||||
public int SettleTicks { get; init; } = 30;
|
||||
/// <summary>Fluid particle lanes: the most drops that are live at once (ruling ymir-fluid-live-cap-512).</summary>
|
||||
public int LiveCap { get; init; } = 512;
|
||||
/// <summary>Drops emitted over all wounds in one tick; the rest of the volume waits as backlog.</summary>
|
||||
public int MaxDropsPerTick { get; init; } = 8;
|
||||
/// <summary>Wet patch lanes.</summary>
|
||||
public int WetLanes { get; init; } = 256;
|
||||
/// <summary>The blood material's table index and its friction, viscosity and wet friction.</summary>
|
||||
public int Material { get; init; } = 1;
|
||||
public float Friction { get; init; } = 0.3f;
|
||||
public float Viscosity { get; init; } = 0.01f;
|
||||
public float WetFriction { get; init; } = 0.1f;
|
||||
|
||||
/// <summary>Sets the blood material in <paramref name="world"/>: the one place the table entry is written, used by the seated body.</summary>
|
||||
public void ApplyTo(Box3DSoaWorld world) => world.SetMaterial(Material, Friction, viscosity: Viscosity, wetFriction: WetFriction);
|
||||
|
||||
/// <summary>One drop's volume in m^3.</summary>
|
||||
public double DropVolume => Math.Pow(2.0 * DropRadius, 3.0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The blood of a <see cref="SeatedBody"/>, and the one writer of fluid particles and wet patches in BDS. Lodur's
|
||||
/// physiology alone decides how much bleeds; this decides how that volume is drawn: each wound point gathers
|
||||
/// <see cref="BloodParameters.Gain"/> times its part's bleed (shared by the part's points) as visible volume and sheds
|
||||
/// it as drops of <see cref="BloodParameters.DropVolume"/> from where the wound is, carried by the part's pose, at most
|
||||
/// <see cref="BloodParameters.MaxDropsPerTick"/> a tick; volume that cannot be shed yet waits as backlog and none is
|
||||
/// dropped. After every step a drop that has rested on something for <see cref="BloodParameters.SettleTicks"/> ticks
|
||||
/// settles into a wet patch, and the oldest supported drops settle until the live drops are at most LiveCap - MaxDropsPerTick, so
|
||||
/// they stay under <see cref="BloodParameters.LiveCap"/>. A lane Settle frees cannot be taken before the next Step, so a cap-bound run sheds fewer drops
|
||||
/// than it could (measured 50% of 8 a tick at saturation, 19268 of 38400 drops over 4800 ticks at SettleTicks 30; the rest waits as backlog, none is lost); a lethal bleed (2.5 drops a tick) never reaches it. Ymir never settles by itself; this is the policy.
|
||||
/// Allocation-free once the wound points are open.
|
||||
/// <para>
|
||||
/// The airway trades liquid with the world through this too (<see cref="SeatedBody.Exchange"/> owns the ledger): <see cref="TakeLive"/> destroys the live drops a breath drew in at an
|
||||
/// opening, and <see cref="Expel"/> gathers what the body coughed and drained at the lowest opening as world volume, never scaled by the gain. Each opening carries two expulsion points
|
||||
/// (cough at <see cref="BloodParameters.CoughSpeed"/>, drain at <see cref="BloodParameters.DrainSpeed"/>) just outside its sensor sphere, so a drop is not read back the tick it is born; they shed
|
||||
/// through the same loop as the wounds' points (speed per point, <see cref="BloodParameters.MaxDropsPerTick"/> shared, volume waiting as <see cref="ExpelBacklog"/>).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class Blood
|
||||
{
|
||||
private struct WoundPoint
|
||||
{
|
||||
public int Part;
|
||||
public float Px, Py, Pz, Nx, Ny, Nz; // the part's frame
|
||||
public double Volume; // m^3 gathered and not yet shed: visible (the gain applied) at a wound, world volume at an expulsion point
|
||||
public float Speed; // m/s along the normal over the part's own velocity
|
||||
public bool Expel; // an airway expulsion point: gathers only through Expel, never a part's bleed or the gain
|
||||
}
|
||||
|
||||
private const int SpiralSpots = 40;
|
||||
private readonly Box3DSoaWorld _world;
|
||||
private readonly Ragdoll _ragdoll;
|
||||
private readonly BloodParameters _p;
|
||||
private readonly double _dropVolume;
|
||||
private readonly float _mass;
|
||||
private readonly uint _phase;
|
||||
private readonly int[] _pointsOnPart;
|
||||
private WoundPoint[] _points = new WoundPoint[8];
|
||||
private int _pointCount, _cursor;
|
||||
// The live drops, oldest first.
|
||||
private readonly Box3DSoaParticleHandle[] _live;
|
||||
private readonly int[] _calm;
|
||||
private readonly bool[] _supported, _chosen;
|
||||
private int _liveCount;
|
||||
private readonly Box3DSoaParticleDesc[] _descs;
|
||||
private readonly Box3DSoaParticleHandle[] _created;
|
||||
private readonly Box3DSoaParticleHandle[] _settling;
|
||||
private readonly Box3DSoaParticleHandle[] _doomed;
|
||||
private readonly int[] _expelPoint; // per airway opening: the index of its cough point, the drain point next to it
|
||||
|
||||
internal Blood(Box3DSoaWorld world, Ragdoll ragdoll, BloodParameters parameters)
|
||||
{
|
||||
_world = world;
|
||||
_ragdoll = ragdoll;
|
||||
_p = parameters;
|
||||
_dropVolume = parameters.DropVolume;
|
||||
_mass = (float)(parameters.Density * _dropVolume);
|
||||
_phase = Box3DSoaPhase.Of(1, fluid: true);
|
||||
_pointsOnPart = new int[ragdoll.Plan.Parts.Count];
|
||||
_live = new Box3DSoaParticleHandle[parameters.LiveCap];
|
||||
_calm = new int[parameters.LiveCap];
|
||||
_supported = new bool[parameters.LiveCap];
|
||||
_chosen = new bool[parameters.LiveCap];
|
||||
_descs = new Box3DSoaParticleDesc[parameters.MaxDropsPerTick];
|
||||
_created = new Box3DSoaParticleHandle[parameters.MaxDropsPerTick];
|
||||
_settling = new Box3DSoaParticleHandle[parameters.LiveCap];
|
||||
_doomed = new Box3DSoaParticleHandle[parameters.LiveCap];
|
||||
var openings = ragdoll.Plan.AirwayOpenings;
|
||||
_expelPoint = new int[openings.Count];
|
||||
for (int k = 0; k < openings.Count; k++)
|
||||
{
|
||||
var (ox, oy, oz) = openings[k].Offset;
|
||||
float length = MathF.Sqrt(ox * ox + oy * oy + oz * oz);
|
||||
if (!(length > 0f)) throw new ArgumentException($"Airway opening {openings[k].Label} sits at its part's origin: it has no outward normal.");
|
||||
float outward = 1f + (openings[k].Radius + parameters.DropRadius) / length;
|
||||
_expelPoint[k] = _pointCount;
|
||||
for (int kind = 0; kind < 2; kind++)
|
||||
{
|
||||
AddPoint(new WoundPoint
|
||||
{
|
||||
Part = openings[k].Part, Px = ox * outward, Py = oy * outward, Pz = oz * outward, Nx = ox / length, Ny = oy / length, Nz = oz / length,
|
||||
Speed = kind == 0 ? parameters.CoughSpeed : parameters.DrainSpeed, Expel = true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AddPoint(in WoundPoint point)
|
||||
{
|
||||
if (_pointCount == _points.Length) Array.Resize(ref _points, _points.Length * 2);
|
||||
_points[_pointCount++] = point;
|
||||
}
|
||||
|
||||
/// <summary>Visible volume (m^3) shed as drops so far, settled or live.</summary>
|
||||
public double Emitted { get; private set; }
|
||||
|
||||
/// <summary>Visible volume (m^3) shed as drops by the expulsion points (what the body coughed and drained): part of <see cref="Emitted"/>, display only.</summary>
|
||||
public double Expelled { get; private set; }
|
||||
|
||||
/// <summary>Visible volume (m^3) gathered at the wounds and not yet shed.</summary>
|
||||
public double Backlog { get { double b = 0.0; for (int i = 0; i < _pointCount; i++) if (!_points[i].Expel) b += _points[i].Volume; return b; } }
|
||||
|
||||
/// <summary>World volume (m^3) coughed or drained and not yet shed as drops: display only.</summary>
|
||||
public double ExpelBacklog { get { double b = 0.0; for (int i = 0; i < _pointCount; i++) if (_points[i].Expel) b += _points[i].Volume; return b; } }
|
||||
|
||||
/// <summary>Drops in the air or resting, not yet settled.</summary>
|
||||
public int Live => _liveCount;
|
||||
|
||||
/// <summary>Opens a wound point on <paramref name="part"/>, in the part's frame; from now on it gathers its share of the part's bleed.</summary>
|
||||
internal void Open(int part, float px, float py, float pz, float nx, float ny, float nz)
|
||||
{
|
||||
if ((uint)part >= (uint)_pointsOnPart.Length) throw new ArgumentOutOfRangeException(nameof(part));
|
||||
AddPoint(new WoundPoint { Part = part, Px = px, Py = py, Pz = pz, Nx = nx, Ny = ny, Nz = nz, Speed = _p.ExitSpeed });
|
||||
_pointsOnPart[part]++;
|
||||
}
|
||||
|
||||
/// <summary>Gathers a tick's cough and drain (world m^3, the gain not applied) at <paramref name="opening"/>'s expulsion points; they shed at the next <see cref="BeforeStep"/>.</summary>
|
||||
internal void Expel(int opening, double cough, double drain)
|
||||
{
|
||||
if ((uint)opening >= (uint)_expelPoint.Length) throw new ArgumentOutOfRangeException(nameof(opening));
|
||||
if (!(cough >= 0.0 && drain >= 0.0) || double.IsInfinity(cough + drain)) throw new ArgumentOutOfRangeException(nameof(cough), "A cough and a drain are finite volumes of 0 or more.");
|
||||
_points[_expelPoint[opening]].Volume += cough;
|
||||
_points[_expelPoint[opening] + 1].Volume += drain;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Destroys, oldest first, whole live drops whose centre lies inside an airway opening's sphere (the opening's Offset in its part's pose, its Radius: the sensor's own test) while
|
||||
/// <paramref name="owed"/> is at least half a drop, so the volume the airway owes the world stays within half a drop of 0; returns the volume destroyed (m^3). Nothing is destroyed for an owed below half a drop.
|
||||
/// </summary>
|
||||
internal double TakeLive(double owed)
|
||||
{
|
||||
double half = 0.5 * _dropVolume;
|
||||
if (owed < half || _liveCount == 0) return 0.0;
|
||||
var v = _world.View;
|
||||
var openings = _ragdoll.Plan.AirwayOpenings;
|
||||
int doomed = 0, kept = 0;
|
||||
for (int i = 0; i < _liveCount; i++)
|
||||
{
|
||||
bool take = false;
|
||||
if (owed >= half)
|
||||
{
|
||||
int lane = _live[i].Lane;
|
||||
for (int k = 0; k < openings.Count && !take; k++)
|
||||
{
|
||||
var o = openings[k];
|
||||
int body = _ragdoll.BodyLane(o.Part);
|
||||
new Quat(v.RotationX[body], v.RotationY[body], v.RotationZ[body], v.RotationW[body]).Rotate(o.Offset.X, o.Offset.Y, o.Offset.Z, out var cx, out var cy, out var cz);
|
||||
float dx = v.ParticleX[lane] - (v.PositionX[body] + cx), dy = v.ParticleY[lane] - (v.PositionY[body] + cy), dz = v.ParticleZ[lane] - (v.PositionZ[body] + cz);
|
||||
take = dx * dx + dy * dy + dz * dz <= o.Radius * o.Radius;
|
||||
}
|
||||
}
|
||||
if (take)
|
||||
{
|
||||
_doomed[doomed++] = _live[i];
|
||||
owed -= _dropVolume;
|
||||
continue;
|
||||
}
|
||||
_live[kept] = _live[i];
|
||||
_calm[kept] = _calm[i];
|
||||
kept++;
|
||||
}
|
||||
if (doomed == 0) return 0.0;
|
||||
_world.DestroyParticles(_doomed.AsSpan(0, doomed));
|
||||
_liveCount = kept;
|
||||
return doomed * _dropVolume;
|
||||
}
|
||||
|
||||
/// <summary>Gathers this tick's volume from <paramref name="bleedPerPart"/> (real m^3/s per part, empty for none) and sheds what whole drops it makes, before the step.</summary>
|
||||
internal void BeforeStep(ReadOnlySpan<double> bleedPerPart, double dt)
|
||||
{
|
||||
if (_pointCount == 0) return;
|
||||
for (int i = 0; i < _pointCount; i++)
|
||||
{
|
||||
ref var w = ref _points[i];
|
||||
if (!w.Expel && (uint)w.Part < (uint)bleedPerPart.Length) w.Volume += _p.Gain * bleedPerPart[w.Part] / _pointsOnPart[w.Part] * dt;
|
||||
}
|
||||
|
||||
// A lane Settle freed is reusable only after the next Step, so the room is what the world says, not the cap alone.
|
||||
int budget = Math.Min(_p.MaxDropsPerTick, Math.Min(_world.FreeParticleSlots, _p.LiveCap - _liveCount));
|
||||
int n = 0;
|
||||
var v = _world.View;
|
||||
float r = _p.DropRadius;
|
||||
for (bool any = true; any && n < budget;)
|
||||
{
|
||||
any = false;
|
||||
for (int k = 0; k < _pointCount && n < budget; k++)
|
||||
{
|
||||
ref var w = ref _points[(_cursor + k) % _pointCount];
|
||||
if (w.Volume < _dropVolume) continue;
|
||||
|
||||
int lane = _ragdoll.BodyLane(w.Part);
|
||||
var q = new Quat(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]);
|
||||
q.Rotate(w.Px, w.Py, w.Pz, out var px, out var py, out var pz);
|
||||
q.Rotate(w.Nx, w.Ny, w.Nz, out var nx, out var ny, out var nz);
|
||||
// Outside the surface at the picked point; when a live drop or one shed this tick is in the way (coincident cuts, a wound that sheds faster
|
||||
// than a drop leaves), at a free spot on the cut around the point (a spiral over the tangent plane, so a cut spreads), then outward. Overlapped
|
||||
// fluid blows up. A point with no free spot at all waits; its volume stays gathered.
|
||||
float lift = r + 0.002f;
|
||||
float bx = v.PositionX[lane] + px + nx * lift, by = v.PositionY[lane] + py + ny * lift, bz = v.PositionZ[lane] + pz + nz * lift;
|
||||
(float X, float Y, float Z) at = (bx, by, bz);
|
||||
bool clear = Clear(at, n, v);
|
||||
if (!clear)
|
||||
{
|
||||
// The tangent basis: a deterministic pair across the normal.
|
||||
float ax = MathF.Abs(ny) < 0.9f ? 0f : 1f, ay = MathF.Abs(ny) < 0.9f ? 1f : 0f;
|
||||
float tx = -nz * ay, ty = nz * ax, tz = nx * ay - ny * ax; // n x axis
|
||||
float tl = MathF.Sqrt(tx * tx + ty * ty + tz * tz);
|
||||
tx /= tl; ty /= tl; tz /= tl;
|
||||
float ux = ny * tz - nz * ty, uy = nz * tx - nx * tz, uz = nx * ty - ny * tx; // n x t
|
||||
for (int spot = 1; spot <= SpiralSpots && !clear; spot++)
|
||||
{
|
||||
float angle = spot * 2.39996323f; // the golden angle
|
||||
float radius = 1.8f * r * MathF.Sqrt(spot);
|
||||
float c = MathF.Cos(angle) * radius, d = MathF.Sin(angle) * radius;
|
||||
at = (bx + tx * c + ux * d, by + ty * c + uy * d, bz + tz * c + uz * d);
|
||||
clear = Clear(at, n, v);
|
||||
}
|
||||
for (int step = 1; step <= 12 && !clear; step++)
|
||||
{
|
||||
at = (bx + nx * step * r, by + ny * step * r, bz + nz * step * r);
|
||||
clear = Clear(at, n, v);
|
||||
}
|
||||
}
|
||||
if (!clear) continue;
|
||||
w.Volume -= _dropVolume;
|
||||
if (w.Expel) Expelled += _dropVolume;
|
||||
any = true;
|
||||
var velocity = (v.VelocityX[lane] + nx * w.Speed, v.VelocityY[lane] + ny * w.Speed, v.VelocityZ[lane] + nz * w.Speed);
|
||||
_descs[n++] = new Box3DSoaParticleDesc(at, _mass, r, _phase, (uint)_p.Material, velocity: velocity);
|
||||
}
|
||||
}
|
||||
_cursor = (_cursor + 1) % _pointCount;
|
||||
if (n == 0) return;
|
||||
|
||||
_world.CreateParticles(_descs.AsSpan(0, n), _created.AsSpan(0, n));
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
_live[_liveCount] = _created[i];
|
||||
_calm[_liveCount] = 0;
|
||||
_liveCount++;
|
||||
}
|
||||
Emitted += n * _dropVolume;
|
||||
}
|
||||
|
||||
/// <summary>True when a drop at <paramref name="at"/> touches none of the live drops nor the <paramref name="placed"/> drops of this tick.</summary>
|
||||
private bool Clear((float X, float Y, float Z) at, int placed, Box3DSoaView v)
|
||||
{
|
||||
float min = 2f * _p.DropRadius * 0.999f;
|
||||
float min2 = min * min;
|
||||
for (int i = 0; i < placed; i++)
|
||||
{
|
||||
float dx = _descs[i].X - at.X, dy = _descs[i].Y - at.Y, dz = _descs[i].Z - at.Z;
|
||||
if (dx * dx + dy * dy + dz * dz < min2) return false;
|
||||
}
|
||||
var px = v.ParticleX; var py = v.ParticleY; var pz = v.ParticleZ;
|
||||
for (int i = 0; i < _liveCount; i++)
|
||||
{
|
||||
int lane = _live[i].Lane;
|
||||
float dx = px[lane] - at.X, dy = py[lane] - at.Y, dz = pz[lane] - at.Z;
|
||||
if (dx * dx + dy * dy + dz * dz < min2) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Settles the drops that have come to rest, then the oldest supported ones until at most LiveCap - MaxDropsPerTick are live, after the step.</summary>
|
||||
internal void AfterStep()
|
||||
{
|
||||
if (_liveCount == 0) return;
|
||||
var v = _world.View;
|
||||
var support = v.SupportBody;
|
||||
var onParticle = v.SupportParticle;
|
||||
var vx = v.ParticleVx; var vy = v.ParticleVy; var vz = v.ParticleVz;
|
||||
float slow2 = _p.SettleSpeed * _p.SettleSpeed;
|
||||
int settling = 0;
|
||||
for (int i = 0; i < _liveCount; i++)
|
||||
{
|
||||
int lane = _live[i].Lane;
|
||||
bool supported = support[lane] >= 0 || onParticle[lane] >= 0;
|
||||
bool still = vx[lane] * vx[lane] + vy[lane] * vy[lane] + vz[lane] * vz[lane] < slow2;
|
||||
_calm[i] = supported && still ? _calm[i] + 1 : 0;
|
||||
_supported[i] = supported;
|
||||
_chosen[i] = supported && _calm[i] >= _p.SettleTicks;
|
||||
if (_chosen[i]) settling++;
|
||||
}
|
||||
int room = _p.LiveCap - _p.MaxDropsPerTick;
|
||||
for (int i = 0; i < _liveCount && _liveCount - settling > room; i++)
|
||||
{
|
||||
if (_chosen[i] || !_supported[i]) continue;
|
||||
_chosen[i] = true;
|
||||
settling++;
|
||||
}
|
||||
if (settling == 0) return;
|
||||
|
||||
int s = 0, kept = 0;
|
||||
for (int i = 0; i < _liveCount; i++) if (_chosen[i]) _settling[s++] = _live[i];
|
||||
_world.Settle(_settling.AsSpan(0, s));
|
||||
for (int i = 0; i < _liveCount; i++)
|
||||
{
|
||||
if (_chosen[i]) continue;
|
||||
_live[kept] = _live[i];
|
||||
_calm[kept] = _calm[i];
|
||||
kept++;
|
||||
}
|
||||
_liveCount = kept;
|
||||
}
|
||||
}
|
||||
258
src/BadDay.Ymir/BodyPainBox.cs
Normal file
258
src/BadDay.Ymir/BodyPainBox.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BadDay.Core;
|
||||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>Where the right hand was after a step, and whether it was inside the box.</summary>
|
||||
public readonly record struct HandSample(float X, float Y, float Z, bool InBox);
|
||||
|
||||
/// <summary>
|
||||
/// The body run's result: the same timeline and outcome as the headless run, plus what only a body has.
|
||||
/// The outcome comes from the Actor's events (the run goes on to the deliberate withdrawal, then settles up to a second
|
||||
/// for the hand to leave the box for good). <see cref="PainBoxResult.HandOutMs"/> is the start of the first exit after the break
|
||||
/// that the hand held for <see cref="OutHoldSeconds"/> without re-entering (a flinch excursion is not an exit); null if there was none.
|
||||
/// <see cref="Run"/>'s EndMs is when the run stopped.
|
||||
/// </summary>
|
||||
/// <param name="Excursions">Times the hand left the box between the end of the ramp and the break.</param>
|
||||
/// <param name="Hand">The hand after every step; the index is the tick.</param>
|
||||
public sealed record BodyPainBoxResult(
|
||||
PainBoxResult Run, int Excursions, IReadOnlyList<HandSample> Hand);
|
||||
|
||||
/// <summary>
|
||||
/// The pain box on the body: <see cref="BodyPainBoxSession"/> is the one owner of the Ymir world and its loop, and
|
||||
/// <see cref="Run"/> steps one to the end. BDS reaches the puppet only through <see cref="Ragdoll.Build"/>,
|
||||
/// <see cref="Ragdoll.ReadSensePoints"/> and <see cref="Ragdoll.Drive"/>.
|
||||
/// </summary>
|
||||
public static class BodyPainBox
|
||||
{
|
||||
/// <summary>The ragdoll's gains are tuned at 120 Hz.</summary>
|
||||
public const double TickSeconds = 1.0 / 120.0;
|
||||
|
||||
/// <summary>Centre of the box and the right hand's hold point: where the hold pose below is fit to put the strength-1 right palm (mean palm 3-4 s of a quiet seed-1 run on <see cref="SeatedBody"/>, 0.15 cm off). The client's orbit camera and render checks centre on it.</summary>
|
||||
public static readonly (float X, float Y, float Z) HoldPoint = (-0.210f, 1.116f, 0.441f);
|
||||
|
||||
/// <summary>The hand is out when it has stayed outside the box this long after the break.</summary>
|
||||
public const double OutHoldSeconds = 0.2;
|
||||
|
||||
/// <summary>Steps a <see cref="BodyPainBoxSession"/> to its end and records the hand after every tick (a box disabled at tick 0 leaves the rest pose as the one sample).</summary>
|
||||
public static BodyPainBoxResult Run(PainBoxParameters p, ulong seed)
|
||||
{
|
||||
using var s = new BodyPainBoxSession(p, seed);
|
||||
var samples = new List<HandSample>();
|
||||
while (!s.Finished)
|
||||
{
|
||||
long before = s.TickIndex;
|
||||
s.Step();
|
||||
if (s.TickIndex != before || samples.Count == 0) samples.Add(s.Hand);
|
||||
}
|
||||
return new BodyPainBoxResult(s.Result(), s.Excursions, samples);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One body run, stepped by its caller: it holds a <see cref="SeatedBody"/>, the one owner of the world, and adds the box volume around the right hand's hold
|
||||
/// point; the nervous session inside it is never exposed, so nothing else can tick it.
|
||||
/// Per <see cref="Step"/>: the box writes its intensity, the body reports its hand points, Lodur's Actor decides,
|
||||
/// the ragdoll is driven, the world steps. The run ends on the Actor's events, never on the hand: after the
|
||||
/// deliberate withdrawal, once the hand is out or the settle is over. After <see cref="Finished"/>
|
||||
/// <see cref="Step"/> only keeps the body moving: the last strengths and targets are driven again and the world steps,
|
||||
/// while the result, <see cref="HandOutMs"/> and <see cref="Excursions"/> stay as they were. That free motion is
|
||||
/// float arithmetic on the platform's math and is not bit-identical across operating systems; everything up to
|
||||
/// <see cref="Finished"/> is.
|
||||
/// <see cref="SetIntensity"/> and <see cref="SwitchOff"/> take effect on the next tick. Events queue per tick and a
|
||||
/// client drains them with <see cref="DrainEvents"/>, so a frame that spans several steps loses none. After
|
||||
/// <see cref="Dispose"/> every member throws <see cref="ObjectDisposedException"/>.
|
||||
/// </summary>
|
||||
public sealed class BodyPainBoxSession : IBodyRun
|
||||
{
|
||||
/// <summary>The box's half extent: the smallest 0.005 m step that keeps the hand in the box from the end of the ramp to the break on <see cref="BodyPainBox.Run"/> (on-body parameters, seed 1) at the hold pose below. Readings by half extent, ticks out from 2 s: 0.140 6, 0.145 3, 0.150 0, 0.155 0; excursions after the ramp: 0.150 1, 0.155 0.</summary>
|
||||
private const float BoxHalf = 0.155f;
|
||||
|
||||
/// <summary>After the deliberate withdrawal begins the run waits this long for the hand to come out.</summary>
|
||||
private const double SettleSeconds = 1.0;
|
||||
|
||||
private readonly PainBoxParameters _p;
|
||||
private readonly SeatedBody _body;
|
||||
private readonly PainBoxSession _session;
|
||||
private readonly int _handR;
|
||||
private readonly long _rampEnd;
|
||||
private readonly long _settleTicks;
|
||||
private readonly long _outHoldTicks;
|
||||
private HandSample _hand;
|
||||
private int _excursions;
|
||||
private long? _handOutMs;
|
||||
private long _outSince = -1; // first tick of the current continuous stay outside the box after the break
|
||||
private bool _wasIn;
|
||||
private long _breakTick = -1, _withdrewTick = -1;
|
||||
private bool _disposed;
|
||||
|
||||
public BodyPainBoxSession(PainBoxParameters p, ulong seed)
|
||||
{
|
||||
if (Math.Abs(p.TickSeconds - BodyPainBox.TickSeconds) > 1e-12)
|
||||
{
|
||||
throw new ArgumentException($"The body run steps at 1/120 s; got TickSeconds {p.TickSeconds}.");
|
||||
}
|
||||
|
||||
_p = p;
|
||||
_body = new SeatedBody();
|
||||
try
|
||||
{
|
||||
var plan = _body.Plan;
|
||||
int senses = plan.SensePoints.Count, joints = plan.Joints.Count;
|
||||
_handR = plan.SenseIndex("Hand", Side.Right);
|
||||
int shoulderR = plan.JointIndex("Shoulder", Side.Right), elbowR = plan.JointIndex("Elbow", Side.Right);
|
||||
|
||||
// Hold: the shoulder and elbow angles fit on this body so the settled strength-1 palm sits on HoldPoint: grid 0.04 then 0.01 over both (the refine reaches 0.08 either side, the fit is a ridge), seed 1, mean palm 3-4 s, box intensity 0, FlinchGain 0, StrainShake 0 give -0.68 and -0.25 at 0.15 cm (the 0.04 grid alone: -0.64, -0.32 at 0.43 cm). Under the gravity feedforward the controller no longer sags the arm onto the box, so the pose is the intent. Withdraw: the arm pulled back and folded.
|
||||
var hold = new Quat[joints];
|
||||
var withdraw = new Quat[joints];
|
||||
Array.Fill(hold, Quat.Identity);
|
||||
Array.Fill(withdraw, Quat.Identity);
|
||||
hold[shoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, -0.68f);
|
||||
hold[elbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -0.25f);
|
||||
withdraw[shoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
|
||||
withdraw[elbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f);
|
||||
|
||||
var hp = BodyPainBox.HoldPoint;
|
||||
var volume = new BoxStimulus(hp.X, hp.Y, hp.Z, BoxHalf, BoxHalf, BoxHalf);
|
||||
_session = new PainBoxSession(p, seed, volume, senses, hold, withdraw, _handR);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_body.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
_rampEnd = (long)Math.Round(p.BoxRampSeconds / p.TickSeconds);
|
||||
_settleTicks = (long)Math.Round(SettleSeconds / p.TickSeconds);
|
||||
_outHoldTicks = Math.Max(1, (long)Math.Round(BodyPainBox.OutHoldSeconds / p.TickSeconds));
|
||||
_hand = ReadHand();
|
||||
}
|
||||
|
||||
/// <summary>The live lanes of the world, for rendering. Read-only: nothing outside this session writes them.</summary>
|
||||
public Box3DSoaView View { get { Live(); return _body.View; } }
|
||||
|
||||
/// <summary>The right hand after the latest step (the rest pose before the first).</summary>
|
||||
public HandSample Hand { get { Live(); return _hand; } }
|
||||
|
||||
/// <summary>Times the hand left the box between the end of the ramp and the break.</summary>
|
||||
public int Excursions { get { Live(); return _excursions; } }
|
||||
|
||||
/// <summary>The start of the first sustained exit after the break; null if there was none (see <see cref="BodyPainBoxResult"/>).</summary>
|
||||
public long? HandOutMs { get { Live(); return _handOutMs; } }
|
||||
|
||||
public bool Finished { get { Live(); return _session.Finished; } }
|
||||
|
||||
/// <summary>Ticks run so far; the tick the next <see cref="Step"/> runs.</summary>
|
||||
public long TickIndex { get { Live(); return _session.TickIndex; } }
|
||||
|
||||
/// <summary>Whether the box is on: until a switch-off (<see cref="SwitchOff"/>, the disable time), which counts from the call even after the run has ended.</summary>
|
||||
public bool BoxOn { get { Live(); return _session.BoxOn; } }
|
||||
|
||||
/// <summary>The box's intensity as written on the latest tick, and 0 once the box is off: what a player sees the box doing.</summary>
|
||||
public double BoxIntensity { get { Live(); return _session.BoxOn ? _session.Box.Intensity : 0.0; } }
|
||||
|
||||
/// <summary>The stimulus volume the hand is held in (a copy), for drawing the chamber.</summary>
|
||||
public BoxStimulus Chamber { get { Live(); return _session.Box; } }
|
||||
|
||||
/// <summary>The Actor's state at the end of the latest tick.</summary>
|
||||
public double Pain { get { Live(); return _session.Actor.Drive.Pain; } }
|
||||
public double Strain { get { Live(); return _session.Actor.Drive.Strain; } }
|
||||
public double Resolve { get { Live(); return _session.Actor.Drive.Resolve; } }
|
||||
public Goal Goal { get { Live(); return ChamberBrain.GoalAt(_session.Actor.GoalIndex); } }
|
||||
|
||||
/// <summary>One step of 1/120 s; see the type's summary for what it does after <see cref="Finished"/>.</summary>
|
||||
public void Step()
|
||||
{
|
||||
Live();
|
||||
bool wasFinished = _session.Finished;
|
||||
bool ticked = !wasFinished && !_session.Disabled(); // a step that finds the box switched off ends the run without stepping the world
|
||||
long tick = _session.TickIndex;
|
||||
var events = TickEvents.None;
|
||||
if (ticked)
|
||||
{
|
||||
_body.ReadSenses();
|
||||
events = _session.Tick(_body.X, _body.Y, _body.Z, _body.Strengths, _body.Targets);
|
||||
if (events != TickEvents.None) _body.Enqueue(tick, events);
|
||||
}
|
||||
if (ticked || wasFinished)
|
||||
{
|
||||
_body.DriveAndStep(_p.TickSeconds); // after Finished: the last strengths and targets again
|
||||
}
|
||||
|
||||
var sample = ReadHand(); // the rest pose when the box was off at tick 0
|
||||
_hand = sample;
|
||||
if (!ticked) return;
|
||||
|
||||
// The first break is the only one this run sees: the withdraw pose is terminal (the goal gates on Breaks and is involuntary for good) and nothing moves the hand back into the box, so the will cannot be pushed to a second break here. PainBoxSession, which can be ticked through a mend, guards its own.
|
||||
if ((events & TickEvents.WillBroke) != 0) _breakTick = tick;
|
||||
bool inBox = sample.InBox;
|
||||
|
||||
if (_breakTick < 0)
|
||||
{
|
||||
if (tick > _rampEnd && _wasIn && !inBox) _excursions++;
|
||||
_wasIn = inBox;
|
||||
}
|
||||
else if (inBox)
|
||||
{
|
||||
_outSince = -1; // back in: whatever exit this was, it was a flinch
|
||||
_handOutMs = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_outSince < 0) _outSince = tick;
|
||||
if (tick - _outSince + 1 >= _outHoldTicks) _handOutMs = _session.Ms(_outSince);
|
||||
}
|
||||
|
||||
// The run ends on the Actor's events, never on the hand.
|
||||
if (_session.Withdrew)
|
||||
{
|
||||
if (_withdrewTick < 0) _withdrewTick = tick;
|
||||
if (_handOutMs is not null || tick - _withdrewTick >= _settleTicks) _session.EndAt(tick);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves the queued events (oldest first) into <paramref name="buffer"/>; see <see cref="SeatedBody.DrainEvents"/>.</summary>
|
||||
public int DrainEvents(Span<BodyEvent> buffer) => _body.DrainEvents(buffer);
|
||||
|
||||
/// <summary>Sets the box intensity from the next tick; refuses a level outside 0 to <see cref="PainBox.MaxLevel"/>.</summary>
|
||||
public void SetIntensity(double level)
|
||||
{
|
||||
Live();
|
||||
_session.SetIntensity(level);
|
||||
}
|
||||
|
||||
/// <summary>Switches the box off from the next tick; the run ends as BoxDisabled if the will still holds.</summary>
|
||||
public void SwitchOff()
|
||||
{
|
||||
Live();
|
||||
_session.SwitchOff();
|
||||
}
|
||||
|
||||
/// <summary>The nervous result so far, with <see cref="HandOutMs"/>.</summary>
|
||||
public PainBoxResult Result()
|
||||
{
|
||||
Live();
|
||||
return _session.Result() with { HandOutMs = _handOutMs };
|
||||
}
|
||||
|
||||
/// <summary>Frees the world; a second call does nothing.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_body.Dispose();
|
||||
}
|
||||
|
||||
private void Live() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
|
||||
private HandSample ReadHand()
|
||||
{
|
||||
_body.ReadSenses();
|
||||
float hx = _body.X[_handR], hy = _body.Y[_handR], hz = _body.Z[_handR];
|
||||
return new HandSample(hx, hy, hz, _session.Box.Contains(hx, hy, hz));
|
||||
}
|
||||
}
|
||||
154
src/BadDay.Ymir/OfficeBody.cs
Normal file
154
src/BadDay.Ymir/OfficeBody.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BadDay.Core;
|
||||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>A point in the world, metres.</summary>
|
||||
public readonly record struct BodyPoint(float X, float Y, float Z);
|
||||
|
||||
/// <summary>
|
||||
/// The office on the body: the same timeline as the headless run, plus what only a body has.
|
||||
/// <see cref="HandL"/>, <see cref="HandR"/> and <see cref="Pelvis"/> hold the point after every step; the index is the tick.
|
||||
/// </summary>
|
||||
public sealed record OfficeBodyResult(
|
||||
StressResult Run, IReadOnlyList<BodyPoint> HandL, IReadOnlyList<BodyPoint> HandR, IReadOnlyList<BodyPoint> Pelvis)
|
||||
{
|
||||
/// <summary>The tick the rage took over (the GoalChanged row whose goal is Rage); null if the will held.</summary>
|
||||
public int? RageTick => Run.Timeline.Any(e => e.Kind == StressEntryKind.GoalChanged && e.Goal == OfficeGoal.Rage)
|
||||
? (int)Math.Round(Run.Timeline.First(e => e.Kind == StressEntryKind.GoalChanged && e.Goal == OfficeGoal.Rage).TimeMs * OfficeBody.Hz / 1000.0)
|
||||
: null;
|
||||
|
||||
/// <summary>Strikes by both hands from tick <paramref name="from"/> up to <paramref name="to"/>, see <see cref="OfficeBody.CountStrikes"/>.</summary>
|
||||
public int Strikes(int from, int to) => OfficeBody.CountStrikes(HandL, from, to) + OfficeBody.CountStrikes(HandR, from, to);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Office Fella on the seated puppet: <see cref="Run"/> records an <see cref="OfficeBodySession"/>, the one stepper of the
|
||||
/// office's world, from its start to its end, the release after calm takes over (or after a death).
|
||||
/// </summary>
|
||||
public static class OfficeBody
|
||||
{
|
||||
public const int Hz = 120;
|
||||
|
||||
/// <summary>The ragdoll's gains are tuned at 120 Hz.</summary>
|
||||
public const double TickSeconds = 1.0 / Hz;
|
||||
|
||||
/// <summary>A strike begins when a hand's forward (+z) speed passes this, m/s [P].</summary>
|
||||
public const float StrikeSpeed = 1.0f;
|
||||
|
||||
/// <summary>A strike is over when the forward speed falls back under this fraction of <see cref="StrikeSpeed"/>.</summary>
|
||||
public const float StrikeEnds = 0.5f;
|
||||
|
||||
/// <summary>
|
||||
/// The office puppet's poses [P]. Composed: every muscle at the creation pose, arms down. Rage: each arm winds up (the
|
||||
/// elbow folded, the fist at the chest) and strikes (the shoulder forward, the elbow straight), left then right. Clutch: both hands at the throat, the shoulders swung across and forward, the elbows folded.
|
||||
/// Thrash: four keys, a flung and kicking one, its mirror, and two between where both arms drop back and the knees come up.
|
||||
/// The clutch and the thrash are placeholders [P] Deru tunes on the capture.
|
||||
/// </summary>
|
||||
public static OfficePoses Poses { get; } = BuildPoses();
|
||||
|
||||
/// <summary>Runs the office on the puppet for <paramref name="seconds"/> (the harness's horizon: the session has no end of its own); the tick rate must be 1/120 s.</summary>
|
||||
public static OfficeBodyResult Run(StressParameters p, ulong seed, double seconds)
|
||||
{
|
||||
using var session = new OfficeBodySession(p, seed);
|
||||
var handL = new List<BodyPoint>();
|
||||
var handR = new List<BodyPoint>();
|
||||
var pelvis = new List<BodyPoint>();
|
||||
long ticks = (long)Math.Round(seconds * Hz);
|
||||
while (session.TickIndex < ticks)
|
||||
{
|
||||
session.Step();
|
||||
handL.Add(session.HandL);
|
||||
handR.Add(session.HandR);
|
||||
pelvis.Add(session.Pelvis);
|
||||
}
|
||||
return new OfficeBodyResult(session.Result(), handL, handR, pelvis);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strikes in <paramref name="hand"/>'s steps from <paramref name="from"/> up to <paramref name="to"/>: forward (+z) speed
|
||||
/// excursions, each from passing <see cref="StrikeSpeed"/> to falling under <see cref="StrikeEnds"/> of it, so a strike
|
||||
/// that wobbles at its peak counts once.
|
||||
/// </summary>
|
||||
public static int CountStrikes(IReadOnlyList<BodyPoint> hand, int from, int to)
|
||||
{
|
||||
int strikes = 0;
|
||||
bool inStrike = false;
|
||||
for (int i = Math.Max(from, 1); i < Math.Min(to, hand.Count); i++)
|
||||
{
|
||||
float forward = (hand[i].Z - hand[i - 1].Z) * Hz;
|
||||
if (!inStrike && forward >= StrikeSpeed) { inStrike = true; strikes++; }
|
||||
else if (inStrike && forward < StrikeSpeed * StrikeEnds) inStrike = false;
|
||||
}
|
||||
return strikes;
|
||||
}
|
||||
|
||||
private static OfficePoses BuildPoses()
|
||||
{
|
||||
var plan = SeatedPuppet.Plan;
|
||||
Quat[] Pose() { var q = new Quat[plan.Joints.Count]; Array.Fill(q, Quat.Identity); return q; }
|
||||
|
||||
var composed = Pose();
|
||||
var keys = new[] { Pose(), Pose(), Pose(), Pose() };
|
||||
// Key order: wind-up left, strike left, wind-up right, strike right. The arm not striking stays wound up.
|
||||
foreach (var k in keys) { Arm(plan, k, left: true, strike: false); Arm(plan, k, left: false, strike: false); }
|
||||
Arm(plan, keys[1], left: true, strike: true);
|
||||
Arm(plan, keys[3], left: false, strike: true);
|
||||
return new OfficePoses(composed, Pose(), keys, Clutch(plan, Pose()), Thrash(plan, Pose));
|
||||
}
|
||||
|
||||
// Both hands at the throat: the shoulder swings across (z) and forward (x), the elbow folds. Left is +sx, right -sx.
|
||||
private static Quat[] Clutch(BodyPlan plan, Quat[] pose)
|
||||
{
|
||||
foreach (var (side, sx) in new[] { (Side.Left, 1f), (Side.Right, -1f) })
|
||||
{
|
||||
pose[plan.JointIndex("Shoulder", side)] = Quat.FromAxisAngle(0f, 0f, 1f, -sx * 1.0f) * Quat.FromAxisAngle(1f, 0f, 0f, -0.8f);
|
||||
pose[plan.JointIndex("Elbow", side)] = Quat.FromAxisAngle(0f, 0f, 1f, -2.4f);
|
||||
}
|
||||
return pose;
|
||||
}
|
||||
|
||||
// Keys 0 and 2 mirror each other (one arm flung up and out, the other forward, the trunk twisted, the head back, one leg kicking);
|
||||
// keys 1 and 3 throw both arms down and back, the head forward, the knees up.
|
||||
private static Quat[][] Thrash(BodyPlan plan, Func<Quat[]> fresh)
|
||||
{
|
||||
var k = new Quat[4][];
|
||||
for (int i = 0; i < 4; i++) k[i] = fresh();
|
||||
int Joint(string name, Side side) => plan.JointIndex(name, side);
|
||||
Quat Q(float x, float y, float z, float a) => Quat.FromAxisAngle(x, y, z, a);
|
||||
foreach (var (key, flip, up, fwd) in new[] { (0, 1f, Side.Left, Side.Right), (2, -1f, Side.Right, Side.Left) })
|
||||
{
|
||||
k[key][Joint("Shoulder", up)] = Q(0f, 0f, 1f, 1.3f * flip);
|
||||
k[key][Joint("Elbow", up)] = Q(1f, 0f, 0f, -0.4f);
|
||||
k[key][Joint("Shoulder", fwd)] = Q(1f, 0f, 0f, -1.2f);
|
||||
k[key][Joint("Elbow", fwd)] = Q(1f, 0f, 0f, -1.6f);
|
||||
k[key][Joint("Spine", Side.Center)] = Q(0f, 1f, 0f, 0.35f * flip);
|
||||
k[key][Joint("Neck", Side.Center)] = Q(1f, 0f, 0f, -0.5f);
|
||||
k[key][Joint("Hip", up)] = Q(1f, 0f, 0f, -0.5f);
|
||||
k[key][Joint("Knee", up)] = Q(1f, 0f, 0f, 0.2f);
|
||||
}
|
||||
foreach (var key in new[] { 1, 3 })
|
||||
{
|
||||
foreach (var side in new[] { Side.Left, Side.Right })
|
||||
{
|
||||
k[key][Joint("Shoulder", side)] = Q(1f, 0f, 0f, 0.6f);
|
||||
k[key][Joint("Elbow", side)] = Q(1f, 0f, 0f, -0.3f);
|
||||
k[key][Joint("Knee", side)] = Q(1f, 0f, 0f, 0.6f);
|
||||
}
|
||||
k[key][Joint("Neck", Side.Center)] = Q(1f, 0f, 0f, 0.3f);
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
private static void Arm(BodyPlan plan, Quat[] pose, bool left, bool strike)
|
||||
{
|
||||
var side = left ? Side.Left : Side.Right;
|
||||
pose[plan.JointIndex("Shoulder", side)] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? -1.5f : -0.5f);
|
||||
pose[plan.JointIndex("Elbow", side)] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? 0f : -2.2f);
|
||||
}
|
||||
}
|
||||
178
src/BadDay.Ymir/OfficeBodySession.cs
Normal file
178
src/BadDay.Ymir/OfficeBodySession.cs
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
using System;
|
||||
using BadDay.Core;
|
||||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>
|
||||
/// The office on the seated body, stepped by its caller like <see cref="BodyPainBoxSession"/>: a <see cref="SeatedBody"/>
|
||||
/// (the one owner of the world), a Lodur <see cref="Physiology"/> on the humanoid plan with the session's slow scale,
|
||||
/// and the <see cref="StressSession"/> the headless run drives, with the desk's emitters moved to where the head sits and
|
||||
/// sensed there. Per <see cref="Step"/>: the body reports its points and what its airway openings hold, the session decides (Lodur's Actor, which steps
|
||||
/// the physiology first), the ragdoll is driven, the world steps. Harm enters only through <see cref="Wound"/>; the
|
||||
/// session never decides death, blood or consciousness: the read-outs are Lodur's. A dead body is limp (the Actor writes
|
||||
/// no strength). The office has no end (ruling bds-office-is-a-sandbox-preset): <see cref="Finished"/> is never true, the will's break is an event, and the caller stops stepping.
|
||||
/// </summary>
|
||||
public sealed class OfficeBodySession : IBodyRun
|
||||
{
|
||||
private readonly SeatedBody _body;
|
||||
private readonly StressSession _session;
|
||||
private readonly Physiology _physiology;
|
||||
private readonly double _tickSeconds;
|
||||
private readonly double[] _bleeds;
|
||||
private readonly int _handL, _handR, _pelvisLane;
|
||||
private bool _disposed;
|
||||
|
||||
public OfficeBodySession(StressParameters p, ulong seed, BloodParameters? blood = null)
|
||||
{
|
||||
if (Math.Abs(p.TickSeconds - OfficeBody.TickSeconds) > 1e-12)
|
||||
{
|
||||
throw new ArgumentException($"The body run steps at 1/120 s; got TickSeconds {p.TickSeconds}.");
|
||||
}
|
||||
|
||||
_tickSeconds = p.TickSeconds;
|
||||
blood ??= new BloodParameters();
|
||||
_body = new SeatedBody(blood);
|
||||
try
|
||||
{
|
||||
var plan = _body.Plan;
|
||||
_bleeds = new double[plan.Parts.Count];
|
||||
_body.ReadSenses();
|
||||
int head = plan.SenseIndex("Head");
|
||||
_handL = plan.SenseIndex("Hand", Side.Left);
|
||||
_handR = plan.SenseIndex("Hand", Side.Right);
|
||||
_pelvisLane = _body.BodyLane(plan.PartIndex("Pelvis"));
|
||||
var physiologyPlan = PhysiologyPlans.Humanoid();
|
||||
_physiology = new Physiology(plan, physiologyPlan, p.SlowScale, blood.Gain);
|
||||
// The desk's emitters sit where the head does and are sensed there.
|
||||
_session = new StressSession(p with { Setting = p.Setting.Shifted(_body.X[head], _body.Y[head], _body.Z[head]) }, seed,
|
||||
plan.SensePoints.Count, OfficeBody.Poses, head, _physiology, plan, physiologyPlan);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_body.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The live lanes of the world, for rendering. Read-only: nothing outside the body writes them.</summary>
|
||||
public Box3DSoaView View { get { Live(); return _body.View; } }
|
||||
|
||||
/// <summary>Ticks run so far; the tick the next <see cref="Step"/> runs.</summary>
|
||||
public long TickIndex { get { Live(); return _session.TickIndex; } }
|
||||
|
||||
/// <summary>Always false: the office is a sandbox preset that lasts until the player ends it. Here for <see cref="IBodyRun"/>, which the chamber ends.</summary>
|
||||
public bool Finished { get { Live(); return false; } }
|
||||
|
||||
/// <summary>The Actor's state at the end of the latest tick, and the body's (Lodur's numbers, never BDS's).</summary>
|
||||
public double Will { get { Live(); return _session.Actor.Drive.Will; } }
|
||||
public double Arousal { get { Live(); return _session.Actor.Drive.Arousal; } }
|
||||
public double Resolve { get { Live(); return _session.Actor.Drive.Resolve; } }
|
||||
public double AirHunger { get { Live(); return _session.Actor.Drive.AirHunger; } }
|
||||
public double Consciousness { get { Live(); return _physiology.Consciousness; } }
|
||||
public double BloodLoss { get { Live(); return _physiology.BloodLoss; } }
|
||||
public bool Dead { get { Live(); return _physiology.Dead; } }
|
||||
/// <summary>The liquid in the airway (m^3), the fraction of it filled, and whether the last sample found liquid at an opening: Lodur's numbers.</summary>
|
||||
public double AirwayLiquid { get { Live(); return _physiology.AirwayLiquid; } }
|
||||
public double Occlusion { get { Live(); return _physiology.Occlusion; } }
|
||||
public bool LiquidAtAirway { get { Live(); return _physiology.LiquidAtAirway; } }
|
||||
/// <summary>The blood the body has shed as drops, the volume still waiting to be shed (visible m^3, the gain applied) and the drops not yet settled: the body's, display only.</summary>
|
||||
public double BloodEmitted { get { Live(); return _body.BloodEmitted; } }
|
||||
public double BloodBacklog { get { Live(); return _body.BloodBacklog; } }
|
||||
public int LiveDrops { get { Live(); return _body.LiveDrops; } }
|
||||
/// <summary>The blood bled into the airway (real m^3/s, entering the airway at the body's blood gain; the HUD reads it) and the live liquid drawn from it (world m^3) in the latest step, then what the airway owes the world (m^3, signed), the part of <see cref="BloodEmitted"/> that was cough and drain, and the cough and drain still waiting to be shed: the body's, display only.</summary>
|
||||
public double AirwayBleed { get { Live(); return _physiology.AirwayBleed; } }
|
||||
public double AirwayDrawnLive { get { Live(); return _physiology.DrawnLive; } }
|
||||
public double AirwayOwed { get { Live(); return _body.Owed; } }
|
||||
public double BloodExpelled { get { Live(); return _body.BloodExpelled; } }
|
||||
public double ExpelBacklog { get { Live(); return _body.ExpelBacklog; } }
|
||||
public DeathCause DeathCause { get { Live(); return _physiology.Cause; } }
|
||||
public OfficeGoal Goal { get { Live(); return OfficeBrain.GoalAt(_session.Actor.GoalIndex); } }
|
||||
|
||||
/// <summary>The hands and the pelvis as of the latest step (read from the world each time).</summary>
|
||||
public BodyPoint HandL { get { Live(); return Sense(_handL); } }
|
||||
public BodyPoint HandR { get { Live(); return Sense(_handR); } }
|
||||
public BodyPoint Pelvis
|
||||
{
|
||||
get
|
||||
{
|
||||
Live();
|
||||
var v = _body.View;
|
||||
return new BodyPoint(v.PositionX[_pelvisLane], v.PositionY[_pelvisLane], v.PositionZ[_pelvisLane]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One step of 1/120 s: the body reports its points and what its airway openings hold, the session decides, the ragdoll is driven, the world steps.</summary>
|
||||
public void Step()
|
||||
{
|
||||
Live();
|
||||
long tick = _session.TickIndex;
|
||||
_body.ReadSenses();
|
||||
var airway = _body.ReadAirway();
|
||||
var events = _session.Tick(_body.X, _body.Y, _body.Z, _body.Strengths, _body.Targets, airway);
|
||||
if (events != TickEvents.None) _body.Enqueue(tick, events);
|
||||
_body.Exchange(_physiology.DrawnLive, _physiology.DrawnPooled, _physiology.Coughed, _physiology.Drained); // the dying step's flows are real; a dead physiology's read 0 (Lodur steps it)
|
||||
for (int part = 0; part < _bleeds.Length; part++) _bleeds[part] = _physiology.Bleed(part);
|
||||
_body.DriveAndStep(_tickSeconds, _bleeds);
|
||||
}
|
||||
|
||||
/// <summary>Moves the queued events (oldest first) into <paramref name="buffer"/>; see <see cref="SeatedBody.DrainEvents"/>.</summary>
|
||||
public int DrainEvents(Span<BodyEvent> buffer)
|
||||
{
|
||||
Live();
|
||||
return _body.DrainEvents(buffer);
|
||||
}
|
||||
|
||||
/// <summary>The player silences a stressor from the next tick; see <see cref="StressSession.Silence"/>.</summary>
|
||||
public void Silence(string stressorId)
|
||||
{
|
||||
Live();
|
||||
_session.Silence(stressorId);
|
||||
}
|
||||
|
||||
/// <summary>The part of the body a ray meets first; see <see cref="SeatedBody.Pick"/>.</summary>
|
||||
public PartHit? Pick(BodyPoint origin, BodyPoint translation)
|
||||
{
|
||||
Live();
|
||||
return _body.Pick(origin, translation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wounds the part <paramref name="hit"/> names from the next tick, and opens the wound at the point it hit so the blood leaves from there;
|
||||
/// the point goes into the part's frame (<see cref="SeatedBody.ToPart"/>) for the layers the tool's depth reaches there.
|
||||
/// False when refused (a part outside the plan, or see <see cref="StressSession.Wound"/>), and then nothing is opened.
|
||||
/// </summary>
|
||||
public bool Wound(in PartHit hit, WoundTool tool)
|
||||
{
|
||||
Live();
|
||||
if ((uint)hit.Part >= (uint)_body.Plan.Parts.Count) return false;
|
||||
if (!_session.Wound(hit.Part, _body.ToPart(hit.Part, hit.Point), tool)) return false;
|
||||
_body.OpenWound(hit.Part, hit.Point, hit.Normal);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The nervous result so far, with the death if there was one.</summary>
|
||||
public StressResult Result()
|
||||
{
|
||||
Live();
|
||||
return _session.Result();
|
||||
}
|
||||
|
||||
/// <summary>Frees the world; a second call does nothing.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_body.Dispose();
|
||||
}
|
||||
|
||||
private BodyPoint Sense(int i)
|
||||
{
|
||||
_body.ReadSenses();
|
||||
return new BodyPoint(_body.X[i], _body.Y[i], _body.Z[i]);
|
||||
}
|
||||
|
||||
private void Live() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
221
src/BadDay.Ymir/SeatedBody.cs
Normal file
221
src/BadDay.Ymir/SeatedBody.cs
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>A part of the body met by a ray: its plan ordinal, the world point and the outward surface normal there.</summary>
|
||||
public readonly record struct PartHit(int Part, BodyPoint Point, BodyPoint Normal);
|
||||
|
||||
/// <summary>What the Actor reported on one tick of a body run; only ticks that reported something are queued.</summary>
|
||||
public readonly record struct BodyEvent(long Tick, TickEvents Events);
|
||||
|
||||
/// <summary>What a client needs of any body run to step it, draw it and drain its events: the pain box and the office. A client holds exactly one.</summary>
|
||||
public interface IBodyRun : IDisposable
|
||||
{
|
||||
/// <summary>The live lanes of the world, for rendering.</summary>
|
||||
Box3DSoaView View { get; }
|
||||
/// <summary>Ticks run so far; the tick the next <see cref="Step"/> runs.</summary>
|
||||
long TickIndex { get; }
|
||||
bool Finished { get; }
|
||||
/// <summary>One step of 1/120 s.</summary>
|
||||
void Step();
|
||||
/// <summary>Moves the queued events (oldest first) into <paramref name="buffer"/>; returns how many.</summary>
|
||||
int DrainEvents(Span<BodyEvent> buffer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one owner of a BDS body world: the <see cref="Box3DSoaWorld"/> sized by <see cref="SeatedPuppet.Needs"/>, the
|
||||
/// ragdoll <see cref="SeatedPuppet.Build"/> puts in it, the body's blood (<see cref="Blood"/>, the one writer of fluid particles and wet patches in the world), the sense-point, strength and target lanes, and the queue of
|
||||
/// the Actor's events. Every body run (the pain box, the office) holds one and decides nothing here: per tick the run
|
||||
/// calls <see cref="ReadSenses"/>, lets its scenario write <see cref="Strengths"/> and <see cref="Targets"/> from the
|
||||
/// points, then <see cref="DriveAndStep"/>. No other code in BDS creates or steps a world. After <see cref="Dispose"/>
|
||||
/// every member throws <see cref="ObjectDisposedException"/>.
|
||||
/// </summary>
|
||||
public sealed class SeatedBody : IDisposable
|
||||
{
|
||||
private readonly Box3DSoaWorld _world;
|
||||
private readonly Ragdoll _ragdoll;
|
||||
private readonly float[] _x, _y, _z;
|
||||
private readonly float[] _strengths;
|
||||
private readonly Quat[] _targets;
|
||||
private readonly Blood _blood;
|
||||
private readonly float[] _airLive, _airPooled, _airDrop;
|
||||
private readonly Queue<BodyEvent> _events = new();
|
||||
private double _owed;
|
||||
private bool _disposed;
|
||||
|
||||
public SeatedBody(BloodParameters? blood = null)
|
||||
{
|
||||
blood ??= new BloodParameters();
|
||||
var needs = SeatedPuppet.Needs;
|
||||
_world = new Box3DSoaWorld(capacity: needs.Bodies, jointCapacity: needs.Joints,
|
||||
particles: new Box3DSoaParticleCapacities(Particles: blood.LiveCap, 0, 0, 0, 0, Materials: blood.Material + 1,
|
||||
Fluid: blood.LiveCap, Wets: blood.WetLanes, Sensors: needs.Sensors));
|
||||
try
|
||||
{
|
||||
blood.ApplyTo(_world);
|
||||
_ragdoll = SeatedPuppet.Build(_world);
|
||||
var plan = _ragdoll.Plan;
|
||||
_blood = new Blood(_world, _ragdoll, blood);
|
||||
_airLive = new float[plan.AirwayOpenings.Count];
|
||||
_airPooled = new float[plan.AirwayOpenings.Count];
|
||||
_airDrop = new float[plan.AirwayOpenings.Count];
|
||||
_x = new float[plan.SensePoints.Count];
|
||||
_y = new float[plan.SensePoints.Count];
|
||||
_z = new float[plan.SensePoints.Count];
|
||||
_strengths = new float[plan.Joints.Count];
|
||||
_targets = new Quat[plan.Joints.Count];
|
||||
}
|
||||
catch
|
||||
{
|
||||
_world.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public BodyPlan Plan => _ragdoll.Plan;
|
||||
|
||||
/// <summary>The lane of a part's body in <see cref="View"/>. The ragdoll itself is not handed out: it is driven only through <see cref="DriveAndStep"/>.</summary>
|
||||
public int BodyLane(int part)
|
||||
{
|
||||
Live();
|
||||
return _ragdoll.BodyLane(part);
|
||||
}
|
||||
|
||||
/// <summary>The live lanes of the world, for rendering. Read-only: nothing outside this body writes them.</summary>
|
||||
public Box3DSoaView View { get { Live(); return _world.View; } }
|
||||
|
||||
/// <summary>The sense points as of the latest <see cref="ReadSenses"/>.</summary>
|
||||
public ReadOnlySpan<float> X { get { Live(); return _x; } }
|
||||
public ReadOnlySpan<float> Y { get { Live(); return _y; } }
|
||||
public ReadOnlySpan<float> Z { get { Live(); return _z; } }
|
||||
|
||||
/// <summary>The muscle strengths and targets the scenario writes and <see cref="DriveAndStep"/> applies; they persist between ticks.</summary>
|
||||
public Span<float> Strengths { get { Live(); return _strengths; } }
|
||||
public Span<Quat> Targets { get { Live(); return _targets; } }
|
||||
|
||||
/// <summary>Reads the body's sense points from the world.</summary>
|
||||
public void ReadSenses()
|
||||
{
|
||||
Live();
|
||||
_ragdoll.ReadSensePoints(_x, _y, _z);
|
||||
}
|
||||
|
||||
/// <summary>Drives the ragdoll with the current strengths and targets, then steps the world one <paramref name="dt"/> seconds.</summary>
|
||||
public void DriveAndStep(double dt, ReadOnlySpan<double> bleedPerPart = default)
|
||||
{
|
||||
Live();
|
||||
_blood.BeforeStep(bleedPerPart, dt);
|
||||
_ragdoll.Drive(_strengths, _targets);
|
||||
_world.Step((float)dt, SeatedPuppet.Substeps);
|
||||
_blood.AfterStep();
|
||||
}
|
||||
|
||||
/// <summary>What the world holds at the airway openings now: Lodur's sample of the liquid sensors and the body's pose, down being the world's gravity.</summary>
|
||||
public AirwaySample ReadAirway()
|
||||
{
|
||||
Live();
|
||||
_ragdoll.ReadAirway(_airLive, _airPooled, _airDrop, _world.Gravity);
|
||||
return AirwaySample.Of(_airLive, _airPooled, _airDrop);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the airway owes the world, m^3 signed: the liquid it holds that the world has not given up. Display only; <see cref="Exchange"/> is the one writer. Live drops at the openings are destroyed against it, so with them it stays within half a drop below 0 and half a drop plus a tick's draw above; it is carried across ticks,
|
||||
/// never netted against a cough and never returned with an overdraw.
|
||||
/// </summary>
|
||||
public double Owed { get { Live(); return _owed; } }
|
||||
|
||||
/// <summary>
|
||||
/// The airway's trade with the world for one tick, called once after the physiology stepped with its flows for that step (world m^3: Physiology owns how much is drawn, coughed and drained, this only
|
||||
/// decides where the liquid goes). A breath's pooled draw leaves the wet patches at the openings (<see cref="Ragdoll.TakeDrawn"/>); what the world did not give up, and the live draw, is added to <see cref="Owed"/>, the
|
||||
/// ledger books the volume the take returned, not the ask; live drops at the openings are destroyed against it; the cough and the drain come out of the lowest opening (<see cref="Ragdoll.LowestOpening"/>) as drops,
|
||||
/// at 1x. The invariant: the world's liquid, the airway's, the expulsion backlog, less Owed, less the drops the wounds shed and the blood bled into the airway, is constant.
|
||||
/// </summary>
|
||||
public void Exchange(double drawnLive, double drawnPooled, double coughed, double drained)
|
||||
{
|
||||
Live();
|
||||
double taken = _ragdoll.TakeDrawn(drawnPooled);
|
||||
_owed += drawnLive + drawnPooled - taken;
|
||||
_owed -= _blood.TakeLive(_owed);
|
||||
if (coughed + drained > 0.0) _blood.Expel(_ragdoll.LowestOpening(_world.Gravity), coughed, drained);
|
||||
}
|
||||
|
||||
/// <summary>The part of the body a ray from <paramref name="origin"/> along <paramref name="translation"/> meets first, with the point and surface normal; null for a miss or when the first thing met is not a part of the body.</summary>
|
||||
public PartHit? Pick(BodyPoint origin, BodyPoint translation)
|
||||
{
|
||||
Live();
|
||||
var hit = _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
|
||||
if (!hit.Hit || hit.StableId < SeatedPuppet.FirstStableId) return null;
|
||||
ulong ordinal = hit.StableId - SeatedPuppet.FirstStableId;
|
||||
if (ordinal >= (ulong)Plan.Parts.Count || _ragdoll.BodyLane((int)ordinal) != hit.Lane) return null;
|
||||
return new PartHit((int)ordinal, new BodyPoint(hit.Point.X, hit.Point.Y, hit.Point.Z), new BodyPoint(hit.Normal.X, hit.Normal.Y, hit.Normal.Z));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A world point in <paramref name="part"/>'s frame: origin the part's position, axes its rotation, the frame the sites of Lodur's PartTissuesDef are
|
||||
/// written in (the body's own, as the airway openings' offsets are). The inverse of the part's live pose.
|
||||
/// </summary>
|
||||
public (float X, float Y, float Z) ToPart(int part, BodyPoint world)
|
||||
{
|
||||
Live();
|
||||
int lane = _ragdoll.BodyLane(part);
|
||||
var v = _world.View;
|
||||
return Inverse(lane, world.X - v.PositionX[lane], world.Y - v.PositionY[lane], world.Z - v.PositionZ[lane]);
|
||||
}
|
||||
|
||||
/// <summary>The part's inverse rotation applied to a vector: a world offset from the part's position, or a world direction, into the part's frame.</summary>
|
||||
private (float X, float Y, float Z) Inverse(int lane, float x, float y, float z)
|
||||
{
|
||||
var v = _world.View;
|
||||
new Quat(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]).Conjugate().Rotate(x, y, z, out var rx, out var ry, out var rz);
|
||||
return (rx, ry, rz);
|
||||
}
|
||||
|
||||
/// <summary>Opens a wound at a world point and normal on <paramref name="part"/>: from now on it sheds its share of the part's bleed, carried by the part.</summary>
|
||||
public void OpenWound(int part, BodyPoint point, BodyPoint normal)
|
||||
{
|
||||
Live();
|
||||
var (px, py, pz) = ToPart(part, point);
|
||||
var (nx, ny, nz) = Inverse(_ragdoll.BodyLane(part), normal.X, normal.Y, normal.Z);
|
||||
_blood.Open(part, px, py, pz, nx, ny, nz);
|
||||
}
|
||||
|
||||
/// <summary>Visible blood volume (m^3) shed so far and still gathered at the wounds, and the drops not yet settled.</summary>
|
||||
public double BloodEmitted { get { Live(); return _blood.Emitted; } }
|
||||
public double BloodBacklog { get { Live(); return _blood.Backlog; } }
|
||||
/// <summary>The part of <see cref="BloodEmitted"/> that was the body's own cough and drain (visible m^3), and what is still waiting to be shed of it: display only.</summary>
|
||||
public double BloodExpelled { get { Live(); return _blood.Expelled; } }
|
||||
public double ExpelBacklog { get { Live(); return _blood.ExpelBacklog; } }
|
||||
public int LiveDrops { get { Live(); return _blood.Live; } }
|
||||
|
||||
public void Enqueue(long tick, TickEvents events)
|
||||
{
|
||||
Live();
|
||||
_events.Enqueue(new BodyEvent(tick, events));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the queued events (oldest first) into <paramref name="buffer"/> and returns how many it wrote; the rest stay
|
||||
/// queued for the next call. Allocation-free once the queue has grown to the client's drain interval.
|
||||
/// </summary>
|
||||
public int DrainEvents(Span<BodyEvent> buffer)
|
||||
{
|
||||
Live();
|
||||
int n = 0;
|
||||
while (n < buffer.Length && _events.Count > 0) buffer[n++] = _events.Dequeue();
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Frees the world; a second call does nothing.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_world.Dispose();
|
||||
}
|
||||
|
||||
private void Live() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
39
src/BadDay.Ymir/SeatedPuppet.cs
Normal file
39
src/BadDay.Ymir/SeatedPuppet.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
using Lodur;
|
||||
using Lodur.Body.Ymir;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Ymir;
|
||||
|
||||
/// <summary>
|
||||
/// The one place BDS builds a seated puppet's world: a ground, a static stool box, the ragdoll, and the weld that
|
||||
/// holds its pelvis to the stool, because the PD ragdoll cannot balance for the length of a scenario. Every body run
|
||||
/// (the pain box, the office) builds through here, so no run has a world of its own.
|
||||
/// </summary>
|
||||
public static class SeatedPuppet
|
||||
{
|
||||
/// <summary>Physics substeps per 1/120 s step. The ragdoll gains were tuned against 4; the behaviour tests, not this number, are the rule.</summary>
|
||||
public const int Substeps = 4;
|
||||
|
||||
/// <summary>The stable id of the first of Fella's parts: a part's stable id is this plus its ordinal. The ground is 1 and the stool 2.</summary>
|
||||
public const ulong FirstStableId = 100;
|
||||
|
||||
/// <summary>The part ordinal of Fella's body with this stable id (<see cref="FirstStableId"/> plus the ordinal), or null for any other body: the one rule from stable id to part.</summary>
|
||||
public static int? PartOf(ulong stableId) =>
|
||||
stableId >= FirstStableId && stableId - FirstStableId < (ulong)Plan.Parts.Count ? (int)(stableId - FirstStableId) : null;
|
||||
|
||||
/// <summary>Bodies, joints and sensors a world needs for <see cref="Build"/>: the ragdoll, the ground and the stool, the weld, and the airway sensors (the world must also have a particle system for them).</summary>
|
||||
public static (int Bodies, int Joints, int Sensors) Needs => (Ragdoll.Needs(Plan).Bodies + 2, Ragdoll.Needs(Plan).Joints + 1, Ragdoll.Needs(Plan).Sensors);
|
||||
|
||||
/// <summary>The humanoid plan every BDS body is built from; classes resolve their labels against it once.</summary>
|
||||
public static BodyPlan Plan { get; } = BodyPlans.Humanoid();
|
||||
|
||||
/// <summary>Adds the ground, the stool, the ragdoll (stable ids from <see cref="FirstStableId"/>) and the pelvis weld to <paramref name="world"/>, which must be sized by <see cref="Needs"/>.</summary>
|
||||
public static Ragdoll Build(Box3DSoaWorld world)
|
||||
{
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
|
||||
var stool = world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
|
||||
var ragdoll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: FirstStableId);
|
||||
world.AddJoint(Box3DSoaJointKind.Weld, stool, ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
|
||||
return ragdoll;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,5 +10,6 @@
|
|||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\BadDay.Core\BadDay.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\BadDay.Cli\BadDay.Cli.csproj" />
|
||||
<ProjectReference Include="..\..\src\BadDay.Ymir\BadDay.Ymir.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
471
tools/FellaMesh/build_fella_mesh.py
Normal file
471
tools/FellaMesh/build_fella_mesh.py
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Builds client/fella/fella_skin.glb: Fella's drawn body, MakeHuman's CC0 base mesh fitted to the Lodur plan's skeleton.
|
||||
|
||||
Pipeline (each step reads only the pinned inputs in tools/FellaMesh/input and the plan JSON from `baddaysim plan`):
|
||||
1. verify the pinned MakeHuman files by size and SHA-256;
|
||||
2. take the base mesh at the macro values (only MakeHuman's neutral ones: see MACROS), keep the body group, scale
|
||||
the whole body so its crown meets the plan's crown, soles on y = 0;
|
||||
3. per plan part, an affine map from the MakeHuman bones it owns to the plan's creation pose: the part's
|
||||
joint-to-joint segment is rotated and stretched along its axis onto the plan's segment (girth kept); every vertex
|
||||
is linearly blended over the parts by MakeHuman's own weights (the LBS pose into the creation pose);
|
||||
4. Blender's Decimate modifier (Collapse, symmetry on X, triangulate) on the whole body, run headless with private user folders;
|
||||
5. every face goes to the part with the most weight; a vertex on faces of two or more parts is a joint-ring vertex,
|
||||
emitted once per part with weight 0.5/0.5 on its two heaviest parts and one shared normal;
|
||||
6. one glTF primitive per part, JOINTS_0/WEIGHTS_0, one skin whose joints are the plan's parts, inverse binds from
|
||||
the plan's creation frames.
|
||||
|
||||
The skeleton is never typed here: part labels, creation frames and joint anchors come from the plan.
|
||||
Usage: build_fella_mesh.py [--out client/fella/fella_skin.glb] [--check] [--plan plan.json] [macro options]
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent.parent
|
||||
INPUT = HERE / "input"
|
||||
|
||||
# The pinned MakeHuman files (makehumancommunity/makehuman, CC0 1.0): name -> (bytes, sha256).
|
||||
PINS = {
|
||||
"base.obj": (1749303, "8e761e6624b8f54536409135d1636da63b32486a90d4897f84e121d144f6fb4c"),
|
||||
"default.mhskel": (117790, "99f179bce0aa850b45d4191a1d0d234c5851f881c057439470ded3bddf729a24"),
|
||||
"default_weights.mhw": (897521, "0f3641d651ae3d00ad6b4ccee43142edb109d3bd909d27d9e4139ef1beed8625"),
|
||||
}
|
||||
# The Blender the glb is built with: its Decimate result is only reproducible on this version (--check refuses any other).
|
||||
BLENDER_VERSION = "5.3.0"
|
||||
BLENDER_DEFAULT = r"C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe" # or the BLENDER environment variable
|
||||
MAKEHUMAN_COMMIT = "a8bc2d54ff0ac92e78ff71431b1023eda42bf482"
|
||||
|
||||
# MakeHuman's neutral macro values (its defaults: gender 0.5 is the androgynous base, lodur:ruling:default-fella-androgynous-base).
|
||||
# The base mesh is the model with no macro target applied; a target set is not pinned yet, so any other value is refused
|
||||
# until the follow-up fella-body-variety pins the macrodetails targets and ports their weighting.
|
||||
MACROS = {"gender": 0.5, "age": 0.5, "muscle": 0.5, "weight": 0.5, "height": 0.5, "proportions": 0.5}
|
||||
|
||||
TARGET_VERTICES = 450 # about the whole body after decimation, before joint rings are copied per part
|
||||
RING_PASSES = 8 # rounds of moving faces off a third part at a vertex; a vertex where three still meet is weighted to its two heaviest
|
||||
RING = 0.5 # a joint-ring vertex's weight on each of its two parts
|
||||
|
||||
SIDE_SUFFIX = {"Left": ".L", "Right": ".R"}
|
||||
|
||||
|
||||
def fail(message):
|
||||
sys.exit(f"build_fella_mesh: {message}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- inputs
|
||||
|
||||
def load_pinned():
|
||||
for name, (size, sha) in PINS.items():
|
||||
data = (INPUT / name).read_bytes()
|
||||
if len(data) != size or hashlib.sha256(data).hexdigest() != sha:
|
||||
fail(f"{INPUT / name} is not the pinned MakeHuman file (size or SHA-256 differs)")
|
||||
obj_v, obj_vt, faces, group = [], [], [], None
|
||||
for line in (INPUT / "base.obj").read_text().splitlines():
|
||||
t = line.split()
|
||||
if not t:
|
||||
continue
|
||||
if t[0] == "v":
|
||||
obj_v.append([float(x) for x in t[1:4]])
|
||||
elif t[0] == "vt":
|
||||
obj_vt.append([float(x) for x in t[1:3]])
|
||||
elif t[0] == "g":
|
||||
group = t[1]
|
||||
elif t[0] == "f" and group == "body":
|
||||
faces.append([tuple(int(i) - 1 for i in c.split("/")) for c in t[1:]])
|
||||
skeleton = json.loads((INPUT / "default.mhskel").read_text())
|
||||
weights = json.loads((INPUT / "default_weights.mhw").read_text())["weights"]
|
||||
return np.array(obj_v), np.array(obj_vt), faces, skeleton, weights
|
||||
|
||||
|
||||
def load_plan(path):
|
||||
if path:
|
||||
text = Path(path).read_text()
|
||||
else:
|
||||
text = subprocess.run(
|
||||
["dotnet", "run", "--project", str(ROOT / "src" / "BadDay.Cli"), "--", "plan"],
|
||||
check=True, capture_output=True, text=True, cwd=ROOT).stdout
|
||||
plan = json.loads(text)
|
||||
if len(plan["parts"]) != 19 or len(plan["joints"]) != 18:
|
||||
fail("the plan is not the 19-part, 18-joint humanoid")
|
||||
return plan
|
||||
|
||||
|
||||
class Plan:
|
||||
def __init__(self, plan):
|
||||
self.parts = plan["parts"]
|
||||
self.index = {(p["label"], p["side"]): i for i, p in enumerate(self.parts)}
|
||||
self.joint = {(j["label"], j["side"]): np.array(j["anchor"]) for j in plan["joints"]}
|
||||
self.parent = {j["child"]: j["parent"] for j in plan["joints"]}
|
||||
|
||||
def center(self, label, side):
|
||||
return np.array(self.parts[self.index[(label, side)]]["position"])
|
||||
|
||||
def anchor(self, label, side):
|
||||
return self.joint[(label, side)]
|
||||
|
||||
def name(self, i):
|
||||
p = self.parts[i]
|
||||
return p["label"] if p["side"] == "Center" else f"{p['label']}.{p['side']}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- fitting
|
||||
|
||||
def unit(v):
|
||||
return v / np.linalg.norm(v)
|
||||
|
||||
|
||||
def frame(axis, across):
|
||||
d = unit(axis)
|
||||
a = unit(across - np.dot(across, d) * d)
|
||||
return np.column_stack([d, a, np.cross(d, a)])
|
||||
|
||||
|
||||
def segment_map(p, q, across, p2, q2, across2, keep_length=False):
|
||||
"""The affine map taking MakeHuman's segment p->q onto the plan's p2->q2: the axis rotated onto the axis with the
|
||||
across reference kept, stretched along the axis by the length ratio; perpendicular extent untouched."""
|
||||
d = unit(q - p)
|
||||
s = 1.0 if keep_length else np.linalg.norm(q2 - p2) / np.linalg.norm(q - p)
|
||||
r = frame(q2 - p2, across2) @ frame(d, across).T
|
||||
a = r @ (np.eye(3) + (s - 1.0) * np.outer(d, d))
|
||||
return a, p2 - a @ p
|
||||
|
||||
|
||||
def part_table(plan, joint):
|
||||
"""(part ordinal) -> (MakeHuman bone names, segment p, q, across, plan p2, q2, across2, keep_length).
|
||||
MakeHuman points are bone heads or tails; plan points are joint anchors, or the part's far end where the plan gives
|
||||
only a centre (a part's joint sits at its near end, so the far end is twice the centre minus the anchor)."""
|
||||
h = lambda bone: joint[bone + "____head"]
|
||||
t = lambda bone: joint[bone + "____tail"]
|
||||
x_axis = np.array([1.0, 0.0, 0.0])
|
||||
z_axis = np.array([0.0, 0.0, 1.0])
|
||||
rows = {}
|
||||
|
||||
def far(label, side, anchor_label, anchor_side=None):
|
||||
return 2.0 * plan.center(label, side) - plan.anchor(anchor_label, anchor_side or side)
|
||||
|
||||
hips = (plan.anchor("Hip", "Left") + plan.anchor("Hip", "Right")) / 2.0
|
||||
crown = 2.0 * plan.center("Head", "Center") - plan.anchor("Neck", "Center") # the plan's head rests on its neck joint
|
||||
rows[plan.index[("Pelvis", "Center")]] = (
|
||||
["root", "pelvis.L", "pelvis.R", "spine05", "spine04"],
|
||||
(h("upperleg01.L") + h("upperleg01.R")) / 2.0, h("spine03"), x_axis, hips, plan.anchor("Spine", "Center"), x_axis, False)
|
||||
rows[plan.index[("Torso", "Center")]] = (
|
||||
["spine03", "spine02", "spine01", "neck01", "clavicle.L", "clavicle.R", "shoulder01.L", "shoulder01.R", "breast.L", "breast.R"],
|
||||
h("spine03"), h("neck02"), x_axis, plan.anchor("Spine", "Center"), plan.anchor("Neck", "Center"), x_axis, False)
|
||||
rows[plan.index[("Head", "Center")]] = (
|
||||
None, # every bone not listed by another part: the neck's upper bones, the skull, jaw, face and tongue
|
||||
h("neck02"), np.array([t("head")[0], joint["__crown"][1], t("head")[2]]), x_axis, plan.anchor("Neck", "Center"), crown, x_axis, False)
|
||||
for side, sx in (("Left", ".L"), ("Right", ".R")):
|
||||
across = h("finger2-1" + sx) - h("finger5-1" + sx) # pinky to index: toward the thumb, the plan's +z
|
||||
hand = lambda bone: bone + sx
|
||||
rows[plan.index[("UpperArm", side)]] = (
|
||||
[hand("upperarm01"), hand("upperarm02")], h(hand("upperarm01")), h(hand("lowerarm01")), across,
|
||||
plan.anchor("Shoulder", side), plan.anchor("Elbow", side), z_axis, False)
|
||||
rows[plan.index[("LowerArm", side)]] = (
|
||||
[hand("lowerarm01"), hand("lowerarm02")], h(hand("lowerarm01")), h(hand("wrist")), across,
|
||||
plan.anchor("Elbow", side), plan.anchor("Wrist", side), z_axis, False)
|
||||
rows[plan.index[("Palm", side)]] = (
|
||||
[hand("wrist")] + [f"metacarpal{i}{sx}" for i in range(1, 5)], h(hand("wrist")), h("finger3-1" + sx), across,
|
||||
plan.anchor("Wrist", side), far("Palm", side, "Wrist"), z_axis, False)
|
||||
rows[plan.index[("Thumb", side)]] = (
|
||||
[f"finger1-{i}{sx}" for i in (1, 2, 3)], h("finger1-1" + sx), t("finger1-3" + sx), across,
|
||||
plan.anchor("Thumb", side), far("Thumb", side, "Thumb"), z_axis, False)
|
||||
rows[plan.index[("Fingers", side)]] = (
|
||||
[f"finger{n}-{i}{sx}" for n in (2, 3, 4, 5) for i in (1, 2, 3)], h("finger3-1" + sx), t("finger3-3" + sx), across,
|
||||
plan.anchor("Fingers", side), far("Fingers", side, "Fingers"), z_axis, False)
|
||||
rows[plan.index[("Thigh", side)]] = (
|
||||
[hand("upperleg01"), hand("upperleg02")], h(hand("upperleg01")), h(hand("lowerleg01")), x_axis,
|
||||
plan.anchor("Hip", side), plan.anchor("Knee", side), x_axis, False)
|
||||
rows[plan.index[("Shin", side)]] = (
|
||||
[hand("lowerleg01"), hand("lowerleg02")], h(hand("lowerleg01")), t(hand("lowerleg02")), x_axis,
|
||||
plan.anchor("Knee", side), plan.anchor("Ankle", side), x_axis, False)
|
||||
toes = [f"toe{n}-{i}{sx}" for n in range(1, 6) for i in (1, 2, 3) if not (n == 1 and i == 3)]
|
||||
rows[plan.index[("Foot", side)]] = (
|
||||
[hand("foot")] + toes, h(hand("foot")), t(hand("foot")), x_axis,
|
||||
plan.anchor("Ankle", side), plan.anchor("Ankle", side) + t(hand("foot")) - h(hand("foot")), x_axis, True) # the foot keeps MakeHuman's pitch and length
|
||||
return rows
|
||||
|
||||
|
||||
def fit(plan, mh_v, mh_faces, skeleton, mh_weights):
|
||||
"""Steps 2 and 3: the body-group mesh posed into the plan's creation pose. Returns positions (n, 3), triangles, part weights (n, 19), uv index."""
|
||||
body = sorted({c[0] for f in mh_faces for c in f})
|
||||
remap = {v: i for i, v in enumerate(body)}
|
||||
pos = mh_v[body]
|
||||
tris, tri_uv = [], []
|
||||
for f in mh_faces: # MakeHuman's quads, split on the first diagonal
|
||||
corners = [(remap[c[0]], c[1]) for c in f]
|
||||
for k in range(1, len(corners) - 1):
|
||||
tris.append([corners[0][0], corners[k][0], corners[k + 1][0]])
|
||||
tri_uv.append([corners[0][1], corners[k][1], corners[k + 1][1]])
|
||||
|
||||
joint = {name: mh_v[idx].mean(axis=0) for name, idx in skeleton["joints"].items()}
|
||||
ymin, ymax = pos[:, 1].min(), pos[:, 1].max()
|
||||
joint["__crown"] = np.array([0.0, ymax, 0.0])
|
||||
crown_plan = 2.0 * plan.center("Head", "Center") - plan.anchor("Neck", "Center")
|
||||
scale = crown_plan[1] / (ymax - ymin)
|
||||
shift = np.array([0.0, ymin, 0.0])
|
||||
pos = (pos - shift) * scale
|
||||
joint = {k: (v - shift) * scale for k, v in joint.items()}
|
||||
|
||||
rows = part_table(plan, joint)
|
||||
owner = {}
|
||||
for part, row in rows.items():
|
||||
for bone in row[0] or []:
|
||||
if bone in owner:
|
||||
fail(f"bone {bone} is claimed by two parts")
|
||||
owner[bone] = part
|
||||
head = plan.index[("Head", "Center")]
|
||||
nparts = len(plan.parts)
|
||||
w = np.zeros((len(pos), nparts))
|
||||
for bone, entries in mh_weights.items():
|
||||
part = owner.get(bone, head)
|
||||
for v, x in entries:
|
||||
if v in remap:
|
||||
w[remap[v], part] += x
|
||||
total = w.sum(axis=1)
|
||||
if total.min() <= 0.0:
|
||||
fail("a body vertex has no skin weight")
|
||||
w /= total[:, None]
|
||||
|
||||
maps = {part: segment_map(*row[1:4], *row[4:7], keep_length=row[7]) for part, row in rows.items()}
|
||||
posed = np.zeros_like(pos)
|
||||
for part, (a, t) in maps.items():
|
||||
posed += w[:, part, None] * (pos @ a.T + t)
|
||||
return posed, np.array(tris), w, tri_uv
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- decimation
|
||||
|
||||
def decimate(pos, tris, w, uv, target):
|
||||
"""Blender's Decimate modifier (Collapse, symmetry on X, triangulate) reduces the posed body to about `target` vertices;
|
||||
each surviving vertex takes the part weights and UV of the nearest vertex of the full mesh. Returns the Blender version used."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
np.save(tmp / "pos.npy", pos)
|
||||
np.save(tmp / "tris.npy", tris)
|
||||
env = dict(os.environ)
|
||||
for name in ("CONFIG", "EXTENSIONS", "SCRIPTS"): # Blender never reads or writes the operator's user folders
|
||||
(tmp / name).mkdir()
|
||||
env[f"BLENDER_USER_{name}"] = str(tmp / name)
|
||||
run = subprocess.run([os.environ.get("BLENDER", BLENDER_DEFAULT), "--background", "--factory-startup", "--python", str(HERE / "decimate_blender.py"), "--", str(tmp), str(target)],
|
||||
env=env, capture_output=True, text=True)
|
||||
line = next((l for l in run.stdout.splitlines() if l.startswith("BLENDER ")), None)
|
||||
if run.returncode or line is None:
|
||||
fail("Blender did not decimate:\n" + run.stdout[-800:] + run.stderr[-800:])
|
||||
version = line.split()[1]
|
||||
out_pos, out_tris = np.load(tmp / "out_pos.npy"), np.load(tmp / "out_tris.npy")
|
||||
nearest = np.array([int(np.argmin(((pos - p) ** 2).sum(axis=1))) for p in out_pos])
|
||||
return out_pos, out_tris, w[nearest], uv[nearest], version
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- partition
|
||||
|
||||
def partition(pos, tris, w):
|
||||
"""Step 5. Returns per-part (vertex ids, triangles) and the per-vertex joint weights."""
|
||||
nparts = w.shape[1]
|
||||
face_part = np.array([int(np.argmax(w[t].sum(axis=0))) for t in tris])
|
||||
for _ in range(RING_PASSES): # a joint ring joins two parts: where three meet, the faces of the part with the least weight there go to the other two
|
||||
touching = [dict() for _ in range(len(pos))]
|
||||
for f, t in enumerate(tris):
|
||||
for v in t:
|
||||
touching[v].setdefault(int(face_part[f]), []).append(f)
|
||||
moved = False
|
||||
for v, parts in enumerate(touching):
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
keep = sorted(parts, key=lambda p: (-w[v, p], p))[:2]
|
||||
for p, faces in parts.items():
|
||||
if p in keep:
|
||||
continue
|
||||
for f in faces:
|
||||
face_part[f] = max(keep, key=lambda q: (w[tris[f]][:, q].sum(), -q))
|
||||
moved = True
|
||||
if not moved:
|
||||
break
|
||||
touching = [set() for _ in range(len(pos))]
|
||||
for f, t in enumerate(tris):
|
||||
for v in t:
|
||||
touching[v].add(int(face_part[f]))
|
||||
joints = np.zeros((len(pos), 2), dtype=np.int64)
|
||||
weights = np.zeros((len(pos), 2))
|
||||
for v, parts in enumerate(touching):
|
||||
if len(parts) == 1:
|
||||
joints[v, 0] = next(iter(parts))
|
||||
weights[v, 0] = 1.0
|
||||
else:
|
||||
two = sorted(parts, key=lambda p: (-w[v, p], p))[:2]
|
||||
joints[v] = two
|
||||
weights[v] = RING
|
||||
normals = np.zeros_like(pos)
|
||||
for t in tris:
|
||||
nrm = np.cross(pos[t[1]] - pos[t[0]], pos[t[2]] - pos[t[0]]) # area-weighted
|
||||
for v in t:
|
||||
normals[v] += nrm
|
||||
length = np.linalg.norm(normals, axis=1)
|
||||
normals /= np.where(length > 0, length, 1.0)[:, None]
|
||||
per_part = []
|
||||
for p in range(nparts):
|
||||
faces = tris[face_part == p]
|
||||
ids = sorted({int(v) for t in faces for v in t})
|
||||
per_part.append((ids, faces))
|
||||
return per_part, joints, weights, normals
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- glTF
|
||||
|
||||
def quat_mul(a, b):
|
||||
x1, y1, z1, w1 = a
|
||||
x2, y2, z2, w2 = b
|
||||
return (w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
|
||||
w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2)
|
||||
|
||||
|
||||
def quat_conj(q):
|
||||
return (-q[0], -q[1], -q[2], q[3])
|
||||
|
||||
|
||||
def quat_rotate(q, v):
|
||||
x, y, z, w = q
|
||||
u = np.array([x, y, z])
|
||||
return v + 2.0 * np.cross(u, np.cross(u, v) + w * v)
|
||||
|
||||
|
||||
def quat_matrix(q):
|
||||
x, y, z, w = q
|
||||
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
|
||||
|
||||
|
||||
def write_glb(plan, per_part, joints, weights, normals, pos, uv, provenance):
|
||||
blob = bytearray()
|
||||
views, accessors = [], []
|
||||
|
||||
def add(array, ctype, ctype_name, target=None, bounds=False):
|
||||
while len(blob) % 4:
|
||||
blob.append(0)
|
||||
data = np.ascontiguousarray(array).tobytes()
|
||||
views.append({"buffer": 0, "byteOffset": len(blob), "byteLength": len(data), **({"target": target} if target else {})})
|
||||
blob.extend(data)
|
||||
acc = {"bufferView": len(views) - 1, "componentType": ctype, "count": len(array), "type": ctype_name}
|
||||
if bounds:
|
||||
acc["min"] = [float(x) for x in array.min(axis=0)]
|
||||
acc["max"] = [float(x) for x in array.max(axis=0)]
|
||||
accessors.append(acc)
|
||||
return len(accessors) - 1
|
||||
|
||||
FLOAT, USHORT, UINT = 5126, 5123, 5125
|
||||
primitives = []
|
||||
for p, (ids, faces) in enumerate(per_part):
|
||||
if not ids:
|
||||
fail(f"part {plan.name(p)} owns no vertices")
|
||||
local = {v: i for i, v in enumerate(ids)}
|
||||
j4 = np.zeros((len(ids), 4), dtype=np.uint16)
|
||||
w4 = np.zeros((len(ids), 4), dtype=np.float32)
|
||||
j4[:, :2] = joints[ids]
|
||||
w4[:, :2] = weights[ids]
|
||||
# a vertex with a single part has weight 0 in slot 1: its joint slot stays 0 with weight 0
|
||||
idx = np.array([[local[v] for v in t] for t in faces], dtype=np.uint32).reshape(-1)
|
||||
primitives.append({"attributes": {
|
||||
"POSITION": add(pos[ids].astype(np.float32), FLOAT, "VEC3", 34962, bounds=True),
|
||||
"NORMAL": add(normals[ids].astype(np.float32), FLOAT, "VEC3", 34962),
|
||||
"TEXCOORD_0": add(uv[ids].astype(np.float32), FLOAT, "VEC2", 34962),
|
||||
"JOINTS_0": add(j4, USHORT, "VEC4", 34962),
|
||||
"WEIGHTS_0": add(w4, FLOAT, "VEC4", 34962)},
|
||||
"indices": add(idx, UINT, "SCALAR", 34963), "mode": 4})
|
||||
|
||||
# joint nodes: the plan's part tree, each node at its creation frame (local = parent^-1 * world)
|
||||
world_q = [tuple(p["rotation"]) for p in plan.parts]
|
||||
world_t = [np.array(p["position"]) for p in plan.parts]
|
||||
nodes, children = [], {}
|
||||
for p in range(len(plan.parts)):
|
||||
if p in plan.parent:
|
||||
parent = plan.parent[p]
|
||||
q = quat_mul(quat_conj(world_q[parent]), world_q[p])
|
||||
t = quat_rotate(quat_conj(world_q[parent]), world_t[p] - world_t[parent])
|
||||
children.setdefault(parent, []).append(p)
|
||||
else:
|
||||
q, t = world_q[p], world_t[p]
|
||||
nodes.append({"name": plan.name(p), "translation": [float(x) for x in np.float32(t)], "rotation": [float(x) for x in np.float32(q)]})
|
||||
for parent, kids in children.items():
|
||||
nodes[parent]["children"] = kids
|
||||
roots = [p for p in range(len(plan.parts)) if p not in plan.parent]
|
||||
inverse = np.zeros((len(plan.parts), 4, 4), dtype=np.float32)
|
||||
for p in range(len(plan.parts)):
|
||||
r = quat_matrix(world_q[p]).T # inverse rotation
|
||||
m = np.eye(4)
|
||||
m[:3, :3] = r
|
||||
m[:3, 3] = -r @ world_t[p]
|
||||
inverse[p] = m.T # glTF matrices are column-major
|
||||
ibm = add(inverse, FLOAT, "MAT4")
|
||||
nodes.append({"name": "Fella", "mesh": 0, "skin": 0})
|
||||
gltf = {
|
||||
"asset": {"version": "2.0", "generator": "tools/FellaMesh/build_fella_mesh.py", "extras": provenance},
|
||||
"scene": 0, "scenes": [{"nodes": roots + [len(nodes) - 1]}], "nodes": nodes,
|
||||
"meshes": [{"name": "Fella", "primitives": primitives}],
|
||||
"skins": [{"name": "Plan", "joints": list(range(len(plan.parts))), "inverseBindMatrices": ibm, "skeleton": roots[0]}],
|
||||
"buffers": [{"byteLength": len(blob)}], "bufferViews": views, "accessors": accessors,
|
||||
}
|
||||
js = json.dumps(gltf, sort_keys=True, separators=(",", ":")).encode()
|
||||
js += b" " * (-len(js) % 4)
|
||||
while len(blob) % 4:
|
||||
blob.append(0)
|
||||
total = 12 + 8 + len(js) + 8 + len(blob)
|
||||
return b"glTF" + struct.pack("<II", 2, total) + struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(blob), b"BIN\0") + bytes(blob)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
def build(args):
|
||||
for name, value in MACROS.items():
|
||||
if getattr(args, name) != value:
|
||||
fail(f"--{name} {getattr(args, name)}: only MakeHuman's neutral macro values ({name} {value}) are pinned; "
|
||||
"other bodies wait for follow-up fella-body-variety, which pins the macrodetails targets")
|
||||
mh_v, mh_vt, faces, skeleton, mh_weights = load_pinned()
|
||||
plan = Plan(load_plan(args.plan))
|
||||
pos, tris, w, tri_uv = fit(plan, mh_v, faces, skeleton, mh_weights)
|
||||
uv = np.zeros((len(pos), 2))
|
||||
for t, tu in zip(tris, tri_uv): # a vertex takes the UV of the first corner that names it (seams keep one island's)
|
||||
for v, c in zip(t, tu):
|
||||
if not uv[v].any():
|
||||
uv[v] = mh_vt[c]
|
||||
pos, tris, w, uv, blender = decimate(pos, tris, w, uv, TARGET_VERTICES)
|
||||
per_part, joints, weights, normals = partition(pos, tris, w)
|
||||
provenance = {"source": "makehumancommunity/makehuman", "commit": MAKEHUMAN_COMMIT, "license": "CC0 1.0",
|
||||
"inputs": {k: v[1] for k, v in PINS.items()}, "macros": MACROS, "blender": blender}
|
||||
return write_glb(plan, per_part, joints, weights, normals, pos, uv, provenance), len(pos), blender
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--out", default=str(ROOT / "client" / "fella" / "fella_skin.glb"))
|
||||
ap.add_argument("--check", action="store_true", help="rebuild and compare bytes with the checked-in glb")
|
||||
ap.add_argument("--plan", help="a plan JSON file instead of running `baddaysim plan`")
|
||||
for name, value in MACROS.items():
|
||||
ap.add_argument(f"--{name}", type=float, default=value)
|
||||
args = ap.parse_args()
|
||||
data, vertices, blender = build(args)
|
||||
out = Path(args.out)
|
||||
if args.check:
|
||||
if blender != BLENDER_VERSION:
|
||||
fail(f"--check is only defined on Blender {BLENDER_VERSION}, the version the checked-in glb was built with; this run used Blender {blender}, so the bytes are not comparable (set BLENDER to a {BLENDER_VERSION} executable)")
|
||||
if not out.exists() or out.read_bytes() != data:
|
||||
fail(f"{out} differs from a rebuild")
|
||||
print(f"fella_skin.glb is the byte-identical rebuild ({len(data)} bytes, {vertices} decimated vertices)")
|
||||
return
|
||||
if blender != BLENDER_VERSION:
|
||||
print(f"warning: built with Blender {blender}, not the pinned {BLENDER_VERSION}: update BLENDER_VERSION and the input README, or --check will refuse", file=sys.stderr)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_bytes(data)
|
||||
print(f"wrote {out} ({len(data)} bytes, {vertices} decimated vertices)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
43
tools/FellaMesh/decimate_blender.py
Normal file
43
tools/FellaMesh/decimate_blender.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"""Runs inside Blender (headless): reduces the posed body to about N vertices with the Decimate modifier (Collapse, symmetry on X, triangulate).
|
||||
blender --background --factory-startup --python decimate_blender.py -- <dir> <target vertices>
|
||||
Reads <dir>/pos.npy and <dir>/tris.npy; writes <dir>/out_pos.npy, <dir>/out_tris.npy and prints BLENDER <version>."""
|
||||
import sys
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
directory, target = sys.argv[sys.argv.index("--") + 1], int(sys.argv[-1])
|
||||
pos = np.load(directory + "/pos.npy")
|
||||
tris = np.load(directory + "/tris.npy")
|
||||
mesh = bpy.data.meshes.new("body")
|
||||
mesh.from_pydata(pos.tolist(), [], tris.tolist())
|
||||
obj = bpy.data.objects.new("body", mesh)
|
||||
bpy.context.scene.collection.objects.link(obj)
|
||||
mod = obj.modifiers.new("d", "DECIMATE")
|
||||
mod.decimate_type = "COLLAPSE"
|
||||
mod.use_symmetry = True
|
||||
mod.symmetry_axis = "X"
|
||||
mod.use_collapse_triangulate = True
|
||||
|
||||
|
||||
def reduced(ratio):
|
||||
mod.ratio = ratio
|
||||
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
|
||||
return evaluated.to_mesh()
|
||||
|
||||
|
||||
low, high = 0.0, 1.0 # bisect the ratio: vertex count rises with it
|
||||
for _ in range(24):
|
||||
mid = (low + high) / 2
|
||||
out = reduced(mid)
|
||||
if len(out.vertices) < target:
|
||||
low = mid
|
||||
else:
|
||||
high = mid
|
||||
out = reduced(high)
|
||||
out.calc_loop_triangles()
|
||||
verts = np.array([v.co[:] for v in out.vertices])
|
||||
faces = np.array([t.vertices[:] for t in out.loop_triangles])
|
||||
np.save(directory + "/out_pos.npy", verts)
|
||||
np.save(directory + "/out_tris.npy", faces)
|
||||
print("BLENDER", bpy.app.version_string, len(verts), len(faces))
|
||||
15
tools/FellaMesh/input/README.md
Normal file
15
tools/FellaMesh/input/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Pinned MakeHuman inputs
|
||||
|
||||
The three files `tools/FellaMesh/build_fella_mesh.py` builds `client/fella/fella_skin.glb` from. They are data: the build reads them, nothing runs them.
|
||||
|
||||
| File | Bytes | SHA-256 |
|
||||
| --- | --- | --- |
|
||||
| `base.obj` | 1,749,303 | `8e761e6624b8f54536409135d1636da63b32486a90d4897f84e121d144f6fb4c` |
|
||||
| `default.mhskel` | 117,790 | `99f179bce0aa850b45d4191a1d0d234c5851f881c057439470ded3bddf729a24` |
|
||||
| `default_weights.mhw` | 897,521 | `0f3641d651ae3d00ad6b4ccee43142edb109d3bd909d27d9e4139ef1beed8625` |
|
||||
|
||||
- Source: https://github.com/makehumancommunity/makehuman at commit `a8bc2d54ff0ac92e78ff71431b1023eda42bf482`, paths `makehuman/data/3dobjs/base.obj`, `makehuman/data/rigs/default.mhskel`, `makehuman/data/rigs/default_weights.mhw`.
|
||||
- Licence: CC0 1.0 (the files state it; the repository's `LICENSE.ASSETS.md` is the grant). Copyright holders at release: Data Collection AB, Joel Palmius, Jonas Hauquier.
|
||||
- Fetched 2026-11-28 into an empty directory, size-checked against the table, hashed, then copied here byte for byte (`.gitattributes` keeps git from touching their line endings). The build refuses any file whose size or SHA-256 differs.
|
||||
- Build tool, pinned: **Blender 5.3.0** (the locally installed Steam build; `BLENDER` names another executable). The build runs it headless with private config, extension and script folders (never the user's), for one job: the Decimate modifier (Collapse, symmetry on X, triangulate) on the posed body, `decimate_blender.py`. Its result is only reproducible on that version, so `build_fella_mesh.py --check` refuses any other and says so; a build on another version warns, and the pin and this line move together.
|
||||
- Not fetched: MakeHuman's macrodetails targets. The default Fella is the base mesh at MakeHuman's neutral macro values (gender 0.5, age 0.5, muscle 0.5, weight 0.5, height 0.5, proportions 0.5; lodur:ruling:default-fella-androgynous-base), which is the mesh with no target applied. Other bodies (lodur:follow_up:fella-body-variety) pin the targets they need here first.
|
||||
59167
tools/FellaMesh/input/base.obj
Normal file
59167
tools/FellaMesh/input/base.obj
Normal file
File diff suppressed because it is too large
Load diff
4835
tools/FellaMesh/input/default.mhskel
Normal file
4835
tools/FellaMesh/input/default.mhskel
Normal file
File diff suppressed because it is too large
Load diff
14613
tools/FellaMesh/input/default_weights.mhw
Normal file
14613
tools/FellaMesh/input/default_weights.mhw
Normal file
File diff suppressed because it is too large
Load diff
1
tools/FellaMesh/requirements.txt
Normal file
1
tools/FellaMesh/requirements.txt
Normal file
|
|
@ -0,0 +1 @@
|
|||
numpy==2.5.4
|
||||
12
tools/PainSweep/PainSweep.csproj
Normal file
12
tools/PainSweep/PainSweep.csproj
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- The sweep runs headless: BadDay.Core and through it Lodur.Core, no Ymir. Run: dotnet run (project path tools/PainSweep). -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\BadDay.Core\BadDay.Core.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
@ -4,9 +4,10 @@ using System.Globalization;
|
|||
using System.Linq;
|
||||
using System.Text;
|
||||
using BadDay.Core;
|
||||
using Lodur;
|
||||
|
||||
// Grid sweep: stimulus intensity (rows) x withdrawal-reflex suppression strength
|
||||
// (columns, PainBoxParameters.MaxSuppression). Each cell runs Seeds consecutive
|
||||
// (columns, PainBoxParameters.Reflex.MaxSuppression). Each cell runs Seeds consecutive
|
||||
// seeds and prints the median time-to-break in seconds over the runs that broke,
|
||||
// "never" if none broke within MaxSeconds, and "(k/N)" when only k of N broke.
|
||||
// Engine-free and deterministic: same build, same table, byte for byte.
|
||||
|
|
@ -17,7 +18,7 @@ double[] suppressions = { 0.0, 0.25, 0.5, 0.75, 0.95, 1.0 };
|
|||
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pull {new PainBoxParameters().ObjectivePull:F2})\n");
|
||||
sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pay ${new PainBoxParameters().Payment:F0}, pull {ChamberBrain.Pull(new PainBoxParameters()):F2})\n");
|
||||
sb.Append("intensity\\suppr ");
|
||||
foreach (var s in suppressions) sb.Append(s.ToString("F2", inv).PadLeft(10));
|
||||
sb.Append('\n');
|
||||
|
|
@ -26,7 +27,7 @@ foreach (var i in intensities)
|
|||
sb.Append(i.ToString("F2", inv).PadRight(16));
|
||||
foreach (var s in suppressions)
|
||||
{
|
||||
var p = new PainBoxParameters { BoxIntensity = i, MaxSuppression = s };
|
||||
var p = new PainBoxParameters { BoxIntensity = i, Reflex = new WithdrawalParameters { MaxSuppression = s } };
|
||||
var sweep = SweepSummary.Run(p, FirstSeed, Seeds);
|
||||
string cell = sweep.MedianBreakMs is { } ms
|
||||
? (ms / 1000.0).ToString("F1", inv) + (sweep.Broke < Seeds ? $"({sweep.Broke}/{Seeds})" : "")
|
||||
|
|
|
|||
Loading…
Reference in a new issue