feat(pbs): add sprite animation and shared Studio authoring

Implement DEC-0084 with factory-only Sprite/Animator structs, complete result
lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP
authoring through shared services.

Qualify native dev/release with ordinary and optimized producers, zero-allocation
playback, private-cycle reclamation, canonical Composer pixels, installed JARs
and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
2026-11-05 15:16:07 +00:00
parent 1d8b8c2101
commit bf31184d4d
151 changed files with 4823 additions and 98 deletions
@@ -0,0 +1,211 @@
---
id: LSN-0100
ticket: pbs-core-sprite-animation
title: Sprite Animation, Typed Results and Shared Authoring
created: 2026-11-05
tags: [compiler, pbs, core, stdlib, animation, studio, packer]
---
## Context and outcome
Owner: **compiler/pbs**. Studio owns the neutral authoring model and editor;
Packer owns registered asset identity and the effective glyph layout.
DEC-0084 and PLN-0162 delivered one complete feature across these domains.
Their workflow artifacts were retired after implementation; the durable contracts
are [PBS chapter 27](../../../docs/specs/compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md)
and [Studio chapter 12](../../../docs/specs/studio/12.%20Animation%20Authoring%20Specification.md).
Games previously supplied primitive Composer arguments and implemented animation
themselves. The final implementation supplies ordinary PBS `Sprite`,
`AnimatorBuilder` and `Animator` structs, explicit-tick playback, generated
factories from canonical JSON, complete JavaFX authoring, task-authorized MCP
operations and installed examples. Composer keeps its public nine arguments,
int status, capability and host identity. No runtime source or ABI changed.
## Model identity and playback separately
`SpriteView.sprite()` returns bank and glyph together. A palette, position,
layer, flip and priority still belong to the caller's emission. A visual query
neither advances an animator nor constructs a Sprite.
The builder fixes its bank and initial clip name. It permits one open clip,
validates operations in the specified order and retains a failed draft for repair.
Every `build()` copies all mutable clip/frame nodes before publishing an animator.
Two builds have independent playback and backing; ordinary assignment aliases
one animator. Only immutable strings may retain ordinary sharing.
The public types carry trusted factory-only construction metadata. Checking the
spelling of an imported type would be insufficient: aliases preserve the declaring
type's identity, and same-module permission is tied to the current file/module.
Game source cannot manufacture the reserved attribute. Public barrels hide node
types and constructor completion surfaces.
Each published clip has immutable frame links with cumulative ends and a tail
link to its head. Animator retains its selected clip, current frame, phase and
playback state. For positive ticks while Playing:
1. Reject `phase > LONG_MAX - ticks` before addition.
2. Loop reduces the new phase modulo the total duration.
3. Once finishes after the entire final duration and retains the last image.
4. Resolve the frame from cumulative ends, traversing at most one clip.
5. Publish the new phase, cursor and state after calculations complete.
No per-tick or per-skipped-loop iteration is needed. Successful advance, negative
and overflow errors, and sprite queries execute no heap allocations after
construction. Builder construction and copying have their ordinary allocation
costs. A VM resource trap remains a trap; recoverable domain-error preservation
does not promise rollback after arbitrary VM failures.
`play` and `select` reset even when passed the current name. Use `play` on an
action transition, then `advance` for continuity. Pause/resume preserve progress;
resume does not restart Finished. Stop resets to Stopped; restart resets to Playing.
## Preserve the complete result group
Executable result returns use the existing VM group:
```text
Int32 status, complete typed payload
0 = success; 1..N = canonical error declaration order
```
Unit returns only status. An inactive reference, function or trait payload uses
runtime-admitted nullable defaults. Reserved, never-assigned locals supply Null
without allocating default-holder structs. Scalars and builtin groups receive
their correct typed defaults. Slot count alone never establishes nominal type or
error identity.
Propagation evaluates once, discards pending expression temporaries on its error
path, returns the same status and supplies the enclosing function's inactive
payload. Handling evaluates once and executes only its selected recovery/remap.
Neither catches a VM trap. Imports, contract calls, discarded results and Registry
signatures must agree on the same status-plus-payload shape. A result-effect
function cannot become a plain `Fn` value; successful Fn payloads remain ordinary
typed function references.
A useful integration pitfall appeared in `let glyph = animator.sprite().glyph_id`.
The tuple-producing method inherited the projected field's expected int type,
which prevented the method call from being selected during lowering. Lowering the
receiver with its own tuple type fixes the call and subsequent projection.
The state-matrix fixture exposed this before native admission.
## Canonical persistence has one owner
The sidecar `animations.studio.json` is the editable persistence surface. Its
strict version-1 codec rejects duplicate/unknown keys, unsupported versions,
invalid UTF-16 strings and fractional/out-of-range integers. Durations retain exact
signed 64-bit values, including numbers above JavaScript's exact integer range.
Bindings use stable selected artifact IDs, current glyph indices and fingerprints.
Paths and list positions are not animation identity. Reordering, removal and
replacement block preview/build until an explicit rebind. Bank relocation retains
identity. Palette and playback clock never become definition fields.
`prometeu-animation` owns DTOs, codec, validation, revisions, rebind and timeline.
It depends on no compiler, concrete Packer, JavaFX or Spring classes. Packer exposes
its effective layout using the same material/composition helpers as packing. App
composition adapts that public API to the neutral layout port.
Revision verification and atomic replacement run under Packer's existing project
exclusion. Preparing rebind returns a binding-only candidate, old/new differences,
affected frames, proposal hash and bank revision. Applying checks the exact current
proposal. The hash correlates content; it introduces no new grant or approval.
Late asynchronous callbacks require attention. Cancelling the waiting task thread
does not necessarily stop a queued Packer callback. Task authority and a sticky
cancellation state are checked again at publication. Concurrent creates admit one
winner; a cancelled late callback cannot overwrite canonical bytes.
Studio's module boundary is also real: session consumes the exported
`assets.AnimationOperations` seam, rather than depending on the hidden
`assets.animation.DefaultAnimationService` implementation. The modularity test
caught that distinction during integration.
## Generate a view instead of another document
Only registered, included banks with valid definitions publish factories:
```pbs
import { create_hero } from @app:generated/animations/b_12345678123412341234123456789abc;
import { AnimationError } from @core:animation;
fn example() -> result<AnimationError> {
let value = create_hero(3)!;
value.play("idle")!;
value.advance(2)!;
let image = value.sprite();
// Caller supplies image.bank_id/image.glyph_id plus external emission inputs.
return ok(());
}
```
PBS owns this deterministic projection. Factories sort by animator ID; clip/frame
order remains authored order. Revisions include the document, resolved bank and
generator version, excluding timestamps and absolute paths. Included invalid
definitions or a missing layout resolver fail explicitly. Physical modules cannot
occupy the reserved namespace.
The compiler/LSP exposes revision-scoped read-only documents and UTF-8 origin
ranges mapped to JSON pointers. The origin command revalidates the current source
and opens the bank/field through Studio's authoring service. Caller-provided paths
are not navigation authority. Wire metadata uses URI strings, not Java filesystem
implementation objects, so JSON-RPC serialization does not reflect into private
`Path` internals. Changed origins are rejected after edits or reconnect.
JavaFX and MCP share validation, persistence, preview and rebind services. Human
draft editing stays in controls; authority and file writes stay in services.
Handoff awaits animation refresh as well as the existing forms. UI autoplay merely
schedules explicit preview ticks. MCP query/update schemas admit only fields for
the selected operation and retain existing task admission and result envelopes.
## Qualify the boundary that actually executes
The production-native matrix executes both ordinary and optimized producers in
dev and release. Result fixtures cover complete payloads, once-only evaluation,
recovery/remapping and uncaught traps. Animation fixtures cover ownership, all
domain errors, state/time boundaries, long/count limits, int-max jumps and zero
executed allocation instructions in the marked paths.
Safepoint fixtures observe live private rings, then zero retained Animator/clip/frame
objects after releasing their last owner. The observed cumulative reclamation is
2,411 objects at the first collection and 4,817 at the second. Test-only near-limit
and safepoint setup is isolated from shipped modules; no billions-of-elements claim
or public mutation hook is implied.
A real saved-project corpus runs direct and generated animators through Composer.
For both producers and native profiles, ticks 0..7 produce glyphs
`0,0,1,1,1,2,0,0`, alternating palettes 0/1. Every sprite pixel matches shared
preview: 32 native frame observations and 16,384 pixel comparisons. The configured
packaged process repeats both producer variants with 8,192 pixel comparisons.
The sidecar bytes remain unchanged by palette selection and execution.
That gate found a pre-existing Composer adapter mismatch: native statuses use an
Int64 carrier while the public PBS facade returns int. The private host declaration
now uses long and the facade explicitly narrows using an existing intrinsic.
Public arguments, status type, slot counts, capability and host identity remain
unchanged. Runtime modification was unnecessary.
Installed knowledge is tested in a separate JVM outside the checkout using product
JARs. It saves a Packer-bound definition, compiles generated factories, verifies
read-only origins and installed MCP schemas, and supplies native firmware fixtures.
The JavaFX gate authors, saves, previews, repairs drift and closes the real editor.
The full regression and architecture/modularity gates pass.
See [qualification evidence](evidence/README.md), [concrete results](evidence/results.json)
and [editor capture](evidence/animation-editor.png). The evidence records exact
hashes, commands, environment and practical test limits. Cargo outputs stayed under
`/tmp`; the runtime checkout remained unchanged. No runtime commits were created.
## Common mistakes
- Treating a result payload as its plain return while forgetting the status slot.
- Allocating a default holder on every unit error or inactive payload path.
- Letting aliases or transitive factory return types lose declaration provenance.
- Sharing mutable builder nodes with published animators.
- Replaying every skipped tick or loop instead of reducing phase first.
- Calling `play` every frame and unintentionally resetting the cursor.
- Retargeting frames by path/order when stable identity drifts.
- Validating a revision before queuing work and assuming it remains current at save.
- Keeping stale generated text as a fallback after validation fails.
- Testing only source compilation when typed native admission and real rendering
are part of the contract.
@@ -0,0 +1,31 @@
# DEC-0084 / PLN-0162 qualification evidence
Owner: compiler/pbs; cross-domain Studio and Packer. Completed 2026-11-05.
- `environment.json` records provider, installed executables, targets and commands.
- `source.sha256` identifies every changed tracked/untracked implementation file.
- `fixtures.sha256.gz` identifies the mandatory Result/Animation PBX, manifests,
packed assets and shared-preview pixel oracles in the Studio build corpus.
- `results.json` records concrete counts and limits; native logs contain assertions.
- Compressed regression and test reports preserve the final successful gates.
- `animation-editor.png` is the real JavaFX editor after authoring/save/preview.
The production VM/firmware matrix ran ordinary and optimized producers in both
native dev/release profiles. The saved-project Composer corpus compares every
sprite pixel against the shared canonical preview while alternating palette IDs.
The configured installed process repeats that comparison for both producers.
Heap counts cover executed allocation opcodes in the marked paths, not constructor
costs, host rendering or a claim about every theoretical program. Test-only count,
phase and safepoint setup does not add a public mutation API. Zero-quota construction
produces resource traps; it does not become a recoverable animation error.
Origin navigation is qualified through the real compiler/LSP bridge and registry,
wire serialization, editor selection and client TypeScript compilation. The new
CodeLens was not separately exercised in a VS Code Extension Development Host.
The JavaFX image uses the standalone control with the default skin, not a full
Studio shell screenshot.
The repository has no CLI operation to create/allocate a lesson. LSN-0100 was
prepared from the next available metadata ID; `discussion housekeep` registers
it and advances that counter. No index edit was performed manually.
@@ -0,0 +1,21 @@
0d28d6891ad8d385c1d103233e85f619005543528269eb6531428f07f1b348c0 README.md
d5260791f61756c7c1d5f9864e4a0c91c76751833a6e7827346a06e21672608c acceptance.md
15525c8aa73b7d940c020721a4fd1aa677d3d0c3fd6186ada0a8ff5082c0334f animation-authoring.xml.gz
95776283387855cb29abf982bc15cf680a2af90db23271e30c86784e16190fd0 animation-editor.png
2c0df78907358c81e820e5339664a221f7abd96583f13f062a303e98eb33943c animation-native-dev.log.gz
86c0ceca52378b4fb3f1750912c33abb878fc7e52d39395a7245a140b51286b0 animation-native-release.log.gz
bd3d04976189f3077709582fb5110c902503cb3af407ff82600b5f56226c6906 animation-ui.xml.gz
a4e58f9a9115d6c69e74e7add930f72f7259306c48c62cad47e3500605f9e9ec authoring-final.log.gz
9fe0bf32db9ca80997ace82d59f67782151cf9196df7e0a7346058960a0d521d composer-installed-process.log.gz
8e3faee9ff1cb98394aa3c08693e497bd03b131f92d4af78f926dec7182ae470 composer-installed-process.xml.gz
dbaa6ef29376e6c0f2763c13acbbcca9b9f188de830db8699b0f49c1bc88f8d7 environment.json
9324e7c344fdcfb0e6aaad7e00fc282a8f6b8424d115bb5f8bc0643176c29214 fixtures.sha256.gz
fa7e3732a4c3b7f2331cafbdcad22c6c30ea7a34c5222d824312b0688f782b02 fn-effect-rejection.log.gz
c0e843b7aeb63dcf4f4f0b1d206f314c5ea827cdfca33b66ddbe7c1c1e09c9fb installed-knowledge.xml.gz
9ef7dc7a127288ad4289a4e37c0d047081ffec3273659ad4912340ba27d985da regression.log.gz
d5caa3ba786b97e3d7de731f5645e9eb5fe448fe4abcc02dfecba5e2e9e9b000 result-native-dev.log.gz
10d6cb9fa5aafcd8f1c989ec87a5720e1a6944c34f47ab82e903af7bb722e39f result-native-release.log.gz
955cfe97d4033ab758024e1735f861fc12ccf1630139841abfd55d8b7f7c2668 results.json
25024cca3fdd75e59d09a6526a64c6cc7ef43d8af2f7121d849c7e61f62aedd4 source.sha256
cd3505eb82eb5e0e60e459b93cb744a5846f520ffe53ff2a214a9378c0f55572 workflow.txt
a33cc281e5263d4e03aa0220b5ab6f7e6a4180222a980d646e68a569963217ef ../LSN-0100-sprite-animation-and-shared-authoring.md
@@ -0,0 +1,26 @@
# Acceptance mapping
All fourteen PLN-0162 criteria were completed. The accepted scope was not split.
| Criterion | Implementation and observed gate |
| --- | --- |
| AC1 | English PBS 27 / Studio 12, propagated compiler/Packer/Studio chapters and indexes. Installed references read from JARs. |
| AC2 | Status-first full typed return groups. 21 Result cases × ordinary/optimized × native dev/release; trap cases remain traps; plain-Fn rejection tested. |
| AC3 | stdlib 1 core/sprite and core/animation, concrete/trait SpriteView queries, factory-only positional/named aliases rejected; forged metadata rejected. |
| AC4 | Reused builder produces independent finalized nodes. Draft repair/removal/rebuild preserves existing animators; assignment aliases. |
| AC5 | Native Loop/Once boundaries, complete state/reset behavior, pause/resume, zero/negative input, checked overflow, int-max jump and limit cases. |
| AC6 | Native instruction counters observe zero heap allocations in marked sprite/advance/error paths; bounded traversal gate; quota traps and cycle reclamation observed. |
| AC7 | Stable identities, fingerprints and exact JSON. Real Packer sidecar leaves assets.pa byte-identical; rebind detects drift; bank relocation retains identity and revision. |
| AC8 | Neutral p.animation module and layout port. Architecture and Spring Modulith gates pass. Included definitions without a resolver fail explicitly. |
| AC9 | Real build factories, reserved collision diagnostic, invalid/excluded behavior, exact UTF-8 including controls/supplementary characters, sorted/byte-identical regeneration; read-only revision-scoped JSON origins reject stale navigation/reconnect. |
| AC10 | Actual JavaFX create/frame/save/preview/rebind/origin selection/close fixture passes. Handoff awaits animation persistence/refresh and retains failed drafts. |
| AC11 | Shared manual/task services and strict MCP schemas. Valid MCP save/get/preview parity, stale revision, invalid authority, revoked task, concurrent creates and cancelled late publication tested. |
| AC12 | Direct/generated Composer pixels equal preview across tick boundaries and alternating palettes in ordinary/optimized producers and native dev/release. Configured packaged process repeats both producers. |
| AC13 | Installed JARs expose specs/modules/examples/MCP schemas and compile a saved project outside the checkout. Generated installed fixtures execute through production firmware. Runtime tree remains clean. |
| AC14 | Full Gradle regression, installed knowledge, architecture/modularity, dedicated JavaFX gate, client TypeScript compilation, native matrices and diff/workflow validation pass. |
The new origin CodeLens was typechecked and its server/editor contracts were
qualified; a new VS Code Extension Development Host session was not performed.
The screenshot is the actual standalone JavaFX control with the default skin.
Count and safepoint fixtures use isolated test setup rather than allocating
billions of nodes or adding shipped mutation hooks.
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

@@ -0,0 +1,33 @@
{
"date": "2026-11-05",
"platform": "macOS-27.2-arm64-arm-64bit-Mach-O",
"studio_head": "1d8b8c21014b5b2e94bcd6621dbea177afc0d4eb",
"studio_tree": "uncommitted implementation; exact changed files in source.sha256",
"runtime_head": "09d8778f046a2819c50ac786bfb50e958ef5af61",
"runtime_working_tree": "clean",
"runtime_writes": false,
"runtime_commits": false,
"cargo_target": "/tmp/studio-animation-native-target",
"rustc": "rustc 1.98.1 (48a229cea 2026-09-01)",
"node": "24.21.0 (existing NVM installation; system Node has a missing ICU dependency)",
"java": {
"gradle_launcher": "Amazon Corretto 25",
"product_and_tests": "Amazon Corretto 21"
},
"installed_runtime": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/dist-staging/stable/prometeu-cli-aarch64-apple-darwin",
"installed_runtime_sha256": {
"prometeu": "182e4d9a4d32201c8ad892a11c297de7059dcc0a837660bdd173be44808b9906",
"prometeu-headless": "7703190f63844d91fa125ba3a322b5e771db79a282b3cfbb3480eef76422b6ef",
"prometeu-runtime": "0e8e692395cedea799b6d555b416e40536dcabf3a98a2061327d2010c478e446"
},
"commands": [
"./gradlew test :prometeu-app:installedKnowledgeTest :prometeu-app:animationDesktopTest --console=plain",
"./gradlew :prometeu-app:test --tests *AnimationIntegrationTest :prometeu-app:headlessProcessTest --tests *AnimationInstalledRuntimeTest -PstudioRuntimeInstall=<environment installed_runtime> --console=plain",
"./gradlew :prometeu-architecture-tests:test --tests *PbsResultTest.resultFunctions* --console=plain",
"CARGO_TARGET_DIR=/tmp/studio-animation-native-target python3 tools/pbx-conformance/run.py --runtime ../runtime --result-only [--release]",
"CARGO_TARGET_DIR=/tmp/studio-animation-native-target python3 tools/pbx-conformance/run.py --runtime ../runtime --animation-only [--release]",
"NVM Node 24.21.0: node tools/vscode-extension/node_modules/typescript/bin/tsc -p tools/vscode-extension",
"git diff --check",
"discussion validate"
]
}
@@ -0,0 +1,134 @@
{
"result": {
"producer_variants": [
"ordinary",
"optimized"
],
"native_profiles": [
"dev",
"release"
],
"cases_per_producer": 21,
"native_fixture_runs": 84,
"trap_cases": "remain VM traps; handle never recovers traps"
},
"animation": {
"cases_per_producer": 9,
"producer_variants": [
"ordinary",
"optimized"
],
"native_profiles": [
"dev",
"release"
],
"native_fixture_runs": 36,
"measured_allocations": 0,
"measured_paths": [
"sprite via concrete/trait",
"successful advance",
"negative advance",
"overflow advance",
"factory/builder error paths"
],
"count_setup": "test-only near-limit nodes; unchanged production operation; no billions-of-elements claim",
"frame_traversal_gate": "less than 50000 measured instructions including int-max jump"
},
"gc": {
"profiles": [
"dev",
"release"
],
"producer_variants": [
"ordinary",
"optimized"
],
"live_root_first_safepoint": true,
"unowned_animation_clip_frame_objects_second_safepoint": 0,
"reclaimed_first_safepoint": 2411,
"reclaimed_cumulative_second_safepoint": 4817
},
"composer": {
"producer_variants": [
"ordinary",
"optimized"
],
"native_profiles": [
"dev",
"release"
],
"ticks": [
0,
1,
2,
3,
4,
5,
6,
7
],
"glyphs": [
0,
0,
1,
1,
1,
2,
0,
0
],
"palettes": [
0,
1,
0,
1,
0,
1,
0,
1
],
"sources": [
"direct builder",
"saved JSON generated factory"
],
"sprite_size": [
16,
16
],
"native_frame_observations": 32,
"native_pixel_comparisons": 16384,
"installed_process_frame_observations": 16,
"installed_process_pixel_comparisons": 8192,
"canonical_sidecar_bytes_preserved": true
},
"ui": {
"toolkit": "actual JavaFX, standalone control, default skin",
"actions": [
"create animator and clip",
"add frame with exact duration",
"save",
"preview canonical PNG",
"bank drift",
"prepare/apply rebind",
"JSON origin selection",
"handoff and close"
],
"screenshot": "animation-editor.png"
},
"navigation": {
"revision_revalidation": true,
"reconnect": true,
"stale_origin_rejection": true,
"wire_origin_serialization": true,
"client_typecheck": true,
"full_vscode_development_host_for_new_codelens": false
},
"boundaries": {
"runtime_unchanged": true,
"neutral_model_architecture": true,
"studio_module_export_contract": true,
"binary_assets_unchanged_by_sidecar": true,
"cancelled_late_publication_blocked": true,
"concurrent_create_single_winner": true
}
}
@@ -0,0 +1,129 @@
bb32a9d1fc9345ee10b604a2e0e6097c4264d8040247901bd626d2dad633720d docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md
c8ad4792299089eb74846a177dedb592a55e1161ca36fb3d3b4682b47a7453b6 docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md
ec3a04c5c732e08c956fba7a1c1913e4915ac9dda7d3452180ec79fcd4517ea6 docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md
9d2721529fafb7b984e158cbed2211d4bdf9b9bc545dbbbc18553c0784aff4e2 docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md
8fae59383422256af30625a1debd8b9d3d06bf79de4b6054fd973826b9351204 docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md
837186551dabf59a829d141f76214800c8933e383da57a279842b7ccda40266e docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md
65b38a52baf784f28f19d0ef993565c028c3731044d7fadc06cb3f465d8823fe docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md
6251c7b245371677d9c3128ed105798a713065ebdb5b3362d1a24fc70a17c20f docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md
4b66f7067ad726857842bc840dde3ca6c86e5e6bf5ccc41bb016fca4b858e4f0 docs/specs/compiler-languages/pbs/README.md
f039d441eaba2d3de051cdd5ead730b3edada225f6022ff4d5f2e450048df08b docs/specs/compiler/18. Standard Library Surface Specification.md
1eef76bdc53e7b8121ff6357ecf7e91a2b278176e189d057d804eba9385a950d docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md
e683f2b322d51848d9bcd2c63b33d926e94cc27135d8763791e6b6262e8032ab docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md
ca0edb95fea030beaa9e7f20913c46eec9de3f204a0dadbfa31d916aa9522a21 docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md
4f380e0b4361e3a52ce286832319bfac0d45e55fc7f9f9b197fb1c87d310493e docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md
3fa1b270d1b4e2a66d12ef6f3025161f3a2a3607baf50b191fd142cd322e5956 docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md
ca3c6005183161313d4371c788058cf4bc6a4eef9a085a55201c453a6893864d docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md
41881dae01a0420ef9f20aa555363e2b8a6b8b6cf4f7126157729b91704f2ba0 docs/specs/studio/12. Animation Authoring Specification.md
1007134a4e37e1070fb90cfb6fda79be2f60a252398c856f8e8a5c13984e40b9 docs/specs/studio/4. Assets Workspace Specification.md
c265f466573474fc5b769705d1e7b80831395635dbf9b74f87965d7b1a8f0e8f docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md
6821f65531e72dfdcd9945685c26af425b6c671b200193ded10a56735c09c02d docs/specs/studio/README.md
7d5951e493364a7815066e76799b93f6a6c614a76911758e937fb70b12e3154c prometeu-animation/build.gradle.kts
4a65d23e0a708337a1d79a8c857cdd074f05b76de11ab2929a6f0d890aac6d0e prometeu-animation/src/main/java/p/animation/AnimationCodec.java
fddda8ae3f78a32d62c5efd85539f5ffab904a1ddafaa17f2becf662510abcbc prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java
1664c83f83f6c56733545707185601d22de7bf5c2027f76d0ab18b2a61c355f2 prometeu-animation/src/main/java/p/animation/AnimationDocument.java
4857bd166d3758d0a8c49ad4963142eff3e4bf64178b8dab7747ddb99308d4c4 prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java
f77ed5b4946fea3452275e0807b0d979519d92f706832f823ae8a460907d01a1 prometeu-animation/src/main/java/p/animation/AnimationRebind.java
d31acf93ecb83f9622966e1d361dc31ef6c366dc35dce3d8bff1a8d20f035150 prometeu-animation/src/main/java/p/animation/AnimationRevision.java
ce9bdadfe16f24fcae358d7de213a8c8450ca8a5e2ed45075c6f2f10bda0d983 prometeu-animation/src/main/java/p/animation/AnimationSource.java
1363b399ef7494abe88b3cb2a1e30d0815347501305558e72b1f4f56dc086bd8 prometeu-animation/src/main/java/p/animation/AnimationTimeline.java
57fcb4956030d63b74d0824e5fa35cdd033516c851ba9cde415201cfa51ebec7 prometeu-animation/src/main/java/p/animation/AnimationValidator.java
6fd1f8b203735769e3ec7a7e62240a41fa34a654a19c09151a11f5668953df66 prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java
176f288b6ea3f984c52227b26264bcf69dbe4bb5535990aa9ef37cab48e8d742 prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java
30980f79ba7c1aeda8c7b7be728b14852320222243f962dcc02cf8e194b85689 prometeu-animation/src/test/java/p/animation/AnimationContractTest.java
843a4dfb03afa46905642c5055171606b65e46937d5bc428d503838f7827ab20 prometeu-app/build.gradle.kts
3cd71fdfcf8dfddf60eacca7b0caff08795ff00b55f7da80d400c57b4dc30ae2 prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java
954626f88beaed539a60be0f9142b4e85ab14106a6baa42abccaefb7756c5352 prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java
a320b60885537e917bef66e34ed3cedea53fa1d1580d05fc38d0e9480f1d91a3 prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java
b1692849f2af66faea261e4cc7e5b68baa15919811a29fb9092971389ad9ac1a prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java
0c258a15eb3f34aafed92d96a6a9fdf0e2356752836972c21248a8b3b2d1cb28 prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java
919e7bcbfaf98f2027291475afc39dc68e7e9b2a086edcfb3bc75f5866e94153 prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java
ed0975206ea18373f6e5f436d7f714c96e93bd728f941fc3548cd7739f5a0486 prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java
86c74b1c1ea5bb74bfc032ff1bebede93e79770d0edb5e1e598856816b9b5d64 prometeu-app/src/main/resources/mcp/studio-tools-v1.json
4c6231869b9fec9827fa0cf8dcc08a9b45c4497268d57f98fcafd91da5865310 prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java
d696dbf3b86e0dfbb49aaf750d7fd31462d4cba8cba903c5fb9de0016121ec4d prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java
1ffbcb740b830a066f4ecb7a89ad780aee9c3bd96a33965eeb9b1947c4b2be67 prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java
61cdc1867697dfe339c4e907f1bfec5873d1a71d93f2297c69994025d3db9d4c prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java
56af831e13d28c8c59d4deb6d21fedef9d8225d96e6748bc56a3e8c98b51b82e prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java
f96ec4cac9d2d4f033ac4449679dae1582f0980b9755b833999641d815cb18f5 prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java
4a66af119ed6d27f6acf05746770aa78cd522aea15b8a0adce303fea5fbe8f69 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java
c22b0666b7dbda7bb1aedc2688fe35e447a05008aa0726cabee70741b8c4e02c prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java
e4a5d6062e3436dad94907cf3afa1b6c569283858c71354d0e1aff19f444c627 prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java
631f454efb56a75ec39b7ea2c99cf48cb32bf12a7b73f25f397915ae20438697 prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java
dad477da094986d9157eaf305f1bf9e15a3cac82ecdcdedabc83074bd5305303 prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java
9d4fc89ca4817842ae795e9515e8836e95b99c508e2e3b5fb8c9f3a61e51229f prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java
018a70ad1fa3edaa971c760937e258fddac8c6ae1a36c9b55575186327f357fc prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java
2a9b6e71c29729060615c10a99acc85496f9920c3bee3017fb184a61bd93961c prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java
f328dccad9f040c84d769cdeffa5d8783b78e86664a4187ff5c23c7cf81b7978 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java
ff57258886cff5b367fdb78ee9518188aa98daffd7d6af44536757d3ccfb7b8f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java
4365be38ea866eced4606fbcf53e61992355f6bbdd8398b5418a01b2e68b464c prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java
bae95724d6b31f5367e6bd9ca96a7da1805be8141d30d506686e7f9a988b0bbb prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java
73954236ba33bcbbdecf5f8f8b6c45dab8a7dd2488e032abd34a3c12cb0a659b prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java
0985dcd45f200a0eb24da602827482f90499f790dcaa52719dc769da3893f71d prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java
d37d6e6cea1090e90913689f28db54cb0cf24e497fc3663c7ea2dc64f6f3ee4e prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java
73f8bf2d22a11191f43c51691d820a606e48c0c0f4fc746ec8ebefec71bbc0f3 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java
c64c11ffce06554da57861c373f81897739c9f93b05c8f8559e292b19d1233b5 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java
ce9ad71e884ad106719ddbbe1db99f183b8fba75db237af08e089e280fd2401f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java
5c6777b8d57027b18f3c19133628335af3a76008f629b9e3b44b8e5fa9bd47c5 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java
b5cc039430efbfacdc3720f72495bb661e50d195fb520cbf6dab31445147c9a4 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java
061c248e8de616e3ce8412b76930744248b1fd36e59454a05b91185bc27be7df prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java
d35633448a3023f837c743d2c96cfc0ccb1df23f2956d0d5934dc1824c686fc6 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java
b65b02effea05dd9a10b32a9a03c9843a92c1ada9902ad19b14e0de7222cbb14 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java
6965b8325f0b7da1a83f7581984b34ea00671d66085d3210488fb672941e390f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java
4429e1dc0dfb27e1aa145011683c589b1a3f4502be1223ef03aa8b2cddc28f65 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java
5907731d1a10036d50021fe8263c2e8f9f2b79d0fddfb9a70b2d8449b42aecbc prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs
36e78b0dafd0a4e5f4b63499a5f197870d9abaa5a2c02364339ffde3a87c3862 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel
61b530fa321c3e69983c8c6e0a48503534a280a9d4b266cd1b62a5fe54d9d382 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs
29c4ffff336a54ab874ed8dce996ebd877f7b3145cdf5844836bff9a2f3757f8 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel
c92f3ab13a0cd2cb2e2adba7b236ce1282b89733d3dde0b1e396da950a7b7552 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs
639beb705a61799351f22109b5356520498824f326ab1af1fd711daef4cdf641 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md
2567aca3b9e0a733871c2f736c7f0a4ce43415cf5b43dddfaf93963cd6db19c6 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs
be65d777f43e82312d565816442bbb565dd00c6005c606a11ced58dbe6dc6f97 prometeu-compiler/prometeu-build-pipeline/build.gradle.kts
f4ec6a28525d2493d6d160409437016bf8973cc2cc01a6fe072a364fe50c29c3 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java
8d6e05a68ebb707442356b9b2975d80a412b6993fe62789c6cbbbc9243e732a3 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java
c9a0ee7309b022c872346a8d7125ac6d24fa77778b9ae2dbfbca003caf6d8213 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java
9a76574ee95514c0bd69d1468f55216984dd57210efc2677798dfbb899f53b81 prometeu-compiler/prometeu-frontend-api/build.gradle.kts
bf4e92a43215d760967e476bf899d0cf9f42ab26ba74c0a4bcb40f22248c8788 prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java
bc7d38ec152c1ff250d45d3eeab1b00fe9a9c83fc384599e0f9c0a161c654863 prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java
6ec24293d82e3606663acf993106a6275094c47be0da28d720762700a56373cf prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java
9bf8484492e08ff3f4839d7e8022e3737d85a2e663987187c86235406eba8ac5 prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java
2f391046cc51604d00a1876cdc99495421d9893a324bd8b2c28edf5d59853a9c prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java
ec8702d093e5845b47312b65cab4421a632f9c57f075843e22570c91fff2365d prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java
82fa22592d2a24a79745f08aae456682994a2994ad2957c66d5ac2d51cfd3d44 prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java
404b12a9131b6aa1607cec4c81bda55e8a403db329494f1e9a386247d4236027 prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java
13079954d52a51b77880ee5988349323eb427b09001f47d1a48f0fa7532aa0c6 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java
c35b1ea511199fc91dab4a7401e37d8a91c0a7debcdfe2b516194fae26ffadb1 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java
d2659d7d9627557e907dd8e77d490c63ea72f2b3e33252601b43c66be78b953a prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java
8b686dd77199cf275ced2101c6351bec4876ec1dfc0dbf723d3c826e68d9a1b4 prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java
276d878ce8e864e4d3badbc54bae754935d7ff565f72b150d76b34be443e0a22 prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java
af1a00db5a065f178fe3f09c487cc8e7f5bfe3da20162ea4584740e1e090a3ce prometeu-studio-api/build.gradle.kts
c9570929f5b3b7e99a42ba7f1784f763a4f35c9896bd3998385a3a3a1e8562fd prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java
5581216eb1e3fbc09651120b889f75ec6619e6f4b0489bb0f6dfdd91794d0347 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java
fc5542118b270ada7c6ea383187028af87920192d7358b6a011adddf114c3af2 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java
4435e427529b0a7ebef4e98dc870e7598ec5d647578b9c3cecfcee2a717bada8 prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java
a8e67f1a3877be23f59c191eb40fbb2036088e53836e8dc13c2c99a43778fdf8 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java
455af9c0f133ab62a70f30758208afd337a202c7a92b8c4064cc1c977ecd39a8 prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java
4e3db0ca8c1b47ac2f8d253188fb93a7d3c6fdccf8f755ab898b3f41181c27f6 prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java
7cd160b03ca0ef1892ed1c8ac1713ab541a4691bdc66680514907ecb0b260ea4 prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java
420a53d8a86c6e3e2d66022f03a616396fa863e2632be4346d470d9808d4e17f prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java
f19f1fb878eeeb5b4167602520042e271f9102c0aef796e7ffe0c5590d88f52a prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java
aaddecc065e53d8942e594cc2e3efe969988084aa7ca30906acfa5f730359c08 prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java
678c32d2cbd9f7d4a31737263fa1f2e56c7bfe4b83e168d9a79448a4c7906761 prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java
cb5fa3bd1d1384145e0cba59bdf18ad8f288949526ec6d00936089ba5a695a0b prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java
a06eaf5fdf327388ca00073e33deb7751bd97a766161d594d51c7180799f5e04 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java
0f928aaf0e3d6cdc5224e7373ef3afa951d810ee8803b0632d07c56fd997d7ca prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java
be51cd5bb0e91986578d4a33c510f1728f66f31011f89ce43c05963f9c5239c1 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java
b95ec37e9554f5fc4f6d48dc5cb13357b36cdc476341898c69ed3ac78d5babd5 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java
bdbb2d8fcab150c398da0a41dec219f97f6b4329d5676b15e01ad3cf8ae6080a prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java
4701d71fc568480a3c204d117a321cd1e398d4b29bdcc4b498396bbe9343d288 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java
0242e87b38301dcd768b604747c368893317b3efe228f5125c821bba933b5e47 settings.gradle.kts
625305ac75a2319dd3a1cee9db450bbeb31a60d85a35b9fc03afbd0ad3441e60 tools/pbx-conformance/README.md
6c1b543960bd0ecabcd4cf89ef3cb6646df2b909cb2cf9e6965c59225a0e1a3f tools/pbx-conformance/animation.rs
51bbebb411078bf4d8336e28d35e438aba49c47deebb3ffbd55859fbda80c432 tools/pbx-conformance/main.rs
7829e50105fc9bc3ced056aa8a34714a644908483532f154a437fa41928122ab tools/pbx-conformance/result.rs
29a6623d2ba1ff3d3e1b0017a2fc10cbb790dfc7126dabf999c75250d9d9ce30 tools/pbx-conformance/run.py
ff7669746d0cb7167a84e3e383d3570968888bbedde812a79a6aaefac2a74f7e tools/vscode-extension/out/extension.js
2ba64626f79b7fe8abeb260ce8572dfd8bb1f4dfcbe8c65e5eaf2e512fecbfe7 tools/vscode-extension/out/externalSources.js
b4a1e93075da5bb89d37d5196110a4aa0ce9070f55692827eef70e9d6d9d01d1 tools/vscode-extension/package.json
2e7babd6f2272c0f96aa3d65bf4bf940dd6e2a4e5cd91f149d7d17ef40b22039 tools/vscode-extension/src/extension.ts
3fec63d03afe610d4a5d0eb7c9ff5758af5bec076d4cd01adbb8da6ba1f0fbec tools/vscode-extension/src/externalSources.ts
@@ -0,0 +1,18 @@
$ discussion mark-plan PLN-0162 done
marked plan PLN-0162 done for DSC-0098
$ discussion housekeep DSC-0098 --lesson discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md
housekept DSC-0098
removed workflow artifacts: 3
registered lesson: LSN-0100
$ discussion validate
validation passed
$ discussion inspect DSC-0098
DSC-0098 done pbs-core-sprite-animation
PBS Core Sprite and Animation
tags: compiler, pbs, core, stdlib, sprites, animation
lessons:
- LSN-0100 done exists /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md
@@ -329,3 +329,10 @@ The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Sp
defines the complete type, optional-flow and storage contract.
This chapter supplies shared reachability and ownership rules; Array storage
and complete-group packing are defined by that owner.
## Animation ownership and allocation
Every AnimatorBuilder.build materializes independent private clips, frames and backing. Immutable strings retain normal sharing; assignment retains ordinary identity/aliasing. Final frame links may form private cycles and must remain rooted/reclaimable under existing GC. After construction, executed advance and sprite paths allocate no heap objects, including negative/overflow error returns.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -291,3 +291,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
## Executable result return groups
Emit an existing typed return group: Int32 status 0 for success or canonical nominal error case index 1..N, followed by the complete plain payload group. Unit result has only status. Error payloads use admitted typed defaults, including nullable references, without constructing payload objects. Preserve typed reference/builtin/Fn/trait groups across signatures, Registry, direct/contract calls, branches and discard. Propagation fills the enclosing inactive payload and returns immediately; handle recovers locally or remaps outward. The common backend consumes neutral typed IR with no PBS branches.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -0,0 +1,180 @@
# Core Sprite and Animation Specification
Status: Normative v1. Owner: compiler/pbs. Applies to Game stdlib major 1.
## Purpose and boundaries
The core provides ordinary executable PBS structs, not VM builtin animation types.
The caller owns bank loading, replacement and lifetime. Core validates structural
ranges and arithmetic; glyph existence and asset-to-slot correspondence belong to
the asset-aware caller. Sprite, internal clips and Animator store neither position
nor palette. Each frame is one glyph, and frame glyph IDs need not be contiguous.
The public API, private construction and executable result rules below are
normative. Finalized clips/frames are private and immutable after publication.
## Core API and ownership
```pbs
// @core:sprite exports Sprite, SpriteView, SpriteError and:
fn make_sprite(bank_id: int, glyph_id: int) -> result<SpriteError> Sprite;
// Sprite and SpriteView:
fn sprite() -> (bank_id: int, glyph_id: int);
// @core:animation exports Animator, AnimatorBuilder, AnimationError and:
declare enum PlaybackMode(Once = 0, Loop = 1);
declare enum PlaybackState(Stopped = 0, Playing = 1, Paused = 2, Finished = 3);
fn animator_builder(bank_id: int, initial_clip: str) -> result<AnimationError> AnimatorBuilder;
// AnimatorBuilder:
fn begin_clip(name: str, mode: PlaybackMode) -> result<AnimationError>;
fn add_frame(glyph_id: int, duration_ticks: long) -> result<AnimationError>;
fn end_clip() -> result<AnimationError>;
fn discard_clip() -> result<AnimationError>;
fn remove_clip(name: str) -> result<AnimationError>;
fn build() -> result<AnimationError> Animator;
// Animator implements SpriteView:
fn sprite() -> (bank_id: int, glyph_id: int);
fn state() -> PlaybackState;
fn active_clip() -> str;
fn clip_count() -> long;
fn frame_count(name: str) -> result<AnimationError> long;
fn frame_at(name: str, index: long) -> result<AnimationError> (glyph_id: int, duration_ticks: long);
fn select(name: str) -> result<AnimationError>;
fn play(name: str) -> result<AnimationError>;
fn pause() -> void;
fn resume() -> void;
fn stop() -> void;
fn restart() -> void;
fn advance(ticks: int) -> result<AnimationError>;
```
Factories are the public construction path. `[StdlibFactoryOnly]` restricts
positional/named `new` to the type's declaring module, using trusted stdlib origin.
Game code cannot forge that metadata or evade it by alias/reexport. Types remain
ordinary PBS structs. Completion/signature help must expose usable factories.
Admit the reserved attribute only on structs from trusted stdlib origin; it is
not a game-defined annotation. Use `declare contract` and `implements` in each
concrete type's module, preserving the existing PBS contract ownership rules.
Clip/frame types and backing never escape. Sprite and Animator implement
SpriteView with joint bank/glyph query, no new Sprite or effects per read.
Banks are int 0..255, glyphs int 0..65535, durations long 1..LONG_MAX,
LONG_MAX=9223372036854775807. Clip totals must not exceed LONG_MAX. Clip/frame
counts are long bounded by 4294967295; final clips/animator are nonempty. Frame
indices are zero-based longs. Tick input remains int; negative is an error,
zero has no effect and positive values are at most 2147483647.
SpriteError cases are invalid_bank, invalid_glyph. AnimationError cases, in order:
invalid_bank, invalid_name, duplicate_clip, clip_already_open, no_open_clip,
empty_clip, unfinished_clip, empty_animator, initial_clip_missing, unknown_clip,
invalid_glyph, invalid_duration, invalid_ticks, index_out_of_range, limit_exceeded,
overflow. Names are nonempty exact UTF-8 strings without implicit normalization.
Builder bank/initial name are fixed; it allows one open clip. end_clip rejects an
empty open clip without closing it; discard_clip discards only the open clip.
remove_clip requires none open. build checks open clip, empty collection, missing
initial in that order and produces Stopped at the initial clip's first frame.
Reuse must create private clips/frames for every animator. Builder edits leave
published animators unchanged. Only immutable strings may retain ordinary sharing.
No clone or external Clip attachment exists. Assignment preserves PBS identity.
Factories check bank ranges and required names before allocation; make_sprite also
checks glyph range. begin_clip requires no open clip and an unused, valid name;
add_frame requires an open clip and valid glyph/duration. For assembly operations,
check state preconditions before arguments, then names, ranges, counts and sums in
that order. Check `total > LONG_MAX - duration` before addition. Inspection checks
clip name before frame index. All recoverable failures preserve the prior draft
or animator, including failed end_clip, unknown remove/select/play and build after
removing the initial clip. Prepare candidate storage before publishing mutations.
### Executable result contract
Use the existing VM return group: first an Int32 status (0 for success, 1..N in
canonical error declaration order), followed by the complete typed plain-return
payload group. Preserve reference, builtin, function and trait-pair shapes and
nominal error identity in analysis/IR; matching slot counts do not establish type
identity. Unit result contains only status. Inactive error payload slots use
runtime-admitted typed defaults, including nullable reference defaults; they must
never be read as success values or require constructing payload objects.
`!` evaluates its operand once and immediately propagates the same error, filling
the enclosing function's inactive payload correctly even when its shape differs.
`handle` evaluates once and executes only the selected arm, preserving success,
local recovery and error remapping. Neither operation catches VM traps. Apply the
same group consistently to signatures, Registry metadata, imports/aliases, direct
and contract calls, branches and discarded results. Unit error paths must not use
the existing allocating default-holder helpers. Keep `Fn(...) -> TypeRef` grammar
and reject conversion of a result-effect function to plain Fn; successful Fn
payloads retain their ordinary typed representation.
### Playback contract
| Operation | State and cursor behavior |
| --- | --- |
| select(name) | From any state: Stopped at frame zero, zero phase, including the current name. |
| play(name) | From any state: Playing at frame zero, zero phase, including the current name. |
| pause() | Playing -> Paused; other states unchanged. Preserve cursor/phase. |
| resume() | Paused -> Playing; other states unchanged, including Finished. |
| stop() | From any state: Stopped/reset on selected clip. |
| restart() | From any state: Playing/reset on selected clip. |
| advance(ticks) | Reject negative in every state; zero is a no-op; positive advances only Playing. |
Check phase > LONG_MAX - ticks before addition; overflow leaves the animator
unchanged. Loop uses the remainder after dividing the new phase by total duration.
Once finishes only after consuming the last frame's full duration, retains its
image and clamps phase to total. Frame intervals are [start,end). Seek traverses
at most one clip's frame count, never each tick or each skipped loop. Failed
selection does not change anything; clips retain no suspended progress.
Use private finalized frame links with long duration/cumulative end, tail linking
to head, and direct selected clip/frame references. Prepare links before publishing
the animator. Advance and sprite must not allocate, including unit error returns;
array/optional wrappers must not be introduced on this path. All computations
precede visible state publication. VM resource/trap faults are not modeled domain
errors and carry no new rollback/safe-retry promise.
## External composition
The caller queries SpriteView and invokes
`Composer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority) -> int`.
Preserve host identity `(composer, emit_sprite, 1)` and capability `composer`.
Composer does not depend on core Sprite/Animator. Palette applies only to the
current emission; query or emission does not advance playback.
Blitable and a draw manager are separate work. Entities, gameplay state machines,
events, ping-pong, clones, collision, multi-glyph frames and runtime animation
resources are outside this contract. There is no new opcode, host ABI, Registry
category or runtime metadata format.
## Authored factory and conformance
[Animation Authoring](../../studio/12.%20Animation%20Authoring%20Specification.md)
defines canonical JSON, binding drift, shared validation and generated sources.
Generated factories use the same builder and return effect as direct PBS code.
Factories construct fresh private clips; they never load banks or call the host.
Conformance must execute ordinary and optimized PBX with the production loader/VM
in dev/release, compare shared preview against native playback, and count executed
heap-allocation instructions for advance/sprite after construction, including
negative/overflow errors. Zero is mandatory. Resource/trap failures are not domain
errors and do not imply rollback or safe retry. A failure to establish zero
allocations requires an explicitly authorized decision revision.
Examples must call play on an action transition and advance for continuity;
calling play/select every frame resets playback every frame.
## Related specifications
See chapters 3/4 for source admission, 5/8 for module resolution/distribution,
9/10 for result/identity/lifetime and 13 for typed executable lowering.
## Native Composer status adaptation
The public Composer facade retains its existing int status and nine arguments.
The private LowComposer declaration uses the native Int64 status carrier and the
facade explicitly narrows it to int. This is a PBS adapter conversion using existing
intrinsics; host identity, capability, slot count and runtime behavior are unchanged.
@@ -1243,3 +1243,10 @@ may accompany them. Targets MUST be nongeneric top-level userland functions;
methods, lambdas, host/interface declarations and other declaration kinds are
invalid targets. Function names are arbitrary and do not select runtime roles.
PBS exposes no sync statement, lifecycle syscall or termination marker.
## Stdlib factory-only construction
`[StdlibFactoryOnly]` is reserved metadata on trusted stdlib structs. Both positional and named `new` are permitted only in the canonical declaring module. Imports, aliases and reexports preserve this admission boundary. Game declarations cannot forge the attribute. Public construction uses the declared recoverable factories. The existing result return-effect and `Fn(...) -> TypeRef` grammar remain unchanged.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -866,3 +866,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
## Factory admission and typed result identity
Factory-only admission uses trusted canonical declaration origin, never visible spelling or slot count. Reject external positional/named construction and forged metadata; omit prohibited constructors from completion/signature help and expose public factories. Result error identity is nominal through imports and aliases; a result-effect function cannot be converted to plain Fn.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -578,3 +578,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
## Core animation and generated module resolution
Game stdlib 1 distributes executable ordinary PBS modules `@core:sprite` and `@core:animation`. Private helpers retain definition-scoped resolution and trusted origin. Reserve `generated/animations` for project-owned virtual modules `@<project>:generated/animations/b_<uuid_without_hyphens>`; physical collisions are diagnostics. Only registered build-included banks publish factories; invalid included definitions block analysis/build.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -366,3 +366,10 @@ documents with revision-consistent text, ranges and frontend semantic context.
Hover and continued definition use that retained context. Compilation, module
admission, ABI and linking rules are unchanged. See Compiler Spec 23 §8.3 and
Studio Spec 11 for the consumer protocol and atomic write restrictions (DEC-0062).
## Executable core animation distribution
Package ordinary PBS bodies, barrels, helpers, documentation and examples for core sprite/animation in stdlib major 1. Compile these bodies through the same executable frontend path used by collections. Restrictions specific to SDK service bodies do not apply to all stdlib functions/structs. Installed consumers must not depend on a source checkout.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -420,3 +420,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
## Result groups and explicit animation time
A result success evaluates its payload once. Propagation and handle evaluate their operand once; only the selected recovery arm runs. Error remapping returns the enclosing error; traps are not caught. Animation advances only through explicit ticks. Queries/emissions are pure with respect to playback; repeated play/select resets the selected clip even when its name is unchanged.
See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations.
@@ -204,3 +204,5 @@ The internal resource path is `pbs-knowledge/specs/<numbered filename>.md`;
reference clients resolve IDs through the catalog instead of constructing paths.
- [Memcard Bootstrap and SDK](<26. Memcard Bootstrap and SDK Specification.md>): opt-in persistence producer and runtime-consumer boundaries.
- [Sprite and animation contract](27.%20Core%20Sprite%20and%20Animation%20Specification.md) — core API, explicit ticks, shared bank authoring and generated factories.
@@ -252,3 +252,10 @@ This specification MUST NOT:
PBS shells MUST repeat identities already published by the runtime catalogs
named in section 3.
## Animation integration contract
Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI.
See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md).
@@ -301,3 +301,10 @@ assigns other IDs to hooks. PBX emission consumes the existing role byte and
validates final targets, without role inference from function names or frontend
ASTs. Synthetic Init/Frame assembly is unchanged. FRAME_SYNC fixtures used to
test controlled-call rejection do not introduce frontend sync syntax.
## Animation integration contract
Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI.
See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md).
@@ -307,3 +307,10 @@ slots 1..64, capability memcard, unique role 3 and the boundary before launch.
This is distinct from a direct CALL to the hook. Host storage and headless transport
remain runtime-owned and absent from the common IR. See the PBS
[producer contract](<../compiler-languages/pbs/26. Memcard Bootstrap and SDK Specification.md>).
## Animation integration contract
Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI.
See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md).
@@ -160,3 +160,10 @@ This specification is complete enough when:
- registered asset boundaries are unambiguous;
- registry authority is explicit;
- identity survives relocation without ambiguity.
## Animation integration contract
Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order.
See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md).
@@ -250,3 +250,10 @@ This specification is complete enough when:
- the common `asset.json` shape is stable;
- raw and virtual assets share a coherent baseline contract;
- format-specific specs can build on it cleanly.
## Animation integration contract
Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order.
See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md).
@@ -307,3 +307,10 @@ This specification is complete enough when:
- runtime-facing artifact authority is explicit;
- companion artifacts are bounded;
- emitted ordering and header behavior are deterministic.
## Animation integration contract
Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order.
See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md).
@@ -631,3 +631,10 @@ per-project desktop Run is required. Explicitly disabled integration MUST remain
disabled. Preparation failure MUST remain visible in DEV readiness without blocking
project use. Opening MUST NOT publish credentials or grant/acquire agent control.
The coding client continues to own its configured stdio process and initial trust.
## Animation integration contract
Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports.
See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md).
@@ -0,0 +1,142 @@
# Animation Authoring Specification
Status: Normative v1. Owner: studio. PBS projection owner: compiler/pbs.
Packer owns registered assets, composition, effective glyph indices and fingerprints.
## Purpose
JavaFX, AI tools and compiler consumers share one versioned editorial document,
validator and bank-layout identity contract. This sidecar is neither a runtime
asset nor generated editable PBS. The entire authoring/projection contract is
specified below.
## Canonical document and services
Each registered glyph bank can contain animations.studio.json, a JSON UTF-8
sidecar distinct from asset.json and studio.asset.json. Its strict schema is:
```json
{
"schema_version": 1,
"bank_asset_uuid": "<containing bank UUID>",
"bindings": [{"artifact_id": "<stable selected artifact>", "glyph_id": 7,
"fingerprint": "<sha256>"}],
"animators": [{"id": "hero", "initial_clip": "idle", "clips": [
{"name": "idle", "mode": "loop", "frames": [
{"artifact_id": "<stable selected artifact>", "duration_ticks": 4}
]}
]}]
}
```
Animator IDs are unique PBS identifiers matching [A-Za-z_][A-Za-z0-9_]*. Modes
are once/loop; frame order matters. Each animator has nonempty named clips;
zero animator definitions is allowed. Decode long integers exactly. No palette,
position or runtime bank slot is stored. Unknown fields/versions and malformed
or duplicate bindings/JSON keys are errors, not fallback triggers.
Every referenced artifact must match the containing bank UUID and Packer's current
effective glyph ID/fingerprint. Reordering, removal and content replacement produce
blocking drift diagnostics. Explicit prepare/apply rebind presents old/new bindings
and affected frames, validates the result and requires the expected revision.
Never silently retarget by list order or path. Save validates the whole candidate
against the current snapshot and uses a revision check plus atomic replacement;
failed validation/conflict preserves the canonical file and editable draft.
Perform revision verification and publication under the same project exclusion;
replace atomically within the same filesystem. Read/validate may expose an invalid
document with diagnostics for repair; preview/build/projection must not fall back
to an older valid document or another schema version.
The new neutral prometeu-animation library (p.animation) owns immutable DTOs,
strict codec, shared validator, revisions and editorial preview timeline. It has
no JavaFX/Spring/compiler/concrete-packer dependency. Packer exposes effective
layout snapshots, and app supplies the neutral GlyphBankLayoutSource port. Both
Studio services and the build context loader use this shared validator. A build
with included definitions but no configured resolver fails explicitly. Existing
projects without definitions retain an empty context and compatible entry points.
FESurfaceContext carries language-neutral validated snapshots; PBS alone emits
virtual modules at @<project-name>:generated/animations/b_<uuid-without-hyphens>.
Factories are create_<animator_id>(bank_id: int) -> result<AnimationError> Animator.
Reserve generated/animations and reject physical-module collisions. Only registered,
build-included banks publish factories. Invalid included definitions block build;
never reuse stale generated text. Sort factories by ID, preserve clip/frame order,
escape PBS literals and exclude timestamps/absolute paths. Keep generated modules
read-only through FrontendSourceDocument and revision-scoped ExternalSourceRegistry
URIs, with generated spans mapped to original JSON fields. No generated source
becomes a second editable persistence surface.
Generated revision includes the document, resolved bindings and generator version.
Invalidate old origins after changes/reconnect, reject generated save/rename, and
let the UI open the original JSON field through the authoring service.
Studio API/core provides list/read, draft validation, save/delete, prepare/apply
rebind and preview. JavaFX provides complete animator/clip/frame authoring, initial
clip/mode, durations, ordering, diagnostics, save and drift repair. Preview has
play/pause, explicit ticks and palette input. Shared neutral rendering returns
canonical image plus observed bank/glyph/state/ticks; its timeline must match PBS
native execution. No palette/position is persisted in the animation definition.
MCP adds task-authorized studio_animation_query (list/get/validate/preview) and
studio_animation_update (save/delete/prepare_rebind/apply_rebind), with strict
schemas, expected revisions and the same services as UI. Reuse existing authority,
operations, cancellation, revocation, conflict handling and document handoff.
Both tools take projectRoot, taskId and operation, plus these exact domain fields:
| Operation | Fields and behavior |
| --- | --- |
| query/list | Optional assetUuid filter; project definitions/diagnostics. |
| query/get | assetUuid; current document, revision, diagnostics. |
| query/validate | assetUuid, optional candidate document; no persistence. |
| query/preview | assetUuid, animatorId, clipName, nonnegative long elapsedTicks, paletteId, optional candidate document; sample from clip start. |
| update/save | assetUuid, expectedRevision, complete document; explicit null revision only for create, never overwrite an existing file on create. |
| update/delete | assetUuid, expectedRevision, animatorId; preserve other definitions. |
| update/prepare_rebind | assetUuid, expectedRevision; return diff, candidate document/hash and bank snapshot revision, without writing. |
| update/apply_rebind | assetUuid, expectedRevision, document, proposalHash, expectedBankRevision; validate the same proposed binding-only change against the current bank. |
Reject fields belonging to a different operation. Use the existing typed result
envelope and image contract. Proposal hashes correlate content, not a new grant or
approval workflow. UI autoplay schedules explicit tick updates with a transient
preview rate; preview never persists an animation clock.
## Persistence and authority
Operations use project identity, asset UUID, animator ID and expected revision;
arbitrary caller-provided file paths are not definition addresses. Resolve authority
before cache lookup. Manual, Agent and Debug use existing project exclusion,
cancellation/revocation and document handoff; no parallel grant or approval flow
is introduced. Save validates the whole document against the current layout,
checks expected revision under project exclusion and atomically replaces the file
on the same filesystem. Conflict or recoverable failure preserves canonical bytes
and the editable draft.
Rebind is the only binding migration operation: preparation returns old/new IDs,
fingerprints and affected frames without persisting; application validates the
same proposal hash, document revision and bank revision before replacement.
Read, preview, analysis and build never silently repair or reuse stale sources.
## Preview and UI
The editor integrates glyph-bank details and supports create/rename/delete of
animators and clips, initial-clip/mode selection, frame addition/removal/reordering,
exact long-duration entry, diagnostics, save conflicts and explicit drift repair.
Palette and position are transient viewing inputs. Play schedules explicit ticks
using a transient preview rate; no clock is persisted in animation definitions.
The renderer returns canonical pixels and observed bank/glyph/state/ticks without
JavaFX and must reject invalid bank/references instead of simulating success.
The timeline follows the complete state/interval table in
[Core Sprite and Animation](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md).
Production-native conformance must compare those observations for identical input
timelines, direct/generated factories and both producer/runtime profiles.
## Dependencies and distribution
`prometeu-animation` (`p.animation`) contains immutable DTOs, strict JSON codec,
structural/snapshot validation, revisions and preview timeline. It depends on no
JavaFX, Spring, HTTP, compiler or concrete Packer implementation. Studio core
orchestrates persistence/layout/rendering; app composes the Packer API adapter.
PBS alone generates PBS source; compiler/backend stay independent of Studio core.
Installed references, examples and MCP schemas must expose this same contract.
@@ -489,3 +489,10 @@ This specification is satisfied when the Studio `Assets` workspace:
- stages sensitive mutations through preview-first flows;
- proves the Studio event-driven workspace framework through lifecycle-managed local ownership;
- and behaves as a didactic helper for the packer model.
## Animation integration contract
Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports.
See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md).
@@ -192,3 +192,10 @@ shutdown through those ports. Application infrastructure owns credentials, file
locks/atomic discovery, HTTP identity checks, TOML preparation and managed
installation/runtime packaging. JavaFX consumes neutral status and actions only.
Filesystem publication MUST NOT run under a long-held authority monitor.
## Animation integration contract
Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports.
See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md).
+2
View File
@@ -100,3 +100,5 @@ terminal remains separate.
See the [specification guide](../README.md) for compiler, language and provider boundaries.
- [Sprite and animation contract](12.%20Animation%20Authoring%20Specification.md) — core API, explicit ticks, shared bank authoring and generated factories.
+2
View File
@@ -0,0 +1,2 @@
plugins { id("gradle.java-library-conventions") }
dependencies { implementation(libs.jackson.databind) }
@@ -0,0 +1,75 @@
package p.animation;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import java.util.*;
import static p.animation.AnimationDocument.*;
/** Strict UTF-8 JSON. Integer values never pass through floating point. */
public final class AnimationCodec {
private final ObjectMapper mapper = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
public AnimationDocument decode(String json) {
try {
JsonNode root = mapper.readTree(json);
object(root, "", "schema_version", "bank_asset_uuid", "bindings", "animators");
int version = integer(root.get("schema_version"), "/schema_version");
if (version != 1) throw invalid("/schema_version", "Unsupported schema version");
var bindings = new ArrayList<Binding>(); int i=0;
for (var node : array(root.get("bindings"), "/bindings")) {
String p="/bindings/"+i++; object(node,p,"artifact_id","glyph_id","fingerprint");
bindings.add(new Binding(string(node.get("artifact_id"),p+"/artifact_id"), integer(node.get("glyph_id"),p+"/glyph_id"), string(node.get("fingerprint"),p+"/fingerprint")));
}
var animators = new ArrayList<Animator>(); i=0;
for (var node : array(root.get("animators"), "/animators")) {
String p="/animators/"+i++; object(node,p,"id","initial_clip","clips");
var clips = new ArrayList<Clip>(); int j=0;
for(var clip : array(node.get("clips"),p+"/clips")) {
String cp=p+"/clips/"+j++; object(clip,cp,"name","mode","frames");
var frames=new ArrayList<Frame>(); int k=0;
for(var frame:array(clip.get("frames"),cp+"/frames")) {
String fp=cp+"/frames/"+k++; object(frame,fp,"artifact_id","duration_ticks");
frames.add(new Frame(string(frame.get("artifact_id"),fp+"/artifact_id"), exactLong(frame.get("duration_ticks"),fp+"/duration_ticks")));
}
clips.add(new Clip(string(clip.get("name"),cp+"/name"),string(clip.get("mode"),cp+"/mode"),frames));
}
animators.add(new Animator(string(node.get("id"),p+"/id"),string(node.get("initial_clip"),p+"/initial_clip"),clips));
}
return new AnimationDocument(version,string(root.get("bank_asset_uuid"),"/bank_asset_uuid"),bindings,animators);
} catch (java.io.IOException error) { throw invalid("", error.getMessage()); }
}
public String encode(AnimationDocument document) {
ObjectNode root=mapper.createObjectNode(); root.put("schema_version",document.schemaVersion()); root.put("bank_asset_uuid",document.bankAssetUuid());
var bindings=root.putArray("bindings");
for(var binding:document.bindings()) bindings.addObject().put("artifact_id",binding.artifactId()).put("glyph_id",binding.glyphId()).put("fingerprint",binding.fingerprint());
var animators=root.putArray("animators");
for(var animator:document.animators()) {
var node=animators.addObject().put("id",animator.id()).put("initial_clip",animator.initialClip()); var clips=node.putArray("clips");
for(var clip:animator.clips()) { var c=clips.addObject().put("name",clip.name()).put("mode",clip.mode()); var frames=c.putArray("frames");
for(var frame:clip.frames()) frames.addObject().put("artifact_id",frame.artifactId()).put("duration_ticks",frame.durationTicks()); }
}
try { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)+"\n"; }
catch(java.io.IOException error) { throw new IllegalStateException(error); }
}
private static void object(JsonNode value,String pointer,String... names) {
if(value==null||!value.isObject())throw invalid(pointer,"Expected object");
var expected=Set.of(names); var keys=value.fieldNames();
while(keys.hasNext()){var key=keys.next();if(!expected.contains(key))throw invalid(pointer+"/"+key,"Unknown field");}
for(var name:names)if(!value.has(name))throw invalid(pointer+"/"+name,"Missing required field");
}
private static JsonNode array(JsonNode node,String pointer){if(node==null||!node.isArray())throw invalid(pointer,"Expected array");return node;}
private static String string(JsonNode node,String pointer){
if(node==null||!node.isTextual())throw invalid(pointer,"Expected string");
String text=node.textValue();
for(int i=0;i<text.length();i++){
char c=text.charAt(i);
if(Character.isHighSurrogate(c)){if(i+1>=text.length()||!Character.isLowSurrogate(text.charAt(++i)))throw invalid(pointer,"Unpaired Unicode surrogate");}
else if(Character.isLowSurrogate(c))throw invalid(pointer,"Unpaired Unicode surrogate");
}
return text;
}
private static long exactLong(JsonNode node,String pointer){if(node==null||!node.isIntegralNumber()||!node.canConvertToLong())throw invalid(pointer,"Expected exact signed 64-bit integer");return node.longValue();}
private static int integer(JsonNode node,String pointer){long value=exactLong(node,pointer);if(value<Integer.MIN_VALUE||value>Integer.MAX_VALUE)throw invalid(pointer,"Integer out of range");return (int)value;}
private static IllegalArgumentException invalid(String pointer,String message){return new IllegalArgumentException(pointer+": "+message);}
}
@@ -0,0 +1,2 @@
package p.animation;
public record AnimationDiagnostic(String code, String pointer, String message) {}
@@ -0,0 +1,24 @@
package p.animation;
import java.util.List;
import java.util.Objects;
/** Canonical editorial values; slots, palette, position and playback clocks are external. */
public record AnimationDocument(int schemaVersion, String bankAssetUuid, List<Binding> bindings, List<Animator> animators) {
public static final String FILE_NAME = "animations.studio.json";
public AnimationDocument {
Objects.requireNonNull(bankAssetUuid); bindings = List.copyOf(bindings); animators = List.copyOf(animators);
}
public record Binding(String artifactId, int glyphId, String fingerprint) {
public Binding { Objects.requireNonNull(artifactId); Objects.requireNonNull(fingerprint); }
}
public record Animator(String id, String initialClip, List<Clip> clips) {
public Animator { Objects.requireNonNull(id); Objects.requireNonNull(initialClip); clips = List.copyOf(clips); }
}
public record Clip(String name, String mode, List<Frame> frames) {
public Clip { Objects.requireNonNull(name); Objects.requireNonNull(mode); frames = List.copyOf(frames); }
}
public record Frame(String artifactId, long durationTicks) {
public Frame { Objects.requireNonNull(artifactId); }
}
}
@@ -0,0 +1,6 @@
package p.animation;
import java.nio.file.Path;
import java.util.UUID;
/** Open an authored field through the Studio editor; this port never writes files. */
@FunctionalInterface
public interface AnimationOriginNavigation { void open(Path projectRoot,UUID assetUuid,String jsonPointer); }
@@ -0,0 +1,28 @@
package p.animation;
import java.util.*;
import static p.animation.AnimationDocument.*;
/** Binding-only proposal, correlated with the exact source and bank revisions. */
public final class AnimationRebind {
public record Difference(Binding before, Binding after, List<String> affectedFrames) { public Difference { affectedFrames=List.copyOf(affectedFrames); } }
public record Proposal(AnimationDocument document, List<Difference> differences, String proposalHash, String bankRevision) { public Proposal { differences=List.copyOf(differences); } }
public Proposal prepare(AnimationDocument document,String revision,GlyphBankLayout bank) {
var current=new HashMap<String,GlyphBankLayout.Glyph>();bank.glyphs().forEach(g->current.put(g.artifactId(),g));
var bindings=new ArrayList<Binding>();var differences=new ArrayList<Difference>();
for(var binding:document.bindings()) {
var glyph=current.get(binding.artifactId());
Binding updated=glyph==null?binding:new Binding(glyph.artifactId(),glyph.glyphId(),glyph.fingerprint());bindings.add(updated);
if(!updated.equals(binding)||glyph==null){var affected=new ArrayList<String>();
for(int a=0;a<document.animators().size();a++)for(int c=0;c<document.animators().get(a).clips().size();c++){
var frames=document.animators().get(a).clips().get(c).frames();
for(int f=0;f<frames.size();f++)if(frames.get(f).artifactId().equals(binding.artifactId()))affected.add("/animators/"+a+"/clips/"+c+"/frames/"+f);
}
differences.add(new Difference(binding,glyph==null?null:updated,affected));
}
}
var candidate=new AnimationDocument(document.schemaVersion(),document.bankAssetUuid(),bindings,document.animators());
String hash=AnimationRevision.of(revision+"\n"+bank.revision()+"\n"+new AnimationCodec().encode(candidate));
return new Proposal(candidate,differences,hash,bank.revision());
}
}
@@ -0,0 +1,12 @@
package p.animation;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
public final class AnimationRevision {
private AnimationRevision() {}
public static String of(String value) { return of(value.getBytes(StandardCharsets.UTF_8)); }
public static String of(byte[] value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); }
catch (java.security.NoSuchAlgorithmException impossible) { throw new AssertionError(impossible); }
}
}
@@ -0,0 +1,8 @@
package p.animation;
import java.nio.file.Path;
import java.util.Objects;
/** Validated language-neutral build input, owned by one project and registered bank. */
public record AnimationSource(String projectName, Path projectRoot, Path definitionPath,
String documentRevision, AnimationDocument document, GlyphBankLayout bank) {
public AnimationSource { Objects.requireNonNull(projectName); Objects.requireNonNull(projectRoot); Objects.requireNonNull(definitionPath); Objects.requireNonNull(documentRevision); Objects.requireNonNull(document); Objects.requireNonNull(bank); }
}
@@ -0,0 +1,50 @@
package p.animation;
import java.util.*;
import static p.animation.AnimationDocument.*;
/** Explicit-tick editorial playback, qualified against the PBS implementation. */
public final class AnimationTimeline {
public enum State { Stopped, Playing, Paused, Finished }
public record Observation(String clipName, String artifactId, int glyphId, long phase, State state) {}
private final Animator animator;
private final Map<String,Binding> bindings;
private Clip clip;
private long phase;
private State state=State.Stopped;
public AnimationTimeline(AnimationDocument document,String animatorId) {
animator=document.animators().stream().filter(a->a.id().equals(animatorId)).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_animator"));
var values=new HashMap<String,Binding>();document.bindings().forEach(b->values.put(b.artifactId(),b));bindings=Map.copyOf(values);
clip=find(animator.initialClip());
}
private Clip find(String name){return animator.clips().stream().filter(c->c.name().equals(name)).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_clip"));}
public void select(String name){var selected=find(name);clip=selected;phase=0;state=State.Stopped;}
public void play(String name){select(name);state=State.Playing;}
public void pause(){if(state==State.Playing)state=State.Paused;}
public void resume(){if(state==State.Paused)state=State.Playing;}
public void stop(){phase=0;state=State.Stopped;}
public void restart(){phase=0;state=State.Playing;}
public void advance(int ticks){
if(ticks<0)throw new IllegalArgumentException("invalid_ticks");
if(ticks==0||state!=State.Playing)return;
if(phase>Long.MAX_VALUE-ticks)throw new IllegalArgumentException("overflow");
long next=phase+ticks;long total=total(clip);var nextState=state;
if(clip.mode().equals("loop"))next%=total;
else if(next>=total){next=total;nextState=State.Finished;}
phase=next;state=nextState;
}
public Observation observation(){
long end=0;Frame selected=clip.frames().getLast();
for(var frame:clip.frames()){end=Math.addExact(end,frame.durationTicks());if(phase<end){selected=frame;break;}}
var binding=bindings.get(selected.artifactId());if(binding==null)throw new IllegalArgumentException("unbound_frame");
return new Observation(clip.name(),selected.artifactId(),binding.glyphId(),phase,state);
}
public static Observation sample(AnimationDocument doc,String animatorId,String clipName,long elapsedTicks){
if(elapsedTicks<0)throw new IllegalArgumentException("invalid_ticks");
var timeline=new AnimationTimeline(doc,animatorId);timeline.play(clipName);long total=total(timeline.clip);
if(timeline.clip.mode().equals("loop"))timeline.phase=elapsedTicks%total;
else {timeline.phase=Math.min(elapsedTicks,total);if(elapsedTicks>=total)timeline.state=State.Finished;}
return timeline.observation();
}
private static long total(Clip clip){long total=0;for(var frame:clip.frames())total=Math.addExact(total,frame.durationTicks());return total;}
}
@@ -0,0 +1,57 @@
package p.animation;
import java.util.*;
/** The single structural and asset-binding validator used by Studio and compiler. */
public final class AnimationValidator {
public List<AnimationDiagnostic> validate(AnimationDocument doc, GlyphBankLayout layout) {
var errors=new ArrayList<AnimationDiagnostic>();
if(doc.schemaVersion()!=1)add(errors,"schema_version","/schema_version","Unsupported version");
try { if(!doc.bankAssetUuid().matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"))throw new IllegalArgumentException("UUID syntax"); if(!UUID.fromString(doc.bankAssetUuid()).equals(layout.assetUuid()))add(errors,"bank_uuid","/bank_asset_uuid","Containing bank UUID does not match"); }
catch(IllegalArgumentException error){add(errors,"bank_uuid","/bank_asset_uuid","Invalid UUID");}
var current=new HashMap<String,GlyphBankLayout.Glyph>(); var indices=new HashSet<Integer>();
for(var glyph:layout.glyphs()) {
if(glyph.artifactId().isEmpty()||current.putIfAbsent(glyph.artifactId(),glyph)!=null||!indices.add(glyph.glyphId())
||glyph.glyphId()<0||glyph.glyphId()>65535||!glyph.fingerprint().matches("[0-9a-f]{64}"))
add(errors,"bank_layout","/bindings","Current bank layout has missing/duplicate/invalid identities");
}
var bound=new HashMap<String,AnimationDocument.Binding>(); indices.clear();
for(int i=0;i<doc.bindings().size();i++) {
var binding=doc.bindings().get(i);String p="/bindings/"+i;
if(binding.artifactId().isEmpty()||bound.putIfAbsent(binding.artifactId(),binding)!=null)
add(errors,"duplicate_binding",p+"/artifact_id","Artifact binding must be unique and nonempty");
if(binding.glyphId()<0||binding.glyphId()>65535||!indices.add(binding.glyphId()))add(errors,"invalid_glyph",p+"/glyph_id","Glyph ID is out of range or duplicated");
var actual=current.get(binding.artifactId());
if(actual==null)add(errors,"missing_artifact",p,"Selected artifact is absent from the current composition");
else if(actual.glyphId()!=binding.glyphId()||!actual.fingerprint().equals(binding.fingerprint()))add(errors,"binding_drift",p,"Glyph index or fingerprint changed; explicit rebind required");
if(!binding.fingerprint().matches("[0-9a-f]{64}"))add(errors,"invalid_fingerprint",p+"/fingerprint","Expected lowercase SHA-256");
}
var ids=new HashSet<String>();
for(int i=0;i<doc.animators().size();i++) {
var animator=doc.animators().get(i);String p="/animators/"+i;
if(!animator.id().matches("[A-Za-z_][A-Za-z0-9_]*")||!ids.add(animator.id()))add(errors,"animator_id",p+"/id","Animator ID must be a unique PBS identifier");
if(animator.clips().isEmpty())add(errors,"empty_animator",p+"/clips","Animator needs at least one clip");
var names=new HashSet<String>();
for(int j=0;j<animator.clips().size();j++) {
var clip=animator.clips().get(j);String cp=p+"/clips/"+j;
if(clip.name().isEmpty()||!names.add(clip.name()))add(errors,"clip_name",cp+"/name","Clip names must be nonempty and unique, with exact comparison");
if(!Set.of("once","loop").contains(clip.mode()))add(errors,"mode",cp+"/mode","Expected once or loop");
if(clip.frames().isEmpty())add(errors,"empty_clip",cp+"/frames","Clip needs at least one frame");
long total=0;
for(int k=0;k<clip.frames().size();k++) {
var frame=clip.frames().get(k);String fp=cp+"/frames/"+k;
if(!bound.containsKey(frame.artifactId()))add(errors,"unbound_frame",fp+"/artifact_id","Frame must reference a unique binding");
if(frame.durationTicks()<=0)add(errors,"invalid_duration",fp+"/duration_ticks","Duration must be positive");
else if(total>Long.MAX_VALUE-frame.durationTicks())add(errors,"overflow",fp+"/duration_ticks","Clip duration exceeds signed 64-bit range");
else total+=frame.durationTicks();
}
}
if(animator.initialClip().isEmpty()||!names.contains(animator.initialClip()))add(errors,"initial_clip_missing",p+"/initial_clip","Initial clip must exist");
}
return List.copyOf(errors);
}
public void requireValid(AnimationDocument doc,GlyphBankLayout layout) {
var errors=validate(doc,layout);if(!errors.isEmpty())throw new IllegalArgumentException(errors.toString());
}
private static void add(List<AnimationDiagnostic> list,String code,String pointer,String message){list.add(new AnimationDiagnostic(code,pointer,message));}
}
@@ -0,0 +1,18 @@
package p.animation;
import java.nio.file.Path;
import java.util.List;
import java.util.UUID;
import java.util.Objects;
/** Effective Packer composition. Paths locate current images; identity never derives from them. */
public record GlyphBankLayout(UUID assetUuid, String revision, Path assetRoot, List<Glyph> glyphs, byte[] rgbaPalettes) {
public GlyphBankLayout { Objects.requireNonNull(assetUuid); Objects.requireNonNull(revision); glyphs = List.copyOf(glyphs); rgbaPalettes=rgbaPalettes.clone(); }
public GlyphBankLayout(UUID uuid,String revision,Path root,List<Glyph> glyphs){this(uuid,revision,root,glyphs,new byte[0]);}
@Override public byte[] rgbaPalettes(){return rgbaPalettes.clone();}
public record Glyph(String artifactId, int glyphId, String fingerprint, Path imagePath, int width, int height, byte[] indices) {
public Glyph { Objects.requireNonNull(artifactId); Objects.requireNonNull(fingerprint); indices=indices.clone(); }
public Glyph(String id,int glyph,String hash,Path path){this(id,glyph,hash,path,0,0,new byte[0]);}
@Override public byte[] indices(){return indices.clone();}
}
}
@@ -0,0 +1,11 @@
package p.animation;
import java.nio.file.Path;
import java.util.UUID;
/** App-composed port; compiler callers inject a public Packer API adapter. */
@FunctionalInterface
public interface GlyphBankLayoutSource {
GlyphBankLayout resolve(Path projectRoot, UUID assetUuid);
default <T> T withLayout(Path projectRoot, UUID assetUuid, java.util.function.Function<GlyphBankLayout,T> work) {
throw new UnsupportedOperationException("Project-exclusive animation access is not configured");
}
}
@@ -0,0 +1,40 @@
package p.animation;
import org.junit.jupiter.api.Test;
import java.util.*;
import static p.animation.AnimationDocument.*;
import static org.junit.jupiter.api.Assertions.*;
class AnimationContractTest {
static final UUID ID=UUID.fromString("12345678-1234-1234-1234-123456789abc");
static final String HASH="a".repeat(64);
static AnimationDocument document(String mode){return new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH),new Binding("b",11,HASH),new Binding("c",4,HASH)),List.of(new Animator("hero"," idle ",List.of(new Clip(" idle ",mode,List.of(new Frame("a",2),new Frame("b",3),new Frame("c",1)))))));}
static GlyphBankLayout bank(){return new GlyphBankLayout(ID,"bank1",null,List.of(new GlyphBankLayout.Glyph("a",7,HASH,null),new GlyphBankLayout.Glyph("b",11,HASH,null),new GlyphBankLayout.Glyph("c",4,HASH,null)));}
@Test void strictCodecPreservesExactLongAndRejectsAmbiguousJson(){
var codec=new AnimationCodec();var doc=new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH)),List.of(new Animator("hero","idle",List.of(new Clip("idle","once",List.of(new Frame("a",9007199254740993L)))))));
String json=codec.encode(doc);assertEquals(doc,codec.decode(json));
for(var invalid:List.of(json.replace("9007199254740993","9007199254740993.0"),json.replace("9007199254740993","9223372036854775808"),json.replace("\"schema_version\" : 1","\"schema_version\" : 1, \"schema_version\" : 1"),json.replace("\"schema_version\" : 1","\"unknown\" : 1, \"schema_version\" : 1"),json+"{}"))assertThrows(IllegalArgumentException.class,()->codec.decode(invalid),invalid);
}
@Test void identityDriftBlocksAndRebindIsAnExplicitImmutableProposal(){
var doc=document("loop");var validator=new AnimationValidator();assertTrue(validator.validate(doc,bank()).isEmpty());
var changed=new GlyphBankLayout(ID,"bank2",null,List.of(new GlyphBankLayout.Glyph("a",8,"b".repeat(64),null),new GlyphBankLayout.Glyph("b",11,HASH,null),new GlyphBankLayout.Glyph("c",4,HASH,null)));
assertTrue(validator.validate(doc,changed).stream().anyMatch(d->d.code().equals("binding_drift")));
var proposal=new AnimationRebind().prepare(doc,"document1",changed);
assertEquals(7,doc.bindings().getFirst().glyphId());assertEquals(8,proposal.document().bindings().getFirst().glyphId());
assertTrue(validator.validate(proposal.document(),changed).isEmpty());assertFalse(proposal.differences().getFirst().affectedFrames().isEmpty());
assertNotEquals(proposal.proposalHash(),new AnimationRebind().prepare(doc,"document2",changed).proposalHash());
}
@Test void timelineMatchesTheNativeBoundaryOracleAndPreservesFailures(){
for(var mode:List.of("once","loop")){
var doc=document(mode);long[] ticks={0,1,2,4,5,6,601};int[] glyphs=mode.equals("loop")?new int[]{7,7,11,11,4,7,7}:new int[]{7,7,11,11,4,4,4};
for(int i=0;i<ticks.length;i++)assertEquals(glyphs[i],AnimationTimeline.sample(doc,"hero"," idle ",ticks[i]).glyphId());
var timeline=new AnimationTimeline(doc,"hero");timeline.play(" idle ");timeline.advance(2);timeline.pause();var paused=timeline.observation();timeline.advance(100);assertEquals(paused,timeline.observation());
assertThrows(IllegalArgumentException.class,()->timeline.advance(-1));assertEquals(paused,timeline.observation());
assertThrows(IllegalArgumentException.class,()->timeline.select("idle"));assertEquals(paused,timeline.observation());
timeline.resume();timeline.stop();assertEquals(7,timeline.observation().glyphId());timeline.restart();assertEquals(AnimationTimeline.State.Playing,timeline.observation().state());
}
}
@Test void overflowAndInvalidReferencesAreBlockingDiagnostics(){
var doc=new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH)),List.of(new Animator("hero","idle",List.of(new Clip("idle","once",List.of(new Frame("a",Long.MAX_VALUE),new Frame("missing",1)))))));
var errors=new AnimationValidator().validate(doc,bank());assertTrue(errors.stream().anyMatch(d->d.code().equals("overflow")));assertTrue(errors.stream().anyMatch(d->d.code().equals("unbound_frame")));
}
}
+14 -1
View File
@@ -63,7 +63,7 @@ javafx {
}
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
tasks.named<Test>("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
tasks.named<Test>("test") { exclude("**/AnimationDesktopTest.class", "**/AnimationInstalledRuntimeTest.class", "**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") }
tasks.register<Test>("devDesktopTest") {
group = "verification"
description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)."
@@ -74,6 +74,16 @@ tasks.register<Test>("devDesktopTest") {
systemProperty("java.awt.headless", "false")
}
tasks.register<Test>("animationDesktopTest") {
group = "verification"
description = "Authors and repairs an animation through the actual JavaFX editor (requires a display)."
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/AnimationDesktopTest.class")
systemProperty("java.awt.headless", "false")
}
tasks.register<Test>("installedKnowledgeTest") {
group = "verification"
description = "Reads installed references and compiles their example in an isolated JVM outside the checkout."
@@ -96,6 +106,9 @@ tasks.register<Test>("headlessProcessTest") {
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/HeadlessInstalledRuntimeTest.class")
include("**/AnimationInstalledRuntimeTest.class")
systemProperty("pbs.registryConformanceDirectory",
project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath)
include("**/HeadlessTaskIntegrationTest.class")
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
}
@@ -171,8 +171,28 @@ public class StudioApplicationConfiguration {
}
@Bean
CompilerBuildGateway compilerBuildGateway() {
return new CompilerBuildGatewayAdapter();
p.animation.GlyphBankLayoutSource glyphBankLayoutSource(PackerWorkspaceService packer,ObjectMapper mapper) {
return new p.studio.app.assets.PackerGlyphBankLayouts(packer,mapper);
}
@Bean
p.studio.core.assets.animation.DefaultAnimationService animationEngine(p.animation.GlyphBankLayoutSource layouts,AssetCatalog catalog) {
return new p.studio.core.assets.animation.DefaultAnimationService(layouts,catalog);
}
@Bean
p.studio.api.assets.animation.AnimationService animationService(p.studio.core.assets.animation.DefaultAnimationService engine,p.studio.api.automation.ProjectAccess access) {
return new p.studio.core.assets.animation.ManualAnimationService(engine,access);
}
@Bean
p.studio.api.assets.animation.AnimationTasks animationTasks(p.studio.core.project.ProjectAccessRegistry projects,ProjectCatalog catalog,p.studio.core.assets.animation.DefaultAnimationService engine) {
return new p.studio.core.session.TaskAnimationService(projects,catalog,engine);
}
@Bean
CompilerBuildGateway compilerBuildGateway(p.animation.GlyphBankLayoutSource layouts) {
return new CompilerBuildGatewayAdapter(layouts);
}
@Bean
@@ -213,8 +233,8 @@ public class StudioApplicationConfiguration {
}
@Bean
LspServerLifecycle lspServerLifecycle() {
return new LspServerLifecycleImpl();
LspServerLifecycle lspServerLifecycle(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events) {
return new LspServerLifecycleImpl(layouts,(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)));
}
@Bean
@@ -284,13 +304,15 @@ public class StudioApplicationConfiguration {
TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) {
return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) {
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
factory.setAnimationService(animationService);
return factory;
}
@Bean
@@ -300,8 +322,8 @@ public class StudioApplicationConfiguration {
@Bean
p.studio.api.automation.ProjectKnowledge projectKnowledge(
p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper) {
return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper);
p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper, p.animation.GlyphBankLayoutSource layouts) {
return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper, layouts);
}
@Bean
@@ -331,10 +353,11 @@ public class StudioApplicationConfiguration {
@Bean
p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper,
p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language,
p.studio.api.automation.TaskTools tasks, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
p.studio.api.automation.TaskTools tasks, p.studio.api.assets.animation.AnimationTasks animations, java.util.Optional<p.studio.core.runtime.HeadlessGateway> headless) {
var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper));
handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper));
handlers.putAll(p.studio.app.mcp.McpTaskTools.handlers(tasks, mapper, headless.isPresent()));
handlers.putAll(p.studio.app.mcp.McpAnimationTools.handlers(animations, mapper));
return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers);
}
@@ -58,6 +58,9 @@ public final class StudioUiFactory {
private final ProjectActivityHistoryStore activityHistoryStore;
private final p.studio.api.automation.AgentConnectionGuide connectionGuide;
private p.studio.api.assets.animation.AnimationService animationService;
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){this.animationService=service;}
public StudioUiFactory(
ProjectCatalog projectCatalog,
KnownProjects knownProjects,
@@ -113,11 +116,13 @@ public final class StudioUiFactory {
}
public StudioWindowCoordinator create(Stage stage) {
return new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
var coordinator = new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, executor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
if(animationService!=null)coordinator.setAnimationService(animationService);
return coordinator;
}
}
@@ -0,0 +1,22 @@
package p.studio.app.assets;
import p.animation.*;
import p.packer.PackerWorkspaceService;
import p.packer.messages.*;
import java.nio.file.Path;
import java.util.UUID;
import java.util.function.Function;
import com.fasterxml.jackson.databind.ObjectMapper;
/** Only application composition knows the public Packer adapter. */
public final class PackerGlyphBankLayouts implements GlyphBankLayoutSource {
private final PackerWorkspaceService packer;private final ObjectMapper mapper;
public PackerGlyphBankLayouts(PackerWorkspaceService packer,ObjectMapper mapper){this.packer=packer;this.mapper=mapper;}
private GetGlyphBankLayoutRequest request(Path root,UUID uuid){
try{return new GetGlyphBankLayoutRequest(new PackerProjectContext(mapper.readTree(root.resolve("prometeu.json").toFile()).path("name").asText(),root),uuid);}
catch(java.io.IOException e){throw new IllegalArgumentException("Cannot read project identity",e);}
}
private static GlyphBankLayout map(p.packer.dtos.PackerGlyphBankLayoutDTO bank){
return new GlyphBankLayout(bank.assetUuid(),bank.revision(),bank.assetRoot(),bank.glyphs().stream().map(g->new GlyphBankLayout.Glyph(g.artifactId(),g.glyphId(),g.fingerprint(),g.imagePath(),g.width(),g.height(),g.indices())).toList(),bank.rgbaPalettes());
}
@Override public GlyphBankLayout resolve(Path root,UUID uuid){return map(packer.getGlyphBankLayout(request(root,uuid)));}
@Override public <T> T withLayout(Path root,UUID uuid,Function<GlyphBankLayout,T> work){return packer.withGlyphBankLayout(request(root,uuid),bank->work.apply(map(bank)));}
}
@@ -11,11 +11,15 @@ import java.util.LinkedHashSet;
import java.util.function.Consumer;
public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
private final p.animation.GlyphBankLayoutSource layouts;
public CompilerBuildGatewayAdapter(){this(null);}
public CompilerBuildGatewayAdapter(p.animation.GlyphBankLayoutSource layouts){this.layouts=layouts;}
@Override
public CompilerBuildOutput compile(ProjectReference project, Consumer<String> logSink) {
final var config = new BuilderPipelineConfig(false, project.rootPath().toString());
var context=BuilderPipelineContext.fromConfig(config);context.glyphBankLayoutSource=layouts;
final var result = BuilderPipelineService.INSTANCE.build(
BuilderPipelineContext.fromConfig(config),
context,
LogAggregator.with(logSink));
final var capabilities = new LinkedHashSet<>(
result.compileResult().analysisSnapshot().irBackend()
@@ -26,9 +26,13 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge {
private final ProjectAccessRegistry openProjects;
private final ProjectCatalog projects;
private final ObjectMapper mapper;
private final CompilerLanguageServiceBridge languageBridge = new CompilerLanguageServiceBridge();
private final CompilerLanguageServiceBridge languageBridge;
public CompilerProjectKnowledge(ProjectAccessRegistry openProjects, ProjectCatalog projects, ObjectMapper mapper) {
this(openProjects,projects,mapper,null);
}
public CompilerProjectKnowledge(ProjectAccessRegistry openProjects,ProjectCatalog projects,ObjectMapper mapper,p.animation.GlyphBankLayoutSource layouts) {
this.languageBridge=new CompilerLanguageServiceBridge(layouts);
this.openProjects = Objects.requireNonNull(openProjects);
this.projects = Objects.requireNonNull(projects);
this.mapper = Objects.requireNonNull(mapper);
@@ -18,6 +18,7 @@ final class ContractSchema {
if (schema.has("const") && !schema.get("const").equals(value)) fail();
if (schema.has("type")) {
boolean valid = switch (schema.get("type").asText()) {
case "null" -> value.isNull();
case "object" -> value.isObject();
case "array" -> value.isArray();
case "string" -> value.isTextual();
@@ -27,6 +28,8 @@ final class ContractSchema {
};
if (!valid) fail();
}
if(schema.has("pattern")&&!value.textValue().matches(schema.get("pattern").textValue()))fail();
if(schema.has("minItems")&&value.size()<schema.get("minItems").intValue())fail();
if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail();
if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail();
if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail();
@@ -0,0 +1,39 @@
package p.studio.app.mcp;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.animation.AnimationCodec;
import p.studio.api.assets.animation.*;
import p.studio.api.automation.*;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
/** Wire adaptation only; UI and AI call the same shared application service. */
public final class McpAnimationTools {
private McpAnimationTools(){}
public static Map<String,Function<JsonNode,McpToolResult>> handlers(AnimationTasks tasks,ObjectMapper mapper){
return Map.of("studio_animation_query",args->call(tasks,mapper,args),"studio_animation_update",args->call(tasks,mapper,args));
}
private static McpToolResult call(AnimationTasks tasks,ObjectMapper mapper,JsonNode args){
try {
var response=tasks.execute(Path.of(args.required("projectRoot").textValue()),args.required("taskId").textValue(),project->new AnimationService.Request(
AnimationService.Operation.valueOf(args.required("operation").textValue().toUpperCase(Locale.ROOT)),project,
args.has("assetUuid")?UUID.fromString(args.get("assetUuid").textValue()):null,
text(args,"animatorId"),text(args,"clipName"),args.has("elapsedTicks")?args.get("elapsedTicks").longValue():null,
args.has("paletteId")?args.get("paletteId").intValue():null,text(args,"expectedRevision"),
args.has("document")?new AnimationCodec().decode(args.get("document").toString()):null,text(args,"proposalHash"),text(args,"expectedBankRevision")));
ObjectNode value=mapper.valueToTree(response);
canonicalView(mapper,value.get("view"));if(value.path("definitions").isArray())for(var view:value.get("definitions"))canonicalView(mapper,view);
if(response.proposal()!=null)((ObjectNode)value.get("proposal")).set("document",mapper.readTree(new AnimationCodec().encode(response.proposal().document())));
if(response.preview()!=null)((ObjectNode)value.get("preview")).remove("image");
return McpToolResult.successWithCapture(mapper,value,response.preview()==null?null:response.preview().image(),false);
}catch(ControlDeniedException|AutomationException authority){throw authority;}
catch(IllegalArgumentException invalid){return McpToolResult.failure(mapper,new AutomationFailure(AutomationFailure.Code.ANIMATION_INVALID,invalid.getMessage()));}
catch(IllegalStateException conflict){return McpToolResult.failure(mapper,new AutomationFailure(conflict.getMessage()!=null&&conflict.getMessage().contains("conflict")?AutomationFailure.Code.ANIMATION_CONFLICT:AutomationFailure.Code.INFRASTRUCTURE_FAILURE,conflict.getMessage()));}
catch(java.io.IOException failure){throw new IllegalStateException("Cannot encode animation response",failure);}
}
private static String text(JsonNode node,String field){return node.hasNonNull(field)?node.get(field).textValue():null;}
private static void canonicalView(ObjectMapper mapper,JsonNode view)throws java.io.IOException{
if(view!=null&&view.isObject()&&view.hasNonNull("document"))((ObjectNode)view).set("document",mapper.readTree(view.required("json").asText()));
}
}
@@ -2378,6 +2378,945 @@
"exampleValue": {
"sessionId": "runtime-example"
}
},
{
"name": "studio_animation_query",
"authority": "task",
"description": "List, get, validate or preview canonical bank animation definitions through the same services as the Assets editor. Preview uses explicit ticks and transient palette input; reads never rebind.",
"inputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "list"
},
"assetUuid": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "get"
},
"assetUuid": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "validate"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "preview"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"animatorId": {
"type": "string",
"minLength": 1
},
"clipName": {
"type": "string",
"minLength": 1
},
"elapsedTicks": {
"type": "integer",
"minimum": 0
},
"paletteId": {
"type": "integer",
"minimum": 0,
"maximum": 63
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"animatorId",
"clipName",
"elapsedTicks",
"paletteId"
],
"additionalProperties": false
}
],
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
]
},
"outputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"status": {
"const": "ok"
},
"value": {
"type": "object"
}
},
"required": [
"status",
"value"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"status": {
"const": "error"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string"
},
"runtimeError": {
"type": "object",
"additionalProperties": true
}
},
"required": [
"code",
"message"
],
"additionalProperties": false
}
},
"required": [
"status",
"error"
],
"additionalProperties": false
}
]
},
"annotations": {
"readOnlyHint": true,
"openWorldHint": false
},
"exampleArguments": {
"projectRoot": "/projects/game",
"taskId": "task-example",
"operation": "get",
"assetUuid": "12345678-1234-1234-1234-123456789abc"
},
"exampleValue": {
"definitions": [],
"diagnostics": []
}
},
{
"name": "studio_animation_update",
"authority": "task",
"description": "Save/delete animator definitions or prepare/apply an explicit binding-only rebind. Expected revisions prevent overwrites; only create accepts explicitly null expectedRevision. No arbitrary file paths or extra approval flow.",
"inputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "save"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"oneOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"document"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "delete"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
},
"animatorId": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"animatorId"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "prepare_rebind"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"const": "apply_rebind"
},
"assetUuid": {
"type": "string",
"minLength": 1
},
"expectedRevision": {
"type": "string",
"minLength": 1
},
"document": {
"type": "object",
"properties": {
"schema_version": {
"type": "integer"
},
"bank_asset_uuid": {
"type": "string",
"minLength": 1
},
"bindings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"glyph_id": {
"type": "integer"
},
"fingerprint": {
"type": "string",
"minLength": 1
}
},
"required": [
"artifact_id",
"glyph_id",
"fingerprint"
],
"additionalProperties": false
}
},
"animators": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "[A-Za-z_][A-Za-z0-9_]*"
},
"initial_clip": {
"type": "string",
"minLength": 1
},
"clips": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"mode": {
"oneOf": [
{
"const": "once"
},
{
"const": "loop"
}
]
},
"frames": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artifact_id": {
"type": "string",
"minLength": 1
},
"duration_ticks": {
"type": "integer"
}
},
"required": [
"artifact_id",
"duration_ticks"
],
"additionalProperties": false
}
}
},
"required": [
"name",
"mode",
"frames"
],
"additionalProperties": false
}
}
},
"required": [
"id",
"initial_clip",
"clips"
],
"additionalProperties": false
}
}
},
"required": [
"schema_version",
"bank_asset_uuid",
"bindings",
"animators"
],
"additionalProperties": false
},
"proposalHash": {
"type": "string",
"minLength": 1
},
"expectedBankRevision": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation",
"assetUuid",
"expectedRevision",
"document",
"proposalHash",
"expectedBankRevision"
],
"additionalProperties": false
}
],
"properties": {
"projectRoot": {
"type": "string",
"minLength": 1
},
"taskId": {
"type": "string",
"minLength": 1
},
"operation": {
"type": "string",
"minLength": 1
}
},
"required": [
"projectRoot",
"taskId",
"operation"
]
},
"outputSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"status": {
"const": "ok"
},
"value": {
"type": "object"
}
},
"required": [
"status",
"value"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"status": {
"const": "error"
},
"error": {
"type": "object",
"properties": {
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string"
},
"runtimeError": {
"type": "object",
"additionalProperties": true
}
},
"required": [
"code",
"message"
],
"additionalProperties": false
}
},
"required": [
"status",
"error"
],
"additionalProperties": false
}
]
},
"annotations": {
"readOnlyHint": false,
"openWorldHint": false
},
"exampleArguments": {
"projectRoot": "/projects/game",
"taskId": "task-example",
"operation": "save",
"assetUuid": "12345678-1234-1234-1234-123456789abc",
"expectedRevision": null,
"document": {
"schema_version": 1,
"bank_asset_uuid": "12345678-1234-1234-1234-123456789abc",
"bindings": [],
"animators": []
}
},
"exampleValue": {
"definitions": [],
"diagnostics": []
}
}
]
}
@@ -30,7 +30,7 @@ class StudioApplicationConfigurationTest {
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(22, tools.size());
org.junit.jupiter.api.Assertions.assertEquals(24, tools.size());
assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway);
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
@@ -0,0 +1,54 @@
package p.studio.app.animation;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl;
import p.animation.*;
import java.nio.file.*;
import java.util.concurrent.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
/** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */
class AnimationDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit()throws Exception{
var ready=new CompletableFuture<Void>();
try{Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});}
catch(IllegalStateException running){ready.complete(null);}
ready.get(10,TimeUnit.SECONDS);
}
@AfterAll static void stopToolkit(){Platform.exit();}
static <T>T fx(Supplier<T> work)throws Exception{var result=new CompletableFuture<T>();Platform.runLater(()->{try{result.complete(work.get());}catch(Throwable f){result.completeExceptionally(f);}});return result.get(10,TimeUnit.SECONDS);}
static void await(BooleanSupplier test)throws Exception{long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);while(!test.getAsBoolean()){if(System.nanoTime()>end)fail("Animation editor did not finish");Thread.sleep(10);}}
static Button button(AnimationEditorControl editor,String text){return editor.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals(text)).map(n->(Button)n).findFirst().orElseThrow();}
@Test void authorsPreviewsSavesRepairsAndCloses()throws Exception{
var fixture=new AnimationIntegrationTest();fixture.root=root;fixture.setup();
var pool=Executors.newCachedThreadPool();var stage=new Stage[1];var editor=new AnimationEditorControl[1];
try{
fx(()->{editor[0]=new AnimationEditorControl(fixture.project,fixture.manual,pool);var scroll=new ScrollPane(editor[0]);scroll.setFitToWidth(true);stage[0]=new Stage();stage[0].setTitle("Animation authoring acceptance");stage[0].setScene(new Scene(scroll,1040,940));stage[0].show();editor[0].bind(fixture.uuid);return null;});
await(()->{try{return fx(()->((Label)editor[0].lookup("#animation-status")).getText().equals("New definition"));}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{((TextField)editor[0].lookup("#animation-id")).setText("hero");button(editor[0],"New animator").fire();((ComboBox<?>)editor[0].lookup("#animation-glyph")).getSelectionModel().selectFirst();((TextField)editor[0].lookup("#animation-duration")).setText("2");button(editor[0],"Add frame").fire();return null;});
assertTrue(editor[0].hasUnsavedChanges().toCompletableFuture().get());
editor[0].saveAll().toCompletableFuture().get(10,TimeUnit.SECONDS);
assertFalse(editor[0].hasUnsavedChanges().toCompletableFuture().get());
assertEquals(2,fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().document().animators().getFirst().clips().getFirst().frames().getFirst().durationTicks());
fx(()->{button(editor[0],"Preview").fire();return null;});
await(()->{try{return fx(()->((ImageView)editor[0].lookup("#animation-image")).getImage()!=null);}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{var snapshot=stage[0].getScene().snapshot(null);var image=new java.awt.image.BufferedImage((int)snapshot.getWidth(),(int)snapshot.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);for(int y=0;y<image.getHeight();y++)for(int x=0;x<image.getWidth();x++)image.setRGB(x,y,snapshot.getPixelReader().getArgb(x,y));try{javax.imageio.ImageIO.write(image,"png",Path.of("/tmp/dec84-animation-desktop.png").toFile());}catch(Exception e){throw new RuntimeException(e);}return null;});
var asset=(com.fasterxml.jackson.databind.node.ObjectNode)fixture.mapper.readTree(fixture.bankRoot.resolve("asset.json").toFile());((com.fasterxml.jackson.databind.node.ObjectNode)asset.path("artifacts").get(0)).put("index",1);((com.fasterxml.jackson.databind.node.ObjectNode)asset.path("artifacts").get(1)).put("index",0);fixture.mapper.writeValue(fixture.bankRoot.resolve("asset.json").toFile(),asset);
editor[0].refreshFromDisk().toCompletableFuture().get(10,TimeUnit.SECONDS);
fx(()->{button(editor[0],"Prepare rebind").fire();return null;});
await(()->{try{return fx(()->!button(editor[0],"Apply rebind").isDisabled());}catch(Exception e){throw new RuntimeException(e);}});
fx(()->{button(editor[0],"Apply rebind").fire();return null;});
await(()->fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().diagnostics().isEmpty());
fx(()->{editor[0].openOrigin("/animators/0/clips/0/frames/0");editor[0].close();stage[0].close();return null;});
assertFalse(pool.isShutdown());
}finally{fx(()->{if(editor[0]!=null)editor[0].close();if(stage[0]!=null)stage[0].close();return null;});pool.shutdownNow();fixture.close();}
}
}
@@ -0,0 +1,55 @@
package p.studio.app.animation;
import java.nio.file.*;
import p.animation.*;
import p.studio.api.assets.animation.AnimationService;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.messages.BuilderPipelineConfig;
import p.studio.compiler.workspaces.BuilderPipelineService;
import p.studio.compiler.backend.bytecode.BytecodeEmitter;
import p.studio.utilities.logs.LogAggregator;
/** Runs only with installed product JARs, outside the checkout. No runtime checkout is read. */
public final class AnimationInstalledProbe {
public static void verify(Path root,Path corpus)throws Exception{
var f=new AnimationProjectFixture();f.root=root;f.setup();
try{
f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;pub fn animationProbe()->int;");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+"""
import { AnimationError } from @core:animation;
declare global trace:int=0;
fn run()->result<AnimationError> {
let value=create_hero(3)!;let other=create_hero(3)!;
value.play("idle")!;value.advance(2)!;
if value.sprite().glyph_id!=1 || other.sprite().glyph_id!=0 {let fail=1/0;}
trace=42;return ok(());
}
[Frame]fn frame()->void {run();}
fn animationProbe()->int {return trace;}
""");
var context=BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=f.layouts;
var result=BuilderPipelineService.INSTANCE.compile(context,LogAggregator.stdout());
if(result.diagnostics().stream().anyMatch(d->d.isError()))throw new AssertionError(result.diagnostics());
Files.createDirectories(corpus);
for(boolean optimized:new boolean[]{false,true}){
var program=optimized?context.optimizedIrvm:context.irvm;
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
String prefix="pbs-animation-installed"+(optimized?"-optimized":"");Files.write(corpus.resolve(prefix+".pbx"),module.serialize());
for(int i=0;i<program.module().functions().size();i++)if(program.module().functions().get(i).name().contains("animationProbe"))Files.writeString(corpus.resolve(prefix+".probe"),Integer.toString(i));
}
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(f.layouts);
var lsp=new p.studio.lsp.messages.LspProjectContext("app","pbs",root);
for(var id:context.fileTable.identifiers()){
var path=context.fileTable.get(id).getCanonPath();if(path.startsWith(Path.of("/virtual/generated/animations"))&&path.endsWith("main.pbs")){
var source=bridge.currentSource(lsp,path).orElseThrow();
if(!source.readOnly()||source.origins().isEmpty())throw new AssertionError("Installed generated origins");
}
}
var schema=AnimationInstalledProbe.class.getClassLoader().getResource("mcp/studio-tools-v1.json");
if(schema==null||!schema.getProtocol().equals("jar"))throw new AssertionError("Installed MCP schema missing");
try(var input=schema.openStream()){String text=new String(input.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);for(var name:new String[]{"studio_animation_query","studio_animation_update"})if(!text.contains(name))throw new AssertionError(name);}
System.out.println("Installed generated animation verified: shared save, factories, read-only origins, MCP schemas, ordinary/optimized corpus");
}finally{f.close();}
}
}
@@ -0,0 +1,96 @@
package p.studio.app.animation;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.animation.*;
import p.studio.api.assets.animation.AnimationService;
import p.studio.api.project.*;
import p.studio.api.automation.*;
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
import p.studio.app.runtime.HeadlessProcessGateway;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.core.shipper.StudioShipperService;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Production packaged runtime: canonical authoring -> generated PBS -> Composer -> pixels. */
class AnimationInstalledRuntimeTest {
@TempDir Path root;
@Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{
var f=new AnimationProjectFixture();f.root=root;f.setup();
var workers=Executors.newSingleThreadExecutor();
try{
f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document()));
var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(f.bankRoot.resolve("asset.json").toFile());
((com.fasterxml.jackson.databind.node.ObjectNode)manifest.path("preload")).put("enabled",true);
((com.fasterxml.jackson.databind.node.ArrayNode)manifest.path("output").path("pipeline").path("palettes"))
.addObject().put("index",1).putObject("palette").putArray("rgba8888").add(0x0000ffff).add(0xff0000ff).add(0x00ff00ff);
f.mapper.writeValue(f.bankRoot.resolve("asset.json").toFile(),manifest);
Path scene=Files.createDirectories(root.resolve("assets/scene"));
var sc=f.mapper.createObjectNode().put("schema_version",1).put("asset_uuid","22345678-1234-1234-1234-123456789abc").put("name","scene").put("type","scene_bank");
sc.putObject("preload").put("enabled",true);sc.putObject("output").put("format","SCENE/tilemap_v1").put("codec","NONE");f.mapper.writeValue(scene.resolve("asset.json").toFile(),sc);
var request=f.mapper.createObjectNode().put("schema_version",1).put("format","SCENE/tilemap_v1").put("version",1);var layers=request.putArray("layers");
for(int i=0;i<4;i++){var layer=layers.addObject().put("active",true).put("glyph_asset_id",1).put("tile_size",16).put("parallax_factor_x",1.0).put("parallax_factor_y",1.0).put("width",1).put("height",1);layer.putArray("tiles").addObject().put("active",false).put("glyph_id",0).put("palette_id",0).put("flip_x",false).put("flip_y",false);}
f.mapper.writeValue(scene.resolve("scene-bank.pack-request.json").toFile(),request);
var registry=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((com.fasterxml.jackson.databind.node.ArrayNode)registry.path("assets")).addObject().put("asset_id",2).put("asset_uuid",sc.path("asset_uuid").asText()).put("root","scene").put("included_in_build",true);registry.put("next_asset_id",3);f.mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+"""
import { AnimationError, PlaybackMode, animator_builder } from @core:animation;
import { Composer } from @sdk:composer;
declare global elapsed:int=0;
fn render()->result<AnimationError> {
let a=create_hero(0)!;a.play("idle")!;a.advance(elapsed)!;
let b=animator_builder(0,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!;
b.add_frame(0,2)!;b.add_frame(1,3)!;b.add_frame(2,1)!;b.end_clip()!;
let other=b.build()!;other.play("idle")!;other.advance(elapsed)!;
if other.sprite().glyph_id!=a.sprite().glyph_id {let fail=1/0;}
if Composer.bind_scene(0)!=0 {let fail=1/0;}
let image=a.sprite();let direct=other.sprite();
if Composer.emit_sprite(image.glyph_id,elapsed%2,32,32,0,image.bank_id,false,false,0)!=0 {let fail=1/0;}
if Composer.emit_sprite(direct.glyph_id,elapsed%2,64,32,0,direct.bank_id,false,false,0)!=0 {let fail=1/0;}
elapsed=elapsed+1;return ok(());
}
[Frame]fn frame()->void {render();}
""");
byte[] definition=Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME));
Path corpus=Path.of(System.getProperty("pbs.registryConformanceDirectory"));Files.createDirectories(corpus);
for(boolean optimized:new boolean[]{false,true}){
p.studio.core.shipper.CompilerBuildGateway compiler=(project,sink)->{
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,project.rootPath().toString()));context.glyphBankLayoutSource=f.layouts;
p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.build(context,p.studio.utilities.logs.LogAggregator.with(sink));
if(!optimized)try{Files.write(context.bytecodeArtifactPath,new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(context.irvm.coherentEmissionPlan()).serialize());}catch(java.io.IOException error){throw new java.io.UncheckedIOException(error);}
return new p.studio.core.shipper.CompilerBuildGateway.CompilerBuildOutput(context.bytecodeArtifactPath,context.irBackend.getReservedMetadata().requiredCapabilities().asList());
};
var build=new StudioShipperService(compiler,f.packer.workspaceService(),f.mapper,new ExecutorOperationExecutor(workers)).prepare(f.project,ignored->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);
assertTrue(build.success(),build.diagnostics().toString());
String prefix="pbs-animation-composer"+(optimized?"-optimized":"");
Files.copy(root.resolve("build/program.pbx"),corpus.resolve(prefix+".pbx"),StandardCopyOption.REPLACE_EXISTING);
Files.copy(root.resolve("build/assets.pa"),corpus.resolve(prefix+".assets.pa"),StandardCopyOption.REPLACE_EXISTING);
Files.copy(build.manifestPath(),corpus.resolve(prefix+".manifest.json"),StandardCopyOption.REPLACE_EXISTING);
String install=System.getProperty("studio.test.runtimeInstall");assertNotNull(install);
var setup=new ProjectLocalStudioSetup(install,null);
var session=new HeadlessProcessGateway(f.mapper,ignored->setup).boot(f.project,"animation-"+optimized,build);
var oracle=f.mapper.createArrayNode();
try{
for(int tick=0;tick<8;tick++){
var outcome=session.advance(1,ignored->{});assertEquals(AutomationOutcome.Kind.SUCCEEDED,outcome.kind(),outcome.toString());
assertNull(session.call(TaskTools.HeadlessAction.FAULT,Map.of()).values().get("fault"));
var frame=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png()));
var preview=f.manual.execute(new AnimationService.Request(AnimationService.Operation.PREVIEW,f.project,f.uuid,"hero","idle",(long)tick,tick%2,null,null,null,null)).preview();
var expected=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(preview.image().png()));
var sample=oracle.addObject().put("tick",tick).put("glyph",preview.observation().glyphId()).put("palette",tick%2);
var pixels=sample.putArray("rgba");
for(int y=0;y<16;y++)for(int dx=0;dx<16;dx++){
int pixel=expected.getRGB(dx,y);pixels.add(Integer.toUnsignedLong((pixel<<8)|(pixel>>>24)));
for(int x:new int[]{32,64})assertEquals(pixel,frame.getRGB(x+dx,32+y),"tick "+tick+" at "+x+" optimized="+optimized);
}
}
}finally{session.shutdown().toCompletableFuture().get(10,TimeUnit.SECONDS);}
f.mapper.writeValue(corpus.resolve(prefix+".oracle.json").toFile(),oracle);
assertArrayEquals(definition,Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME)));
}
}finally{workers.shutdownNow();f.close();}
}
}
@@ -0,0 +1,197 @@
package p.studio.app.animation;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import p.animation.*;
import p.packer.Packer;
import p.packer.messages.*;
import p.studio.api.assets.animation.*;
import p.studio.core.assets.animation.*;
import p.studio.app.assets.PackerGlyphBankLayouts;
import p.studio.app.mcp.*;
import p.studio.core.assets.PackerAssetCatalog;
import p.studio.core.project.*;
import p.studio.core.session.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.api.automation.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import static org.junit.jupiter.api.Assertions.*;
import static p.animation.AnimationDocument.*;
class AnimationIntegrationTest {
@TempDir Path root;
final ObjectMapper mapper=new ObjectMapper();
final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc");
Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual;
p.studio.api.project.ProjectReference project;Path bankRoot;
@BeforeEach void setup()throws Exception{
root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank");
manifest.putObject("preload").put("enabled",false);
var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16");
output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff);
var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff};
for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));}
mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper);
engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{});
project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root);
}
@AfterEach void close(){packer.close();}
AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));}
AnimationService.Request request(AnimationService.Operation op,String revision,AnimationDocument doc,String hash,String bankRevision){return new AnimationService.Request(op,project,uuid,"hero","idle",2L,0,revision,doc,hash,bankRevision);}
@Test void savedDefinitionBuildsARealGeneratedFactoryAndKeepsBinaryAssetsUnchanged()throws Exception{
var context=new PackerProjectContext("app",root);var before=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,before.status(),before.toString());byte[] binary=Files.readAllBytes(root.resolve("build/assets.pa"));
var saved=manual.execute(AnimationService.Request.save(project,uuid,null,document())).view();assertTrue(saved.diagnostics().isEmpty());
var after=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,after.status());assertArrayEquals(binary,Files.readAllBytes(root.resolve("build/assets.pa")));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String module="b_"+uuid.toString().replace("-","");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\nimport { AnimationError } from @core:animation;\n"+"""
fn verify() -> result<AnimationError> { let a=create_hero(3)!;a.play("idle")!;a.advance(2)!;
if a.sprite().glyph_id!=1 { let fail=1/0; }return ok(()); }
[Frame] fn frame() -> void { verify(); }
""");
var build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts;
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(result.bytecodeBytes().length>0);
var source=new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().getFirst();
Path generatedPath=null;String generatedText=null;
for(var id:build.fileTable.identifiers()){var handle=build.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs")){generatedPath=handle.getCanonPath();generatedText=handle.readUtf8().orElseThrow();}}
assertNotNull(generatedPath);assertFalse(generatedText.contains(root.toString()));
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts);
var generated=bridge.currentSource(new p.studio.lsp.messages.LspProjectContext("app","pbs",root),generatedPath).orElseThrow();
assertEquals("generated",generated.origin());assertTrue(generated.readOnly());assertFalse(generated.origins().isEmpty());assertEquals("/animators/0/id",generated.origins().getFirst().jsonPointer());
assertThrows(IllegalStateException.class,()->new p.studio.compiler.workspaces.AssetSurfaceContextLoader().load(root));
Files.createDirectories(root.resolve("src/generated/animations/"+module));Files.writeString(root.resolve("src/generated/animations/"+module+"/mod.barrel"),"pub fn collision() -> void;");Files.writeString(root.resolve("src/generated/animations/"+module+"/main.pbs"),"fn collision() -> void {}");
build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts;
var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_LINK_GENERATED_COLLISION")),failed.diagnostics().toString());
}
@Test void generatedOriginsRejectStaleRevisionsAndReconnect() throws Exception {
manual.execute(AnimationService.Request.save(project,uuid,null,document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
String module="b_"+uuid.toString().replace("-","");
Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\n[Frame] fn frame()->void { create_hero(1); }");
var calls=new ArrayList<String>();
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts,(r,id,p)->calls.add(id+":"+p));
var context=new p.studio.lsp.messages.LspProjectContext("app","pbs",root);
try(var registry=new p.studio.lsp.services.compiler.ExternalSourceRegistry()){
String consumer=registry.connect(null,false);
String text=Files.readString(root.resolve("src/main.pbs"));
var navigation=bridge.navigation(context,root.resolve("src/main.pbs").toUri().toString(),text,1,29,registry,consumer);
assertEquals(1,navigation.locations().size());String uri=navigation.locations().getFirst().uri();
var content=registry.read(consumer,uri);var origin=content.descriptor().origins().getFirst();
bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer);
assertEquals(List.of(uuid+":/animators/0/id"),calls);
registry.disconnect(consumer);registry.connect(consumer,false);
bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer);
var current=manual.execute(AnimationService.Request.get(project,uuid)).view();
var next=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of());
manual.execute(AnimationService.Request.save(project,uuid,current.revision(),next));
assertThrows(RuntimeException.class,()->bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer));
assertEquals(2,calls.size());
}
}
@Test void conflictsDriftAndExplicitRebindPreserveCanonicalBytes()throws Exception{
var original=document();var saved=manual.execute(AnimationService.Request.save(project,uuid,null,original)).view();byte[] bytes=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME));
assertThrows(IllegalStateException.class,()->manual.execute(AnimationService.Request.save(project,uuid,null,original)));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
ObjectNode manifest=(ObjectNode)mapper.readTree(bankRoot.resolve("asset.json").toFile());((ObjectNode)manifest.path("artifacts").get(0)).put("index",1);((ObjectNode)manifest.path("artifacts").get(1)).put("index",0);mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var drift=manual.execute(AnimationService.Request.get(project,uuid)).view();assertTrue(drift.diagnostics().stream().anyMatch(d->d.code().equals("binding_drift")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
var prepared=manual.execute(request(AnimationService.Operation.PREPARE_REBIND,saved.revision(),null,null,null)).proposal();assertEquals(2,prepared.differences().size());
assertThrows(IllegalStateException.class,()->manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),"stale-bank")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
var updated=manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),prepared.bankRevision())).view();assertTrue(updated.diagnostics().isEmpty());assertNotEquals(saved.revision(),updated.revision());
}
@Test void utf8ProjectionIsExactDeterministicAndSurvivesBankRelocation() throws Exception {
String clip="idle \"\\\n\r\té😀"+(char)0+(char)1;
var value=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of(
new Animator("zeta",clip,List.of(new Clip(clip,"once",List.of(new Frame("g0",9007199254740993L))))),
new Animator("alpha",clip,List.of(new Clip(clip,"loop",List.of(new Frame("g1",1)))))));
var saved=manual.execute(AnimationService.Request.save(project,uuid,null,value)).view();String bankRevision=saved.bankRevision();
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
Files.writeString(root.resolve("src/main.pbs"),"import {create_zeta,create_alpha} from @app:generated/animations/b_"+uuid.toString().replace("-","")+";[Frame]fn frame()->void {create_zeta(0);create_alpha(0);}");
byte[] previous=null;String generated=null;
for(int repeat=0;repeat<2;repeat++){
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts;
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(context,p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(result.bytecodeModule().constPool().stream().anyMatch(c->c instanceof p.studio.compiler.backend.bytecode.BytecodeModule.StringConstant text&&text.value().equals(clip)));
if(previous!=null)assertArrayEquals(previous,result.bytecodeBytes());previous=result.bytecodeBytes();
for(var id:context.fileTable.identifiers()){var handle=context.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs"))generated=handle.readUtf8().orElseThrow();}
}
assertNotNull(generated);assertTrue(generated.indexOf("fn create_alpha")<generated.indexOf("fn create_zeta"));assertFalse(generated.contains(root.toString()));
bankRoot=Files.move(bankRoot,root.resolve("assets/renamed"));
var registry=(ObjectNode)mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((ObjectNode)registry.path("assets").get(0)).put("root","renamed");mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
var moved=manual.execute(AnimationService.Request.get(project,uuid)).view();assertEquals(value,moved.document());assertEquals(saved.revision(),moved.revision());assertEquals(bankRevision,moved.bankRevision());assertTrue(moved.diagnostics().isEmpty());
}
@Test void concurrentCreatesAndLateCancelledCallbacksCannotOverwrite() throws Exception {
var pool=Executors.newCachedThreadPool();
try {
var start=new CountDownLatch(1);var results=new ArrayList<Future<Boolean>>();
for(int i=0;i<2;i++)results.add(pool.submit(()->{start.await();try{manual.execute(AnimationService.Request.save(project,uuid,null,document()));return true;}catch(IllegalStateException conflict){return false;}}));
start.countDown();int accepted=0;for(var result:results)if(result.get(10,TimeUnit.SECONDS))accepted++;
assertEquals(1,accepted);byte[] original=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME));
var entered=new CountDownLatch(1);var release=new CountDownLatch(1);var settled=new CountDownLatch(1);
GlyphBankLayoutSource delayed=new GlyphBankLayoutSource(){
public GlyphBankLayout resolve(Path path,UUID id){return layouts.resolve(path,id);}
public <T>T withLayout(Path path,UUID id,java.util.function.Function<GlyphBankLayout,T> work){
return layouts.withLayout(path,id,bank->{entered.countDown();try{release.await(10,TimeUnit.SECONDS);return work.apply(bank);}catch(InterruptedException error){throw new RuntimeException(error);}finally{settled.countDown();}});
}
};
var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session);
var taskService=new TaskAnimationService(access,new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)),new DefaultAnimationService(delayed,new PackerAssetCatalog(packer.workspaceService())));
session.grant(false).toCompletableFuture().get();String task=session.acquire().task().value();
String revision=AnimationRevision.of(original);
var call=pool.submit(()->taskService.execute(root,task,p->AnimationService.Request.save(p,uuid,revision,document())));
assertTrue(entered.await(5,TimeUnit.SECONDS));
session.reclaim().toCompletableFuture().get(5,TimeUnit.SECONDS);
release.countDown();assertTrue(settled.await(5,TimeUnit.SECONDS));
assertThrows(ExecutionException.class,()->call.get(5,TimeUnit.SECONDS));
assertArrayEquals(original,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)));
session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);
} finally {pool.shutdownNow();}
}
@Test void excludedAndMalformedDefinitionsDoNotProduceStaleFactories()throws Exception{
manual.execute(AnimationService.Request.save(project,uuid,null,document()));
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");Files.writeString(root.resolve("src/main.pbs"),"[Frame]fn frame()->void {}");
Files.writeString(bankRoot.resolve(AnimationDocument.FILE_NAME),"{broken");
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts;
var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(context,p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_ANIMATION_SURFACE")));
var registry=(ObjectNode)mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((ObjectNode)registry.path("assets").get(0)).put("included_in_build",false);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
assertTrue(new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().isEmpty());
assertNull(manual.execute(AnimationService.Request.get(project,uuid)).view().document());
}
@Test void taskToolsShareDocumentsPreviewAndExistingAuthority()throws Exception{
var workers=Executors.newCachedThreadPool();var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(workers));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session);
var guarded=new ManualAnimationService(engine,access);var saved=guarded.execute(AnimationService.Request.save(project,uuid,null,document())).view();
var preview=guarded.execute(request(AnimationService.Operation.PREVIEW,null,null,null,null)).preview();
var catalog=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper));var tasks=new TaskAnimationService(access,catalog,engine);var tools=new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpAnimationTools.handlers(tasks,mapper));
try {
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId","stale").put("operation","get").put("assetUuid",uuid.toString());
assertEquals("INVALID_TASK",tools.call("studio_animation_query",args).wire().path("structuredContent").path("error").path("code").asText());
session.grant(false).toCompletableFuture().join();String task=session.acquire().task().value();args.put("taskId",task);
assertThrows(ControlDeniedException.class,()->guarded.execute(AnimationService.Request.get(project,uuid)));
var get=tools.call("studio_animation_query",args).wire();assertFalse(get.path("isError").asBoolean(),get.toString());assertEquals(saved.revision(),get.path("structuredContent").path("value").path("view").path("revision").asText());
args.put("operation","preview").put("animatorId","hero").put("clipName","idle").put("elapsedTicks",2L).put("paletteId",0);
var rendered=tools.call("studio_animation_query",args).wire();assertFalse(rendered.path("isError").asBoolean(),rendered.toString());assertArrayEquals(preview.image().png(),Base64.getDecoder().decode(rendered.path("content").get(1).path("data").asText()));
assertEquals(1,rendered.path("structuredContent").path("value").path("preview").path("observation").path("glyphId").asInt());
var save=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("operation","save").put("assetUuid",uuid.toString()).put("expectedRevision","stale");save.set("document",mapper.readTree(new AnimationCodec().encode(document())));
assertEquals("ANIMATION_CONFLICT",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText());
save.put("expectedRevision",saved.revision());
var published=tools.call("studio_animation_update",save).wire();assertFalse(published.path("isError").asBoolean(),published.toString());
assertEquals(document(),new AnimationCodec().decode(published.path("structuredContent").path("value").path("view").path("json").asText()));
session.release(session.snapshot().task()).toCompletableFuture().get(5,TimeUnit.SECONDS);
assertEquals("INVALID_TASK",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText());
}finally{session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);workers.shutdownNow();}
}
}
@@ -0,0 +1,47 @@
package p.studio.app.animation;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import p.animation.*;
import p.packer.Packer;
import p.packer.messages.*;
import p.studio.api.assets.animation.*;
import p.studio.core.assets.animation.*;
import p.studio.app.assets.PackerGlyphBankLayouts;
import p.studio.app.mcp.*;
import p.studio.core.assets.PackerAssetCatalog;
import p.studio.core.project.*;
import p.studio.core.session.*;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.api.automation.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import static p.animation.AnimationDocument.*;
public class AnimationProjectFixture {
Path root;
final ObjectMapper mapper=new ObjectMapper();
final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc");
Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual;
p.studio.api.project.ProjectReference project;Path bankRoot;
void setup()throws Exception{
root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank");
manifest.putObject("preload").put("enabled",false);
var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16");
output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff);
var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff};
for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));}
mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest);
var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry);
packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper);
engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{});
project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root);
}
void close(){packer.close();}
AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));}
}
@@ -117,20 +117,21 @@ public final class InstalledKnowledgeProbe {
check(linkedResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed Linked example must compile");
Files.write(fixtures.resolve("pbs-linked-installed.pbx"),linkedResult.bytecodeBytes());
System.out.println("Installed Linked execution fixture generated");
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs").entrySet()) {
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs","animation","animation.pbs").entrySet()) {
Path exampleRoot=Files.createDirectory(Path.of(example.getKey()+"-example")).toRealPath();
Files.createDirectories(exampleRoot.resolve("src"));
Files.copy(root.resolve("prometeu.json"),exampleRoot.resolve("prometeu.json"));
Files.writeString(exampleRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String function=switch(example.getKey()){case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";};
String function=switch(example.getKey()){case "animation"->"animationExample";case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";};
Files.writeString(exampleRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/"+example.getValue()))
+"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}");
+(example.getKey().equals("animation")?"\n[Frame] fn frame()->void { animationExample(); }":"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}"));
var exampleResult=BuilderPipelineService.INSTANCE.compile(
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,exampleRoot.toString())),LogAggregator.stdout());
check(exampleResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed "+example.getKey()+" example must compile: "+exampleResult.diagnostics());
Files.write(fixtures.resolve("pbs-"+example.getKey()+"-installed.pbx"),exampleResult.bytecodeBytes());
System.out.println("Installed "+example.getKey()+" execution fixture generated");
}
p.studio.app.animation.AnimationInstalledProbe.verify(Files.createDirectory(Path.of("animation-authored")).toRealPath(),fixtures);
verifyExternalSources(provider.getClass().getClassLoader());
registration.unsubscribe();
System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled");
@@ -21,6 +21,8 @@ class InstalledKnowledgeTest {
assertTrue(log.contains("Installed map execution fixture generated"), log);
assertTrue(log.contains("Installed stack-queue execution fixture generated"), log);
assertTrue(log.contains("Installed memcard execution fixture generated"), log);
assertTrue(log.contains("Installed animation execution fixture generated"), log);
assertTrue(log.contains("Installed generated animation verified"), log);
}
@Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception {
@@ -12,7 +12,7 @@ class McpContractTest {
final McpToolCatalog catalog = new McpToolCatalog(mapper);
@Test void everyToolHasValidExampleAuthorityAndResultEnvelope() {
assertEquals(22, catalog.names().size());
assertEquals(24, catalog.names().size());
for (var name : catalog.names()) {
var definition = catalog.definition(name);
assertDoesNotThrow(() -> catalog.validateArguments(name, definition.get("exampleArguments")), name + " arguments");
@@ -27,7 +27,7 @@ class StudioMcpStdioTest {
var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100);
try (var process = new Connector(root); var server = server(count, pixels)) {
process.initialize();
assertEquals(22, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
assertEquals(24, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size());
var waiting = process.call("studio_project_context", root);
assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText());
assertFalse(Files.exists(root.resolve(".studio")));
@@ -7,8 +7,15 @@ import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
@AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class)
@AnalyzeClasses(packages = {"p.studio", "p.packer", "p.animation"}, importOptions = ImportOption.DoNotIncludeTests.class)
class StudioBoundaryArchTest {
@ArchTest
static final ArchRule animationModelIsNeutral = noClasses()
.that().resideInAPackage("p.animation..")
.should().dependOnClassesThat().resideInAnyPackage(
"p.studio..", "p.packer..", "javafx..", "org.springframework..")
.because("DEC-0084 shares authoring DTOs and validation without a provider or UI dependency");
@ArchTest
static final ArchRule automationTransportStaysInTheApp = noClasses()
.that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..")
@@ -0,0 +1,57 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.SourceKind;
import p.studio.compiler.models.registry.IRRegistry;
import java.util.LinkedHashMap;
import java.nio.file.*;
import static org.junit.jupiter.api.Assertions.*;
/** Production producers; results are independently checked by the native verifier. */
class PbsResultTest {
@Test void resultFunctionsCannotBecomePlainFunctionValues() {
for(String value:new String[]{"let f:Fn()->int=fallible;","let f=fallible;"}){
var diagnostics=p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
assertDoesNotThrow(()->new p.studio.compiler.pbs.PbsFrontendCompiler().compileFile(new p.studio.compiler.source.identifiers.FileId(0),
"declare error E {bad;} fn fallible()->result<E> int {return err(E.bad);} fn check(){"+value+"}",diagnostics));
assertTrue(diagnostics.hasErrors(),value);
}
}
@Test void completeResultGroupsAndControlFlowReachProductionPbx() throws Exception {
var fixtures = new LinkedHashMap<String, String>();
String errors = "declare error E { bad; other; } declare error F { retry; abort; }\n";
fixtures.put("unit-ok", "fn main() -> result<E> { return ok(()); }");
fixtures.put("unit-err", "fn main() -> result<E> { return err(E.other); }");
fixtures.put("scalar", "fn main() -> result<E> int { return ok(42); }");
fixtures.put("error", "fn main() -> result<E> long { return err(E.bad); }");
fixtures.put("tuple", "fn main() -> result<E> (a: long, b: int) { return ok((a: 9007199254740993, b: 42)); }");
fixtures.put("reference", "fn main() -> result<E> array<int> { return err(E.other); }");
fixtures.put("propagate", "fn source() -> result<E> int { return err(E.other); } fn main() -> result<E> (a: long, b: str) { let v = Probe.source()!; return ok((a: v as long, b: \"unused\")); }");
fixtures.put("nested", "fn source() -> result<E> int { return err(E.other); } fn main() -> result<E> int { return ok(100 + Probe.source()!); }");
fixtures.put("recover", "fn source() -> result<E> int { return err(E.bad); } fn main() -> result<F> int { let v = handle Probe.source() { E.bad -> { ok(42) }, E.other -> F.abort }; return ok(v); }");
fixtures.put("remap", "fn source() -> result<E> int { return err(E.other); } fn main() -> result<F> int { let v = handle Probe.source() { E.bad -> { ok(42) }, E.other -> F.abort }; return ok(v); }");
fixtures.put("success", "fn source() -> result<E> int { return ok(42); } fn main() -> result<F> int { let v = handle Probe.source() { _ -> { ok(99) } }; return ok(v); }");
fixtures.put("trait", "fn main() -> result<E> Reader { return err(E.bad); }");
fixtures.put("fn", "fn main() -> result<E> Fn() -> int { return err(E.bad); }");
fixtures.put("once", "fn source() -> result<E> int { calls=calls+1; return err(E.bad); } fn unused() -> int { calls=calls+100; return 99; } fn main() -> result<F> int { let value=handle Probe.source() { E.bad -> { ok(42) }, E.other -> { ok(Probe.unused()) } }; if calls!=1 { let fail=1/0; } return ok(value); }");
fixtures.put("block-remap", "fn source() -> result<E> int { return err(E.bad); } fn main() -> result<F> int { let value=handle Probe.source() { E.bad -> { err(F.abort) }, _ -> { ok(42) } }; return ok(value); }");
fixtures.put("reference-ok", "fn source() -> result<E> array<int> { return ok([42]); } fn main() -> result<E> int { let values=Probe.source()!; return ok(values[0] else 0); }");
fixtures.put("fn-ok", "fn source() -> result<E> Fn() -> int { return ok(answer); } fn main() -> result<E> int { let f=Probe.source()!; return ok(f()); }");
fixtures.put("trait-ok", "fn source() -> result<E> Fallible { return ok(new ReaderValue(42)); } fn main() -> result<E> int { let reader=Probe.source()!; return ok(reader.read()!); }");
fixtures.put("color-ok", "fn main() -> result<E> Color { return ok(Color.from_raw(42)); }");
fixtures.put("color-err", "fn main() -> result<E> Color { return err(E.bad); }");
fixtures.put("trap", "fn source() -> result<E> int { let fail=1/0; return ok(1); } fn main() -> result<F> int { let value=handle Probe.source() { _ -> { ok(42) } }; return ok(value); }");
String color;
try(var input=p.studio.compiler.pbs.PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/core/color/main.pbs")){assertNotNull(input);color=new String(input.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);}
String support="declare global calls: int=0; fn answer() -> int { return 42; } declare contract Fallible { fn read() -> result<E> int; } declare struct ReaderValue(pub value:int); implements Fallible for ReaderValue using reader { fn read() -> result<E> int { return ok(reader.value); } }\n";
var manifest = new StringBuilder();
for (var entry : fixtures.entrySet()) for (var suffix : new String[]{"", "-optimized"}) {
var source = errors + support + color + "declare contract Reader { fn read() -> int; }\n" + entry.getValue().replace("Probe.", "");
var module = PbsRuntimeAlignmentTest.compile("result-" + entry.getKey() + suffix, source, SourceKind.SDK_INTERFACE, "main");
assertEquals(IRRegistry.TypeRef.builtin(0x10), module.functions().getFirst().metadata().signature().results().getFirst());
manifest.append(entry.getKey()).append(suffix).append('\n');
}
Files.writeString(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-result-manifest.txt"), manifest);
}
}
@@ -20,6 +20,9 @@ class PbsRuntimeAlignmentTest {
return compile(name, source, SourceKind.SDK_INTERFACE);
}
static BytecodeModule compile(String name,String source,SourceKind sourceKind) throws Exception {
return compile(name,source,sourceKind,"Probe.main");
}
static BytecodeModule compile(String name,String source,SourceKind sourceKind,String entryPoint) throws Exception {
var diagnostics=DiagnosticSink.empty();
var fileId = new FileId(0);
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
@@ -27,7 +30,7 @@ class PbsRuntimeAlignmentTest {
new p.studio.compiler.source.identifiers.ModuleId(0),p.studio.utilities.structures.ReadOnlyList.empty(),
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
assertFalse(diagnostics.hasErrors(), ()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
var backend=IRBackend.builder().entryPointCallableName("Probe.main").entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions())
var backend=IRBackend.builder().entryPointCallableName(entryPoint).entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions())
.globals(file.globals()).registry(file.registry()).intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build();
var program=new LowerToIRVMService().lower(backend);
if (name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program);
@@ -0,0 +1,269 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.SourceKind;
import p.studio.compiler.pbs.PbsFrontendCompiler;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class PbsSpriteAnimationTest {
static String core() throws Exception {
var text = new StringBuilder();
for (var path : new String[]{"sprite", "animation"}) {
try (var input = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/core/"+path+"/main.pbs")) {
assertNotNull(input);
text.append(new String(input.readAllBytes(), StandardCharsets.UTF_8).replace("import { SpriteView } from @core:sprite;", ""));
}
}
return text.toString();
}
@Test void directCoreLibraryUsesTheProductionCompiler() throws Exception {
for (var suffix : new String[]{"", "-optimized"}) {
PbsRuntimeAlignmentTest.compile("animation-basic"+suffix, core()+"""
declare service Probe {
fn main() -> result<AnimationError> int {
let builder = animator_builder(3, "idle")!;
builder.begin_clip("idle", PlaybackMode.Loop)!;
builder.add_frame(7, 2)!; builder.add_frame(11, 3)!; builder.add_frame(4, 1)!;
builder.end_clip()!;
let first = builder.build()!; let second = builder.build()!;
first.play("idle")!; first.advance(2)!;
if second.sprite().glyph_id != 7 { let failed = 1 / 0; }
if first.sprite().glyph_id != 11 { let failed = 1 / 0; }
first.advance(4)!;
if first.sprite().glyph_id != 7 { let failed = 1 / 0; }
let frame = first.frame_at("idle", 1)!;
if frame.glyph_id != 11 { let failed = 1 / 0; }
return ok(42);
}
}
""", SourceKind.PROJECT);
}
}
@Test void playbackFailuresAndAllocationPathsHaveNativeFixtures() throws Exception {
var cases = new java.util.LinkedHashMap<String, String>();
var build = """
fn fixture(mode: PlaybackMode) -> result<AnimationError> Animator {
let b = animator_builder(3, "idle")!;
b.begin_clip("idle", mode)!;
b.add_frame(7, 2)!; b.add_frame(11, 3)!; b.add_frame(4, 1)!;
b.end_clip()!; return ok(b.build()!);
}
""";
cases.put("loop", """
let a = fixture(PlaybackMode.Loop)!; a.play("idle")!;
let view: SpriteView = a;
let start = 162000001;
if view.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.advance(1)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.advance(1)!; if a.sprite().glyph_id != 11 { let fail = 1 / 0; }
a.advance(3)!; if a.sprite().glyph_id != 4 { let fail = 1 / 0; }
a.advance(1)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.advance(601)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.advance(2147483647)!; if a.sprite().glyph_id != 11 { let fail = 1 / 0; }
for i: int from 0 until 100 { a.advance(0)!; view.sprite(); }
let end = 162000002;
return ok(42);
""");
cases.put("once", """
let a = fixture(PlaybackMode.Once)!; a.play("idle")!;
let start = 162000001;
a.advance(5)!; if a.state() != PlaybackState.Playing { let fail = 1 / 0; }
if a.sprite().glyph_id != 4 { let fail = 1 / 0; }
a.advance(1)!; if a.state() != PlaybackState.Finished { let fail = 1 / 0; }
a.resume(); a.advance(100)!;
if a.sprite().glyph_id != 4 || a.state() != PlaybackState.Finished { let fail = 1 / 0; }
a.restart(); if a.sprite().glyph_id != 7 || a.state() != PlaybackState.Playing { let fail = 1 / 0; }
a.advance(2)!; a.pause(); a.advance(100)!;
if a.sprite().glyph_id != 11 { let fail = 1 / 0; }
a.resume(); a.play("idle")!;
if a.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.select("idle")!; if a.state() != PlaybackState.Stopped { let fail = 1 / 0; }
let end = 162000002; return ok(42);
""");
cases.put("negative", """
let a = fixture(PlaybackMode.Loop)!;
let start = 162000001;
handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow };
if a.state() != PlaybackState.Stopped || a.sprite().glyph_id != 7 { let fail = 1 / 0; }
a.play("idle")!; a.advance(2)!;
handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow };
if a.sprite().glyph_id != 11 || a.state() != PlaybackState.Playing { let fail = 1 / 0; }
let end = 162000002; return ok(42);
""");
cases.put("overflow", """
// Isolated test-only near-limit setup; calls the unchanged production advance.
let maximum: long = 9223372036854775807;
let frame = new _AnimationFrame.make(7, maximum, maximum);
let clip = new _AnimationClip.make("idle", PlaybackMode.Once);
clip.head = frame; clip.tail = frame; clip.count = 1; clip.total = maximum;
let a = new Animator(3, clip, clip, frame, maximum - 2, PlaybackState.Playing, 1);
let start = 162000001;
handle a.advance(3) { AnimationError.overflow -> { ok(()) }, _ -> AnimationError.invalid_ticks };
if a.sprite().glyph_id != 7 || a.state() != PlaybackState.Playing { let fail = 1 / 0; }
let end = 162000002; return ok(42);
""");
cases.put("draft", """
let b = animator_builder(3, "idle")!;
handle b.build() { AnimationError.empty_animator -> { ok(new Animator(0, new _AnimationClip.make("", PlaybackMode.Once), new _AnimationClip.make("", PlaybackMode.Once), new _AnimationFrame.make(0, 1, 1), 0, PlaybackState.Stopped, 0)) }, _ -> AnimationError.empty_animator };
b.begin_clip("idle", PlaybackMode.Once)!;
handle b.end_clip() { AnimationError.empty_clip -> { ok(()) }, _ -> AnimationError.empty_clip };
b.add_frame(7, 2)!; b.end_clip()!;
let a = b.build()!; b.remove_clip("idle")!;
if a.sprite().glyph_id != 7 || a.clip_count() != (1 as long) { let fail = 1 / 0; }
b.begin_clip("idle", PlaybackMode.Loop)!; b.add_frame(11, 3)!; b.end_clip()!;
let other = b.build()!;
if other.sprite().glyph_id != 11 || a.sprite().glyph_id != 7 { let fail = 1 / 0; }
return ok(42);
""");
cases.put("limits", """
let maximum: long = 9223372036854775807;
let b = animator_builder(255, "idle")!;
handle b.add_frame(-1, 0) { AnimationError.no_open_clip -> { ok(()) }, _ -> AnimationError.overflow };
handle b.discard_clip() { AnimationError.no_open_clip -> { ok(()) }, _ -> AnimationError.overflow };
b.begin_clip("idle", PlaybackMode.Once)!;
handle b.begin_clip("", PlaybackMode.Once) { AnimationError.clip_already_open -> { ok(()) }, _ -> AnimationError.overflow };
handle b.add_frame(-1, 0) { AnimationError.invalid_glyph -> { ok(()) }, _ -> AnimationError.overflow };
handle b.add_frame(0, 0) { AnimationError.invalid_duration -> { ok(()) }, _ -> AnimationError.overflow };
b.add_frame(65535, maximum)!;
handle b.add_frame(0, 1) { AnimationError.overflow -> { ok(()) }, _ -> AnimationError.invalid_duration };
handle b.remove_clip("") { AnimationError.unfinished_clip -> { ok(()) }, _ -> AnimationError.overflow };
b.end_clip()!;
handle b.begin_clip("idle", PlaybackMode.Loop) { AnimationError.duplicate_clip -> { ok(()) }, _ -> AnimationError.overflow };
handle b.begin_clip("", PlaybackMode.Loop) { AnimationError.invalid_name -> { ok(()) }, _ -> AnimationError.overflow };
let a = b.build()!;
handle a.frame_at("missing", -1) { AnimationError.unknown_clip -> { ok((glyph_id: 0, duration_ticks: 0 as long)) }, _ -> AnimationError.overflow };
handle a.frame_at("idle", 1) { AnimationError.index_out_of_range -> { ok((glyph_id: 0, duration_ticks: 0 as long)) }, _ -> AnimationError.overflow };
handle a.select("missing") { AnimationError.unknown_clip -> { ok(()) }, _ -> AnimationError.overflow };
handle a.play("missing") { AnimationError.unknown_clip -> { ok(()) }, _ -> AnimationError.overflow };
if a.sprite().glyph_id != 65535 || a.state() != PlaybackState.Stopped { let fail=1/0; }
let alias = a; alias.play("idle")!;
if a.state() != PlaybackState.Playing { let fail=1/0; }
// Test-only count setup avoids billions of allocations; production add_frame executes.
let frame = new _AnimationFrame.make(7, 1, 1);
let clip = new _AnimationClip.make("idle", PlaybackMode.Once);
clip.head=frame;clip.tail=frame;clip.count=4294967295;clip.total=1;
let full = new AnimatorBuilder(0,"idle",clip,clip,clip,0,true);
handle full.add_frame(0,1) { AnimationError.limit_exceeded -> { ok(()) }, _ -> AnimationError.overflow };
let countMaximum: long = 4294967295;
if clip.count != countMaximum { let fail=1/0; }
return ok(42);
""");
cases.put("matrix", """
let a = fixture(PlaybackMode.Once)!;
for stage: int from 0 until 4 {
a.stop();
if stage == 1 { a.play("idle")!;a.advance(2)!; }
if stage == 2 { a.play("idle")!;a.advance(2)!;a.pause(); }
if stage == 3 { a.play("idle")!;a.advance(6)!; }
let before = a.sprite().glyph_id;let state = a.state();
handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow };
a.advance(0)!;if a.state()!=state || a.sprite().glyph_id!=before {let fail=1/0;}
a.select("idle")!;if a.state()!=PlaybackState.Stopped || a.sprite().glyph_id!=7 {let fail=1/0;}
a.play("idle")!;a.advance(2)!;a.play("idle")!;
if a.sprite().glyph_id!=7 || a.state()!=PlaybackState.Playing {let fail=1/0;}
a.pause();a.pause();a.advance(100)!;if a.state()!=PlaybackState.Paused || a.sprite().glyph_id!=7 {let fail=1/0;}
a.resume();a.resume();a.advance(2)!;if a.sprite().glyph_id!=11 {let fail=1/0;}
a.stop();a.resume();if a.state()!=PlaybackState.Stopped {let fail=1/0;}
a.restart();if a.sprite().glyph_id!=7 || a.state()!=PlaybackState.Playing {let fail=1/0;}
}
return ok(42);
""");
cases.put("errors", """
let s = handle make_sprite(255,65535) { _ -> AnimationError.invalid_glyph };
let s0 = handle make_sprite(0,0) { _ -> AnimationError.invalid_glyph };
let view: SpriteView = s;
let b = animator_builder(0,"idle")!;let a=fixture(PlaybackMode.Once)!;
let start=162000001;
if view.sprite().bank_id!=255 || view.sprite().glyph_id!=65535 || s0.sprite().glyph_id!=0 {let fail=1/0;}
handle make_sprite(-1,-1) { SpriteError.invalid_bank -> {ok(s)}, _ -> AnimationError.overflow };
handle make_sprite(256,0) { SpriteError.invalid_bank -> {ok(s)}, _ -> AnimationError.overflow };
handle make_sprite(0,-1) { SpriteError.invalid_glyph -> {ok(s)}, _ -> AnimationError.overflow };
handle make_sprite(0,65536) { SpriteError.invalid_glyph -> {ok(s)}, _ -> AnimationError.overflow };
handle animator_builder(256,"") { AnimationError.invalid_bank -> {ok(b)}, _ -> AnimationError.overflow };
handle animator_builder(0,"") { AnimationError.invalid_name -> {ok(b)}, _ -> AnimationError.overflow };
handle b.build() { AnimationError.empty_animator -> {ok(a)}, _ -> AnimationError.overflow };
handle b.remove_clip("missing") { AnimationError.unknown_clip -> {ok(())}, _ -> AnimationError.overflow };
handle b.end_clip() { AnimationError.no_open_clip -> {ok(())}, _ -> AnimationError.overflow };
let end=162000002;
b.begin_clip("jump",PlaybackMode.Once)!;
handle b.build() { AnimationError.unfinished_clip -> {ok(a)}, _ -> AnimationError.overflow };
b.add_frame(0,1)!;b.end_clip()!;
handle b.build() { AnimationError.initial_clip_missing -> {ok(a)}, _ -> AnimationError.overflow };
b.begin_clip("discard",PlaybackMode.Loop)!;b.add_frame(1,1)!;b.discard_clip()!;
handle b.build() { AnimationError.initial_clip_missing -> {ok(a)}, _ -> AnimationError.overflow };
if a.sprite().glyph_id!=7 {let fail=1/0;}
return ok(42);
""");
var manifest = new StringBuilder("basic\n");
for (var entry : cases.entrySet()) {
for (var suffix : new String[]{"", "-optimized"})
PbsRuntimeAlignmentTest.compile("animation-"+entry.getKey()+suffix,
core()+build+"declare service Probe { fn main() -> result<AnimationError> int {"+entry.getValue()+"} }", SourceKind.PROJECT);
manifest.append(entry.getKey()).append('\n');
}
java.nio.file.Files.writeString(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-animation-manifest.txt"), manifest);
}
@Test void privateCyclesHaveAnExplicitNativeGcOracle() throws Exception {
String source=core()+"""
fn keep(owners: array<Animator>) -> result<AnimationError> {
let b=animator_builder(3,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!;
b.add_frame(7,2)!;b.add_frame(11,3)!;b.add_frame(4,1)!;b.end_clip()!;
owners[0]=b.build()!;return ok(());
}
fn churn() -> result<AnimationError> {
for i:int from 0 until 200 { let b=animator_builder(0,"x")!;b.begin_clip("x",PlaybackMode.Once)!;b.add_frame(0,1)!;b.end_clip()!;b.build(); }
return ok(());
}
declare service Probe { fn main() -> result<AnimationError> int {
let owners:array<Animator> = new array(1);keep(owners)!;
for round:int from 0 until 2 {
if round==1 { owners.clear(0); }churn()!;
let marker=314159;
}
return ok(42);
} }
""";
for(String suffix:new String[]{"","-optimized"}){
var module=PbsRuntimeAlignmentTest.compile("animation-gc"+suffix,source,SourceKind.PROJECT);
module=PbsStructuredValuesTest.withTestSafepoint(module);
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-animation-gc"+suffix+".pbx"),module.serialize());
}
}
@Test void actualCoreImportsFactoriesAndConstructionBoundary(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
java.nio.file.Files.createDirectories(root.resolve("src"));
java.nio.file.Files.writeString(root.resolve("prometeu.json"), """
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
java.nio.file.Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String imports="import { Sprite, SpriteView, SpriteError, make_sprite } from @core:sprite;\nimport { Animator, AnimatorBuilder, AnimationError, PlaybackMode, animator_builder } from @core:animation;\n";
java.nio.file.Files.writeString(root.resolve("src/main.pbs"),imports+"""
fn verify() -> result<AnimationError> {
let b=animator_builder(3,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!;
b.add_frame(7,2)!;b.end_clip()!;let a=b.build()!;a.play("idle")!;a.advance(2)!;
if a.sprite().glyph_id!=7 { let fail=1/0; } return ok(());
}
[Frame] fn frame() -> void { verify(); }
""");
var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));
var analysis=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(context,p.studio.utilities.logs.LogAggregator.stdout());
assertFalse(analysis.diagnostics().stream().anyMatch(d->d.isError()),analysis.diagnostics().toString());
var compiled=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(compiled.bytecodeBytes().length>0);
java.nio.file.Files.writeString(root.resolve("src/main.pbs"),imports+"[Frame] fn frame() -> void { let forged=new Sprite(3,7); }");
analysis=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(analysis.diagnostics().stream().anyMatch(d->d.getCode().equals("E_SEM_STDLIB_FACTORY_ONLY")),analysis.diagnostics().toString());
for(String construction:new String[]{"new Alias(3,7)","new Alias.make(3,7)"}){
java.nio.file.Files.writeString(root.resolve("src/main.pbs"),"import { Sprite as Alias } from @core:sprite;[Frame] fn frame()->void {let bad="+construction+";}");
var denied=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(denied.diagnostics().stream().anyMatch(d->d.getCode().equals("E_SEM_STDLIB_FACTORY_ONLY")),denied.diagnostics().toString());
}
java.nio.file.Files.writeString(root.resolve("src/main.pbs"),"[StdlibFactoryOnly] declare struct Forged(value:int) {} [Frame]fn frame()->void{}");
var forged=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout());
assertTrue(forged.diagnostics().stream().anyMatch(d->d.isError()));
}
}
@@ -82,13 +82,20 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
if (text.isEmpty()) return Optional.empty();
final boolean bundled = surface.sourceKindByFile().get(entry.getKey()) == SourceKind.SDK_INTERFACE;
final Path owner = surface.ownerRootByFile().get(entry.getKey());
final boolean external = bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize());
final boolean generated = path.toAbsolutePath().normalize().startsWith(Path.of("/virtual/generated/animations"));
final boolean external = generated || bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize());
final var source = new FrontendSourceDocument(path, text.orElseThrow(),
bundled ? "bundled" : external ? "dependency" : "project",
generated ? "generated" : bundled ? "bundled" : external ? "dependency" : "project",
handle.getRelativePath().toString(), "pbs", external,
new FrontendEditorialContext(entry.getValue(),
surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty()),
context.semanticContext(), files, surface));
context.semanticContext(), files, surface),
generated && context.semanticContext() instanceof FESurfaceContext animationContext
? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate)
.filter(g->g.path().equals(path)).flatMap(g->g.origins().stream()).toList() : List.of(),
generated && context.semanticContext() instanceof FESurfaceContext animationContext
? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate)
.filter(g->g.path().equals(path)).map(p.studio.compiler.services.PbsAnimationProjection.Generated::revision).findFirst().orElse("") : "");
// A dependency may physically overlap a project source root. External
// ownership wins even if another file-table entry treats it as local.
if (external) return Optional.of(source);
@@ -11,7 +11,7 @@ public final class PbsCallableSlotCounter {
final PbsAst.TypeRef returnType) {
return switch (returnKind) {
case INFERRED_UNIT, EXPLICIT_UNIT -> 0;
case RESULT -> 1;
case RESULT -> 1 + Math.max(0, typeSlots(returnType));
case PLAIN -> Math.max(0, typeSlots(returnType));
};
}
@@ -0,0 +1,19 @@
package p.studio.compiler.pbs;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.utilities.structures.ReadOnlyList;
/** Trusted declaration identity survives aliases/reexports; same-module admission is explicit. */
public final class PbsStdlibConstruction {
private PbsStdlibConstruction() {}
public static boolean factoryOnly(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s
&& PbsSdkCollections.attribute(s.attributes(), "StdlibFactoryOnly") != null;
}
public static boolean allowed(PbsAst.TopDecl declaration, PbsAst.File file, ReadOnlyList<PbsAst.TopDecl> supplemental) {
if (!factoryOnly(declaration)) return true;
if (file.topDecls().stream().anyMatch(d -> d.span().equals(declaration.span()))) return true;
return supplemental.stream().anyMatch(d -> d instanceof PbsAst.TypeBindingDecl binding
&& binding.sameModule() && binding.span().getFileId().equals(file.span().getFileId()) && binding.declaration().span().equals(declaration.span()));
}
}
@@ -227,7 +227,9 @@ public final class PbsAst {
}
/** Imported lexical binding; retains the original declaration and the importing source scope. */
public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {}
public record TypeBindingDecl(String name, TopDecl declaration, Span span, boolean sameModule) implements TopDecl {
public TypeBindingDecl(String name, TopDecl declaration, Span span) { this(name, declaration, span, false); }
}
public record HostDecl(
String name,
@@ -44,7 +44,7 @@ public class PbsAstRewriter {
map(b.signatures(), this::signature), b.attributes(), b.span());
case PbsAst.GlobalDecl g -> new PbsAst.GlobalDecl(g.name(), type(g.explicitType()), expression(g.initializer(), type(g.explicitType())), g.span());
case PbsAst.ConstDecl c -> new PbsAst.ConstDecl(c.name(), type(c.explicitType()), expression(c.initializer(), type(c.explicitType())), c.attributes(), c.span());
case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span());
case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span(), b.sameModule());
case PbsAst.EnumDecl e -> e;
case PbsAst.ErrorDecl e -> e;
case PbsAst.InvalidDecl i -> i;
@@ -49,6 +49,8 @@ final class PbsExecutableBodyLowerer {
var separator=callableName.indexOf('.');
if(separator>0 && metadataIndex.types().services.containsKey(callableName.substring(0,separator))) context.serviceOwner=callableName.substring(0,separator);
context.returnType = functionDecl.returnType();
context.returnKind = functionDecl.returnKind();
context.resultErrorType = functionDecl.resultErrorType();
int captureIndex = 0;
for (var capture : metadataIndex.types().capturesByFunction.getOrDefault(functionDecl.name(), java.util.List.of())) {
var type = capture.typeRef();
@@ -91,7 +93,7 @@ final class PbsExecutableBodyLowerer {
} else terminated = lowerBlock(functionDecl.body(), context);
finalizeFunctionInstructions(functionDecl, context, terminated);
final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0;
final var returnSlots = context.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType());
final int maxStackSlots;
try {
maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots);
@@ -450,14 +452,10 @@ final class PbsExecutableBodyLowerer {
case PbsAst.ElseExpr elseExpr -> lowerOptionalFallback(elseExpr, context);
case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context);
case PbsAst.SwitchExpr switchExpr -> lowerSwitch(switchExpr, context);
case PbsAst.HandleExpr handleExpr -> lowerUnsupportedExpression(
handleExpr.value(),
"handle expression is not lowerable in executable lowering v1",
handleExpr.span(),
context);
case PbsAst.HandleExpr handleExpr -> lowerHandle(handleExpr, context);
case PbsAst.AsExpr asExpr -> lowerConversion(asExpr, context);
case PbsAst.MemberExpr memberExpr -> lowerMemberExpression(memberExpr, context);
case PbsAst.PropagateExpr propagateExpr -> lowerExpression(propagateExpr.expression(), context);
case PbsAst.PropagateExpr propagateExpr -> lowerPropagate(propagateExpr, context);
case PbsAst.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context);
case PbsAst.NewExpr newExpr -> {
if (newExpr.typeName().equals("array")) {
@@ -479,7 +477,12 @@ final class PbsExecutableBodyLowerer {
lowerExpected(someExpr.value(), payload, context);
wrapOptional(payload, someExpr.span(), context);
}
case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context);
case PbsAst.OkExpr okExpr -> {
lowerExpected(okExpr.value(), context.returnType, context);
int payload = save(context.types().slots(context.returnType), okExpr.span(), context);
emitPushI32(0, okExpr.span(), context);
emitLoadLocalSlots(payload, context.types().slots(context.returnType), okExpr.span(), context);
}
case PbsAst.TupleExpr tupleExpr -> {
var expected = context.expectedType;
for (int index=0; index<tupleExpr.items().size(); index++) {
@@ -500,8 +503,7 @@ final class PbsExecutableBodyLowerer {
else lowerServiceValue(context.serviceOwner,value.span(),context);
}
case PbsAst.NoneExpr value -> emitDefault(context.types().registryType(context.expectedType), 1, value.span(), context);
case PbsAst.ErrExpr ignored -> {
}
case PbsAst.ErrExpr error -> emitResultError(error.errorPath(), error.span(), context);
case PbsAst.UnitExpr ignored -> {
}
}
@@ -663,7 +665,7 @@ final class PbsExecutableBodyLowerer {
return;
}
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
lowerExpression(memberExpr.receiver(),context);
lowerExpected(memberExpr.receiver(),receiverType,context);
int slot=save(context.types().slots(receiverType),memberExpr.span(),context);
int offset=0;
for(var field:receiverType.fields()) {
@@ -886,6 +888,8 @@ final class PbsExecutableBodyLowerer {
if (expression == null) {
return 0;
}
var resultSignature = resultSignature(expression, context);
if (resultSignature != null) return context.types().returnSlots(resultSignature.returnKind(), resultSignature.returnType());
var resolvedType = expressionType(expression, context);
if (resolvedType != null) return context.types().slots(resolvedType);
return switch (expression) {
@@ -1171,6 +1175,8 @@ final class PbsExecutableBodyLowerer {
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
if (e == null) return null;
if (e instanceof PbsAst.PropagateExpr p) return expressionType(p.expression(), c);
if (e instanceof PbsAst.HandleExpr h) return expressionType(h.value(), c);
if (e instanceof PbsAst.LambdaExpr lambda) return lambda.functionType();
if (e instanceof PbsAst.ArrayLiteralExpr || e instanceof PbsAst.NoneExpr) return c.expectedType;
if (e instanceof PbsAst.TupleExpr tuple) return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(tuple.items().stream()
@@ -1751,6 +1757,115 @@ final class PbsExecutableBodyLowerer {
null, "", null, null, null, "", "", pops, pushes, span,
new IRRegistryInstruction(kind,type,null,null,field)));
}
private PbsAst.FunctionSignature resultSignature(PbsAst.Expression expression, PbsExecutableLoweringContext c) {
if (expression instanceof PbsAst.GroupExpr group) return resultSignature(group.expression(), c);
if (expression instanceof PbsAst.ApplyExpr apply) return resultSignature(applyCall(apply), c);
if (!(expression instanceof PbsAst.CallExpr call)) return null;
PbsAst.FunctionSignature signature = null;
var free = sourceFunction(call, c);
if (free != null) signature = new PbsAst.FunctionSignature(free.name(), free.parameters(), free.returnKind(),
free.returnType(), free.resultErrorType(), free.attributes(), free.span());
if (call.callee() instanceof PbsAst.MemberExpr member) {
var owner = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
if (owner != null) {
var contract = c.types().contract(owner);
if (contract != null) signature = contract.signatures().stream().filter(m ->
m.name().equals(member.memberName()) && parametersMatch(m.parameters(), call.arguments(), c))
.findFirst().orElse(null);
else signature = c.types().signatures.get(owner.name() + "." + member.memberName() + "#" + call.arguments().size());
}
}
if (signature == null) signature = c.types().signatures.get(PbsRuntimeTypes.path(call.callee()) + "#" + call.arguments().size());
return signature != null && signature.returnKind() == PbsAst.ReturnKind.RESULT ? signature : null;
}
private void clearPendingStack(Span span, PbsExecutableLoweringContext c) {
int pending = stackAnalyzer.pendingStackSlots(ReadOnlyList.wrap(c.instructions()));
for (int i = 0; i < pending; i++)
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.POP, "", null, null, span));
}
private void emitInactivePayload(PbsAst.TypeRef payload, Span span, PbsExecutableLoweringContext c) {
for (var part : c.types().results(payload)) {
var declaration = c.types().registry().types().stream().filter(d -> d.identity().equals(part)).findFirst().orElseThrow();
if (declaration.body() instanceof IRRegistry.Builtin builtin) {
switch (builtin.id()) {
case 0x10 -> emitPushI32(0, span, c);
case 0x11, 1 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c);
case 0x12 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c);
case 0x13 -> emitPushBool(false, span, c);
case 2 -> { emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); }
case 3 -> { for (int i = 0; i < 3; i++) emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c); }
default -> emitNullGroup(registryWidth(part, c), span, c);
}
} else emitNullGroup(registryWidth(part, c), span, c);
}
}
/** Extra locals start Null in the existing VM; these reserved slots are never assigned. */
private void emitNullGroup(int width, Span span, PbsExecutableLoweringContext c) {
int slot = c.declareLocalSlots(c.nextLabel("inactive_null"), width);
emitLoadLocalSlots(slot, width, span, c);
}
private void emitResultError(PbsAst.ErrorPath path, Span span, PbsExecutableLoweringContext c) {
emitPushI32(c.types().errorCode(path), span, c);
emitInactivePayload(c.returnType, span, c);
}
private void lowerPropagate(PbsAst.PropagateExpr expression, PbsExecutableLoweringContext c) {
var signature = resultSignature(expression.expression(), c);
if (signature == null) { reportUnsupportedLowering("Propagation requires an exact result signature", expression.span(), c); return; }
lowerExpected(expression.expression(), signature.returnType(), c);
int width = c.types().slots(signature.returnType());
int group = save(1 + width, expression.span(), c);
var success = c.nextLabel("result_success");
emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c);
emitBinaryOperatorInstruction("==", expression.span(), c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c);
clearPendingStack(expression.span(), c);
emitGetLocal(group, expression.span(), c); emitInactivePayload(c.returnType, expression.span(), c);
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, expression.span()));
emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c);
}
private void lowerHandle(PbsAst.HandleExpr expression, PbsExecutableLoweringContext c) {
var signature = resultSignature(expression.value(), c);
if (signature == null) { reportUnsupportedLowering("Handle requires an exact result signature", expression.span(), c); return; }
lowerExpected(expression.value(), signature.returnType(), c);
int width = c.types().slots(signature.returnType());
int group = save(1 + width, expression.span(), c);
var success = c.nextLabel("handle_success"); var end = c.nextLabel("handle_end");
emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c);
emitBinaryOperatorInstruction("==", expression.span(), c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c);
for (var arm : expression.arms()) {
var next = c.nextLabel("handle_next");
if (arm.pattern() instanceof PbsAst.ErrorPathHandlePattern pattern) {
emitGetLocal(group, arm.span(), c); emitPushI32(c.types().errorCode(pattern.path()), arm.span(), c);
emitBinaryOperatorInstruction("==", arm.span(), c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, next, arm.span(), c);
}
var scope = c.snapshotScope();
if (arm.block() != null) for (var statement : arm.block().statements()) lowerStatement(statement, c);
var terminal = arm.block() == null ? null : arm.block().tailExpression();
while (terminal instanceof PbsAst.GroupExpr g) terminal = g.expression();
var error = arm.remapTarget() != null ? arm.remapTarget() : terminal instanceof PbsAst.ErrExpr e ? e.errorPath() : null;
if (error != null) {
clearPendingStack(arm.span(), c); emitResultError(error, arm.span(), c);
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, arm.span()));
} else if (terminal instanceof PbsAst.OkExpr ok) {
lowerExpected(ok.value(), signature.returnType(), c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP, end, arm.span(), c);
}
c.restoreScope(scope); emitLabel(next, arm.span(), c);
}
// Static semantics proves exhaustiveness. An invalid code cannot become a payload.
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP, "", null, null, expression.span()));
emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c);
emitLabel(end, expression.span(), c);
}
private void emitDefault(IRRegistry.TypeRef type, int width, Span span, PbsExecutableLoweringContext c) {
var holder = c.types().holder(type);
registry(STRUCT_NEW,holder,0,0,1,span,c);
@@ -1899,7 +2014,11 @@ final class PbsExecutableBodyLowerer {
return hasElseBranch(stmt)&&yes&&no;
}
private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) {
var declaration=c.types().structs.get(expr.typeName());var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName()));
var declaration=c.types().structs.get(expr.typeName());
if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaration) && !c.types().allowedFactoryOrigins.contains(declaration.span())) {
reportUnsupportedLowering("Stdlib construction requires its canonical declaring module", expr.span(), c); return;
}
var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName()));
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(declaration)) {
if (expr.arguments().size()!=1 || expr.ctorName()!=null && !expr.ctorName().equals("make")) {
reportUnsupportedLowering("MemcardBuffer requires one int capacity",expr.span(),c);
@@ -1975,7 +2094,7 @@ final class PbsExecutableBodyLowerer {
pops += c.types().slots(type);
}
emitStructuredFunction(name.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
method.returnType(),pops,c.types().slots(method.returnType()),call.span(),c);
method.returnType(),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);
return true;
}
if(!(call.callee() instanceof PbsAst.MemberExpr member))return false;
@@ -1994,7 +2113,7 @@ final class PbsExecutableBodyLowerer {
int pops=2;
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
emitLoadLocalSlots(receiverView, 2, member.receiver().span(), c);
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().slots(method.returnType()),call.span(),c);return true;
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
}
var service=c.types().services.get(owner.name());
if(service!=null) {
@@ -2010,7 +2129,7 @@ final class PbsExecutableBodyLowerer {
emitHostForward(method,call,pops,c);
return true;
}
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
}
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(struct) && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
@@ -2018,7 +2137,7 @@ final class PbsExecutableBodyLowerer {
if(method==null)return false;
lowerExpected(member.receiver(),owner,c);int pops=1;
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());if(listIndex&&i==0)lowerArrayIndex(call.arguments().get(i),c);else lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
emitStructuredFunction(owner.name()+"."+method.name(),receiverParameters(owner.name(),method.parameters()),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
emitStructuredFunction(owner.name()+"."+method.name(),receiverParameters(owner.name(),method.parameters()),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
}
private java.util.List<PbsAst.TypeRef> receiverParameters(String owner, ReadOnlyList<PbsAst.Parameter> parameters) {
var types = new java.util.ArrayList<PbsAst.TypeRef>();
@@ -2102,7 +2221,12 @@ final class PbsExecutableBodyLowerer {
private void emitStructuredFunction(String name, java.util.List<PbsAst.TypeRef> parameters, PbsAst.TypeRef returnType,
int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
var callableId = c.exactLocalCallable(name, parameters, returnType);
emitStructuredFunction(name, parameters, returnType, PbsAst.ReturnKind.PLAIN, null, pops, pushes, span, c);
}
private void emitStructuredFunction(String name, java.util.List<PbsAst.TypeRef> parameters, PbsAst.TypeRef returnType,
PbsAst.ReturnKind kind, PbsAst.TypeRef errorType, int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
var callableId = c.exactLocalCallable(name, parameters, returnType, kind, errorType);
if (callableId == null) {
reportUnsupportedLowering("Structured call requires exact overload: " + name, span, c);
return;
@@ -27,6 +27,8 @@ final class PbsExecutableLoweringContext {
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
PbsExecutableCallableRegistry callableRegistry() { return callableRegistry; }
PbsRuntimeTypes types() { return metadataIndex.types(); }
p.studio.compiler.pbs.ast.PbsAst.ReturnKind returnKind;
p.studio.compiler.pbs.ast.PbsAst.TypeRef resultErrorType;
String serviceOwner;
private int nextLabelId = 0;
private int nextLocalSlot;
@@ -97,10 +99,20 @@ final class PbsExecutableLoweringContext {
p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name,
java.util.List<p.studio.compiler.pbs.ast.PbsAst.TypeRef> parameterTypes,
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType) {
return exactLocalCallable(name, parameterTypes, returnType, p.studio.compiler.pbs.ast.PbsAst.ReturnKind.PLAIN, null);
}
p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name,
java.util.List<p.studio.compiler.pbs.ast.PbsAst.TypeRef> parameterTypes,
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType,
p.studio.compiler.pbs.ast.PbsAst.ReturnKind kind,
p.studio.compiler.pbs.ast.PbsAst.TypeRef errorType) {
for (var callable : callableRegistry.localCallables()) {
var parameters = callable.functionDecl().parameters();
if (!callable.callableName().equals(name) || parameters.size() != parameterTypes.size()) continue;
boolean matches = true;
boolean matches = (callable.functionDecl().returnKind() == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
== (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
&& types().key(callable.functionDecl().resultErrorType()).equals(types().key(errorType));
for (int i = 0; i < parameters.size(); i++)
matches &= types().key(parameters.get(i).typeRef()).equals(types().key(parameterTypes.get(i)));
matches &= types().shapeKey(callable.functionDecl().returnType()).equals(types().shapeKey(returnType));
@@ -111,10 +123,13 @@ final class PbsExecutableLoweringContext {
.collect(java.util.stream.Collectors.joining(",")) + ")->";
var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT
? "unit" : formatter.typeSurfaceKey(returnType);
if (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
output = "result<" + formatter.typeSurfaceKey(errorType) + ">" + formatter.typeSurfaceKey(returnType);
final var expectedOutput = output;
var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of());
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size()
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList();
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + expectedOutput))).toList();
if (candidates.size() == 1) return candidates.getFirst().getKey();
return null;
}
@@ -49,12 +49,12 @@ public final class PbsExecutableLoweringService {
importedCallables, metadataIndex.types());
for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) {
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), metadataIndex.types().returnSlots(signature.returnKind(), signature.returnType()));
}
for (var callable : callableRegistry.localCallables()) {
var f=callable.functionDecl();
callableRegistry.returnSlotsByCallableId().put(callableRegistry.callableIdByDeclaration().get(callable),
f.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(f.returnType()) : 0);
metadataIndex.types().returnSlots(f.returnKind(), f.returnType()));
metadataIndex.types().signatures.put(callable.callableName()+"#"+f.parameters().size(),
new PbsAst.FunctionSignature(f.name(),f.parameters(),f.returnKind(),f.returnType(),f.resultErrorType(),f.attributes(),f.span()));
}
@@ -65,6 +65,8 @@ public final class PbsExecutableLoweringService {
var candidates = callableRegistry.localCallables().stream().filter(callable ->
callable.callableName().equals(metadataIndex.types().implementationCallableName(implementation, signature.name()))
&& callable.functionDecl().parameters().size()==signature.parameters().size()+1
&& callable.functionDecl().returnKind() == signature.returnKind()
&& metadataIndex.types().key(callable.functionDecl().resultErrorType()).equals(metadataIndex.types().key(signature.resultErrorType()))
&& metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType()))
&& java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i ->
metadataIndex.types().key(callable.functionDecl().parameters().get(i+1).typeRef()).equals(
@@ -151,7 +153,7 @@ public final class PbsExecutableLoweringService {
safeToInt(functionDecl.span().getEnd()),
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum(),
loweredBody.localSlots(),
functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(functionDecl.returnType()) : 0,
metadataIndex.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType()),
loweredBody.maxStackSlots(),
loweredBody.instructions(),
functionDecl.span(),
@@ -10,8 +10,17 @@ final class PbsExecutableStackAnalyzer {
int analyzeMaxStackSlots(
final ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions,
final int returnSlots) {
return analyze(instructions, returnSlots, false)[0];
}
int pendingStackSlots(ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions) {
return analyze(instructions, 0, true)[1];
}
private int[] analyze(ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions,
int returnSlots, boolean prefix) {
if (instructions.isEmpty()) {
return Math.max(1, returnSlots);
return new int[]{Math.max(1, returnSlots), 0};
}
final var labelToIndex = new HashMap<String, Integer>();
@@ -31,6 +40,7 @@ final class PbsExecutableStackAnalyzer {
worklist.add(0);
var maxHeight = 0;
var tailHeight = 0;
while (!worklist.isEmpty()) {
final var index = worklist.removeFirst();
visited.add(index);
@@ -43,7 +53,7 @@ final class PbsExecutableStackAnalyzer {
case POP, SET_LOCAL, SET_GLOBAL -> {
if (outHeight <= 0) {
throw new ExecutableLoweringAnalysisException(
"stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight);
"stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight);
}
outHeight -= 1;
}
@@ -57,7 +67,7 @@ final class PbsExecutableStackAnalyzer {
case NOT, NEG -> {
if (outHeight <= 0) {
throw new ExecutableLoweringAnalysisException(
"stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight);
"stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight);
}
}
case REGISTRY, CALL_FUNC -> {
@@ -110,17 +120,18 @@ final class PbsExecutableStackAnalyzer {
|| instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE) {
final var targetIndex = labelToIndex.get(instruction.targetLabel());
if (targetIndex == null) {
throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel());
if (!prefix) throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel());
}
successors.add(targetIndex);
if (targetIndex != null) successors.add(targetIndex);
if (instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP) {
mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight);
if (targetIndex != null) mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight);
continue;
}
}
final var nextIndex = index + 1;
if (nextIndex >= instructions.size()) {
if (prefix) { tailHeight = outHeight; continue; }
throw new ExecutableLoweringAnalysisException("reachable path ends without terminal instruction");
}
successors.add(nextIndex);
@@ -129,10 +140,10 @@ final class PbsExecutableStackAnalyzer {
}
}
if (!visited.contains(instructions.size() - 1)) {
if (!prefix && !visited.contains(instructions.size() - 1)) {
throw new ExecutableLoweringAnalysisException("entrypoint does not reach function tail");
}
return Math.max(1, Math.max(maxHeight, returnSlots));
return new int[]{Math.max(1, Math.max(maxHeight, returnSlots)), tailHeight};
}
private void mergeIncomingHeights(
@@ -14,12 +14,14 @@ final class PbsRuntimeTypes {
final Map<String, String> builtinNames;
final Map<String, String> aliases = new HashMap<>();
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
final Map<String, PbsAst.ErrorDecl> errors = new LinkedHashMap<>();
final Map<String, PbsAst.EnumDecl> enums = new HashMap<>();
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
final Map<String, List<PbsAst.FunctionDecl>> functions = new HashMap<>();
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
final Map<String, PbsAst.ConstDecl> constants = new HashMap<>();
private final Map<String, IRRegistry.TypeDeclaration> used = new TreeMap<>();
final Set<Span> allowedFactoryOrigins = new HashSet<>();
final Map<String, PbsAst.StructDecl> structs = new LinkedHashMap<>();
final Map<String, PbsAst.ContractDecl> contracts = new LinkedHashMap<>();
final p.studio.compiler.pbs.PbsContractTypes contractTypes;
@@ -29,6 +31,8 @@ final class PbsRuntimeTypes {
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
builtinNames = builtins;
ast.topDecls().forEach(d -> allowedFactoryOrigins.add(d.span()));
supplemental.forEach(d -> { if (d instanceof PbsAst.TypeBindingDecl b && b.sameModule() && b.span().getFileId().equals(ast.span().getFileId())) allowedFactoryOrigins.add(b.declaration().span()); });
contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplemental, p.studio.compiler.source.diagnostics.DiagnosticSink.empty());
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation)
implementations.add(implementation);
@@ -43,6 +47,7 @@ final class PbsRuntimeTypes {
if (decl instanceof PbsAst.ContractDecl c) contracts.put(c.name(), c);
if (decl instanceof PbsAst.ServiceDecl s) services.put(s.name(), s);
if (decl instanceof PbsAst.EnumDecl e) enums.put(e.name(), e);
if (decl instanceof PbsAst.ErrorDecl e) errors.put(e.name(), e);
if (decl instanceof PbsAst.ConstDecl c) values.put(c.name(), c.explicitType());
if (decl instanceof PbsAst.GlobalDecl g) values.put(g.name(), g.explicitType());
if (decl instanceof PbsAst.FunctionDecl f) {
@@ -119,6 +124,7 @@ final class PbsRuntimeTypes {
if (origin != null) return nominal + ":" + origin.key();
return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t);
}
if (contractTypes.declaration(t) instanceof PbsAst.ErrorDecl error) return nominalKey("error", error.span());
return canonical(t);
}
String shapeKey(PbsAst.TypeRef type) {
@@ -206,7 +212,7 @@ final class PbsRuntimeTypes {
for (var method : contract(t).signatures()) {
var args = new ArrayList<IRRegistry.NamedType>();
for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name()));
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType())))));
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(returnTypes(method.returnKind(), method.returnType())))));
}
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
}
@@ -227,6 +233,27 @@ final class PbsRuntimeTypes {
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().flatMap(f->results(f.typeRef()).stream()).toList();
return List.of(registryType(t));
}
int returnSlots(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) {
return switch (kind) {
case RESULT -> 1 + slots(payload);
case PLAIN -> slots(payload);
default -> 0;
};
}
List<IRRegistry.TypeRef> returnTypes(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) {
if (kind == PbsAst.ReturnKind.PLAIN) return results(payload);
if (kind != PbsAst.ReturnKind.RESULT) return List.of();
var group = new ArrayList<IRRegistry.TypeRef>();
group.add(builtin(0x10)); group.addAll(results(payload)); return List.copyOf(group);
}
int errorCode(PbsAst.ErrorPath path) {
var resolved=contractTypes.declaration(PbsAst.TypeRef.simple(path.segments().getFirst(),path.span()));
var declaration=resolved instanceof PbsAst.ErrorDecl error?error:errors.get(aliases.getOrDefault(path.segments().getFirst(),path.segments().getFirst()));
if (declaration == null) throw new IllegalStateException("Missing canonical error declaration: " + path);
int index = declaration.cases().asList().indexOf(path.segments().getLast());
if (index < 0) throw new IllegalStateException("Missing error case: " + path);
return index + 1;
}
IRRegistry.FunctionMetadata metadata(PbsAst.FunctionDecl f) {
// Preserve the pre-existing unsupported executable boundary for types outside this port.
// The common backend still rejects missing typed metadata; never infer a carrier by width.
@@ -235,7 +262,7 @@ final class PbsRuntimeTypes {
private IRRegistry.FunctionMetadata supportedMetadata(PbsAst.FunctionDecl f) {
var params=new ArrayList<IRRegistry.NamedType>();
for(var p:f.parameters()) for(var type:results(p.typeRef())) params.add(new IRRegistry.NamedType(type,p.name()));
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
var returns=returnTypes(f.returnKind(), f.returnType());
var captures = capturesByFunction.getOrDefault(f.name(), List.of()).stream().flatMap(c -> results(c.typeRef()).stream()).toList();
return new IRRegistry.FunctionMetadata(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)),
ReadOnlyList.wrap(captures), switch (f.lifecycleMarker()) {
@@ -696,7 +696,7 @@ final class PbsDeclarationParser {
final String targetSurface) {
for (final var attribute : attributes) {
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer", "StdlibFactoryOnly").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
continue;
}
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
@@ -1483,6 +1483,7 @@ public final class PbsEditorialSupportService {
}
private List<PbsEditorialSignature> constructorSignaturesForTopDecl(final PbsAst.TopDecl topDecl) {
if (!p.studio.compiler.pbs.PbsStdlibConstruction.allowed(topDecl, ast, editorialSupplementalTopDecls)) return List.of();
if (topDecl instanceof PbsAst.StructDecl structDecl) {
if (structDecl.ctors().isEmpty()) {
return List.of(new PbsEditorialSignature(structDecl.name(), structDecl.name() + "()", List.of(), "unit"));
@@ -217,6 +217,7 @@ final class PbsFlowSemanticSupport {
return declaration instanceof PbsAst.StructDecl owner && owner.methods().stream()
.anyMatch(m -> m.name().equals(member) && p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(), "SdkPrivate") != null);
}
final Set<p.studio.compiler.source.Span> allowedFactoryOrigins = new HashSet<>();
final Map<String, List<CallableSymbol>> topLevelCallables = new HashMap<>();
final Map<String, StructInfo> structs = new HashMap<>();
final Map<String, ServiceInfo> services = new HashMap<>();
@@ -248,6 +249,9 @@ final class PbsFlowSemanticSupport {
final var model = new Model();
model.contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplementalTopDecls, diagnostics);
model.contractTypes.validate(ast);
for (var declaration : ast.topDecls()) model.allowedFactoryOrigins.add(declaration.span());
for (var declaration : supplementalTopDecls) if (declaration instanceof PbsAst.TypeBindingDecl binding && binding.sameModule() && binding.span().getFileId().equals(ast.span().getFileId()))
model.allowedFactoryOrigins.add(binding.declaration().span());
for (final var topDecl : ast.topDecls()) {
model.registerKnownTopDecl(topDecl);
}
@@ -230,6 +230,13 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(TypeView.optional(payloadExpected == null ? payload : payloadExpected));
}
if (expression instanceof PbsAst.NewExpr newExpr) {
var declaredType = model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span()));
if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaredType)
&& !model.allowedFactoryOrigins.contains(declaredType.span())) {
Diagnostics.error(diagnostics, "E_SEM_STDLIB_FACTORY_ONLY",
"Construct this stdlib type through its public factory", newExpr.span());
return ExprResult.type(TypeView.unknown());
}
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span())))) {
if (newExpr.arguments().size() != 1 || newExpr.ctorName() != null && !newExpr.ctorName().equals("make")) {
Diagnostics.error(diagnostics, "E_SEM_MEMCARD_BUFFER_CONSTRUCTOR",
@@ -0,0 +1,52 @@
package p.studio.compiler.services;
import p.animation.*;
import java.nio.file.Path;
import java.nio.charset.StandardCharsets;
import java.util.*;
/** PBS-only deterministic projection; canonical persistence remains the JSON sidecar. */
public final class PbsAnimationProjection {
public static final String VERSION="1";
public record Generated(String moduleName,Path path,String source,String barrel,String revision,List<FrontendSourceDocument.OriginSpan> origins) {
public Generated { origins=List.copyOf(origins); }
}
public static Generated generate(AnimationSource source) {
var text=new StringBuilder("import { Animator, AnimationError, PlaybackMode, animator_builder } from @core:animation;\n\n");
var barrel=new StringBuilder();var origins=new ArrayList<FrontendSourceDocument.OriginSpan>();
var binding=new HashMap<String,AnimationDocument.Binding>();source.document().bindings().forEach(b->binding.put(b.artifactId(),b));
var definitions=new ArrayList<>(source.document().animators());definitions.sort(Comparator.comparing(AnimationDocument.Animator::id));
for(var animator:definitions) {
int index=source.document().animators().indexOf(animator);String pointer="/animators/"+index;
String name="create_"+animator.id();String signature=name+"(bank_id: int) -> result<AnimationError> Animator";
barrel.append("pub fn ").append(signature).append(";\n");
int begin=bytes(text);text.append("fn ").append(signature).append(" {\n");
origins.add(new FrontendSourceDocument.OriginSpan(begin,bytes(text),source.definitionPath(),pointer+"/id",source.bank().assetUuid().toString()));
line(text,origins,source.definitionPath(),pointer+"/initial_clip"," let builder = animator_builder(bank_id, "+quote(animator.initialClip())+")!;\n");
for(int c=0;c<animator.clips().size();c++) {
var clip=animator.clips().get(c);String cp=pointer+"/clips/"+c;
line(text,origins,source.definitionPath(),cp," builder.begin_clip("+quote(clip.name())+", PlaybackMode."+(clip.mode().equals("once")?"Once":"Loop")+")!;\n");
for(int f=0;f<clip.frames().size();f++){
var frame=clip.frames().get(f);var glyph=binding.get(frame.artifactId());
if(glyph==null)throw new IllegalArgumentException("Unvalidated animation frame");
line(text,origins,source.definitionPath(),cp+"/frames/"+f," builder.add_frame("+glyph.glyphId()+", "+frame.durationTicks()+")!;\n");
}
text.append(" builder.end_clip()!;\n");
}
text.append(" return ok(builder.build()!);\n}\n\n");
}
String revision=AnimationRevision.of(VERSION+"\n"+source.documentRevision()+"\n"+source.bank().revision()+"\n"+text);
String module="b_"+source.bank().assetUuid().toString().replace("-","");
var path=Path.of("/virtual/generated/animations").resolve(source.projectName()).resolve(module).resolve(revision).resolve("main.pbs");
return new Generated(module,path,text.toString(),barrel.toString(),revision,origins.stream().map(o->new FrontendSourceDocument.OriginSpan(o.startOffset(),o.endOffset(),o.definitionPath(),o.jsonPointer(),source.bank().assetUuid().toString())).toList());
}
private static int bytes(StringBuilder s){return s.toString().getBytes(StandardCharsets.UTF_8).length;}
private static void line(StringBuilder out,List<FrontendSourceDocument.OriginSpan> spans,Path path,String pointer,String line){int start=bytes(out);out.append(line);spans.add(new FrontendSourceDocument.OriginSpan(start,bytes(out),path,pointer));}
public static String quote(String value){
var out=new StringBuilder("\"");
for(int i=0;i<value.length();i++){char c=value.charAt(i);switch(c){
case '\\'->out.append("\\\\");case '"'->out.append("\\\"");case '\n'->out.append("\\n");case '\r'->out.append("\\r");case '\t'->out.append("\\t");
default->out.append(c);
}}return out.append('"').toString();
}
}
@@ -84,7 +84,7 @@ final class PbsImportedSemanticContextService {
if (sibling.fileId().equals(parsedSource.fileId())) continue;
for (var declaration : sibling.ast().topDecls()) {
if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys);
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span(), true), supplementalTopDecls, supplementalKeys);
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
}
}
@@ -228,6 +228,37 @@ final class PbsImportedSemanticContextService {
ReadOnlyList.wrap(declarations), context.importedCallables(), context.importedGlobals(), context.importedReservedMetadata()));
}
} while (changed);
// Factories expose usable concrete values even when callers do not import the
// return type explicitly. Preserve the declaring module for all such methods.
for(var source:parsedSourceFiles) {
var context=contexts.get(source.fileId());
var declarations=new ArrayList<>(context.supplementalTopDecls().asList());
var declarationKeys=new HashSet<String>();declarations.forEach(d->declarationKeys.add(topDeclKey(d)));
var callables=new ArrayList<>(context.importedCallables().asList());var callableKeys=new HashSet<String>();
callables.forEach(c->callableKeys.add(c.moduleId().getIndex()+"#"+c.callableName()+"#"+c.arity()+"#"+c.shapeSurface()));
for(int index=0;index<declarations.size();index++) {
var bound=declarations.get(index);
var declaration=bound instanceof PbsAst.TypeBindingDecl binding?binding.declaration():bound;
if(!(declaration instanceof PbsAst.StructDecl struct)||struct.span().getFileId().equals(source.fileId()))continue;
var definingModule=moduleBySource.get(struct.span().getFileId());if(definingModule==null)continue;
String local=bound instanceof PbsAst.TypeBindingDecl binding?binding.name():struct.name();
var methods=new ArrayList<>(struct.methods().asList());
for(var ctor:struct.ctors())methods.add(new PbsAst.FunctionDecl("$ctor."+ctor.name(),ctor.parameters(),PbsAst.ReturnKind.EXPLICIT_UNIT,
PbsAst.TypeRef.unit(ctor.span()),null,ReadOnlyList.empty(),PbsAst.LifecycleMarker.NONE,ctor.body(),ctor.span()));
for(var method:methods) {
var executable=p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.withReceiver(method,struct.name(),"this");
appendImportedCallable(callables,callableKeys,new PbsFrontendCompiler.ImportedCallableSurface(definingModule,local+"."+method.name(),
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
frontendCompiler.callableShapeSurfaceOf(executable),struct.name()+"."+method.name()));
}
for(var provider:sourcesByModule.getOrDefault(definingModule,new ArrayList<>()))for(var member:provider.ast().topDecls())
if(member instanceof PbsAst.ImplementsDecl implementation&&implementation.ownerName().equals(struct.name())) {
appendSupplementalTopDecl(implementation,declarations,declarationKeys);
appendTypeDependencyDecls(implementation,topDeclsByNameByModule.getOrDefault(definingModule,Map.of()),declarations,declarationKeys);
}
}
contexts.put(source.fileId(),new PbsImportedSemanticContext(ReadOnlyList.wrap(declarations),ReadOnlyList.wrap(callables),context.importedGlobals(),context.importedReservedMetadata()));
}
return contexts;
}
@@ -72,6 +72,7 @@ final class PbsModuleAssemblyService {
for (final var fileId : fileIds) {
final var sourceHandle = ctx.fileTable.get(fileId);
if(sourceHandle.getRelativePath().startsWith("@generated"))continue;
sourceHandle.readUtf8().ifPresentOrElse(
utf8Content -> consumeSourceFile(
projectDescriptor,
@@ -91,6 +92,9 @@ final class PbsModuleAssemblyService {
}
}
loadAnimationModules(ctx, writableFileTable, projectIdByName, modulesByCoordinates,
parsedSourceFiles, moduleIdByFile, moduleTable, failedModuleIds, diagnostics);
loadReservedStdlibModules(
modulesByCoordinates,
parsedSourceFiles,
@@ -199,6 +203,37 @@ final class PbsModuleAssemblyService {
}
}
private void loadAnimationModules(FrontendPhaseContext ctx, FileTable files,
Map<String,ProjectId> owners, Map<PbsModuleVisibilityValidator.ModuleCoordinates,MutableModuleUnit> modules,
ArrayList<PbsParsedSourceFile> parsed, Map<FileId,ModuleId> moduleByFile, ModuleTable table,
Set<ModuleId> failed, DiagnosticSink diagnostics) {
for(var entry:modules.entrySet()) {
var path=entry.getKey().pathSegments();
if(path.size()>=2&&path.get(0).equals("generated")&&path.get(1).equals("animations")) {
var span=entry.getValue().sources.isEmpty()?Span.none():entry.getValue().sources.getFirst().ast().span();
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,"E_LINK_GENERATED_COLLISION",
"generated/animations is reserved for read-only animation projection",span);
failed.add(moduleId(table,entry.getKey()));
}
}
for(var source:ctx.feSurfaceContext().animations()) {
var owner=owners.get(source.projectName());if(owner==null)continue;
var generated=PbsAnimationProjection.generate(source);
var coordinates=new PbsModuleVisibilityValidator.ModuleCoordinates(source.projectName(),ReadOnlyList.from("generated","animations",generated.moduleName()));
if(modules.containsKey(coordinates))continue;
var unit=new MutableModuleUnit();var module=moduleId(table,coordinates);
byte[] utf8=generated.source().getBytes(StandardCharsets.UTF_8);
var file=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("main.pbs"),generated.path(),utf8.length,0,ignored->()->utf8));
var ast=parseSourceFile(file,generated.source(),diagnostics,SourceKind.PROJECT);
unit.sources.add(new PbsModuleVisibilityValidator.SourceFile(file,ast));moduleByFile.put(file,module);
parsed.add(new PbsParsedSourceFile(file,ast,module,SourceKind.PROJECT));
byte[] barrel=generated.barrel().getBytes(StandardCharsets.UTF_8);
var barrelId=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("mod.barrel"),generated.path().resolveSibling("mod.barrel"),barrel.length,0,ignored->()->barrel));
unit.barrels.add(new PbsModuleVisibilityValidator.BarrelFile(barrelId,parseBarrelFile(barrelId,generated.barrel(),diagnostics)));
moduleByFile.put(barrelId,module);modules.put(coordinates,unit);
}
}
private void loadReservedStdlibModules(
final Map<PbsModuleVisibilityValidator.ModuleCoordinates, MutableModuleUnit> modulesByCoordinates,
final ArrayList<PbsParsedSourceFile> parsedSourceFiles,
@@ -0,0 +1,199 @@
import { SpriteView } from @core:sprite;
declare enum PlaybackMode(Once = 0, Loop = 1);
declare enum PlaybackState(Stopped = 0, Playing = 1, Paused = 2, Finished = 3);
declare error AnimationError {
invalid_bank; invalid_name; duplicate_clip; clip_already_open; no_open_clip;
empty_clip; unfinished_clip; empty_animator; initial_clip_missing; unknown_clip;
invalid_glyph; invalid_duration; invalid_ticks; index_out_of_range;
limit_exceeded; overflow;
}
// Module-private nodes never appear in the public barrel or API. Published frame
// rings are immutable. Direct links avoid array/optional wrappers while advancing.
declare struct _AnimationFrame(pub glyph: int, pub duration: long, pub end: long, pub mut next: _AnimationFrame) {
ctor make(glyph: int, duration: long, end: long) {
this.glyph = glyph; this.duration = duration; this.end = end; this.next = this;
}
}
declare struct _AnimationClip(pub name: str, pub mode: PlaybackMode,
pub mut head: _AnimationFrame, pub mut tail: _AnimationFrame,
pub mut count: long, pub mut total: long, pub mut next: _AnimationClip) {
ctor make(name: str, mode: PlaybackMode) {
let empty = new _AnimationFrame.make(0, 0, 0);
this.name = name; this.mode = mode; this.head = empty; this.tail = empty;
this.count = 0; this.total = 0; this.next = this;
}
}
[StdlibFactoryOnly]
declare struct Animator(bank: int, first: _AnimationClip, selected: _AnimationClip,
cursor: _AnimationFrame, phase: long, playback: PlaybackState, count: long) {
fn sprite() -> (bank_id: int, glyph_id: int) { return (bank_id: this.bank, glyph_id: this.cursor.glyph); }
fn state() -> PlaybackState { return this.playback; }
fn active_clip() -> str { return this.selected.name; }
fn clip_count() -> long { return this.count; }
fn frame_count(name: str) -> result<AnimationError> long {
if name == "" { return err(AnimationError.invalid_name); }
let clip = this.first; let index: long = 0;
while index < this.count {
if clip.name == name { return ok(clip.count); }
clip = clip.next; index = index + 1;
}
return err(AnimationError.unknown_clip);
}
fn frame_at(name: str, index: long) -> result<AnimationError> (glyph_id: int, duration_ticks: long) {
if name == "" { return err(AnimationError.invalid_name); }
let clip = this.first; let ordinal: long = 0;
while ordinal < this.count {
if clip.name == name {
if index < (0 as long) || index >= clip.count { return err(AnimationError.index_out_of_range); }
let frame = clip.head; let offset: long = 0;
while offset < index { frame = frame.next; offset = offset + 1; }
return ok((glyph_id: frame.glyph, duration_ticks: frame.duration));
}
clip = clip.next; ordinal = ordinal + 1;
}
return err(AnimationError.unknown_clip);
}
fn select(name: str) -> result<AnimationError> {
if name == "" { return err(AnimationError.invalid_name); }
let clip = this.first; let index: long = 0;
while index < this.count {
if clip.name == name {
this.selected = clip; this.cursor = clip.head; this.phase = 0;
this.playback = PlaybackState.Stopped; return ok(());
}
clip = clip.next; index = index + 1;
}
return err(AnimationError.unknown_clip);
}
fn play(name: str) -> result<AnimationError> { this.select(name)!; this.playback = PlaybackState.Playing; return ok(()); }
fn pause() { if this.playback == PlaybackState.Playing { this.playback = PlaybackState.Paused; } }
fn resume() { if this.playback == PlaybackState.Paused { this.playback = PlaybackState.Playing; } }
fn stop() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Stopped; }
fn restart() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Playing; }
fn advance(ticks: int) -> result<AnimationError> {
if ticks < 0 { return err(AnimationError.invalid_ticks); }
if ticks == 0 || this.playback != PlaybackState.Playing { return ok(()); }
let delta: long = ticks as long; let maximum: long = 9223372036854775807;
if this.phase > maximum - delta { return err(AnimationError.overflow); }
let nextPhase: long = this.phase + delta;
let nextState = this.playback; let nextFrame = this.selected.head;
if this.selected.mode == PlaybackMode.Loop { nextPhase = nextPhase % this.selected.total; }
else {
if nextPhase >= this.selected.total {
nextPhase = this.selected.total; nextState = PlaybackState.Finished;
nextFrame = this.selected.tail;
}
}
if nextState != PlaybackState.Finished {
while nextPhase >= nextFrame.end { nextFrame = nextFrame.next; }
}
this.phase = nextPhase; this.cursor = nextFrame; this.playback = nextState;
return ok(());
}
}
implements SpriteView for Animator using value {
fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); }
}
[StdlibFactoryOnly]
declare struct AnimatorBuilder(bank: int, initial: str, first: _AnimationClip,
last: _AnimationClip, draft: _AnimationClip, count: long, open: bool) {
fn begin_clip(name: str, mode: PlaybackMode) -> result<AnimationError> {
if this.open { return err(AnimationError.clip_already_open); }
if name == "" { return err(AnimationError.invalid_name); }
let clip = this.first; let index: long = 0;
while index < this.count {
if clip.name == name { return err(AnimationError.duplicate_clip); }
clip = clip.next; index = index + 1;
}
let maximum: long = 4294967295;
if this.count == maximum { return err(AnimationError.limit_exceeded); }
let candidate = new _AnimationClip.make(name, mode);
this.draft = candidate; this.open = true; return ok(());
}
fn add_frame(glyph_id: int, duration_ticks: long) -> result<AnimationError> {
if !this.open { return err(AnimationError.no_open_clip); }
if glyph_id < 0 || glyph_id > 65535 { return err(AnimationError.invalid_glyph); }
if duration_ticks <= (0 as long) { return err(AnimationError.invalid_duration); }
let countMaximum: long = 4294967295; let durationMaximum: long = 9223372036854775807;
if this.draft.count == countMaximum { return err(AnimationError.limit_exceeded); }
if this.draft.total > durationMaximum - duration_ticks { return err(AnimationError.overflow); }
let total: long = this.draft.total + duration_ticks;
let candidate = new _AnimationFrame.make(glyph_id, duration_ticks, total);
if this.draft.count == (0 as long) { this.draft.head = candidate; }
else { this.draft.tail.next = candidate; }
candidate.next = this.draft.head;
this.draft.tail = candidate; this.draft.count = this.draft.count + 1; this.draft.total = total;
return ok(());
}
fn end_clip() -> result<AnimationError> {
if !this.open { return err(AnimationError.no_open_clip); }
if this.draft.count == (0 as long) { return err(AnimationError.empty_clip); }
if this.count == (0 as long) { this.first = this.draft; }
else { this.last.next = this.draft; }
this.draft.next = this.first; this.last = this.draft;
this.count = this.count + 1; this.open = false; return ok(());
}
fn discard_clip() -> result<AnimationError> {
if !this.open { return err(AnimationError.no_open_clip); }
this.open = false; return ok(());
}
fn remove_clip(name: str) -> result<AnimationError> {
if this.open { return err(AnimationError.unfinished_clip); }
if name == "" { return err(AnimationError.invalid_name); }
let previous = this.last; let clip = this.first; let index: long = 0;
while index < this.count {
if clip.name == name {
if this.count > (1 as long) {
previous.next = clip.next;
if index == (0 as long) { this.first = clip.next; }
if index == this.count - (1 as long) { this.last = previous; }
}
this.count = this.count - 1; return ok(());
}
previous = clip; clip = clip.next; index = index + 1;
}
return err(AnimationError.unknown_clip);
}
fn build() -> result<AnimationError> Animator {
if this.open { return err(AnimationError.unfinished_clip); }
if this.count == (0 as long) { return err(AnimationError.empty_animator); }
let source = this.first; let index: long = 0; let found = false;
while index < this.count {
if source.name == this.initial { found = true; }
source = source.next; index = index + 1;
}
if !found { return err(AnimationError.initial_clip_missing); }
// No domain errors remain. Copy every mutable node before publishing.
let first = new _AnimationClip.make("", PlaybackMode.Once); let last = first; let selected = first;
source = this.first; index = 0;
while index < this.count {
let copy = new _AnimationClip.make(source.name, source.mode);
let frame = source.head; let ordinal: long = 0;
while ordinal < source.count {
let fresh = new _AnimationFrame.make(frame.glyph, frame.duration, frame.end);
if ordinal == (0 as long) { copy.head = fresh; }
else { copy.tail.next = fresh; }
fresh.next = copy.head; copy.tail = fresh;
frame = frame.next; ordinal = ordinal + 1;
}
copy.count = source.count; copy.total = source.total;
if index == (0 as long) { first = copy; }
else { last.next = copy; }
copy.next = first; last = copy;
if source.name == this.initial { selected = copy; }
source = source.next; index = index + 1;
}
return ok(new Animator(this.bank, first, selected, selected.head, 0, PlaybackState.Stopped, this.count));
}
}
fn animator_builder(bank_id: int, initial_clip: str) -> result<AnimationError> AnimatorBuilder {
if bank_id < 0 || bank_id > 255 { return err(AnimationError.invalid_bank); }
if initial_clip == "" { return err(AnimationError.invalid_name); }
let empty = new _AnimationClip.make("", PlaybackMode.Once);
return ok(new AnimatorBuilder(bank_id, initial_clip, empty, empty, empty, 0, false));
}
@@ -0,0 +1,6 @@
pub struct Animator;
pub struct AnimatorBuilder;
pub enum PlaybackMode;
pub enum PlaybackState;
pub error AnimationError;
pub fn animator_builder(bank_id: int, initial_clip: str) -> result<AnimationError> AnimatorBuilder;
@@ -0,0 +1,24 @@
[Doc(markdown = """
A pure visual query. Bank slots are already loaded by the caller; position and
palette belong to the emission. Querying never advances time or allocates a Sprite.
""")]
declare contract SpriteView { fn sprite() -> (bank_id: int, glyph_id: int); }
declare error SpriteError { invalid_bank; invalid_glyph; }
[StdlibFactoryOnly]
declare struct Sprite(bank_id: int, glyph_id: int) {
fn sprite() -> (bank_id: int, glyph_id: int) {
return (bank_id: this.bank_id, glyph_id: this.glyph_id);
}
}
implements SpriteView for Sprite using value {
fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); }
}
fn make_sprite(bank_id: int, glyph_id: int) -> result<SpriteError> Sprite {
if bank_id < 0 || bank_id > 255 { return err(SpriteError.invalid_bank); }
if glyph_id < 0 || glyph_id > 65535 { return err(SpriteError.invalid_glyph); }
return ok(new Sprite(bank_id, glyph_id));
}
@@ -0,0 +1,4 @@
pub struct Sprite;
pub contract SpriteView;
pub error SpriteError;
pub fn make_sprite(bank_id: int, glyph_id: int) -> result<SpriteError> Sprite;
@@ -19,14 +19,14 @@ declare host LowComposer {
""")]
[Host(module = "composer", name = "bind_scene", version = 1)]
[Capability(name = "composer")]
fn bind_scene(scene_bank_id: int) -> int;
fn bind_scene(scene_bank_id: int) -> long;
[Doc(markdown = """
Unbinds the active scene bank.
""")]
[Host(module = "composer", name = "unbind_scene", version = 1)]
[Capability(name = "composer")]
fn unbind_scene() -> int;
fn unbind_scene() -> long;
[Doc(markdown = """
Emits a sprite command into the active scene.
@@ -53,7 +53,7 @@ declare host LowComposer {
flip_x: bool,
flip_y: bool,
priority: int
) -> int;
) -> long;
}
[Doc(markdown = """
@@ -79,7 +79,7 @@ declare service Composer
""")]
fn bind_scene(scene_bank_id: int) -> int
{
return LowComposer.bind_scene(scene_bank_id);
return LowComposer.bind_scene(scene_bank_id) as int;
}
[Doc(markdown = """
@@ -87,7 +87,7 @@ declare service Composer
""")]
fn unbind_scene() -> int
{
return LowComposer.unbind_scene();
return LowComposer.unbind_scene() as int;
}
[Doc(markdown = """
@@ -115,6 +115,6 @@ declare service Composer
priority: int
) -> int
{
return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority);
return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority) as int;
}
}

Some files were not shown because too many files have changed in this diff Show More