Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c55f34780f | ||
|
|
1ab3886028 | ||
|
|
9a67a25a15 | ||
|
|
0ce43fc399 | ||
|
|
0e7aed40f1 |
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# Collider Authoring Diagnostics - 2026-07-12
|
||||
|
||||
Issue: Gitea #26 (`BS-JD-305`)
|
||||
|
||||
## Outcome
|
||||
|
||||
Collider authoring exposes one consistent health result to the inspector, Collider viewport,
|
||||
Diagnostics panel, and physics placement preflight. Shape changes preserve useful dimensions and
|
||||
remain one typed undo operation.
|
||||
|
||||
## Contract
|
||||
|
||||
- Authored box, sphere, and capsule overlays include actor world scale.
|
||||
- Static mesh colliders show cooked runtime bounds when available.
|
||||
- Green is ready, cyan is a trigger, gray is disabled, amber is warning/stale, and red is invalid
|
||||
or missing.
|
||||
- Invalid dimensions and mesh references block dependent workflows. Missing hydration and
|
||||
colliders over 1,000 meters in world extent are warnings.
|
||||
- Physics placement consumes the same collider-health checks instead of maintaining a separate
|
||||
prerequisite definition.
|
||||
|
||||
## Work
|
||||
|
||||
- [x] Add shared authored/runtime collider diagnostics and focused fixtures.
|
||||
- [x] Add shape/status-aware viewport overlays and selected-collider HUD state.
|
||||
- [x] Add inspector health/repair feedback and dimension-preserving undoable shape switching.
|
||||
- [x] Add scene-wide selectable collider findings to Diagnostics.
|
||||
- [x] Reuse diagnostics in physics placement prerequisites.
|
||||
- [x] Add a committed non-blocking showcase scene and update documentation.
|
||||
- [x] Run source gates and live Wayland acceptance; packaged tests remain skipped by request.
|
||||
- [x] Commit, push, attach native Gitea evidence, close #26, and close M3 when empty.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Operator Invariants Completion
|
||||
|
||||
Working plan for Gitea
|
||||
[`#33`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33).
|
||||
|
||||
## Status
|
||||
|
||||
Implementation complete. Source and headless gates pass on the publication branch; the final exact
|
||||
commit is recorded in the issue closure comment. Packaged-runtime testing remains deferred by the
|
||||
project owner.
|
||||
|
||||
## Scope
|
||||
|
||||
1. Make registered commands distinguish immediate completion from modal Preview ownership.
|
||||
2. Require stable operator IDs and terminal phases for commit, cancel, block, failure, no-op, and
|
||||
automatic interruption paths.
|
||||
3. Make Group Selection and lighting changes atomic history transactions with repeatable undo/redo.
|
||||
4. Exercise production dispatch/finalizers for assets, material drops, brushes, terrain, physics
|
||||
placement, and transform gizmos through reusable semantic projections.
|
||||
5. Publish the invariant contract, acceptance evidence, and production-gate status without claiming
|
||||
release-candidate acceptance.
|
||||
|
||||
## Verification
|
||||
|
||||
- `cargo test -p editor --lib --no-fail-fast`
|
||||
- `cargo clippy -p editor --lib --tests -- -D warnings`
|
||||
- `cargo fmt --all -- --check`
|
||||
- `cargo test --workspace --all-targets --no-fail-fast`
|
||||
- `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
- `cargo validate-levels --project .`
|
||||
|
||||
Live editor checks cover command-palette modal ownership and the grouped selection/lighting history
|
||||
surface. Packaged tests are deliberately excluded until re-enabled by the project owner.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Physics Placement Tool - 2026-07-12
|
||||
|
||||
Issue: Gitea #25 (`BS-JD-304`)
|
||||
|
||||
## Outcome
|
||||
|
||||
Selected authored props can be released into deterministic Avian gravity, preview their
|
||||
settled transforms in the Scene viewport, and either commit the result as one undoable
|
||||
transform operation or cancel back to the exact pre-placement state.
|
||||
|
||||
## Contract
|
||||
|
||||
- Physics is paused during normal Edit mode and while Play mode is paused.
|
||||
- Placement runs only in Edit mode and owns a transactional physics session.
|
||||
- Selected mutable level objects must have active rigid-body and non-trigger collider
|
||||
authoring. Invalid selections produce a precise, non-destructive diagnostic.
|
||||
- Selected bodies are temporarily dynamic with clean motion state.
|
||||
- Other movable bodies are temporarily static so they remain collision surfaces without
|
||||
advancing unrelated authored state.
|
||||
- Commit restores all temporary runtime overrides and records only changed local transforms
|
||||
as one grouped history command.
|
||||
- Cancel restores transforms and runtime physics state exactly and creates no history entry.
|
||||
- Escape cancels. Enter commits once the session has reached rest. A bounded timeout keeps
|
||||
unstable scenes controllable.
|
||||
|
||||
## Work
|
||||
|
||||
- [x] Establish Edit/Play ownership of `Time<Physics>` and preserve paused single-step PIE.
|
||||
- [x] Implement placement validation, runtime snapshots, deterministic stepping, settling,
|
||||
timeout, commit, and cancel.
|
||||
- [x] Add the placement action and session controls to the existing horizontal viewport
|
||||
toolbar plus a compact status HUD.
|
||||
- [x] Add unit/integration coverage for prerequisites, settling, cancel, commit, and history.
|
||||
- [x] Update editor workflow documentation and implementation checklist.
|
||||
- [x] Run source gates and live Wayland acceptance; packaged tests remain skipped by request.
|
||||
- [x] Commit, push, attach native Gitea evidence, and close #25.
|
||||
@@ -15,12 +15,12 @@ owner requests it again.
|
||||
|
||||
1. Keep one evidence matrix under `docs/editor/evaluations/production-readiness/`; historical H1-H6
|
||||
notes remain context only.
|
||||
2. Close implementation blockers before nominating a candidate: the deformed Solari geometry
|
||||
boundary in `#51`, terrain `#22`-`#24`, physics placement/diagnostics `#25`-`#26`, and their
|
||||
regression fixtures. Collaborative safety `#49`, Material Library/targeted drops `#16`/`#18`,
|
||||
and native-dialog responsiveness `#52` are accepted and integrated.
|
||||
3. Complete the representative regression project, mutation-invariant coverage, performance budgets,
|
||||
and first-hour workflow tracked by `#32`-`#36`.
|
||||
2. Close implementation blockers before nominating a candidate. Renderer foundation `#51`, terrain
|
||||
`#22`-`#24`, physics placement/diagnostics `#25`-`#26`, operator invariants `#33`, collaborative
|
||||
safety `#49`, Material Library/targeted drops `#16`/`#18`, and native-dialog responsiveness `#52`
|
||||
are accepted and integrated.
|
||||
3. Complete the representative regression project, performance budgets, and first-hour workflow
|
||||
tracked by `#32`, `#34`, `#35`, and `#36`.
|
||||
4. Nominate one exact commit, validate it from a clean checkout, and record source/headless results.
|
||||
5. When packaged testing is re-enabled, run the candidate's package/build and packaged-runtime
|
||||
matrix without substituting older artifacts.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Renderer Foundation Acceptance Split - 2026-07-12
|
||||
|
||||
Issue: Gitea #51 (`BS-JD-207`)
|
||||
|
||||
## Outcome
|
||||
|
||||
Accept the shipped renderer/material/Surface foundation without claiming two independent future
|
||||
systems. Preserve the existing safe raster/Forward behavior and track each remaining boundary with
|
||||
its own implementation and acceptance contract.
|
||||
|
||||
## Decisions
|
||||
|
||||
- #51 owns stable static/skinned slots, shared Material/Instance assets, Surface ABI parity for
|
||||
eligible geometry, transactional migration, and the honest exclusion of deformed Solari meshes.
|
||||
- #53 owns actual runtime Material Property Block application and promote-to-instance UX. The
|
||||
existing component schema/persistence exclusion is not represented as runtime completion.
|
||||
- #54 owns dynamic post-morph/post-skin buffers and instance BLAS updates. It is a documented P2
|
||||
Solari enhancement, not a raster/Forward production blocker.
|
||||
|
||||
## Work
|
||||
|
||||
- [x] Audit #51 scope and repository evidence against current runtime behavior.
|
||||
- [x] Create focused Gitea follow-ups with independent acceptance criteria.
|
||||
- [x] Correct ADR, material guide, README checklist, evaluation, and production matrix claims.
|
||||
- [x] Run documentation/diff gates, commit, push, and close #51 with exact follow-up links.
|
||||
@@ -144,6 +144,7 @@ deep-stale variants.
|
||||
| Brush selected: `1` / `2` / `3` / `4` | Vertex / edge / face / clip edit modes |
|
||||
| Brush edit mode: LMB / `Shift+LMB` / `W` / `E` / `R` / `Esc` | Select element / toggle element selection / move / rotate / scale selected brush elements / return to object mode |
|
||||
| Viewport toolbar (sun / brush / box icons) | Shading: Lit, Unlit (albedo), Colliders (mesh off) |
|
||||
| Collider viewport mode | Inspect world-scale box/sphere/capsule overlays and cooked mesh bounds; green/cyan/gray/amber/red identify ready/trigger/disabled/warning/invalid state, with selected health in the lower-left HUD |
|
||||
| Viewport eye/options | Toggle actor root icon categories, adjust icon/gizmo size, and control colliders, lights, spawns, gameplay markers, volumes, prefab/model anchors, and runtime player/camera visualizers |
|
||||
| `Tab` in viewport | Cycle selection through overlapping objects at last click |
|
||||
| Viewport selection/orientation HUD | Identify the primary selection, multi-selection count, overlapping-pick position, camera axes, shading mode, and active render path |
|
||||
@@ -173,6 +174,7 @@ deep-stale variants.
|
||||
| Inspector footer → Add Component → Terrain | Add a height-grid terrain actor; configure grid scale/chunking/collision in its component card and use Resize Flat only for deliberate grid replacement |
|
||||
| Selected Terrain → viewport mountains tool | Sculpt Raise/Lower/Flatten/Smooth/Noise strokes with a terrain-following footprint; release commits one undo step, while Escape/right-click restores the pre-stroke grid |
|
||||
| Terrain card → Material Layers; selected Terrain → viewport paint tool | Assign up to four shared materials, then Paint/Erase normalized layer weights with live blended preview; release commits one undo step and Escape/right-click restores the pre-stroke map |
|
||||
| Selected physics props → viewport hand/down-arrow tool | Release the selection into real gravity/colliders; check commits one grouped transform edit, while Escape/X restores the exact starting state |
|
||||
| Audio Source / Listener inspector | Assign and audition clips; edit gain, pitch, loop/autoplay, spatial blend, attenuation, bus, listener priority, and ear gap |
|
||||
| Edit → Project Settings… | Edit `assets/project.ron` rendering, audio buses, physics, and input |
|
||||
|
||||
@@ -404,6 +406,8 @@ crates/
|
||||
- [x] First-class height-grid Terrain actor with deterministic generated render/collider chunks, reflected history, validation, and a committed showcase fixture ([ADR 0039](docs/adr/0039-inline-height-grid-terrain-foundation.md), [terrain guide](docs/editor/terrain.md), [Gitea #22](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/22))
|
||||
- [x] Modal terrain Raise/Lower/Flatten/Smooth/Noise sculpting with a terrain-following footprint, deterministic noise, safe cancel restore, and one undo transaction per stroke ([terrain guide](docs/editor/terrain.md), [Gitea #23](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/23))
|
||||
- [x] Four shared terrain Material/Material Instance layers with compact normalized sample weights, blended raster hydration, drag/browse assignment, Paint/Erase preview, exact cancel, and one undo transaction per stroke ([ADR 0040](docs/adr/0040-terrain-material-layer-weights.md), [terrain guide](docs/editor/terrain.md), [Gitea #24](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/24))
|
||||
- [x] Transactional physics placement with real Avian gravity/colliders, paused Edit-mode physics, prerequisite diagnostics, isolated non-selected bodies, exact cancel, and grouped transform undo ([ADR 0041](docs/adr/0041-transactional-editor-physics-placement.md), [workflow guide](docs/editor/physics-placement.md), [Gitea #25](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/25))
|
||||
- [x] Collider authoring health shared by the inspector, Collider viewport, Diagnostics panel, and physics placement, with scaled shape overlays, cooked mesh bounds, missing/stale/invalid/oversized findings, and undoable dimension-preserving shape switching ([collider guide](docs/editor/collider-authoring.md), [Gitea #26](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/26))
|
||||
- [x] Non-blocking native file/folder/confirmation broker across scene, asset, prefab, composition, collaboration, and Project Browser workflows ([ADR 0038](docs/adr/0038-non-blocking-native-dialog-broker.md), [workflow guide](docs/editor/native-dialogs.md), [Gitea #52](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/52))
|
||||
- [x] Asset import, static mesh/prefab placement, texture assignment, and selection export
|
||||
- [x] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
|
||||
@@ -415,7 +419,7 @@ crates/
|
||||
- [x] CI workflow for format, check, clippy, tests, and binary builds
|
||||
- [x] ADRs for roadmap architecture and Bevy migration policy
|
||||
- [x] Determinism harness: same inputs over same ticks produce the same state summary/hash
|
||||
- [x] Reusable editor operator harness for commit/cancel/block, helper cleanup, dirty state, grouped undo, and undo/redo round trips
|
||||
- [x] Production operator invariants across palette dispatch, assets/material drops, brush/terrain/physics modal tools, grouping/lighting, and the transform finalizer: stable terminal status, exact cancel/failure rollback, helper cleanup, grouped history, and repeated undo/redo projections ([testing contract](docs/editor/operator-regression-testing.md), [evaluation](docs/editor/evaluations/operator-invariants/), [Gitea #33](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33))
|
||||
- [x] Verify: `cargo fmt --check` / `cargo check --workspace` / `cargo clippy --workspace` / strict foundation clippy / `cargo test -p sim`
|
||||
- [x] Stable asset registry with UUIDs + import settings in asset browser details
|
||||
- [x] Asset Browser expandable model subasset shelves, independent mesh/material/texture thumbnails, staged import/material details with shader-schema parameters, context actions, and trash-first file removal
|
||||
@@ -443,7 +447,7 @@ crates/
|
||||
- [x] Editor lib/bin split + `EditorPluginGroup`; game EditorPlugin dogfood panel
|
||||
- [x] FBX/glTF model import + normalized static/skinned renderer routing; explicit generic scene-instance load via `bevy_ufbx` / `ModelRef`
|
||||
- [x] Asset browser model thumbnails (unified `assets/thumbnails/` pipeline; `ThumbnailState` cache; FBX via `FbxThumbnailSource`)
|
||||
- [x] Shared Material/Material Instance assets, stable static/skinned renderer material slots, imported-source fallback, orphan preservation, and runtime-only property blocks ([ADR 0035](docs/adr/0035-shared-material-assets-and-renderer-slots.md), [material-system guide](docs/editor/material-system.md))
|
||||
- [x] Shared Material/Material Instance assets, stable static/skinned renderer material slots, imported-source fallback, orphan preservation, and a persistence-excluded property-block schema; runtime block application/promotion remains tracked in [Gitea #53](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/53) ([ADR 0035](docs/adr/0035-shared-material-assets-and-renderer-slots.md), [material-system guide](docs/editor/material-system.md))
|
||||
- [x] Docked Material Library with cross-folder type/usage filters, resolved Material Instance thumbnails, shared guarded editors, and exact reversible viewport Material/Texture drops for renderer slots, primitives, and brush faces ([material-system guide](docs/editor/material-system.md); [Gitea #16](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/16), [Gitea #18](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/18))
|
||||
- [x] Prefab v2 core: shared stable nested override paths, property/component/structural scopes, recursive graph validation, linked-root variants, conflict recovery, transactional source Apply, and undoable unpack/convert ([ADR 0027](docs/adr/0027-stable-prefab-ownership-and-variants.md))
|
||||
- [x] Prefab v2 production acceptance: committed base/nested/variant fixtures pass workspace tests, recursive headless validation, packaged release startup, and live editor placement/inspection regression coverage ([Gitea #43](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/43))
|
||||
@@ -487,7 +491,7 @@ crates/
|
||||
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
|
||||
authoring UI coverage and production-acceptance gaps are tracked in
|
||||
[prefab-authoring.md](docs/editor/prefab-authoring.md).
|
||||
- Material and direct-base Material Instance assets live under `assets/materials/`; shader schemas live under `assets/shaders/`. **Window > Material Library** provides cross-folder creation, editing, usage filters, and drag sources. Viewport Material drops target one exact renderer slot, primitive, or brush face and use reversible preview plus one-step history; loose Textures target primitives/brush faces and are rejected on renderer slots. Shared edits propagate through live-updated handles without reloading skinned geometry. Custom Surface evaluators share one constrained ABI between raster and Solari-eligible non-deformed geometry. Dynamic skinned/morph Solari geometry and a persisted property-block authoring workflow remain future work; see the [material-system guide](docs/editor/material-system.md).
|
||||
- Material and direct-base Material Instance assets live under `assets/materials/`; shader schemas live under `assets/shaders/`. **Window > Material Library** provides cross-folder creation, editing, usage filters, and drag sources. Viewport Material drops target one exact renderer slot, primitive, or brush face and use reversible preview plus one-step history; loose Textures target primitives/brush faces and are rejected on renderer slots. Shared edits propagate through live-updated handles without reloading skinned geometry. Custom Surface evaluators share one constrained ABI between raster and Solari-eligible non-deformed geometry. Runtime property-block application/promotion is tracked in [#53](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/53); dynamic skinned/morph Solari geometry is tracked in [#54](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/54). See the [material-system guide](docs/editor/material-system.md).
|
||||
- Per-field reflect undo for all components remains future work; typed `shared` inspectors cover the common authoring path.
|
||||
- The authoring/hydration layer is intentionally small so richer asset workflows (terrain,
|
||||
material graphs, lighting profiles) can be added without changing the scene format foundation.
|
||||
|
||||
@@ -197,6 +197,24 @@
|
||||
),
|
||||
dependencies: [],
|
||||
),
|
||||
(
|
||||
id: ("78c6850b-5a76-4a4f-b48e-7fb00f6dd1ed"),
|
||||
path: "assets/levels/physics_placement_showcase.scn.ron",
|
||||
label: "physics_placement_showcase.scn",
|
||||
kind_tag: "Level",
|
||||
import_settings: (
|
||||
scale: 1.0,
|
||||
generate_collider: true,
|
||||
lod0_only: true,
|
||||
placement_mode: StaticAsset,
|
||||
hierarchy_mode: SingleActor,
|
||||
material_policy: SourceMaterials,
|
||||
static_mesh_manifest_path: None,
|
||||
animation_manifest_path: None,
|
||||
default_animation_clip_id: None,
|
||||
),
|
||||
dependencies: [],
|
||||
),
|
||||
(
|
||||
id: ("706e604e-1a63-4e97-b35d-eeb1d88fe3a9"),
|
||||
path: "assets/levels/navigation_authoring_showcase.scn.ron",
|
||||
@@ -233,6 +251,24 @@
|
||||
),
|
||||
dependencies: [],
|
||||
),
|
||||
(
|
||||
id: ("a7ef65b4-24d6-4c3a-b637-5bb52d8e9a26"),
|
||||
path: "assets/levels/collider_diagnostics_showcase.scn.ron",
|
||||
label: "collider_diagnostics_showcase.scn",
|
||||
kind_tag: "Level",
|
||||
import_settings: (
|
||||
scale: 1.0,
|
||||
generate_collider: true,
|
||||
lod0_only: true,
|
||||
placement_mode: StaticAsset,
|
||||
hierarchy_mode: SingleActor,
|
||||
material_policy: SourceMaterials,
|
||||
static_mesh_manifest_path: None,
|
||||
animation_manifest_path: None,
|
||||
default_animation_clip_id: None,
|
||||
),
|
||||
dependencies: [],
|
||||
),
|
||||
(
|
||||
id: ("f3dfcd11-aa5b-4fd4-872b-06832b865c99"),
|
||||
path: "assets/levels/audio_authoring_showcase.scn.ron",
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
(schema_version: 4, resources: {}, entities: {
|
||||
1: (components: {
|
||||
"bevy_ecs::name::Name": "Valid Box Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (-4.5, 1.0, 0.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-box"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (0),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.18, g: 0.62, b: 0.36, a: 1.0),
|
||||
metallic: 0.05, roughness: 0.55,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true, is_trigger: false,
|
||||
shape: Cuboid(x_length: 1.8, y_length: 2.0, z_length: 1.8),
|
||||
),
|
||||
}),
|
||||
2: (components: {
|
||||
"bevy_ecs::name::Name": "Valid Sphere Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (-2.25, 1.0, 0.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.35, 0.8),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-sphere"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (1),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.16, g: 0.52, b: 0.78, a: 1.0),
|
||||
metallic: 0.08, roughness: 0.42,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Sphere, size: (2.0, 2.0, 2.0)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true, is_trigger: false, shape: Sphere(radius: 1.0),
|
||||
),
|
||||
}),
|
||||
3: (components: {
|
||||
"bevy_ecs::name::Name": "Valid Capsule Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, 1.4, 0.0),
|
||||
rotation: (0.0, 0.1950903, 0.0, 0.9807853),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-capsule"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (2),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.58, g: 0.34, b: 0.78, a: 1.0),
|
||||
metallic: 0.06, roughness: 0.48,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.4, 2.8, 1.4)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true, is_trigger: false, shape: Capsule(radius: 0.7, height: 2.8),
|
||||
),
|
||||
}),
|
||||
4: (components: {
|
||||
"bevy_ecs::name::Name": "Trigger Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (2.25, 1.0, 0.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-trigger"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (3),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.12, g: 0.68, b: 0.82, a: 1.0),
|
||||
metallic: 0.03, roughness: 0.4,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Sphere, size: (2.0, 2.0, 2.0)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true, is_trigger: true, shape: Sphere(radius: 1.0),
|
||||
),
|
||||
}),
|
||||
5: (components: {
|
||||
"bevy_ecs::name::Name": "Disabled Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (4.5, 1.0, 0.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-disabled"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (4),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.38, g: 0.40, b: 0.46, a: 1.0),
|
||||
metallic: 0.02, roughness: 0.68,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: false, is_trigger: false,
|
||||
shape: Cuboid(x_length: 1.8, y_length: 2.0, z_length: 1.8),
|
||||
),
|
||||
}),
|
||||
6: (components: {
|
||||
"bevy_ecs::name::Name": "Missing Collider",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, 1.0, -3.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-missing"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (5),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.78, g: 0.16, b: 0.20, a: 1.0),
|
||||
metallic: 0.02, roughness: 0.58,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), emissive_intensity: 0.0,
|
||||
base_color_texture: None, emissive_texture: None, normal_map_texture: None,
|
||||
metallic_roughness_texture: None, material_asset_path: None, parameters: [], textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.8, 2.0, 1.8)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
}),
|
||||
7: (components: {
|
||||
"bevy_ecs::name::Name": "Collider Showcase Sun",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, 8.0, 4.0),
|
||||
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("collider-showcase-sun"),
|
||||
"shared::components::ActorKind": Light,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (6),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::LightDesc": (
|
||||
kind: Directional, color: (r: 1.0, g: 0.95, b: 0.88, a: 1.0),
|
||||
intensity: 100000.0, range: 0.0, shadows: true,
|
||||
inner_angle_deg: 25.0, outer_angle_deg: 35.0,
|
||||
),
|
||||
}),
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
(schema_version: 4, resources: {}, entities: {
|
||||
1: (components: {
|
||||
"bevy_ecs::name::Name": "Placement Floor",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, -0.25, 0.0),
|
||||
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("physics-placement-floor"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (0),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.12, g: 0.14, b: 0.16, a: 1.0),
|
||||
metallic: 0.05,
|
||||
roughness: 0.72,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
|
||||
emissive_intensity: 0.0,
|
||||
base_color_texture: None,
|
||||
emissive_texture: None,
|
||||
normal_map_texture: None,
|
||||
metallic_roughness_texture: None,
|
||||
material_asset_path: None,
|
||||
parameters: [],
|
||||
textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (14.0, 0.5, 10.0)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true,
|
||||
is_trigger: false,
|
||||
shape: Cuboid(x_length: 14.0, y_length: 0.5, z_length: 10.0),
|
||||
),
|
||||
}),
|
||||
2: (components: {
|
||||
"bevy_ecs::name::Name": "Placement Prop A",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (-2.0, 3.0, 0.0),
|
||||
rotation: (0.1305262, 0.0, 0.0, 0.9914449),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("physics-placement-prop-a"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (1),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.88, g: 0.48, b: 0.12, a: 1.0),
|
||||
metallic: 0.1,
|
||||
roughness: 0.42,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
|
||||
emissive_intensity: 0.0,
|
||||
base_color_texture: None,
|
||||
emissive_texture: None,
|
||||
normal_map_texture: None,
|
||||
metallic_roughness_texture: None,
|
||||
material_asset_path: None,
|
||||
parameters: [],
|
||||
textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.2, 1.2, 1.2)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true,
|
||||
is_trigger: false,
|
||||
shape: Cuboid(x_length: 1.2, y_length: 1.2, z_length: 1.2),
|
||||
),
|
||||
}),
|
||||
3: (components: {
|
||||
"bevy_ecs::name::Name": "Placement Prop B",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, 5.0, 0.0),
|
||||
rotation: (0.0, 0.2164396, 0.0, 0.976296),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("physics-placement-prop-b"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (2),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.10, g: 0.58, b: 0.72, a: 1.0),
|
||||
metallic: 0.15,
|
||||
roughness: 0.35,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
|
||||
emissive_intensity: 0.0,
|
||||
base_color_texture: None,
|
||||
emissive_texture: None,
|
||||
normal_map_texture: None,
|
||||
metallic_roughness_texture: None,
|
||||
material_asset_path: None,
|
||||
parameters: [],
|
||||
textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.0, 1.6, 1.0)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true,
|
||||
is_trigger: false,
|
||||
shape: Cuboid(x_length: 1.0, y_length: 1.6, z_length: 1.0),
|
||||
),
|
||||
}),
|
||||
4: (components: {
|
||||
"bevy_ecs::name::Name": "Placement Prop C",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (2.0, 7.0, 0.0),
|
||||
rotation: (0.092296, 0.092296, -0.008077, 0.991405),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("physics-placement-prop-c"),
|
||||
"shared::components::ActorKind": StaticMesh,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (3),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::MaterialDesc": (
|
||||
shader: (kind: StandardLit, schema_path: None, shader_path: None),
|
||||
base_color: (r: 0.62, g: 0.24, b: 0.56, a: 1.0),
|
||||
metallic: 0.08,
|
||||
roughness: 0.5,
|
||||
emissive_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
|
||||
emissive_intensity: 0.0,
|
||||
base_color_texture: None,
|
||||
emissive_texture: None,
|
||||
normal_map_texture: None,
|
||||
metallic_roughness_texture: None,
|
||||
material_asset_path: None,
|
||||
parameters: [],
|
||||
textures: [],
|
||||
),
|
||||
"shared::components::Primitive": (shape: Box, size: (1.4, 0.8, 1.0)),
|
||||
"shared::components::RigidBodyDesc": (body: Static),
|
||||
"shared::components::ColliderDesc": (
|
||||
enabled: true,
|
||||
is_trigger: false,
|
||||
shape: Cuboid(x_length: 1.4, y_length: 0.8, z_length: 1.0),
|
||||
),
|
||||
}),
|
||||
5: (components: {
|
||||
"bevy_ecs::name::Name": "Placement Sun",
|
||||
"bevy_transform::components::transform::Transform": (
|
||||
translation: (0.0, 8.0, 2.0),
|
||||
rotation: (-0.3826834, 0.0, 0.0, 0.9238795),
|
||||
scale: (1.0, 1.0, 1.0),
|
||||
),
|
||||
"shared::components::ActorId": ("physics-placement-sun"),
|
||||
"shared::components::ActorKind": Light,
|
||||
"shared::components::EditorVisibility": (visible: true),
|
||||
"shared::components::HierarchySiblingIndex": (4),
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::LightDesc": (
|
||||
kind: Directional,
|
||||
color: (r: 1.0, g: 0.95, b: 0.85, a: 1.0),
|
||||
intensity: 100000.0,
|
||||
range: 0.0,
|
||||
shadows: true,
|
||||
inner_angle_deg: 25.0,
|
||||
outer_angle_deg: 35.0,
|
||||
),
|
||||
}),
|
||||
})
|
||||
@@ -311,11 +311,22 @@ fn sync_terrain_layer_material_bindings(
|
||||
);
|
||||
handle
|
||||
});
|
||||
queue_terrain_material_binding(&mut commands, entity, handle);
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_terrain_material_binding(
|
||||
commands: &mut Commands,
|
||||
entity: Entity,
|
||||
handle: Handle<TerrainLayerMaterial>,
|
||||
) {
|
||||
// Generated render entities can be removed by a scene switch after this system's query
|
||||
// but before deferred commands apply. That lifecycle race is expected and must not abort
|
||||
// the editor while opening another scene.
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<MeshMaterial3d<StandardMaterial>>()
|
||||
.insert(MeshMaterial3d(handle));
|
||||
}
|
||||
.try_remove::<MeshMaterial3d<StandardMaterial>>()
|
||||
.try_insert(MeshMaterial3d(handle));
|
||||
}
|
||||
|
||||
fn terrain_layer_revision(layers: &[TerrainMaterialLayer]) -> u64 {
|
||||
@@ -469,8 +480,8 @@ fn sync_surface_material_bindings(
|
||||
{
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<MeshMaterial3d<SurfaceMaterial>>()
|
||||
.insert(MeshMaterial3d(handle));
|
||||
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
|
||||
.try_insert(MeshMaterial3d(handle));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
@@ -540,8 +551,8 @@ fn sync_surface_material_bindings(
|
||||
{
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<MeshMaterial3d<SurfaceMaterial>>()
|
||||
.insert(MeshMaterial3d(handle));
|
||||
.try_remove::<MeshMaterial3d<SurfaceMaterial>>()
|
||||
.try_insert(MeshMaterial3d(handle));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -565,8 +576,8 @@ fn sync_surface_material_bindings(
|
||||
if surface_handle.is_none_or(|current| current.0 != handle) {
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<MeshMaterial3d<StandardMaterial>>()
|
||||
.insert(MeshMaterial3d(handle));
|
||||
.try_remove::<MeshMaterial3d<StandardMaterial>>()
|
||||
.try_insert(MeshMaterial3d(handle));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -957,6 +968,21 @@ pub fn compose_surface_shader(evaluator: &str) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::ecs::world::CommandQueue;
|
||||
|
||||
#[test]
|
||||
fn stale_generated_terrain_binding_is_nonfatal_during_scene_switch() {
|
||||
let mut world = World::new();
|
||||
let entity = world.spawn_empty().id();
|
||||
let mut queue = CommandQueue::default();
|
||||
let mut commands = Commands::new(&mut queue, &world);
|
||||
queue_terrain_material_binding(&mut commands, entity, Handle::default());
|
||||
|
||||
world.entity_mut(entity).despawn();
|
||||
queue.apply(&mut world);
|
||||
|
||||
assert!(world.get_entity(entity).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_resource_bindings_and_missing_entry() {
|
||||
|
||||
@@ -469,6 +469,86 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_actor_material_assignment_is_one_undo_group() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let material_path = std::env::temp_dir().join(format!(
|
||||
"blacksite-material-operator-{}.material.ron",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let fixture = shared::MaterialAsset {
|
||||
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
|
||||
label: "Concrete".into(),
|
||||
shader: None,
|
||||
shader_ref: None,
|
||||
render_state: Default::default(),
|
||||
material: MaterialDesc {
|
||||
roughness: 0.85,
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
std::fs::write(
|
||||
&material_path,
|
||||
ron::ser::to_string_pretty(&fixture, ron::ser::PrettyConfig::default()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let material_path = material_path.to_string_lossy().into_owned();
|
||||
world.insert_resource(AssetRegistry {
|
||||
records: vec![AssetRecord {
|
||||
id: AssetId::new(),
|
||||
path: material_path.clone(),
|
||||
label: "Concrete".into(),
|
||||
kind_tag: "Material".into(),
|
||||
import_settings: Default::default(),
|
||||
dependencies: Vec::new(),
|
||||
}],
|
||||
index_dirty: false,
|
||||
});
|
||||
let first = world.spawn((LevelObject, MaterialDesc::default())).id();
|
||||
let second = world.spawn((LevelObject, MaterialDesc::default())).id();
|
||||
let mut selected = SelectedEntities::default();
|
||||
selected.select_replace(first);
|
||||
selected.select_maybe_add(second, true);
|
||||
let asset = EditorAsset {
|
||||
label: "Concrete".to_string(),
|
||||
path: Some(material_path.clone()),
|
||||
folder_path: "assets/materials".to_string(),
|
||||
kind: super::super::EditorAssetKind::Material,
|
||||
};
|
||||
super::super::materials::material_desc_from_asset(&material_path)
|
||||
.expect("committed material fixture should resolve");
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
let read_materials = move |world: &mut World| {
|
||||
[first, second]
|
||||
.into_iter()
|
||||
.map(|entity| {
|
||||
world
|
||||
.get::<MaterialDesc>(entity)
|
||||
.and_then(|material| material.material_asset_path.clone())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let applied = apply_material_operator(&mut world, asset, &selected);
|
||||
assert!(
|
||||
applied,
|
||||
"material operator failed: {:?}",
|
||||
world.resource::<ActiveOperator>().status
|
||||
);
|
||||
|
||||
harness.assert_committed(&mut world, 1, 0);
|
||||
assert_undo_redo_round_trip(
|
||||
&mut world,
|
||||
vec![None, None],
|
||||
vec![Some(material_path.clone()), Some(material_path.clone())],
|
||||
read_materials,
|
||||
);
|
||||
let _ = std::fs::remove_file(material_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_subasset_commit_cancels_without_side_effects() {
|
||||
let mut world = World::new();
|
||||
@@ -533,4 +613,59 @@ mod tests {
|
||||
|
||||
harness.assert_blocked(&mut world);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_assignment_without_authored_selection_is_blocked() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
let asset = EditorAsset {
|
||||
label: "Concrete".to_string(),
|
||||
path: Some("assets/materials/concrete.ron".to_string()),
|
||||
folder_path: "assets/materials".to_string(),
|
||||
kind: super::super::EditorAssetKind::Material,
|
||||
};
|
||||
|
||||
assert!(!apply_material_operator(
|
||||
&mut world,
|
||||
asset,
|
||||
&SelectedEntities::default()
|
||||
));
|
||||
|
||||
harness.assert_blocked(&mut world);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_and_animation_assignment_reject_incompatible_actors() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let entity = world.spawn(LevelObject).id();
|
||||
let audio = EditorAsset {
|
||||
label: "Impact".into(),
|
||||
path: Some("assets/audio/impact.ogg".into()),
|
||||
folder_path: "assets/audio".into(),
|
||||
kind: super::super::EditorAssetKind::AudioClip,
|
||||
};
|
||||
let audio_harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
assert!(!assign_audio_clip_operator(&mut world, audio, entity));
|
||||
audio_harness.assert_blocked(&mut world);
|
||||
|
||||
let animation_harness = OperatorInvariantHarness::capture(&mut world);
|
||||
let selection = AssetSelection::SubAsset {
|
||||
parent_path: "assets/models/missing.glb".into(),
|
||||
sub_asset_id: "animation:missing".into(),
|
||||
label: "Missing".into(),
|
||||
kind: super::super::AssetSubAssetKind::AnimationClip,
|
||||
source_path: None,
|
||||
};
|
||||
assert!(!assign_animation_clip_operator(
|
||||
&mut world, selection, entity
|
||||
));
|
||||
animation_harness.assert_blocked(&mut world);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use bevy::prelude::*;
|
||||
use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass};
|
||||
|
||||
use crate::history::group_selection_with_history;
|
||||
use crate::operators::{run_immediate_operator, OperatorAvailability};
|
||||
use crate::operators::{run_operator_action, OperatorAction, OperatorAvailability};
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
use crate::ui::helpers::{
|
||||
reset_scene_lighting_to_project_defaults, toggle_play_mode, toggle_play_paused,
|
||||
@@ -27,7 +27,7 @@ pub trait EditorCommand: Send + Sync {
|
||||
fn disabled_reason(&self, _world: &World) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn execute(&self, world: &mut World);
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String>;
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
@@ -70,13 +70,11 @@ impl EditorCommandRegistry {
|
||||
.map(|cmd| (cmd.label().to_string(), cmd.disabled_reason(world)))
|
||||
}
|
||||
|
||||
pub fn run(&self, world: &mut World, name: &str) -> bool {
|
||||
if let Some(command) = self.commands.iter().find(|cmd| cmd.name() == name) {
|
||||
command.execute(world);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
pub fn run(&self, world: &mut World, name: &str) -> Option<Result<OperatorAction, String>> {
|
||||
self.commands
|
||||
.iter()
|
||||
.find(|command| command.name() == name)
|
||||
.map(|command| command.execute(world))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,6 +189,10 @@ pub fn register_editor_plugin(app: &mut App, plugin: Box<dyn EditorPlugin>) {
|
||||
}
|
||||
|
||||
fn register_builtin_commands(mut registry: ResMut<EditorCommandRegistry>) {
|
||||
populate_builtin_commands(&mut registry);
|
||||
}
|
||||
|
||||
fn populate_builtin_commands(registry: &mut EditorCommandRegistry) {
|
||||
registry.register(Box::new(TogglePlayCommand));
|
||||
registry.register(Box::new(TogglePlayPausedCommand));
|
||||
registry.register(Box::new(TogglePossessionCommand));
|
||||
@@ -235,7 +237,7 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
|
||||
let name_for_commit = name.to_string();
|
||||
let name_for_status = name.to_string();
|
||||
let label_for_commit = label.clone();
|
||||
run_immediate_operator(
|
||||
run_operator_action(
|
||||
world,
|
||||
&name_for_status,
|
||||
&label,
|
||||
@@ -244,14 +246,10 @@ fn dispatch_editor_command(world: &mut World, name: &str) {
|
||||
None => OperatorAvailability::Ready,
|
||||
},
|
||||
move |world| {
|
||||
let ran = world.resource_scope(|world, registry: Mut<EditorCommandRegistry>| {
|
||||
let result = world.resource_scope(|world, registry: Mut<EditorCommandRegistry>| {
|
||||
registry.run(world, &name_for_commit)
|
||||
});
|
||||
if ran {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Unknown editor command: {name_for_commit}"))
|
||||
}
|
||||
result.unwrap_or_else(|| Err(format!("Unknown editor command: {name_for_commit}")))
|
||||
},
|
||||
);
|
||||
|
||||
@@ -269,8 +267,9 @@ impl EditorCommand for TogglePlayCommand {
|
||||
"Toggle Play / Edit"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
toggle_play_mode(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,8 +289,9 @@ impl EditorCommand for TogglePlayPausedCommand {
|
||||
.then(|| "Enter Play mode before pausing the simulation".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
toggle_play_paused(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,12 +311,13 @@ impl EditorCommand for TogglePossessionCommand {
|
||||
.then(|| "Enter Play mode before toggling possession".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
let next = match *world.resource::<PlayPossession>() {
|
||||
PlayPossession::Possessed => PlayPossession::Ejected,
|
||||
PlayPossession::Ejected => PlayPossession::Possessed,
|
||||
};
|
||||
*world.resource_mut::<PlayPossession>() = next;
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,8 +332,9 @@ impl EditorCommand for ResetLightingCommand {
|
||||
"Reset Scene Lighting"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
reset_scene_lighting_to_project_defaults(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,13 +349,23 @@ impl EditorCommand for GroupSelectionCommand {
|
||||
"Group Selection"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn disabled_reason(&self, world: &World) -> Option<String> {
|
||||
world
|
||||
.resource::<UiState>()
|
||||
.selected_entities
|
||||
.as_slice()
|
||||
.is_empty()
|
||||
.then(|| "Select at least one actor to group".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
let selected: Vec<Entity> = world
|
||||
.resource::<UiState>()
|
||||
.selected_entities
|
||||
.iter()
|
||||
.collect();
|
||||
group_selection_with_history(world, &selected);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,8 +380,9 @@ impl EditorCommand for FocusSelectionCommand {
|
||||
"Focus Selection"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
focus_editor_camera_on_selection(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,8 +397,9 @@ impl EditorCommand for ResetSelectionTransformCommand {
|
||||
"Reset Selection Transform"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
reset_selected_transforms(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,8 +419,9 @@ impl EditorCommand for DrawBrushCommand {
|
||||
.then(|| "Enter Edit mode before drawing brushes".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
start_draw_brush_tool(world);
|
||||
Ok(OperatorAction::ContinuePreview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,8 +440,9 @@ impl EditorCommand for IntersectBrushesCommand {
|
||||
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
intersect_selected_brushes(world);
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
intersect_selected_brushes(world)?;
|
||||
Ok(OperatorAction::ContinuePreview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,8 +461,9 @@ impl EditorCommand for MergeBrushesCommand {
|
||||
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
merge_selected_brushes(world);
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
merge_selected_brushes(world)?;
|
||||
Ok(OperatorAction::ContinuePreview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,8 +482,9 @@ impl EditorCommand for SubtractBrushesCommand {
|
||||
(selected_brush_count(world) < 2).then(|| "Select at least two brushes".to_string())
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
subtract_selected_brushes(world);
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
subtract_selected_brushes(world)?;
|
||||
Ok(OperatorAction::ContinuePreview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,8 +499,9 @@ impl EditorCommand for CreatePostProcessVolumeCommand {
|
||||
"Create Post-process Volume"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,9 +516,10 @@ impl EditorCommand for FocusActiveVolumesCommand {
|
||||
"Focus Active Post-process Volumes"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
crate::rendering_diagnostics::select_volumes_at_camera(world);
|
||||
focus_editor_camera_on_selection(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,8 +534,9 @@ impl EditorCommand for SelectVolumesAtCameraCommand {
|
||||
"Select Volumes at Camera"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
fn execute(&self, world: &mut World) -> Result<OperatorAction, String> {
|
||||
crate::rendering_diagnostics::select_volumes_at_camera(world);
|
||||
Ok(OperatorAction::Commit)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,6 +563,7 @@ fn command_palette_ui(
|
||||
}
|
||||
|
||||
let mut open = palette.open;
|
||||
let mut dismiss_requested = false;
|
||||
let palette_width = (ctx.content_rect().width() - 32.0).clamp(320.0, 520.0);
|
||||
egui::Window::new("Command Palette")
|
||||
.open(&mut open)
|
||||
@@ -590,13 +612,11 @@ fn command_palette_ui(
|
||||
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
|
||||
if let Some(entry) = filtered_entries.get(palette.selected_index) {
|
||||
palette.pending_run = Some(entry.name.clone());
|
||||
palette.open = false;
|
||||
ui.close();
|
||||
dismiss_requested = true;
|
||||
}
|
||||
}
|
||||
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
palette.open = false;
|
||||
ui.close();
|
||||
dismiss_requested = true;
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
@@ -618,17 +638,20 @@ fn command_palette_ui(
|
||||
if response.clicked() {
|
||||
palette.selected_index = index;
|
||||
palette.pending_run = Some(entry.name.clone());
|
||||
palette.open = false;
|
||||
ui.close();
|
||||
dismiss_requested = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
palette.open = open;
|
||||
palette.open = resolve_palette_open(open, dismiss_requested);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_palette_open(window_open: bool, dismiss_requested: bool) -> bool {
|
||||
window_open && !dismiss_requested
|
||||
}
|
||||
|
||||
fn filtered_command_entries(
|
||||
registry: &EditorCommandRegistry,
|
||||
filter: &str,
|
||||
@@ -671,6 +694,53 @@ fn command_palette_row(entry: &EditorCommandEntry) -> egui::WidgetText {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||
use crate::operators::test_harness::OperatorInvariantHarness;
|
||||
use crate::operators::{ActiveOperator, OperatorPhase};
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::selection::{SelectedEntity, ViewportClick};
|
||||
use crate::viewport::brush_tool::BrushToolState;
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, BrushDesc, EditorVisibility, HierarchySiblingIndex,
|
||||
LevelObject, LightDesc,
|
||||
};
|
||||
|
||||
fn command_world() -> World {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<SelectedEntity>();
|
||||
world.init_resource::<ViewportClick>();
|
||||
world.init_resource::<BrushToolState>();
|
||||
world.init_resource::<crate::viewport::brush_csg::BrushCsgPreview>();
|
||||
world.insert_resource(State::new(EditorMode::Editing));
|
||||
world.insert_resource(UiState::default_layout());
|
||||
let mut registry = EditorCommandRegistry::default();
|
||||
populate_builtin_commands(&mut registry);
|
||||
world.insert_resource(registry);
|
||||
world
|
||||
}
|
||||
|
||||
fn hierarchy_projection(world: &mut World) -> Vec<(String, Option<String>, i32)> {
|
||||
let mut query = world.query_filtered::<(Entity, &Name), With<LevelObject>>();
|
||||
let mut result = query
|
||||
.iter(world)
|
||||
.map(|(entity, name)| {
|
||||
let parent = world
|
||||
.get::<ChildOf>(entity)
|
||||
.and_then(|child| world.get::<Name>(child.parent()))
|
||||
.map(|name| name.as_str().to_string());
|
||||
let sibling_index = world
|
||||
.get::<HierarchySiblingIndex>(entity)
|
||||
.map(|index| index.0)
|
||||
.unwrap_or_default();
|
||||
(name.as_str().to_string(), parent, sibling_index)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
result.sort();
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_filter_matches_human_label_and_stable_id() {
|
||||
@@ -697,4 +767,228 @@ mod tests {
|
||||
assert_eq!(entries[0].name, "play.toggle");
|
||||
assert_eq!(entries[1].name, "scene.reset_lighting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_palette_dismissal_wins_over_stale_window_open_state() {
|
||||
assert!(!resolve_palette_open(true, true));
|
||||
assert!(!resolve_palette_open(false, false));
|
||||
assert!(resolve_palette_open(true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouping_dispatch_is_one_history_transaction_and_round_trips() {
|
||||
let mut world = command_world();
|
||||
let first = world
|
||||
.spawn((
|
||||
Name::new("First"),
|
||||
LevelObject,
|
||||
ActorKind::Empty,
|
||||
Transform::from_xyz(1.0, 0.0, 0.0),
|
||||
GlobalTransform::default(),
|
||||
HierarchySiblingIndex(0),
|
||||
EditorVisibility::default(),
|
||||
))
|
||||
.id();
|
||||
let second = world
|
||||
.spawn((
|
||||
Name::new("Second"),
|
||||
LevelObject,
|
||||
ActorKind::Empty,
|
||||
Transform::from_xyz(2.0, 0.0, 0.0),
|
||||
GlobalTransform::default(),
|
||||
HierarchySiblingIndex(1),
|
||||
EditorVisibility::default(),
|
||||
))
|
||||
.id();
|
||||
let unselected = world
|
||||
.spawn((
|
||||
Name::new("Unselected"),
|
||||
LevelObject,
|
||||
ActorKind::Empty,
|
||||
Transform::from_xyz(3.0, 0.0, 0.0),
|
||||
GlobalTransform::default(),
|
||||
HierarchySiblingIndex(2),
|
||||
EditorVisibility::default(),
|
||||
))
|
||||
.id();
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_replace(first);
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_maybe_add(second, true);
|
||||
let initial = hierarchy_projection(&mut world);
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "selection.group");
|
||||
|
||||
harness.assert_committed(&mut world, 1, 1);
|
||||
harness.assert_status(&world, "selection.group", OperatorPhase::Committed);
|
||||
let committed = hierarchy_projection(&mut world);
|
||||
assert!(committed
|
||||
.iter()
|
||||
.any(|(name, parent, _)| name == "First" && parent.as_deref() == Some("Group")));
|
||||
assert!(committed
|
||||
.iter()
|
||||
.any(|(name, parent, _)| name == "Second" && parent.as_deref() == Some("Group")));
|
||||
assert_group_has_visibility_hierarchy(&mut world);
|
||||
apply_command_undo(&mut world);
|
||||
assert_eq!(hierarchy_projection(&mut world), initial);
|
||||
apply_command_redo(&mut world);
|
||||
assert_eq!(hierarchy_projection(&mut world), committed);
|
||||
assert_group_has_visibility_hierarchy(&mut world);
|
||||
assert!(world.get::<ChildOf>(unselected).is_none());
|
||||
apply_command_undo(&mut world);
|
||||
assert_eq!(hierarchy_projection(&mut world), initial);
|
||||
apply_command_redo(&mut world);
|
||||
assert_eq!(hierarchy_projection(&mut world), committed);
|
||||
assert!(world.get::<ChildOf>(unselected).is_none());
|
||||
}
|
||||
|
||||
fn assert_group_has_visibility_hierarchy(world: &mut World) {
|
||||
let group = world
|
||||
.query::<(Entity, &Name)>()
|
||||
.iter(world)
|
||||
.find_map(|(entity, name)| (name.as_str() == "Group").then_some(entity))
|
||||
.expect("group command should spawn the group actor");
|
||||
assert!(world.get::<Visibility>(group).is_some());
|
||||
assert!(world.get::<InheritedVisibility>(group).is_some());
|
||||
assert!(world.get::<ViewVisibility>(group).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_lighting_dispatch_is_one_undoable_group() {
|
||||
let mut world = command_world();
|
||||
let point = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorKind::Light,
|
||||
LightDesc {
|
||||
kind: AuthoringLightKind::Point,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let directional = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ActorKind::Light,
|
||||
LightDesc {
|
||||
kind: AuthoringLightKind::Directional,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "scene.reset_lighting");
|
||||
|
||||
harness.assert_committed(&mut world, 1, 0);
|
||||
harness.assert_status(&world, "scene.reset_lighting", OperatorPhase::Committed);
|
||||
assert!(world.get::<LightDesc>(point).is_none());
|
||||
assert!(world.get::<LightDesc>(directional).is_none());
|
||||
apply_command_undo(&mut world);
|
||||
assert!(world.get::<LightDesc>(point).is_some());
|
||||
assert!(world.get::<LightDesc>(directional).is_some());
|
||||
apply_command_redo(&mut world);
|
||||
assert!(world.get::<LightDesc>(point).is_none());
|
||||
assert!(world.get::<LightDesc>(directional).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modal_command_dispatch_retains_preview_ownership() {
|
||||
let mut world = command_world();
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "brush.draw");
|
||||
|
||||
harness.assert_status(&world, "brush.draw", OperatorPhase::Preview);
|
||||
harness.assert_projection_unchanged(&mut world, 0, |world| {
|
||||
world.resource::<EditorHistory>().undo_depth()
|
||||
});
|
||||
assert!(!world.resource::<SceneIo>().dirty);
|
||||
assert!(world.resource::<BrushToolState>().active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_csg_dispatch_terminates_without_preview_or_history() {
|
||||
let mut world = command_world();
|
||||
let first = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
BrushDesc::cuboid(Vec3::splat(1.0)),
|
||||
Transform::IDENTITY,
|
||||
))
|
||||
.id();
|
||||
let mut invalid = BrushDesc::cuboid(Vec3::splat(1.0));
|
||||
invalid.faces.clear();
|
||||
let second = world
|
||||
.spawn((LevelObject, invalid, Transform::IDENTITY))
|
||||
.id();
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_replace(first);
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_maybe_add(second, true);
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "brush.intersect");
|
||||
|
||||
harness.assert_canceled(&mut world);
|
||||
harness.assert_status(&world, "brush.intersect", OperatorPhase::Canceled);
|
||||
assert!(!world.resource::<SceneIo>().dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csg_dispatch_blocks_read_only_selection_without_history() {
|
||||
let mut world = command_world();
|
||||
let first = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
BrushDesc::cuboid(Vec3::splat(1.0)),
|
||||
Transform::IDENTITY,
|
||||
))
|
||||
.id();
|
||||
let second = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
BrushDesc::cuboid(Vec3::splat(1.0)),
|
||||
Transform::from_xyz(0.5, 0.0, 0.0),
|
||||
))
|
||||
.id();
|
||||
let mut hierarchy = crate::ui::hierarchy_state::HierarchyPanelState::default();
|
||||
hierarchy.locked.insert(second);
|
||||
world.insert_resource(hierarchy);
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_replace(first);
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_maybe_add(second, true);
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "brush.merge_convex");
|
||||
|
||||
harness.assert_blocked(&mut world);
|
||||
harness.assert_status(&world, "brush.merge_convex", OperatorPhase::Blocked);
|
||||
assert!(!world.resource::<SceneIo>().dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_command_dispatch_is_a_blocked_no_op() {
|
||||
let mut world = command_world();
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
dispatch_editor_command(&mut world, "selection.group");
|
||||
|
||||
harness.assert_blocked(&mut world);
|
||||
harness.assert_status(&world, "selection.group", OperatorPhase::Blocked);
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,11 @@ pub struct PrefabEditState {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum EditorCommand {
|
||||
GroupSelection {
|
||||
snapshot: EditorEntitySnapshot,
|
||||
group: Option<Entity>,
|
||||
changes: Vec<SiblingChange>,
|
||||
},
|
||||
Spawn {
|
||||
snapshot: EditorEntitySnapshot,
|
||||
entity: Option<Entity>,
|
||||
@@ -152,6 +157,12 @@ pub enum EditorCommand {
|
||||
old: Option<LightDesc>,
|
||||
new: LightDesc,
|
||||
},
|
||||
SetLightGroup {
|
||||
entities: Vec<Entity>,
|
||||
olds: Vec<Option<LightDesc>>,
|
||||
news: Vec<Option<LightDesc>>,
|
||||
label: &'static str,
|
||||
},
|
||||
SetAnimationController {
|
||||
entity: Entity,
|
||||
old: Option<AnimationControllerDesc>,
|
||||
@@ -293,6 +304,7 @@ pub enum EditorCommand {
|
||||
impl EditorCommand {
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
EditorCommand::GroupSelection { .. } => "Group Selection",
|
||||
EditorCommand::Spawn { .. } => "Spawn",
|
||||
EditorCommand::SpawnMany { .. } => "Spawn Brushes",
|
||||
EditorCommand::Despawn { .. } => "Delete",
|
||||
@@ -303,6 +315,7 @@ impl EditorCommand {
|
||||
EditorCommand::SetMaterialGroup { .. } => "Apply Material to Selection",
|
||||
EditorCommand::SetMaterialOverride { .. } => "Set Material Override",
|
||||
EditorCommand::SetLight { .. } => "Set Light",
|
||||
EditorCommand::SetLightGroup { label, .. } => label,
|
||||
EditorCommand::SetAnimationController { .. } => "Set Animation Controller",
|
||||
EditorCommand::SetAudioSource { .. } => "Set Audio Source",
|
||||
EditorCommand::SetAudioListener { .. } => "Set Audio Listener",
|
||||
|
||||
@@ -17,6 +17,7 @@ use shared::{
|
||||
TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::scene_tools_active;
|
||||
@@ -197,7 +198,20 @@ fn spawn_snapshot_with_parent(
|
||||
snapshot: &EditorEntitySnapshot,
|
||||
parent: Option<Entity>,
|
||||
) -> Entity {
|
||||
let mut entity_mut = world.spawn((LevelObject, snapshot.actor_kind, snapshot.transform));
|
||||
let visibility = if snapshot.editor_visibility.visible {
|
||||
Visibility::Visible
|
||||
} else {
|
||||
Visibility::Hidden
|
||||
};
|
||||
let mut entity_mut = world.spawn((
|
||||
LevelObject,
|
||||
snapshot.actor_kind,
|
||||
snapshot.transform,
|
||||
snapshot.editor_visibility,
|
||||
visibility,
|
||||
InheritedVisibility::default(),
|
||||
ViewVisibility::default(),
|
||||
));
|
||||
entity_mut.insert(
|
||||
snapshot
|
||||
.actor_id
|
||||
@@ -290,7 +304,6 @@ fn spawn_snapshot_with_parent(
|
||||
entity_mut.insert(link.clone());
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(snapshot.hierarchy_sibling_index));
|
||||
entity_mut.insert(snapshot.editor_visibility);
|
||||
if let Some(order) = &snapshot.inspector_order {
|
||||
entity_mut.insert(order.clone());
|
||||
}
|
||||
@@ -560,6 +573,40 @@ pub fn set_light_with_history(world: &mut World, entity: Entity, new: LightDesc)
|
||||
push_history(world, EditorCommand::SetLight { entity, old, new });
|
||||
}
|
||||
|
||||
pub fn set_light_group_with_history(
|
||||
world: &mut World,
|
||||
changes: impl IntoIterator<Item = (Entity, Option<LightDesc>)>,
|
||||
label: &'static str,
|
||||
) {
|
||||
let mut entities = Vec::new();
|
||||
let mut olds = Vec::new();
|
||||
let mut news = Vec::new();
|
||||
for (entity, new) in changes {
|
||||
if !is_mutable_level_object(world, entity) {
|
||||
continue;
|
||||
}
|
||||
let old = world.get::<LightDesc>(entity).cloned();
|
||||
if old.is_none() && new.is_none() {
|
||||
continue;
|
||||
}
|
||||
apply_light(world, entity, &new);
|
||||
entities.push(entity);
|
||||
olds.push(old);
|
||||
news.push(new);
|
||||
}
|
||||
if !entities.is_empty() {
|
||||
push_history(
|
||||
world,
|
||||
EditorCommand::SetLightGroup {
|
||||
entities,
|
||||
olds,
|
||||
news,
|
||||
label,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_audio_source_with_history(world: &mut World, entity: Entity, new: AudioSourceDesc) {
|
||||
if !is_mutable_level_object(world, entity) {
|
||||
return;
|
||||
@@ -752,9 +799,13 @@ pub fn apply_brush_csg_with_history(
|
||||
new_transform: Transform,
|
||||
new_brush: BrushDesc,
|
||||
delete_entities: &[Entity],
|
||||
) {
|
||||
if !is_level_object(world, primary) {
|
||||
return;
|
||||
) -> bool {
|
||||
if !is_mutable_level_object(world, primary)
|
||||
|| delete_entities
|
||||
.iter()
|
||||
.any(|entity| !is_mutable_level_object(world, *entity))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let old_transform = world.get::<Transform>(primary).copied().unwrap_or_default();
|
||||
let old_brush = world.get::<BrushDesc>(primary).cloned();
|
||||
@@ -769,7 +820,7 @@ pub fn apply_brush_csg_with_history(
|
||||
&& old_brush.as_ref() == Some(&new_brush)
|
||||
&& deleted.is_empty()
|
||||
{
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(primary) {
|
||||
entity_mut.insert(new_transform);
|
||||
@@ -790,6 +841,7 @@ pub fn apply_brush_csg_with_history(
|
||||
},
|
||||
);
|
||||
select_one(world, primary);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_static_mesh_renderer_with_history(
|
||||
@@ -943,14 +995,16 @@ pub fn group_selection_with_history(world: &mut World, entities: &[Entity]) {
|
||||
children: Vec::new(),
|
||||
};
|
||||
let group = spawn_snapshot(world, &snapshot);
|
||||
let changes = reorder_entities_under_parent(world, &entities, Some(group), i32::MAX);
|
||||
push_history(
|
||||
world,
|
||||
EditorCommand::Spawn {
|
||||
EditorCommand::GroupSelection {
|
||||
snapshot,
|
||||
entity: Some(group),
|
||||
group: Some(group),
|
||||
changes,
|
||||
},
|
||||
);
|
||||
reorder_siblings_with_history(world, &entities, Some(group), i32::MAX);
|
||||
select_one(world, group);
|
||||
}
|
||||
|
||||
pub fn create_empty_child_with_history(world: &mut World, parent: Entity) {
|
||||
@@ -1637,6 +1691,13 @@ fn prepare_prefab_source_history(
|
||||
|
||||
fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
match command {
|
||||
EditorCommand::GroupSelection { group, changes, .. } => {
|
||||
for change in changes.iter().rev() {
|
||||
apply_sibling_change(world, change);
|
||||
}
|
||||
despawn_entity(world, *group);
|
||||
clear_selection(world);
|
||||
}
|
||||
EditorCommand::Spawn { entity, .. } => {
|
||||
despawn_entity(world, entity.take());
|
||||
clear_selection(world);
|
||||
@@ -1682,6 +1743,11 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
EditorCommand::SetLight { entity, old, .. } => {
|
||||
apply_light(world, *entity, old);
|
||||
}
|
||||
EditorCommand::SetLightGroup { entities, olds, .. } => {
|
||||
for (entity, old) in entities.iter().zip(olds.iter()) {
|
||||
apply_light(world, *entity, old);
|
||||
}
|
||||
}
|
||||
EditorCommand::SetAnimationController { entity, old, .. } => {
|
||||
apply_animation_controller(world, *entity, old);
|
||||
}
|
||||
@@ -1818,6 +1884,25 @@ fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
|
||||
fn redo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
match command {
|
||||
EditorCommand::GroupSelection {
|
||||
snapshot,
|
||||
group,
|
||||
changes,
|
||||
} => {
|
||||
let previous_group = *group;
|
||||
let spawned = spawn_snapshot(world, snapshot);
|
||||
*group = Some(spawned);
|
||||
for change in changes.iter_mut() {
|
||||
if Some(change.entity) == previous_group {
|
||||
change.entity = spawned;
|
||||
}
|
||||
if change.new_parent == previous_group {
|
||||
change.new_parent = Some(spawned);
|
||||
}
|
||||
apply_sibling_change_new(world, change);
|
||||
}
|
||||
select_one(world, spawned);
|
||||
}
|
||||
EditorCommand::Spawn { snapshot, entity } => {
|
||||
let spawned = spawn_snapshot(world, snapshot);
|
||||
*entity = Some(spawned);
|
||||
@@ -1881,6 +1966,11 @@ fn redo_command(world: &mut World, command: &mut EditorCommand) {
|
||||
entity_mut.insert(new.clone());
|
||||
}
|
||||
}
|
||||
EditorCommand::SetLightGroup { entities, news, .. } => {
|
||||
for (entity, new) in entities.iter().zip(news.iter()) {
|
||||
apply_light(world, *entity, new);
|
||||
}
|
||||
}
|
||||
EditorCommand::SetAnimationController { entity, new, .. } => {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
entity_mut.insert(new.clone());
|
||||
@@ -2614,16 +2704,22 @@ fn capture_gizmo_transform_edits(world: &mut World) {
|
||||
let start_group =
|
||||
active.map(|(entity, transform)| selected_transforms(world, &selection, entity, transform));
|
||||
|
||||
let mut started_edit = false;
|
||||
let (finished_edit, live_edit) = {
|
||||
let mut tracker = world.resource_mut::<TransformEditTracker>();
|
||||
if tracker.active.is_none() {
|
||||
if let (Some((entity, transform)), Some(group)) = (active, start_group) {
|
||||
tracker.active = Some((entity, transform, group));
|
||||
return;
|
||||
started_edit = true;
|
||||
}
|
||||
}
|
||||
if started_edit {
|
||||
(None, None)
|
||||
} else {
|
||||
match tracker.active.take() {
|
||||
Some((primary, old, group)) if active.is_none() => (Some((primary, old, group)), None),
|
||||
Some((primary, old, group)) if active.is_none() => {
|
||||
(Some((primary, old, group)), None)
|
||||
}
|
||||
Some(state) if active.is_some() => {
|
||||
let live = Some(state.clone());
|
||||
tracker.active = Some(state);
|
||||
@@ -2631,8 +2727,18 @@ fn capture_gizmo_transform_edits(world: &mut World) {
|
||||
}
|
||||
_ => (None, None),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if started_edit {
|
||||
set_transform_operator_status(
|
||||
world,
|
||||
OperatorPhase::Preview,
|
||||
"Transform gizmo drag in progress",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some((primary, old_primary, group)) = live_edit {
|
||||
let Some(new_primary) = world.get::<Transform>(primary).copied() else {
|
||||
return;
|
||||
@@ -2645,15 +2751,51 @@ fn capture_gizmo_transform_edits(world: &mut World) {
|
||||
|
||||
if let Some((primary, old_primary, group)) = finished_edit {
|
||||
let Some(new_primary) = world.get::<Transform>(primary).copied() else {
|
||||
for (entity, old) in group {
|
||||
if let Some(mut transform) = world.get_mut::<Transform>(entity) {
|
||||
*transform = old;
|
||||
}
|
||||
}
|
||||
set_transform_operator_status(
|
||||
world,
|
||||
OperatorPhase::Canceled,
|
||||
"Transform target disappeared; surviving previews restored",
|
||||
);
|
||||
return;
|
||||
};
|
||||
let undo_depth = world.resource::<EditorHistory>().undo_depth();
|
||||
if group.len() <= 1 {
|
||||
set_transform_with_history(world, primary, old_primary, new_primary);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
let changes = transform_group_changes(old_primary, new_primary, group);
|
||||
set_transform_group_with_history(world, changes);
|
||||
}
|
||||
if world.resource::<EditorHistory>().undo_depth() > undo_depth {
|
||||
set_transform_operator_status(
|
||||
world,
|
||||
OperatorPhase::Committed,
|
||||
"Transform gizmo edit committed",
|
||||
);
|
||||
} else {
|
||||
set_transform_operator_status(
|
||||
world,
|
||||
OperatorPhase::Canceled,
|
||||
"Transform gizmo edit made no changes",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_transform_operator_status(world: &mut World, phase: OperatorPhase, hint: impl Into<String>) {
|
||||
if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() {
|
||||
active.status = Some(OperatorStatus {
|
||||
id: "transform.gizmo".to_string(),
|
||||
label: "Transform Gizmo".to_string(),
|
||||
phase,
|
||||
hint: hint.into(),
|
||||
warnings: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_group_changes(
|
||||
@@ -2796,7 +2938,7 @@ pub(crate) fn material_eq(a: &MaterialDesc, b: &MaterialDesc) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::operators::{ActiveOperator, OperatorPhase};
|
||||
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq)]
|
||||
#[reflect(Component, Default)]
|
||||
@@ -3074,6 +3216,7 @@ mod tests {
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<TransformEditTracker>();
|
||||
let first = world.spawn((LevelObject, Transform::default())).id();
|
||||
let second = world
|
||||
.spawn((
|
||||
@@ -3085,30 +3228,19 @@ mod tests {
|
||||
let committed = vec![Vec3::Z, Vec3::new(2.0, 0.0, 1.0)];
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
set_transform_group_with_history(
|
||||
&mut world,
|
||||
[
|
||||
(
|
||||
world.resource_mut::<TransformEditTracker>().active = Some((
|
||||
first,
|
||||
Transform::default(),
|
||||
Transform::from_translation(committed[0]),
|
||||
),
|
||||
(
|
||||
second,
|
||||
Transform::from_translation(initial[1]),
|
||||
Transform::from_translation(committed[1]),
|
||||
),
|
||||
vec![
|
||||
(first, Transform::default()),
|
||||
(second, Transform::from_translation(initial[1])),
|
||||
],
|
||||
);
|
||||
world.resource_mut::<ActiveOperator>().status = Some(OperatorStatus {
|
||||
id: "transform.gizmo".to_string(),
|
||||
label: "Transform Gizmo".to_string(),
|
||||
phase: OperatorPhase::Committed,
|
||||
hint: "Committed multi-selection drag".to_string(),
|
||||
warnings: Vec::new(),
|
||||
});
|
||||
));
|
||||
*world.get_mut::<Transform>(first).unwrap() = Transform::from_translation(committed[0]);
|
||||
capture_gizmo_transform_edits(&mut world);
|
||||
|
||||
harness.assert_committed(&mut world, 1, 0);
|
||||
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Committed);
|
||||
assert_undo_redo_round_trip(&mut world, initial, committed, |world| {
|
||||
[first, second]
|
||||
.into_iter()
|
||||
@@ -3117,6 +3249,63 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_op_transform_release_terminates_preview_without_history() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<TransformEditTracker>();
|
||||
let transform = Transform::from_xyz(1.0, 2.0, 3.0);
|
||||
let entity = world.spawn((LevelObject, transform)).id();
|
||||
world.resource_mut::<TransformEditTracker>().active =
|
||||
Some((entity, transform, vec![(entity, transform)]));
|
||||
set_transform_operator_status(
|
||||
&mut world,
|
||||
OperatorPhase::Preview,
|
||||
"Transform gizmo drag in progress",
|
||||
);
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
capture_gizmo_transform_edits(&mut world);
|
||||
|
||||
harness.assert_canceled(&mut world);
|
||||
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Canceled);
|
||||
assert_eq!(world.get::<Transform>(entity), Some(&transform));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_primary_transform_rolls_back_surviving_preview_targets() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<TransformEditTracker>();
|
||||
let primary_old = Transform::from_xyz(1.0, 0.0, 0.0);
|
||||
let survivor_old = Transform::from_xyz(2.0, 0.0, 0.0);
|
||||
let primary = world.spawn((LevelObject, primary_old)).id();
|
||||
let survivor = world.spawn((LevelObject, survivor_old)).id();
|
||||
world.resource_mut::<TransformEditTracker>().active = Some((
|
||||
primary,
|
||||
primary_old,
|
||||
vec![(primary, primary_old), (survivor, survivor_old)],
|
||||
));
|
||||
*world.get_mut::<Transform>(survivor).unwrap() = Transform::from_xyz(8.0, 0.0, 0.0);
|
||||
world.despawn(primary);
|
||||
set_transform_operator_status(
|
||||
&mut world,
|
||||
OperatorPhase::Preview,
|
||||
"Transform gizmo drag in progress",
|
||||
);
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
|
||||
capture_gizmo_transform_edits(&mut world);
|
||||
|
||||
harness.assert_canceled(&mut world);
|
||||
harness.assert_status(&world, "transform.gizmo", OperatorPhase::Canceled);
|
||||
assert_eq!(world.get::<Transform>(survivor), Some(&survivor_old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpack_prefab_is_one_undoable_history_command() {
|
||||
let mut world = World::new();
|
||||
|
||||
@@ -39,6 +39,7 @@ pub use viewport::brush_tool;
|
||||
pub use viewport::camera;
|
||||
pub use viewport::gizmos;
|
||||
pub use viewport::material_drop;
|
||||
pub use viewport::physics_placement;
|
||||
pub use viewport::render_view;
|
||||
pub use viewport::rendering_diagnostics;
|
||||
pub use viewport::selection;
|
||||
@@ -68,6 +69,7 @@ use history::EditorHistoryPlugin;
|
||||
use infra::EditorInfraPlugin;
|
||||
use material_drop::MaterialDropPlugin;
|
||||
use operators::OperatorPlugin;
|
||||
use physics_placement::PhysicsPlacementPlugin;
|
||||
use play::audio_preview::AudioPreviewPlugin;
|
||||
use play::PlaySessionPlugin;
|
||||
use project::collaboration::CollaborationPlugin;
|
||||
@@ -119,6 +121,7 @@ impl PluginGroup for EditorPluginGroup {
|
||||
.add(AudioPreviewPlugin)
|
||||
.add(ActorIconsPlugin)
|
||||
.add(MaterialDropPlugin)
|
||||
.add(PhysicsPlacementPlugin)
|
||||
.add(EditorSelectionPlugin)
|
||||
.add(SelectionOutlinePlugin)
|
||||
.add(EditorGizmoPlugin)
|
||||
|
||||
@@ -59,6 +59,12 @@ pub enum OperatorAvailability {
|
||||
Disabled(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OperatorAction {
|
||||
Commit,
|
||||
ContinuePreview,
|
||||
}
|
||||
|
||||
pub trait EditorOperator {
|
||||
fn id(&self) -> &str;
|
||||
fn label(&self) -> &str;
|
||||
@@ -221,6 +227,51 @@ pub fn run_immediate_operator(
|
||||
run_operator(world, &mut operator)
|
||||
}
|
||||
|
||||
/// Runs an editor command that may either complete immediately or hand ownership to a modal tool.
|
||||
/// Modal starters retain the preview status installed by their production entry point.
|
||||
pub fn run_operator_action(
|
||||
world: &mut World,
|
||||
id: &str,
|
||||
label: &str,
|
||||
availability: OperatorAvailability,
|
||||
action: impl FnOnce(&mut World) -> Result<OperatorAction, String>,
|
||||
) -> bool {
|
||||
if let OperatorAvailability::Disabled(reason) = availability {
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorStatus::new(id, label, OperatorPhase::Blocked, reason),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorStatus::new(id, label, OperatorPhase::Preview, "Starting"),
|
||||
);
|
||||
match action(world) {
|
||||
Ok(OperatorAction::Commit) => {
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorStatus::new(
|
||||
id,
|
||||
label,
|
||||
OperatorPhase::Committed,
|
||||
format!("Completed {label}"),
|
||||
),
|
||||
);
|
||||
true
|
||||
}
|
||||
Ok(OperatorAction::ContinuePreview) => true,
|
||||
Err(error) => {
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorStatus::new(id, label, OperatorPhase::Canceled, error),
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_operator_status(world: &mut World, status: OperatorStatus) {
|
||||
if let Some(mut active) = world.get_resource_mut::<ActiveOperator>() {
|
||||
active.status = Some(status);
|
||||
@@ -355,6 +406,52 @@ mod tests {
|
||||
harness.assert_no_helpers::<PreviewHelper>(&mut world);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_failure_runs_cancel_and_cleans_helpers() {
|
||||
struct PreviewFailure(CounterOperator);
|
||||
|
||||
impl EditorOperator for PreviewFailure {
|
||||
fn id(&self) -> &str {
|
||||
self.0.id()
|
||||
}
|
||||
|
||||
fn label(&self) -> &str {
|
||||
self.0.label()
|
||||
}
|
||||
|
||||
fn begin(&mut self, world: &mut World) -> Result<(), String> {
|
||||
self.0.begin(world)
|
||||
}
|
||||
|
||||
fn preview(&mut self, world: &mut World) -> Result<(), String> {
|
||||
self.0.preview(world)?;
|
||||
Err("preview failed".to_string())
|
||||
}
|
||||
|
||||
fn commit(&mut self, _world: &mut World) -> Result<(), String> {
|
||||
panic!("commit must not run after preview failure")
|
||||
}
|
||||
|
||||
fn cancel(&mut self, world: &mut World) {
|
||||
self.0.cancel(world);
|
||||
}
|
||||
}
|
||||
|
||||
let mut world = test_world();
|
||||
let harness = OperatorInvariantHarness::capture(&mut world);
|
||||
let mut operator = PreviewFailure(CounterOperator {
|
||||
before: 0,
|
||||
helper: None,
|
||||
});
|
||||
|
||||
assert!(!run_operator(&mut world, &mut operator));
|
||||
|
||||
harness.assert_canceled(&mut world);
|
||||
harness.assert_status(&world, "test.counter", OperatorPhase::Canceled);
|
||||
harness.assert_no_helpers::<PreviewHelper>(&mut world);
|
||||
assert_eq!(world.resource::<Counter>().0, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_operator_never_begins_or_mutates_world() {
|
||||
let mut world = test_world();
|
||||
|
||||
@@ -47,6 +47,12 @@ impl OperatorInvariantHarness {
|
||||
world.resource::<SceneIo>().dirty,
|
||||
"a committed authored mutation must mark the scene dirty"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
world.resource::<SceneIo>().dirty,
|
||||
self.dirty,
|
||||
"a committed non-authoring operator must preserve the prior dirty state"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
authored_count(world) as isize,
|
||||
@@ -93,6 +99,39 @@ impl OperatorInvariantHarness {
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn assert_status(
|
||||
&self,
|
||||
world: &World,
|
||||
expected_id: &str,
|
||||
expected_phase: OperatorPhase,
|
||||
) {
|
||||
let status = world
|
||||
.resource::<ActiveOperator>()
|
||||
.status
|
||||
.as_ref()
|
||||
.expect("operator must retain an inspectable lifecycle status");
|
||||
assert_eq!(status.id, expected_id, "operator reported the wrong id");
|
||||
assert_eq!(
|
||||
status.phase, expected_phase,
|
||||
"operator reported the wrong phase"
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn assert_projection_unchanged<T>(
|
||||
&self,
|
||||
world: &mut World,
|
||||
expected: T,
|
||||
mut read: impl FnMut(&mut World) -> T,
|
||||
) where
|
||||
T: Debug + PartialEq,
|
||||
{
|
||||
assert_eq!(
|
||||
read(world),
|
||||
expected,
|
||||
"operator changed authored state without a committed history transaction"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_phase(&self, world: &World, expected: OperatorPhase) {
|
||||
let phase = world
|
||||
.resource::<ActiveOperator>()
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use avian3d::prelude::{Physics, PhysicsTime};
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
|
||||
use bevy_egui::PrimaryEguiContext;
|
||||
use game::player::PlayerCamera;
|
||||
use game::{GameInputEnabled, GameInputFocused, SimEnabled};
|
||||
use protocol::PlayerInputIntent;
|
||||
use protocol::{PlayerInputIntent, SIM_TICK_RATE_HZ};
|
||||
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
@@ -195,6 +198,7 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
mut step: ResMut<PlayStepOnce>,
|
||||
mut input_enabled: ResMut<GameInputEnabled>,
|
||||
mut sim_enabled: ResMut<SimEnabled>,
|
||||
mut physics_time: ResMut<Time<Physics>>,
|
||||
mut editor_cameras: Query<&mut Camera, With<EditorCamera>>,
|
||||
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
|
||||
mut egui_cameras: Query<
|
||||
@@ -212,9 +216,11 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
let ejected = playing && *possession == PlayPossession::Ejected;
|
||||
let possessed = playing && *possession == PlayPossession::Possessed;
|
||||
|
||||
sim_enabled.0 = playing && (!paused.0 || step.0);
|
||||
let stepping = step.0;
|
||||
sim_enabled.0 = playing && (!paused.0 || stepping);
|
||||
input_enabled.0 = possessed && !paused.0;
|
||||
if step.0 {
|
||||
sync_editor_physics_clock(&mut physics_time, playing, paused.0, stepping);
|
||||
if stepping {
|
||||
step.0 = false;
|
||||
}
|
||||
|
||||
@@ -240,6 +246,22 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_editor_physics_clock(
|
||||
physics_time: &mut Time<Physics>,
|
||||
playing: bool,
|
||||
paused: bool,
|
||||
stepping: bool,
|
||||
) {
|
||||
if playing && !paused {
|
||||
physics_time.unpause();
|
||||
return;
|
||||
}
|
||||
physics_time.pause();
|
||||
if playing && stepping {
|
||||
physics_time.advance_by(Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64));
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_play_input_focus(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
@@ -414,3 +436,29 @@ pub fn toggle_play_possession_world(world: &mut World) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn editor_physics_clock_tracks_edit_play_pause_and_single_step() {
|
||||
let mut time = Time::<Physics>::default();
|
||||
|
||||
sync_editor_physics_clock(&mut time, false, false, false);
|
||||
assert!(time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, false, false);
|
||||
assert!(!time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, true, false);
|
||||
assert!(time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, true, true);
|
||||
assert!(time.is_paused());
|
||||
assert_eq!(
|
||||
time.delta(),
|
||||
Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,9 @@ use crate::project_io::ProjectWorkspace;
|
||||
use crate::scene_io::{SceneIo, SceneIoEventSeverity};
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::collider_diagnostics::{
|
||||
ColliderDiagnosticSeverity, ColliderDiagnosticsState, ColliderOverlayStatus,
|
||||
};
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct DiagnosticsPanel {
|
||||
@@ -138,6 +141,9 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
collider_diagnostics_ui(world, ui);
|
||||
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.strong("Support bundle");
|
||||
@@ -193,6 +199,73 @@ pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
ui.small("BRP is enabled on the editor for external tooling.");
|
||||
}
|
||||
|
||||
fn collider_diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let Some(state) = world.get_resource::<ColliderDiagnosticsState>() else {
|
||||
return;
|
||||
};
|
||||
let mut rows = state.entries.values().cloned().collect::<Vec<_>>();
|
||||
rows.sort_by(|left, right| left.actor_name.cmp(&right.actor_name));
|
||||
let valid = state.valid_actors;
|
||||
let disabled = state.disabled_actors;
|
||||
let warnings = state.warning_actors;
|
||||
let errors = state.error_actors;
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong("Collider health");
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(125, 210, 145),
|
||||
format!("{valid} ready"),
|
||||
);
|
||||
if disabled > 0 {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(143, 151, 163),
|
||||
format!("{disabled} disabled"),
|
||||
);
|
||||
}
|
||||
if warnings > 0 {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(242, 173, 72),
|
||||
format!("{warnings} warning"),
|
||||
);
|
||||
}
|
||||
if errors > 0 {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(244, 91, 99),
|
||||
format!("{errors} invalid"),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for row in rows.into_iter().filter(|row| {
|
||||
matches!(
|
||||
row.overlay_status,
|
||||
ColliderOverlayStatus::Warning | ColliderOverlayStatus::Error
|
||||
)
|
||||
}) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let color = match row.overlay_status {
|
||||
ColliderOverlayStatus::Error => egui::Color32::from_rgb(244, 91, 99),
|
||||
_ => egui::Color32::from_rgb(242, 173, 72),
|
||||
};
|
||||
ui.colored_label(color, row.shape_label);
|
||||
ui.label(&row.actor_name);
|
||||
if ui.small_button("Select").clicked() {
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(row.entity);
|
||||
world
|
||||
.resource_mut::<UiState>()
|
||||
.selected_entities
|
||||
.select_replace(row.entity);
|
||||
}
|
||||
});
|
||||
for diagnostic in &row.diagnostics {
|
||||
if diagnostic.severity == ColliderDiagnosticSeverity::Info {
|
||||
continue;
|
||||
}
|
||||
ui.small(format!("{}: {}", diagnostic.code, diagnostic.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn brush_diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
|
||||
if !*open {
|
||||
return;
|
||||
|
||||
@@ -11,7 +11,10 @@ use sim::Player;
|
||||
use crate::assets::{snapshot_for_asset, EditorAsset, EditorAssetKind};
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::history::{set_material_group_with_history, spawn_with_history, EditorEntitySnapshot};
|
||||
use crate::history::{
|
||||
set_light_group_with_history, set_material_group_with_history, spawn_with_history,
|
||||
EditorEntitySnapshot,
|
||||
};
|
||||
use crate::play::default_player_spawn;
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::viewport::{recall_camera_bookmark, save_camera_bookmark, CameraBookmarks};
|
||||
@@ -191,37 +194,23 @@ pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
|
||||
|
||||
/// Removes all authored [`LightDesc`] so project sun/ambient drive outdoor lighting.
|
||||
pub fn reset_scene_lighting_to_project_defaults(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let with_lights: Vec<Entity> = query
|
||||
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
|
||||
let changes = query
|
||||
.iter(world)
|
||||
.filter(|entity| world.get::<LightDesc>(*entity).is_some())
|
||||
.collect();
|
||||
for entity in with_lights {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
.map(|(entity, _)| (entity, None))
|
||||
.collect::<Vec<_>>();
|
||||
set_light_group_with_history(world, changes, "Reset Scene Lighting");
|
||||
}
|
||||
|
||||
/// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting.
|
||||
pub fn use_project_sun(world: &mut World) {
|
||||
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
|
||||
let directionals: Vec<Entity> = query
|
||||
let changes = query
|
||||
.iter(world)
|
||||
.filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional))
|
||||
.map(|(e, _)| e)
|
||||
.collect();
|
||||
for entity in directionals {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
.map(|(entity, _)| (entity, None))
|
||||
.collect::<Vec<_>>();
|
||||
set_light_group_with_history(world, changes, "Use Project Sun");
|
||||
}
|
||||
|
||||
pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Entity {
|
||||
|
||||
@@ -44,6 +44,9 @@ use crate::ui::theme::{
|
||||
};
|
||||
use crate::ui::widgets::{icon_button_small, phosphor_icon, phosphor_icon_text};
|
||||
use crate::viewport::brush_edit::{BrushElementKey, BrushElementSelection};
|
||||
use crate::viewport::collider_diagnostics::{
|
||||
diagnose_collider, ColliderDiagnosticSeverity, ColliderOverlayStatus,
|
||||
};
|
||||
|
||||
use super::component_registry::{
|
||||
EditorComponentCategory, EditorComponentDescriptor, EditorComponentRegistry,
|
||||
@@ -4213,6 +4216,7 @@ fn rigid_body_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
|
||||
fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let mesh_candidates = static_mesh_asset_ref_candidates(world, AssetRefCandidateKind::Mesh);
|
||||
let diagnostic_entry = diagnose_collider(world, entity);
|
||||
let Some(mut collider) = world.get::<ColliderDesc>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
@@ -4235,13 +4239,60 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
ComponentCardOptions::removable(COMPONENT_COLLIDER_DESC, "Collider", icons::SELECTION),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
if let Some(entry) = diagnostic_entry.as_ref() {
|
||||
let (label, color) = match entry.overlay_status {
|
||||
ColliderOverlayStatus::Valid => ("Ready", egui::Color32::from_rgb(112, 210, 144)),
|
||||
ColliderOverlayStatus::Trigger => {
|
||||
("Trigger", egui::Color32::from_rgb(86, 195, 235))
|
||||
}
|
||||
ColliderOverlayStatus::Disabled => {
|
||||
("Disabled", egui::Color32::from_rgb(143, 151, 163))
|
||||
}
|
||||
ColliderOverlayStatus::Warning => {
|
||||
("Warning", egui::Color32::from_rgb(242, 173, 72))
|
||||
}
|
||||
ColliderOverlayStatus::Error => ("Invalid", egui::Color32::from_rgb(244, 91, 99)),
|
||||
};
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.colored_label(color, egui::RichText::new(label).strong());
|
||||
ui.label(egui::RichText::new(entry.shape_label).color(TEXT_DIM));
|
||||
if entry.runtime_ready {
|
||||
ui.label(egui::RichText::new("Hydrated").color(TEXT_MUTED).small());
|
||||
}
|
||||
});
|
||||
for diagnostic in &entry.diagnostics {
|
||||
let color = match diagnostic.severity {
|
||||
ColliderDiagnosticSeverity::Info => TEXT_MUTED,
|
||||
ColliderDiagnosticSeverity::Warning => egui::Color32::from_rgb(242, 173, 72),
|
||||
ColliderDiagnosticSeverity::Error => egui::Color32::from_rgb(244, 91, 99),
|
||||
};
|
||||
ui.label(
|
||||
egui::RichText::new(&diagnostic.message)
|
||||
.color(color)
|
||||
.small(),
|
||||
);
|
||||
ui.label(
|
||||
egui::RichText::new(&diagnostic.repair)
|
||||
.color(TEXT_MUTED)
|
||||
.small(),
|
||||
);
|
||||
}
|
||||
if entry.highest_severity() == Some(ColliderDiagnosticSeverity::Error)
|
||||
&& ui.small_button("Reset shape").clicked()
|
||||
{
|
||||
collider.shape = ColliderShapeDesc::default();
|
||||
collider.enabled = true;
|
||||
changed = true;
|
||||
}
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
property_row(ui, "Mode", |ui| {
|
||||
changed |= ui.checkbox(&mut collider.enabled, "Enabled").changed();
|
||||
changed |= ui.checkbox(&mut collider.is_trigger, "Trigger").changed();
|
||||
});
|
||||
property_row(ui, "Shape", |ui| {
|
||||
let mut shape_kind = collider_shape_kind(&collider.shape);
|
||||
egui::ComboBox::from_id_salt("collider_shape_kind")
|
||||
egui::ComboBox::from_id_salt(("collider_shape_kind", entity))
|
||||
.selected_text(shape_kind)
|
||||
.show_ui(ui, |ui| {
|
||||
for label in ["Box", "Sphere", "Capsule", "Static Mesh"] {
|
||||
@@ -4251,15 +4302,8 @@ fn collider_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
}
|
||||
});
|
||||
if shape_kind != collider_shape_kind(&collider.shape) {
|
||||
collider.shape = match shape_kind {
|
||||
"Sphere" => ColliderShapeDesc::Sphere { radius: 0.5 },
|
||||
"Capsule" => ColliderShapeDesc::Capsule {
|
||||
radius: 0.5,
|
||||
height: 1.0,
|
||||
},
|
||||
"Static Mesh" => ColliderShapeDesc::static_mesh(renderer_meshes.clone()),
|
||||
_ => ColliderShapeDesc::default(),
|
||||
};
|
||||
collider.shape =
|
||||
convert_collider_shape(&collider.shape, shape_kind, renderer_meshes.clone());
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
@@ -4327,12 +4371,48 @@ fn collider_shape_kind(shape: &ColliderShapeDesc) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_collider_shape(
|
||||
previous: &ColliderShapeDesc,
|
||||
shape_kind: &str,
|
||||
renderer_meshes: Vec<EditorAssetRef>,
|
||||
) -> ColliderShapeDesc {
|
||||
let dimensions = match previous {
|
||||
ColliderShapeDesc::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => Vec3::new(*x_length, *y_length, *z_length),
|
||||
ColliderShapeDesc::Sphere { radius } => Vec3::splat(*radius * 2.0),
|
||||
ColliderShapeDesc::Capsule { radius, height } => {
|
||||
Vec3::new(*radius * 2.0, *height, *radius * 2.0)
|
||||
}
|
||||
ColliderShapeDesc::StaticMesh { .. } => Vec3::ONE,
|
||||
}
|
||||
.max(Vec3::splat(0.001));
|
||||
|
||||
match shape_kind {
|
||||
"Sphere" => ColliderShapeDesc::Sphere {
|
||||
radius: dimensions.max_element() * 0.5,
|
||||
},
|
||||
"Capsule" => ColliderShapeDesc::Capsule {
|
||||
radius: dimensions.x.max(dimensions.z) * 0.5,
|
||||
height: dimensions.y,
|
||||
},
|
||||
"Static Mesh" => ColliderShapeDesc::static_mesh(renderer_meshes),
|
||||
_ => ColliderShapeDesc::Cuboid {
|
||||
x_length: dimensions.x,
|
||||
y_length: dimensions.y,
|
||||
z_length: dimensions.z,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn dimension_drag(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool {
|
||||
property_row(ui, label, |ui| {
|
||||
ui.add_sized(
|
||||
[fit_width(ui, 72.0, 120.0), 20.0],
|
||||
egui::DragValue::new(value)
|
||||
.range(0.0..=10_000.0)
|
||||
.range(0.001..=10_000.0)
|
||||
.speed(0.05)
|
||||
.min_decimals(2)
|
||||
.max_decimals(3),
|
||||
@@ -4839,3 +4919,30 @@ fn option_string_ui(ui: &mut egui::Ui, label: &str, value: &mut Option<String>)
|
||||
};
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod collider_inspector_tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_undo, EditorHistory};
|
||||
|
||||
#[test]
|
||||
fn shape_switch_preserves_dimensions_and_is_one_undoable_edit() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<EditorHistory>();
|
||||
let original = ColliderDesc::static_cuboid(Vec3::new(2.0, 4.0, 6.0));
|
||||
let entity = world.spawn((LevelObject, original.clone())).id();
|
||||
|
||||
let sphere = ColliderDesc {
|
||||
shape: convert_collider_shape(&original.shape, "Sphere", Vec::new()),
|
||||
..original.clone()
|
||||
};
|
||||
assert_eq!(sphere.shape, ColliderShapeDesc::Sphere { radius: 3.0 });
|
||||
|
||||
set_collider_with_history(&mut world, entity, sphere.clone());
|
||||
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
|
||||
assert_eq!(world.get::<ColliderDesc>(entity), Some(&sphere));
|
||||
|
||||
apply_command_undo(&mut world);
|
||||
assert_eq!(world.get::<ColliderDesc>(entity), Some(&original));
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,15 @@ use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::render_target::ViewportRenderTarget;
|
||||
use crate::selection::{ViewportClick, ViewportPickStack};
|
||||
use crate::selection::{SelectedEntity, ViewportClick, ViewportPickStack};
|
||||
use crate::state::PlayPossession;
|
||||
use crate::viewport::actor_icons::ActorIconSettings;
|
||||
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
|
||||
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
|
||||
use crate::viewport::physics_placement::{
|
||||
begin_physics_placement, request_physics_placement, PhysicsPlacementPhase,
|
||||
PhysicsPlacementRequest, PhysicsPlacementState,
|
||||
};
|
||||
use crate::viewport::terrain_paint::{TerrainPaintMode, TerrainPaintState};
|
||||
use crate::viewport::terrain_sculpt::{TerrainSculptMode, TerrainSculptState};
|
||||
use crate::viewport::{
|
||||
@@ -146,11 +150,12 @@ pub fn viewport_tab_ui(
|
||||
return;
|
||||
}
|
||||
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect, selected_entities);
|
||||
scene_view_selection_hud(world, ui.ctx(), rect, selected_entities);
|
||||
scene_view_brush_draw_hints(world, ui.ctx(), rect);
|
||||
scene_view_terrain_sculpt_hints(world, ui.ctx(), rect);
|
||||
scene_view_terrain_paint_hints(world, ui.ctx(), rect);
|
||||
scene_view_physics_placement_hud(world, ui.ctx(), rect);
|
||||
scene_view_render_badge(world, ui.ctx(), rect);
|
||||
scene_view_brush_mode_badge(world, ui.ctx(), rect);
|
||||
scene_view_volume_hud(world, ui.ctx(), rect);
|
||||
@@ -195,16 +200,54 @@ fn scene_view_render_badge(world: &World, ctx: &egui::Context, scene_rect: egui:
|
||||
});
|
||||
|
||||
if mode == EditorViewportMode::Collider {
|
||||
let health =
|
||||
world.get_resource::<crate::viewport::collider_diagnostics::ColliderDiagnosticsState>();
|
||||
let selected_entry = world
|
||||
.get_resource::<SelectedEntity>()
|
||||
.and_then(|selected| selected.0)
|
||||
.and_then(|entity| health.and_then(|health| health.entry(entity)));
|
||||
egui::Area::new(egui::Id::new("scene_view_collider_warning"))
|
||||
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
overlay_chip_frame().show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(
|
||||
egui::RichText::new("Collider view / meshes hidden")
|
||||
egui::RichText::new("Collider View")
|
||||
.color(WARNING)
|
||||
.strong()
|
||||
.small(),
|
||||
);
|
||||
if let Some(health) = health {
|
||||
ui.label(
|
||||
egui::RichText::new(format!(
|
||||
"{} ready {} disabled {} warning {} invalid",
|
||||
health.valid_actors,
|
||||
health.disabled_actors,
|
||||
health.warning_actors,
|
||||
health.error_actors
|
||||
))
|
||||
.color(TEXT_MUTED)
|
||||
.small(),
|
||||
);
|
||||
}
|
||||
});
|
||||
if let Some(entry) = selected_entry {
|
||||
ui.label(
|
||||
egui::RichText::new(format!(
|
||||
"{} / {} / {}",
|
||||
entry.actor_name,
|
||||
entry.shape_label,
|
||||
if entry.runtime_ready {
|
||||
"hydrated"
|
||||
} else {
|
||||
"not hydrated"
|
||||
}
|
||||
))
|
||||
.color(SELECTION)
|
||||
.small(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -582,7 +625,12 @@ fn scene_view_volume_hud(world: &World, ctx: &egui::Context, scene_rect: egui::R
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
fn scene_view_overlay_toolbar(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
scene_rect: egui::Rect,
|
||||
selected_entities: &SelectedEntities,
|
||||
) {
|
||||
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
||||
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
||||
let terrain_selected = world
|
||||
@@ -737,6 +785,56 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
||||
}
|
||||
}
|
||||
|
||||
let placement_active = world.resource::<PhysicsPlacementState>().active();
|
||||
ui.separator();
|
||||
if placement_active {
|
||||
let phase = world.resource::<PhysicsPlacementState>().phase;
|
||||
ui.label(
|
||||
egui::RichText::new(phase.label())
|
||||
.color(match phase {
|
||||
PhysicsPlacementPhase::Settled => SUCCESS,
|
||||
PhysicsPlacementPhase::TimedOut => WARNING,
|
||||
_ => SELECTION,
|
||||
})
|
||||
.strong()
|
||||
.small(),
|
||||
);
|
||||
if icon_button_small(
|
||||
ui,
|
||||
icons::CHECK,
|
||||
"Commit physics placement (Enter when settled)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
request_physics_placement(world, PhysicsPlacementRequest::Commit);
|
||||
}
|
||||
if icon_button_small(ui, icons::X, "Cancel physics placement (Esc)")
|
||||
.clicked()
|
||||
{
|
||||
request_physics_placement(world, PhysicsPlacementRequest::Cancel);
|
||||
}
|
||||
} else {
|
||||
let selected = selected_entities.iter().collect::<Vec<_>>();
|
||||
let can_start = !selected.is_empty();
|
||||
let clicked = ui
|
||||
.add_enabled(
|
||||
can_start,
|
||||
egui::Button::new(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0)),
|
||||
)
|
||||
.on_hover_text(if can_start {
|
||||
"Release selected props into physics"
|
||||
} else {
|
||||
"Select one or more props to place with physics"
|
||||
})
|
||||
.clicked();
|
||||
if clicked && begin_physics_placement(world, selected).is_ok() {
|
||||
world.resource_mut::<TerrainSculptState>().stop();
|
||||
world.resource_mut::<TerrainPaintState>().stop();
|
||||
world.resource_mut::<BrushToolState>().cancel();
|
||||
world.resource_mut::<ViewportClick>().0 = None;
|
||||
}
|
||||
}
|
||||
|
||||
let sculpt_active = world.resource::<TerrainSculptState>().active;
|
||||
let paint_active = world.resource::<TerrainPaintState>().active;
|
||||
if terrain_selected.is_some() || sculpt_active || paint_active {
|
||||
@@ -950,6 +1048,66 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = shortcuts_open;
|
||||
}
|
||||
|
||||
fn scene_view_physics_placement_hud(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let state = world.resource::<PhysicsPlacementState>();
|
||||
if !state.active() {
|
||||
let Some(error) = state.last_error.as_deref() else {
|
||||
return;
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_physics_placement_error"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
overlay_chip_frame().show(ui, |ui| {
|
||||
ui.label(
|
||||
egui::RichText::new("Physics placement unavailable")
|
||||
.color(ERROR)
|
||||
.strong(),
|
||||
);
|
||||
for line in error.lines().take(4) {
|
||||
ui.label(egui::RichText::new(line).color(TEXT_DIM).small());
|
||||
}
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_physics_placement_hud"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
overlay_chip_frame().show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0).color(SELECTION));
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Physics Placement / {}", state.phase.label()))
|
||||
.color(match state.phase {
|
||||
PhysicsPlacementPhase::Settled => SUCCESS,
|
||||
PhysicsPlacementPhase::TimedOut => WARNING,
|
||||
_ => SELECTION,
|
||||
})
|
||||
.strong(),
|
||||
);
|
||||
ui.label(
|
||||
egui::RichText::new(format!(
|
||||
"{} props / {:.1}s",
|
||||
state.selected_count,
|
||||
state.simulated_seconds()
|
||||
))
|
||||
.color(TEXT_DIM)
|
||||
.monospace()
|
||||
.small(),
|
||||
);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
key_hint(ui, "Esc", "Cancel");
|
||||
key_hint(ui, "Enter", "Commit when settled");
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_options_popover(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
|
||||
@@ -4,7 +4,7 @@ use bevy::math::Affine3A;
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
brush_math::{validate_brush, BrushDiagnosticSeverity},
|
||||
BrushDesc, LevelObject,
|
||||
BrushDesc,
|
||||
};
|
||||
|
||||
use crate::history::apply_brush_csg_with_history;
|
||||
@@ -64,24 +64,27 @@ pub fn selected_brush_count(world: &World) -> usize {
|
||||
.resource::<UiState>()
|
||||
.selected_entities
|
||||
.iter()
|
||||
.filter(|entity| world.get::<BrushDesc>(*entity).is_some())
|
||||
.filter(|entity| {
|
||||
world.get::<BrushDesc>(*entity).is_some()
|
||||
&& crate::ui::selection_ops::is_mutable_level_object(world, *entity)
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn intersect_selected_brushes(world: &mut World) {
|
||||
run_bounds_csg(world, BrushCsgOp::Intersect);
|
||||
pub fn intersect_selected_brushes(world: &mut World) -> Result<(), String> {
|
||||
run_bounds_csg(world, BrushCsgOp::Intersect)
|
||||
}
|
||||
|
||||
pub fn merge_selected_brushes(world: &mut World) {
|
||||
run_bounds_csg(world, BrushCsgOp::Merge);
|
||||
pub fn merge_selected_brushes(world: &mut World) -> Result<(), String> {
|
||||
run_bounds_csg(world, BrushCsgOp::Merge)
|
||||
}
|
||||
|
||||
pub fn subtract_selected_brushes(world: &mut World) {
|
||||
run_bounds_csg(world, BrushCsgOp::Subtract);
|
||||
pub fn subtract_selected_brushes(world: &mut World) -> Result<(), String> {
|
||||
run_bounds_csg(world, BrushCsgOp::Subtract)
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Debug, Clone)]
|
||||
struct BrushCsgPreview {
|
||||
pub(crate) struct BrushCsgPreview {
|
||||
pending: Option<PendingBrushCsg>,
|
||||
}
|
||||
|
||||
@@ -99,18 +102,18 @@ enum BrushCsgOp {
|
||||
Subtract,
|
||||
}
|
||||
|
||||
fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
fn run_bounds_csg(world: &mut World, op: BrushCsgOp) -> Result<(), String> {
|
||||
let selected: Vec<Entity> = world
|
||||
.resource::<UiState>()
|
||||
.selected_entities
|
||||
.iter()
|
||||
.filter(|entity| {
|
||||
world.get::<LevelObject>(*entity).is_some() && world.get::<BrushDesc>(*entity).is_some()
|
||||
world.get::<BrushDesc>(*entity).is_some()
|
||||
&& crate::ui::selection_ops::is_mutable_level_object(world, *entity)
|
||||
})
|
||||
.collect();
|
||||
if selected.len() < 2 {
|
||||
set_status(world, "Select at least two brushes for CSG");
|
||||
return;
|
||||
return csg_failure(world, "Select at least two editable brushes for CSG");
|
||||
}
|
||||
for entity in &selected {
|
||||
let Some(brush) = world.get::<BrushDesc>(*entity) else {
|
||||
@@ -118,20 +121,18 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
};
|
||||
let validation = validate_brush(brush);
|
||||
if !validation.is_valid() {
|
||||
set_status(
|
||||
return csg_failure(
|
||||
world,
|
||||
format!(
|
||||
"CSG failed: selected brush is invalid: {}",
|
||||
first_brush_error(&validation)
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let Some(primary_bounds) = brush_world_bounds(world, selected[0]) else {
|
||||
set_status(world, "Primary brush has no valid bounds");
|
||||
return;
|
||||
return csg_failure(world, "Primary brush has no valid bounds");
|
||||
};
|
||||
|
||||
let result = match op {
|
||||
@@ -147,8 +148,7 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
continue;
|
||||
};
|
||||
let Some(intersection) = result.intersection(bounds) else {
|
||||
set_status(world, "Brush intersect failed: no overlap");
|
||||
return;
|
||||
return csg_failure(world, "Brush intersect failed: no overlap");
|
||||
};
|
||||
result = intersection;
|
||||
}
|
||||
@@ -156,16 +156,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
}
|
||||
BrushCsgOp::Subtract => {
|
||||
let Some(cutter_bounds) = brush_world_bounds(world, selected[1]) else {
|
||||
set_status(world, "Subtract failed: cutter brush has no valid bounds");
|
||||
return;
|
||||
return csg_failure(world, "Subtract failed: cutter brush has no valid bounds");
|
||||
};
|
||||
let Some(overlap) = primary_bounds.intersection(cutter_bounds) else {
|
||||
set_status(world, "Subtract failed: brushes do not overlap");
|
||||
return;
|
||||
return csg_failure(world, "Subtract failed: brushes do not overlap");
|
||||
};
|
||||
let Some(result) = largest_remaining_slab(primary_bounds, overlap) else {
|
||||
set_status(world, "Subtract failed: result would be empty");
|
||||
return;
|
||||
return csg_failure(world, "Subtract failed: result would be empty");
|
||||
};
|
||||
result
|
||||
}
|
||||
@@ -175,14 +172,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
let new_brush = BrushDesc::cuboid(size);
|
||||
let validation = validate_brush(&new_brush);
|
||||
if !validation.is_valid() {
|
||||
set_status(
|
||||
return csg_failure(
|
||||
world,
|
||||
format!(
|
||||
"CSG failed: result is invalid: {}",
|
||||
first_brush_error(&validation)
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
world.resource_mut::<BrushCsgPreview>().pending = Some(PendingBrushCsg {
|
||||
@@ -197,6 +193,13 @@ fn run_bounds_csg(world: &mut World, op: BrushCsgOp) {
|
||||
};
|
||||
set_status(world, hint);
|
||||
set_csg_operator_status(world, OperatorPhase::Preview, hint);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn csg_failure(world: &mut World, message: impl Into<String>) -> Result<(), String> {
|
||||
let message = message.into();
|
||||
set_status(world, message.clone());
|
||||
Err(message)
|
||||
}
|
||||
|
||||
fn brush_csg_preview_input(world: &mut World) {
|
||||
@@ -253,6 +256,22 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
if pending
|
||||
.selected
|
||||
.iter()
|
||||
.any(|entity| !crate::ui::selection_ops::is_mutable_level_object(world, *entity))
|
||||
{
|
||||
set_status(
|
||||
world,
|
||||
"Brush CSG commit blocked: selected content is no longer editable",
|
||||
);
|
||||
set_csg_operator_status(
|
||||
world,
|
||||
OperatorPhase::Blocked,
|
||||
"Commit blocked: selected content is no longer editable",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let new_brush = BrushDesc::cuboid(pending.result.size());
|
||||
let to_delete: Vec<_> = if matches!(pending.op, BrushCsgOp::Merge | BrushCsgOp::Intersect) {
|
||||
pending
|
||||
@@ -265,7 +284,11 @@ fn commit_csg_preview(world: &mut World, pending: PendingBrushCsg) {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
apply_bounds_result(world, primary, pending.result, new_brush, &to_delete);
|
||||
if !apply_bounds_result(world, primary, pending.result, new_brush, &to_delete) {
|
||||
set_status(world, "Brush CSG commit made no changes");
|
||||
set_csg_operator_status(world, OperatorPhase::Canceled, "No changes");
|
||||
return;
|
||||
}
|
||||
let hint = match pending.op {
|
||||
BrushCsgOp::Intersect => "Brush intersect committed",
|
||||
BrushCsgOp::Merge => "Brush convex merge committed",
|
||||
@@ -332,14 +355,14 @@ fn apply_bounds_result(
|
||||
bounds: BrushBounds,
|
||||
new_brush: BrushDesc,
|
||||
delete_entities: &[Entity],
|
||||
) {
|
||||
) -> bool {
|
||||
let center = bounds.center();
|
||||
let old_transform = world.get::<Transform>(entity).copied().unwrap_or_default();
|
||||
let mut new_transform = old_transform;
|
||||
new_transform.translation = center;
|
||||
new_transform.rotation = Quat::IDENTITY;
|
||||
new_transform.scale = Vec3::ONE;
|
||||
apply_brush_csg_with_history(world, entity, new_transform, new_brush, delete_entities);
|
||||
apply_brush_csg_with_history(world, entity, new_transform, new_brush, delete_entities)
|
||||
}
|
||||
|
||||
fn brush_world_bounds(world: &World, entity: Entity) -> Option<BrushBounds> {
|
||||
@@ -426,6 +449,7 @@ mod tests {
|
||||
use crate::history::{EditorCommand, EditorHistory};
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use crate::selection::SelectedEntity;
|
||||
use shared::LevelObject;
|
||||
|
||||
fn bounds(min: Vec3, max: Vec3) -> BrushBounds {
|
||||
BrushBounds { min, max }
|
||||
|
||||
@@ -1308,4 +1308,55 @@ mod tests {
|
||||
assert!(state.old_brush.is_none());
|
||||
assert!(!state.changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_element_release_uses_production_finalizer_and_round_trips() {
|
||||
let mut app = App::new();
|
||||
app.init_resource::<ActiveOperator>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<SceneIo>()
|
||||
.init_resource::<BrushEditMode>()
|
||||
.init_resource::<BrushElementSelection>()
|
||||
.init_resource::<BrushElementGizmoState>()
|
||||
.add_systems(Update, apply_brush_element_gizmo);
|
||||
let original = BrushDesc::cuboid(Vec3::ONE);
|
||||
let preview = BrushDesc::cuboid(Vec3::new(1.5, 1.0, 1.0));
|
||||
let brush_entity = app
|
||||
.world_mut()
|
||||
.spawn((LevelObject, preview.clone(), GlobalTransform::default()))
|
||||
.id();
|
||||
let helper = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
BrushElementGizmo,
|
||||
Transform::default(),
|
||||
GizmoTarget::default(),
|
||||
))
|
||||
.id();
|
||||
*app.world_mut().resource_mut::<BrushEditMode>() = BrushEditMode::Vertex;
|
||||
*app.world_mut().resource_mut::<BrushElementSelection>() = BrushElementSelection {
|
||||
brush: Some(brush_entity),
|
||||
elements: vec![BrushElementKey::Vertex {
|
||||
face: original.faces[0].id.clone(),
|
||||
index: 0,
|
||||
}],
|
||||
};
|
||||
*app.world_mut().resource_mut::<BrushElementGizmoState>() = BrushElementGizmoState {
|
||||
entity: Some(helper),
|
||||
brush: Some(brush_entity),
|
||||
old_brush: Some(original.clone()),
|
||||
old_gizmo: Some(Transform::default()),
|
||||
last_gizmo: Some(Transform::from_translation(Vec3::X * 0.25)),
|
||||
changed: true,
|
||||
};
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
app.update();
|
||||
|
||||
harness.assert_committed(app.world_mut(), 1, 0);
|
||||
harness.assert_status(app.world(), "brush.edit_mode", OperatorPhase::Committed);
|
||||
assert_undo_redo_round_trip(app.world_mut(), original, preview, |world| {
|
||||
world.get::<BrushDesc>(brush_entity).unwrap().clone()
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Shared authored/runtime collider diagnostics for editor workflows.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use avian3d::prelude::{Collider, RigidBody};
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
authoring_component_active, AuthoringComponentStates, ColliderDesc, ColliderShapeDesc,
|
||||
InspectorOrder, LevelObject, PhysicsBody, RigidBodyDesc, COMPONENT_COLLIDER_DESC,
|
||||
COMPONENT_PHYSICS_BODY, COMPONENT_RIGID_BODY_DESC,
|
||||
};
|
||||
|
||||
use crate::assets::asset_db::{find_asset_by_id, AssetRegistry};
|
||||
use crate::ui::selection_ops::entity_name;
|
||||
|
||||
/// Collider dimensions beyond this world-space extent are usually accidental in a meter-scale
|
||||
/// project and can severely degrade broad-phase performance.
|
||||
pub const OVERSIZED_COLLIDER_EXTENT: f32 = 1_000.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum ColliderDiagnosticSeverity {
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ColliderDiagnostic {
|
||||
pub code: &'static str,
|
||||
pub severity: ColliderDiagnosticSeverity,
|
||||
pub message: String,
|
||||
pub repair: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ColliderOverlayStatus {
|
||||
Valid,
|
||||
Trigger,
|
||||
Disabled,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ColliderDiagnosticEntry {
|
||||
pub entity: Entity,
|
||||
pub actor_name: String,
|
||||
pub shape_label: &'static str,
|
||||
pub runtime_ready: bool,
|
||||
pub diagnostics: Vec<ColliderDiagnostic>,
|
||||
pub overlay_status: ColliderOverlayStatus,
|
||||
}
|
||||
|
||||
impl ColliderDiagnosticEntry {
|
||||
pub fn highest_severity(&self) -> Option<ColliderDiagnosticSeverity> {
|
||||
self.diagnostics
|
||||
.iter()
|
||||
.map(|diagnostic| diagnostic.severity)
|
||||
.max()
|
||||
}
|
||||
|
||||
pub fn blocking_messages(&self) -> impl Iterator<Item = &str> {
|
||||
self.diagnostics
|
||||
.iter()
|
||||
.filter(|diagnostic| diagnostic.severity == ColliderDiagnosticSeverity::Error)
|
||||
.map(|diagnostic| diagnostic.message.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct ColliderDiagnosticsState {
|
||||
pub entries: HashMap<Entity, ColliderDiagnosticEntry>,
|
||||
pub valid_actors: usize,
|
||||
pub disabled_actors: usize,
|
||||
pub warning_actors: usize,
|
||||
pub error_actors: usize,
|
||||
}
|
||||
|
||||
impl ColliderDiagnosticsState {
|
||||
pub fn entry(&self, entity: Entity) -> Option<&ColliderDiagnosticEntry> {
|
||||
self.entries.get(&entity)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh_collider_diagnostics(world: &mut World) {
|
||||
let entities = world
|
||||
.iter_entities()
|
||||
.filter(|entity| entity.contains::<LevelObject>())
|
||||
.map(|entity| entity.id())
|
||||
.collect::<Vec<_>>();
|
||||
let mut state = ColliderDiagnosticsState::default();
|
||||
for entity in entities {
|
||||
let Some(entry) = diagnose_collider(world, entity) else {
|
||||
continue;
|
||||
};
|
||||
match entry.overlay_status {
|
||||
ColliderOverlayStatus::Error => state.error_actors += 1,
|
||||
ColliderOverlayStatus::Warning => state.warning_actors += 1,
|
||||
ColliderOverlayStatus::Disabled => state.disabled_actors += 1,
|
||||
_ => state.valid_actors += 1,
|
||||
}
|
||||
state.entries.insert(entity, entry);
|
||||
}
|
||||
world.insert_resource(state);
|
||||
}
|
||||
|
||||
pub fn diagnose_collider(world: &World, entity: Entity) -> Option<ColliderDiagnosticEntry> {
|
||||
let states = world.get::<AuthoringComponentStates>(entity);
|
||||
let order = world.get::<InspectorOrder>(entity);
|
||||
let rigid_body_active = world.get::<RigidBodyDesc>(entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_RIGID_BODY_DESC);
|
||||
let legacy_active = world.get::<PhysicsBody>(entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_PHYSICS_BODY);
|
||||
let collider = world.get::<ColliderDesc>(entity);
|
||||
let collider_active =
|
||||
collider.is_some() && authoring_component_active(states, order, COMPONENT_COLLIDER_DESC);
|
||||
|
||||
if !rigid_body_active && !legacy_active && collider.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut diagnostics = Vec::new();
|
||||
if rigid_body_active && !legacy_active && !collider_active {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.missing",
|
||||
severity: ColliderDiagnosticSeverity::Error,
|
||||
message: "Rigid body has no active Collider component.".into(),
|
||||
repair: "Add or enable a Collider component on this actor.".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut shape_label = if legacy_active { "Legacy" } else { "Missing" };
|
||||
let mut enabled = legacy_active;
|
||||
let mut trigger = false;
|
||||
let mut authoring_valid = true;
|
||||
if let Some(collider) = collider {
|
||||
shape_label = collider_shape_label(&collider.shape);
|
||||
enabled = collider_active && collider.enabled;
|
||||
trigger = collider.is_trigger;
|
||||
if !collider_active {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.inactive",
|
||||
severity: ColliderDiagnosticSeverity::Info,
|
||||
message: "Collider component is inactive.".into(),
|
||||
repair: "Enable the component when this actor should participate in collision."
|
||||
.into(),
|
||||
});
|
||||
} else if !collider.enabled {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.disabled",
|
||||
severity: ColliderDiagnosticSeverity::Info,
|
||||
message: "Collider is disabled.".into(),
|
||||
repair: "Enable the collider when collision is required.".into(),
|
||||
});
|
||||
} else {
|
||||
let shape_diagnostics = validate_shape(world, entity, &collider.shape);
|
||||
authoring_valid = shape_diagnostics
|
||||
.iter()
|
||||
.all(|diagnostic| diagnostic.severity != ColliderDiagnosticSeverity::Error);
|
||||
diagnostics.extend(shape_diagnostics);
|
||||
}
|
||||
}
|
||||
|
||||
let runtime_ready = has_runtime_collider(world, entity);
|
||||
if enabled && authoring_valid && !runtime_ready {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.runtime_stale",
|
||||
severity: ColliderDiagnosticSeverity::Warning,
|
||||
message: "Authored collider has not hydrated into a runtime shape.".into(),
|
||||
repair: "Check mesh cooking and asset references, then refresh the scene.".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let highest = diagnostics
|
||||
.iter()
|
||||
.map(|diagnostic| diagnostic.severity)
|
||||
.max();
|
||||
let overlay_status = match highest {
|
||||
Some(ColliderDiagnosticSeverity::Error) => ColliderOverlayStatus::Error,
|
||||
Some(ColliderDiagnosticSeverity::Warning) => ColliderOverlayStatus::Warning,
|
||||
_ if !enabled => ColliderOverlayStatus::Disabled,
|
||||
_ if trigger => ColliderOverlayStatus::Trigger,
|
||||
_ => ColliderOverlayStatus::Valid,
|
||||
};
|
||||
|
||||
Some(ColliderDiagnosticEntry {
|
||||
entity,
|
||||
actor_name: entity_name(world, entity),
|
||||
shape_label,
|
||||
runtime_ready,
|
||||
diagnostics,
|
||||
overlay_status,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn physics_placement_prerequisite_problems(world: &World, entity: Entity) -> Vec<String> {
|
||||
let name = entity_name(world, entity);
|
||||
let states = world.get::<AuthoringComponentStates>(entity);
|
||||
let order = world.get::<InspectorOrder>(entity);
|
||||
let split_body = world.get::<RigidBodyDesc>(entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_RIGID_BODY_DESC);
|
||||
let legacy = world.get::<PhysicsBody>(entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_PHYSICS_BODY);
|
||||
let collider = world.get::<ColliderDesc>(entity).filter(|collider| {
|
||||
collider.enabled
|
||||
&& !collider.is_trigger
|
||||
&& authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
|
||||
});
|
||||
|
||||
let mut problems = Vec::new();
|
||||
if !split_body && !legacy {
|
||||
problems.push(format!("{name}: add and enable a Rigid Body component"));
|
||||
}
|
||||
if collider.is_none() && !legacy {
|
||||
problems.push(format!(
|
||||
"{name}: add and enable a non-trigger Collider component"
|
||||
));
|
||||
}
|
||||
if let Some(entry) = diagnose_collider(world, entity) {
|
||||
problems.extend(
|
||||
entry
|
||||
.diagnostics
|
||||
.iter()
|
||||
.filter(|diagnostic| {
|
||||
diagnostic.severity == ColliderDiagnosticSeverity::Error
|
||||
&& diagnostic.code != "collider.missing"
|
||||
})
|
||||
.map(|diagnostic| format!("{name}: {}", diagnostic.message)),
|
||||
);
|
||||
}
|
||||
if world.get::<RigidBody>(entity).is_none() {
|
||||
problems.push(format!("{name}: rigid body has not hydrated yet"));
|
||||
}
|
||||
if !has_runtime_collider(world, entity) {
|
||||
problems.push(format!(
|
||||
"{name}: collider has not hydrated or finished cooking"
|
||||
));
|
||||
}
|
||||
problems.sort();
|
||||
problems.dedup();
|
||||
problems
|
||||
}
|
||||
|
||||
pub fn has_runtime_collider(world: &World, root: Entity) -> bool {
|
||||
let mut pending = vec![root];
|
||||
while let Some(entity) = pending.pop() {
|
||||
if world.get::<Collider>(entity).is_some() {
|
||||
return true;
|
||||
}
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
pending.extend(children.iter());
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn collider_shape_label(shape: &ColliderShapeDesc) -> &'static str {
|
||||
match shape {
|
||||
ColliderShapeDesc::Cuboid { .. } => "Box",
|
||||
ColliderShapeDesc::Sphere { .. } => "Sphere",
|
||||
ColliderShapeDesc::Capsule { .. } => "Capsule",
|
||||
ColliderShapeDesc::StaticMesh { .. } => "Static Mesh",
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_shape(
|
||||
world: &World,
|
||||
entity: Entity,
|
||||
shape: &ColliderShapeDesc,
|
||||
) -> Vec<ColliderDiagnostic> {
|
||||
let mut diagnostics = Vec::new();
|
||||
let dimensions = match shape {
|
||||
ColliderShapeDesc::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => Some(Vec3::new(*x_length, *y_length, *z_length)),
|
||||
ColliderShapeDesc::Sphere { radius } => Some(Vec3::splat(*radius * 2.0)),
|
||||
ColliderShapeDesc::Capsule { radius, height } => {
|
||||
Some(Vec3::new(*radius * 2.0, *height, *radius * 2.0))
|
||||
}
|
||||
ColliderShapeDesc::StaticMesh { meshes, .. } => {
|
||||
if meshes.is_empty() {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.mesh_missing",
|
||||
severity: ColliderDiagnosticSeverity::Error,
|
||||
message: "Static mesh collider has no mesh sources.".into(),
|
||||
repair: "Choose a mesh source or use the actor renderer meshes.".into(),
|
||||
});
|
||||
}
|
||||
for mesh in meshes {
|
||||
if !mesh.is_resolved() {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.mesh_invalid_ref",
|
||||
severity: ColliderDiagnosticSeverity::Error,
|
||||
message: format!(
|
||||
"Static mesh source `{}` has no stable asset or sub-asset ID.",
|
||||
mesh.label
|
||||
),
|
||||
repair: "Choose a valid mesh from the asset browser.".into(),
|
||||
});
|
||||
} else if world
|
||||
.get_resource::<AssetRegistry>()
|
||||
.is_some_and(|registry| find_asset_by_id(registry, &mesh.asset_id).is_none())
|
||||
{
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.mesh_stale_ref",
|
||||
severity: ColliderDiagnosticSeverity::Error,
|
||||
message: format!(
|
||||
"Static mesh source `{}` no longer exists in the asset registry.",
|
||||
mesh.label
|
||||
),
|
||||
repair: "Relink the collider to an existing mesh asset.".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(dimensions) = dimensions {
|
||||
if !dimensions.is_finite() || dimensions.min_element() <= 0.0 {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.invalid_dimensions",
|
||||
severity: ColliderDiagnosticSeverity::Error,
|
||||
message: "Collider dimensions must be positive finite values.".into(),
|
||||
repair: "Reset the shape or enter valid dimensions.".into(),
|
||||
});
|
||||
} else {
|
||||
let scale = world
|
||||
.get::<GlobalTransform>(entity)
|
||||
.map(|global| global.to_scale_rotation_translation().0.abs())
|
||||
.unwrap_or(Vec3::ONE);
|
||||
let world_extent = (dimensions * scale).max_element();
|
||||
if world_extent > OVERSIZED_COLLIDER_EXTENT {
|
||||
diagnostics.push(ColliderDiagnostic {
|
||||
code: "collider.oversized",
|
||||
severity: ColliderDiagnosticSeverity::Warning,
|
||||
message: format!(
|
||||
"Collider spans {world_extent:.1} m in world space (recommended maximum: {OVERSIZED_COLLIDER_EXTENT:.0} m)."
|
||||
),
|
||||
repair: "Reduce collider dimensions or actor scale; split large collision into smaller actors."
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
diagnostics
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shared::AuthoringRigidBody;
|
||||
|
||||
#[test]
|
||||
fn reports_missing_invalid_oversized_and_stale_runtime_colliders() {
|
||||
let mut world = World::new();
|
||||
let missing = world
|
||||
.spawn((LevelObject, RigidBodyDesc::default(), Transform::default()))
|
||||
.id();
|
||||
let invalid = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ColliderDesc {
|
||||
enabled: true,
|
||||
is_trigger: false,
|
||||
shape: ColliderShapeDesc::Sphere { radius: 0.0 },
|
||||
},
|
||||
Transform::default(),
|
||||
))
|
||||
.id();
|
||||
let oversized = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
ColliderDesc::static_cuboid(Vec3::splat(2.0)),
|
||||
Transform::from_scale(Vec3::splat(600.0)),
|
||||
GlobalTransform::from(Transform::from_scale(Vec3::splat(600.0))),
|
||||
))
|
||||
.id();
|
||||
|
||||
let missing = diagnose_collider(&world, missing).unwrap();
|
||||
assert!(missing
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code == "collider.missing"));
|
||||
|
||||
let invalid = diagnose_collider(&world, invalid).unwrap();
|
||||
assert!(invalid
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code == "collider.invalid_dimensions"));
|
||||
|
||||
let oversized = diagnose_collider(&world, oversized).unwrap();
|
||||
assert!(oversized
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code == "collider.oversized"));
|
||||
assert!(oversized
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|diagnostic| diagnostic.code == "collider.runtime_stale"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hydrated_trigger_has_trigger_overlay_status() {
|
||||
let mut world = World::new();
|
||||
let entity = world
|
||||
.spawn((
|
||||
LevelObject,
|
||||
RigidBodyDesc {
|
||||
body: AuthoringRigidBody::Static,
|
||||
},
|
||||
ColliderDesc {
|
||||
enabled: true,
|
||||
is_trigger: true,
|
||||
shape: ColliderShapeDesc::Sphere { radius: 1.0 },
|
||||
},
|
||||
Collider::sphere(1.0),
|
||||
Transform::default(),
|
||||
))
|
||||
.id();
|
||||
|
||||
let entry = diagnose_collider(&world, entity).unwrap();
|
||||
assert_eq!(entry.overlay_status, ColliderOverlayStatus::Trigger);
|
||||
assert!(entry.runtime_ready);
|
||||
}
|
||||
}
|
||||
@@ -779,31 +779,17 @@ fn update_material_drop_session(world: &mut World) {
|
||||
.is_some_and(|buttons| buttons.just_pressed(MouseButton::Right));
|
||||
|
||||
if cancel_requested && (selection.is_some() || state.preview.is_some()) {
|
||||
restore_material_drop_preview(world, state.preview.take());
|
||||
cancel_material_drop_session(world, &mut state, true);
|
||||
clear_drag_and_viewport_click(world);
|
||||
state.feedback = None;
|
||||
state.captures_viewport_input = false;
|
||||
state.cancel_consumed = true;
|
||||
set_drop_operator_status(
|
||||
world,
|
||||
OperatorPhase::Canceled,
|
||||
"Surface assignment canceled",
|
||||
);
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(selection) = selection else {
|
||||
let had_preview = state.preview.is_some();
|
||||
restore_material_drop_preview(world, state.preview.take());
|
||||
state.feedback = None;
|
||||
state.captures_viewport_input = false;
|
||||
if had_preview {
|
||||
set_drop_operator_status(
|
||||
world,
|
||||
OperatorPhase::Canceled,
|
||||
"Surface assignment canceled",
|
||||
);
|
||||
if state.preview.is_some() {
|
||||
cancel_material_drop_session(world, &mut state, false);
|
||||
} else {
|
||||
reset_material_drop_session(&mut state, false);
|
||||
}
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
@@ -877,19 +863,44 @@ fn update_material_drop_session(world: &mut World) {
|
||||
);
|
||||
|
||||
if primary_released {
|
||||
let preview = state.preview.take();
|
||||
if let Some(preview) = preview.as_ref() {
|
||||
preview.snapshot.restore(world);
|
||||
}
|
||||
if let Some(preview) = preview {
|
||||
commit_material_drop_preview(world, preview);
|
||||
}
|
||||
commit_material_drop_session(world, &mut state);
|
||||
clear_drag_and_viewport_click(world);
|
||||
state.captures_viewport_input = false;
|
||||
}
|
||||
world.insert_resource(state);
|
||||
}
|
||||
|
||||
fn cancel_material_drop_session(
|
||||
world: &mut World,
|
||||
state: &mut MaterialDropState,
|
||||
cancel_consumed: bool,
|
||||
) {
|
||||
restore_material_drop_preview(world, state.preview.take());
|
||||
reset_material_drop_session(state, cancel_consumed);
|
||||
set_drop_operator_status(
|
||||
world,
|
||||
OperatorPhase::Canceled,
|
||||
"Surface assignment canceled",
|
||||
);
|
||||
}
|
||||
|
||||
fn commit_material_drop_session(world: &mut World, state: &mut MaterialDropState) -> bool {
|
||||
let Some(preview) = state.preview.take() else {
|
||||
reset_material_drop_session(state, false);
|
||||
return false;
|
||||
};
|
||||
preview.snapshot.restore(world);
|
||||
let committed = commit_material_drop_preview(world, preview);
|
||||
reset_material_drop_session(state, false);
|
||||
committed
|
||||
}
|
||||
|
||||
fn reset_material_drop_session(state: &mut MaterialDropState, cancel_consumed: bool) {
|
||||
state.resolved = None;
|
||||
state.feedback = None;
|
||||
state.captures_viewport_input = false;
|
||||
state.cancel_consumed = cancel_consumed;
|
||||
}
|
||||
|
||||
fn restore_material_drop_preview(world: &mut World, preview: Option<MaterialDropPreview>) {
|
||||
if let Some(preview) = preview {
|
||||
preview.snapshot.restore(world);
|
||||
@@ -1029,7 +1040,8 @@ fn draw_material_drop_target(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_undo, EditorHistory};
|
||||
use crate::history::EditorHistory;
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use shared::{ActorKind, RendererMaterialSet, RendererMaterialSlot, SharedTypesPlugin};
|
||||
|
||||
fn test_app() -> App {
|
||||
@@ -1098,6 +1110,7 @@ mod tests {
|
||||
hit_point: Vec3::ZERO,
|
||||
hit_normal: Vec3::Y,
|
||||
};
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
let preview = begin_material_drop_preview(
|
||||
world,
|
||||
AssetSelection::File("assets/materials/steel.ron".into()),
|
||||
@@ -1123,18 +1136,25 @@ mod tests {
|
||||
assert!(!world.resource::<SceneIo>().dirty);
|
||||
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 0);
|
||||
|
||||
preview.snapshot.restore(world);
|
||||
assert!(world
|
||||
.get::<StaticMeshRenderer>(entity)
|
||||
.unwrap()
|
||||
.materials
|
||||
.slot(&slot_b)
|
||||
.unwrap()
|
||||
.material
|
||||
.is_none());
|
||||
assert!(commit_material_drop_preview(world, preview));
|
||||
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
|
||||
assert!(world.resource::<SceneIo>().dirty);
|
||||
let mut state = MaterialDropState {
|
||||
resolved: Some(target),
|
||||
preview: Some(preview),
|
||||
feedback: Some(MaterialDropFeedback {
|
||||
valid: true,
|
||||
action: "Assign material".into(),
|
||||
target: "Crate / B".into(),
|
||||
}),
|
||||
captures_viewport_input: true,
|
||||
cancel_consumed: false,
|
||||
};
|
||||
assert!(commit_material_drop_session(world, &mut state));
|
||||
harness.assert_committed(world, 1, 0);
|
||||
harness.assert_status(world, "assets.assign_surface", OperatorPhase::Committed);
|
||||
assert!(state.preview.is_none());
|
||||
assert!(state.resolved.is_none());
|
||||
assert!(state.feedback.is_none());
|
||||
assert!(!state.captures_viewport_input);
|
||||
assert!(!state.cancel_consumed);
|
||||
assert!(world
|
||||
.get::<StaticMeshRenderer>(entity)
|
||||
.unwrap()
|
||||
@@ -1143,16 +1163,17 @@ mod tests {
|
||||
.unwrap()
|
||||
.material
|
||||
.is_none());
|
||||
|
||||
apply_command_undo(world);
|
||||
assert!(world
|
||||
assert_undo_redo_round_trip(world, None, Some("steel".to_string()), |world| {
|
||||
world
|
||||
.get::<StaticMeshRenderer>(entity)
|
||||
.unwrap()
|
||||
.materials
|
||||
.slot(&slot_b)
|
||||
.unwrap()
|
||||
.material
|
||||
.is_none());
|
||||
.as_ref()
|
||||
.map(|material| material.0.asset_id.clone())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1172,6 +1193,7 @@ mod tests {
|
||||
hit_point: Vec3::ZERO,
|
||||
hit_normal: Vec3::Y,
|
||||
};
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
let preview = begin_material_drop_preview(
|
||||
world,
|
||||
AssetSelection::File("assets/materials/steel.ron".into()),
|
||||
@@ -1196,9 +1218,26 @@ mod tests {
|
||||
.material
|
||||
.is_none());
|
||||
|
||||
preview.snapshot.restore(world);
|
||||
let mut state = MaterialDropState {
|
||||
resolved: Some(target),
|
||||
preview: Some(preview),
|
||||
feedback: Some(MaterialDropFeedback {
|
||||
valid: true,
|
||||
action: "Assign material".into(),
|
||||
target: "Blockout / face".into(),
|
||||
}),
|
||||
captures_viewport_input: true,
|
||||
cancel_consumed: false,
|
||||
};
|
||||
cancel_material_drop_session(world, &mut state, true);
|
||||
harness.assert_canceled(world);
|
||||
harness.assert_status(world, "assets.assign_surface", OperatorPhase::Canceled);
|
||||
assert_eq!(world.get::<BrushDesc>(entity), Some(&brush));
|
||||
assert!(!world.resource::<SceneIo>().dirty);
|
||||
assert!(state.preview.is_none());
|
||||
assert!(state.resolved.is_none());
|
||||
assert!(state.feedback.is_none());
|
||||
assert!(!state.captures_viewport_input);
|
||||
assert!(state.cancel_consumed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,9 +5,11 @@ pub mod brush_csg;
|
||||
pub mod brush_edit;
|
||||
pub mod brush_tool;
|
||||
pub mod camera;
|
||||
pub mod collider_diagnostics;
|
||||
pub mod gizmos;
|
||||
pub mod material_drop;
|
||||
mod panel;
|
||||
pub mod physics_placement;
|
||||
pub mod render_view;
|
||||
pub mod rendering_diagnostics;
|
||||
pub mod selection;
|
||||
@@ -26,6 +28,7 @@ pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
|
||||
pub use brush_tool::{BrushToolPlugin, BrushToolState};
|
||||
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
|
||||
pub use panel::*;
|
||||
pub use physics_placement::{PhysicsPlacementPlugin, PhysicsPlacementState};
|
||||
pub use terrain_paint::{TerrainPaintMode, TerrainPaintPlugin, TerrainPaintState};
|
||||
pub use terrain_sculpt::{TerrainSculptMode, TerrainSculptPlugin, TerrainSculptState};
|
||||
pub use viewport_mode::EditorViewportMode;
|
||||
@@ -0,0 +1,697 @@
|
||||
//! Transactional gravity placement using the editor's hydrated Avian world.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use avian3d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::history::{set_transform_group_with_history, EditorHistory};
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::state::EditorMode;
|
||||
use crate::ui::selection_ops::{entity_name, is_mutable_level_object};
|
||||
use crate::viewport::collider_diagnostics::physics_placement_prerequisite_problems;
|
||||
|
||||
const STEP_HZ: f64 = 120.0;
|
||||
const STEPS_PER_FRAME: usize = 4;
|
||||
const SETTLE_LINEAR_SPEED: f32 = 0.04;
|
||||
const SETTLE_ANGULAR_SPEED: f32 = 0.04;
|
||||
const SETTLE_STEPS: u32 = 30;
|
||||
const MAX_STEPS: u32 = 1_200;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PhysicsPlacementPhase {
|
||||
#[default]
|
||||
Inactive,
|
||||
Dropping,
|
||||
Settled,
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
impl PhysicsPlacementPhase {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Inactive => "Inactive",
|
||||
Self::Dropping => "Simulating",
|
||||
Self::Settled => "Settled",
|
||||
Self::TimedOut => "Preview stopped",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PhysicsPlacementRequest {
|
||||
#[default]
|
||||
None,
|
||||
Commit,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[derive(Component, Debug, Clone, Copy, Default)]
|
||||
pub struct PhysicsPlacementPreview;
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct PhysicsPlacementState {
|
||||
pub phase: PhysicsPlacementPhase,
|
||||
pub request: PhysicsPlacementRequest,
|
||||
pub last_error: Option<String>,
|
||||
pub selected_count: usize,
|
||||
pub simulated_steps: u32,
|
||||
session: Option<PlacementSession>,
|
||||
}
|
||||
|
||||
impl PhysicsPlacementState {
|
||||
pub fn active(&self) -> bool {
|
||||
self.session.is_some()
|
||||
}
|
||||
|
||||
pub fn simulated_seconds(&self) -> f32 {
|
||||
self.simulated_steps as f32 / STEP_HZ as f32
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PlacementSession {
|
||||
selected: Vec<BodySnapshot>,
|
||||
frozen: Vec<BodySnapshot>,
|
||||
stable_steps: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct BodySnapshot {
|
||||
entity: Entity,
|
||||
transform: Transform,
|
||||
position: Option<Position>,
|
||||
rotation: Option<Rotation>,
|
||||
rigid_body: RigidBody,
|
||||
linear_velocity: Option<LinearVelocity>,
|
||||
angular_velocity: Option<AngularVelocity>,
|
||||
gravity_scale: Option<GravityScale>,
|
||||
sleeping: bool,
|
||||
sleeping_disabled: bool,
|
||||
rigid_body_disabled: bool,
|
||||
}
|
||||
|
||||
impl BodySnapshot {
|
||||
fn capture(world: &World, entity: Entity) -> Result<Self, String> {
|
||||
Ok(Self {
|
||||
entity,
|
||||
transform: world
|
||||
.get::<Transform>(entity)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("{} has no Transform", entity_name(world, entity)))?,
|
||||
position: world.get::<Position>(entity).copied(),
|
||||
rotation: world.get::<Rotation>(entity).copied(),
|
||||
rigid_body: world.get::<RigidBody>(entity).copied().ok_or_else(|| {
|
||||
format!("{} has no hydrated rigid body", entity_name(world, entity))
|
||||
})?,
|
||||
linear_velocity: world.get::<LinearVelocity>(entity).copied(),
|
||||
angular_velocity: world.get::<AngularVelocity>(entity).copied(),
|
||||
gravity_scale: world.get::<GravityScale>(entity).copied(),
|
||||
sleeping: world.get::<Sleeping>(entity).is_some(),
|
||||
sleeping_disabled: world.get::<SleepingDisabled>(entity).is_some(),
|
||||
rigid_body_disabled: world.get::<RigidBodyDisabled>(entity).is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PhysicsPlacementPlugin;
|
||||
|
||||
impl Plugin for PhysicsPlacementPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<PhysicsPlacementState>()
|
||||
.add_systems(PostStartup, pause_physics_for_editor)
|
||||
.add_systems(PostUpdate, tick_physics_placement)
|
||||
.add_systems(OnExit(EditorMode::Editing), cancel_physics_placement);
|
||||
}
|
||||
}
|
||||
|
||||
fn pause_physics_for_editor(mut physics_time: ResMut<Time<Physics>>) {
|
||||
physics_time.pause();
|
||||
}
|
||||
|
||||
pub fn begin_physics_placement(
|
||||
world: &mut World,
|
||||
selected: impl IntoIterator<Item = Entity>,
|
||||
) -> Result<(), String> {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Editing {
|
||||
return placement_error(world, "Physics placement is available only in Edit mode");
|
||||
}
|
||||
if world.resource::<PhysicsPlacementState>().active() {
|
||||
return placement_error(world, "A physics placement preview is already active");
|
||||
}
|
||||
|
||||
let mut unique = HashSet::new();
|
||||
let selected = selected
|
||||
.into_iter()
|
||||
.filter(|entity| unique.insert(*entity))
|
||||
.collect::<Vec<_>>();
|
||||
validate_selection(world, &selected)?;
|
||||
|
||||
let selected_set = selected.iter().copied().collect::<HashSet<_>>();
|
||||
let selected_snapshots = selected
|
||||
.iter()
|
||||
.map(|entity| BodySnapshot::capture(world, *entity))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let movable = world
|
||||
.query::<(Entity, &RigidBody)>()
|
||||
.iter(world)
|
||||
.filter_map(|(entity, body)| {
|
||||
(!selected_set.contains(&entity) && *body != RigidBody::Static).then_some(entity)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let frozen_snapshots = movable
|
||||
.iter()
|
||||
.map(|entity| BodySnapshot::capture(world, *entity))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
for snapshot in &frozen_snapshots {
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.insert(RigidBody::Static);
|
||||
}
|
||||
}
|
||||
for snapshot in &selected_snapshots {
|
||||
let global = world
|
||||
.get::<GlobalTransform>(snapshot.entity)
|
||||
.copied()
|
||||
.unwrap_or_else(|| GlobalTransform::from(snapshot.transform));
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.insert((
|
||||
RigidBody::Dynamic,
|
||||
LinearVelocity::ZERO,
|
||||
AngularVelocity::ZERO,
|
||||
GravityScale(1.0),
|
||||
Position(global.translation()),
|
||||
Rotation(global.rotation()),
|
||||
PhysicsPlacementPreview,
|
||||
));
|
||||
entity.remove::<Sleeping>();
|
||||
entity.remove::<RigidBodyDisabled>();
|
||||
}
|
||||
}
|
||||
|
||||
let selected_count = selected_snapshots.len();
|
||||
let mut state = world.resource_mut::<PhysicsPlacementState>();
|
||||
state.phase = PhysicsPlacementPhase::Dropping;
|
||||
state.request = PhysicsPlacementRequest::None;
|
||||
state.last_error = None;
|
||||
state.selected_count = selected_count;
|
||||
state.simulated_steps = 0;
|
||||
state.session = Some(PlacementSession {
|
||||
selected: selected_snapshots,
|
||||
frozen: frozen_snapshots,
|
||||
stable_steps: 0,
|
||||
});
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorPhase::Preview,
|
||||
format!("Dropping {selected_count} selected prop(s)"),
|
||||
Vec::new(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn request_physics_placement(world: &mut World, request: PhysicsPlacementRequest) {
|
||||
if world.resource::<PhysicsPlacementState>().active() {
|
||||
world.resource_mut::<PhysicsPlacementState>().request = request;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel_physics_placement(world: &mut World) {
|
||||
finish_physics_placement(world, false);
|
||||
}
|
||||
|
||||
pub fn commit_physics_placement(world: &mut World) {
|
||||
finish_physics_placement(world, true);
|
||||
}
|
||||
|
||||
fn finish_physics_placement(world: &mut World, commit: bool) {
|
||||
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
|
||||
return;
|
||||
};
|
||||
let Some(session) = state.session.take() else {
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
};
|
||||
|
||||
let final_transforms = session
|
||||
.selected
|
||||
.iter()
|
||||
.filter_map(|snapshot| {
|
||||
world
|
||||
.get::<Transform>(snapshot.entity)
|
||||
.copied()
|
||||
.map(|transform| (snapshot.entity, transform))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for snapshot in &session.frozen {
|
||||
restore_snapshot(world, snapshot, true);
|
||||
}
|
||||
for snapshot in &session.selected {
|
||||
restore_snapshot(world, snapshot, !commit);
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.remove::<PhysicsPlacementPreview>();
|
||||
}
|
||||
}
|
||||
|
||||
let undo_depth = world.resource::<EditorHistory>().undo_depth();
|
||||
if commit {
|
||||
let changes = session.selected.iter().filter_map(|snapshot| {
|
||||
final_transforms
|
||||
.iter()
|
||||
.find(|(entity, _)| *entity == snapshot.entity)
|
||||
.map(|(_, new)| (snapshot.entity, snapshot.transform, *new))
|
||||
});
|
||||
set_transform_group_with_history(world, changes);
|
||||
}
|
||||
let committed = commit && world.resource::<EditorHistory>().undo_depth() > undo_depth;
|
||||
|
||||
state.phase = PhysicsPlacementPhase::Inactive;
|
||||
state.request = PhysicsPlacementRequest::None;
|
||||
state.selected_count = 0;
|
||||
state.simulated_steps = 0;
|
||||
state.last_error = None;
|
||||
world.insert_resource(state);
|
||||
let (phase, hint) = if committed {
|
||||
(OperatorPhase::Committed, "Physics placement committed")
|
||||
} else if commit {
|
||||
(OperatorPhase::Canceled, "Physics placement made no changes")
|
||||
} else {
|
||||
(OperatorPhase::Canceled, "Physics placement canceled")
|
||||
};
|
||||
set_operator_status(world, phase, hint.to_string(), Vec::new());
|
||||
}
|
||||
|
||||
fn tick_physics_placement(world: &mut World) {
|
||||
let escape = world
|
||||
.get_resource::<ButtonInput<KeyCode>>()
|
||||
.is_some_and(|keys| keys.just_pressed(KeyCode::Escape));
|
||||
let enter = world
|
||||
.get_resource::<ButtonInput<KeyCode>>()
|
||||
.is_some_and(|keys| keys.just_pressed(KeyCode::Enter));
|
||||
let request = world.resource::<PhysicsPlacementState>().request;
|
||||
let settled = matches!(
|
||||
world.resource::<PhysicsPlacementState>().phase,
|
||||
PhysicsPlacementPhase::Settled | PhysicsPlacementPhase::TimedOut
|
||||
);
|
||||
if escape || request == PhysicsPlacementRequest::Cancel {
|
||||
cancel_physics_placement(world);
|
||||
return;
|
||||
}
|
||||
if request == PhysicsPlacementRequest::Commit || (enter && settled) {
|
||||
commit_physics_placement(world);
|
||||
return;
|
||||
}
|
||||
if world.resource::<PhysicsPlacementState>().phase != PhysicsPlacementPhase::Dropping {
|
||||
return;
|
||||
}
|
||||
|
||||
for _ in 0..STEPS_PER_FRAME {
|
||||
world
|
||||
.resource_mut::<Time<Physics>>()
|
||||
.advance_by(Duration::from_secs_f64(1.0 / STEP_HZ));
|
||||
world.run_schedule(FixedPostUpdate);
|
||||
}
|
||||
|
||||
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
|
||||
return;
|
||||
};
|
||||
state.simulated_steps = state.simulated_steps.saturating_add(STEPS_PER_FRAME as u32);
|
||||
let Some(session) = state.session.as_mut() else {
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
};
|
||||
let at_rest = session.selected.iter().all(|snapshot| {
|
||||
let linear = world
|
||||
.get::<LinearVelocity>(snapshot.entity)
|
||||
.map_or(0.0, |velocity| velocity.length());
|
||||
let angular = world
|
||||
.get::<AngularVelocity>(snapshot.entity)
|
||||
.map_or(0.0, |velocity| velocity.length());
|
||||
(linear <= SETTLE_LINEAR_SPEED && angular <= SETTLE_ANGULAR_SPEED)
|
||||
|| world.get::<Sleeping>(snapshot.entity).is_some()
|
||||
});
|
||||
session.stable_steps = if at_rest {
|
||||
session.stable_steps.saturating_add(STEPS_PER_FRAME as u32)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let mut status = None;
|
||||
if session.stable_steps >= SETTLE_STEPS {
|
||||
state.phase = PhysicsPlacementPhase::Settled;
|
||||
status = Some((
|
||||
OperatorPhase::Preview,
|
||||
"Placement settled; commit or cancel".to_string(),
|
||||
Vec::new(),
|
||||
));
|
||||
} else if state.simulated_steps >= MAX_STEPS {
|
||||
state.phase = PhysicsPlacementPhase::TimedOut;
|
||||
status = Some((
|
||||
OperatorPhase::Preview,
|
||||
"Placement reached its 10 second preview limit".to_string(),
|
||||
vec!["Bodies are still moving; commit the current pose or cancel".to_string()],
|
||||
));
|
||||
}
|
||||
world.insert_resource(state);
|
||||
if let Some((phase, hint, warnings)) = status {
|
||||
set_operator_status(world, phase, hint, warnings);
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_selection(world: &mut World, selected: &[Entity]) -> Result<(), String> {
|
||||
if selected.is_empty() {
|
||||
return placement_error(world, "Select at least one prop to place with physics");
|
||||
}
|
||||
let mut problems = Vec::new();
|
||||
for entity in selected {
|
||||
let name = entity_name(world, *entity);
|
||||
if !is_mutable_level_object(world, *entity) {
|
||||
problems.push(format!(
|
||||
"{name}: selection is locked, linked, or not a level object"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
problems.extend(physics_placement_prerequisite_problems(world, *entity));
|
||||
}
|
||||
if problems.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
placement_error(world, problems.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_snapshot(world: &mut World, snapshot: &BodySnapshot, restore_pose: bool) {
|
||||
let Ok(mut entity) = world.get_entity_mut(snapshot.entity) else {
|
||||
return;
|
||||
};
|
||||
entity.insert(snapshot.rigid_body);
|
||||
restore_optional(&mut entity, snapshot.linear_velocity);
|
||||
restore_optional(&mut entity, snapshot.angular_velocity);
|
||||
restore_optional(&mut entity, snapshot.gravity_scale);
|
||||
restore_marker::<Sleeping>(&mut entity, snapshot.sleeping);
|
||||
restore_marker::<SleepingDisabled>(&mut entity, snapshot.sleeping_disabled);
|
||||
restore_marker::<RigidBodyDisabled>(&mut entity, snapshot.rigid_body_disabled);
|
||||
if restore_pose {
|
||||
entity.insert(snapshot.transform);
|
||||
restore_optional(&mut entity, snapshot.position);
|
||||
restore_optional(&mut entity, snapshot.rotation);
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_optional<T: Component + Clone>(entity: &mut EntityWorldMut<'_>, value: Option<T>) {
|
||||
if let Some(value) = value {
|
||||
entity.insert(value);
|
||||
} else {
|
||||
entity.remove::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_marker<T: Component + Default>(entity: &mut EntityWorldMut<'_>, present: bool) {
|
||||
if present {
|
||||
entity.insert(T::default());
|
||||
} else {
|
||||
entity.remove::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
fn placement_error<T>(world: &mut World, message: impl Into<String>) -> Result<T, String> {
|
||||
let message = message.into();
|
||||
world.resource_mut::<PhysicsPlacementState>().last_error = Some(message.clone());
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorPhase::Blocked,
|
||||
"Physics placement could not start".to_string(),
|
||||
message.lines().map(str::to_string).collect(),
|
||||
);
|
||||
Err(message)
|
||||
}
|
||||
|
||||
fn set_operator_status(
|
||||
world: &mut World,
|
||||
phase: OperatorPhase,
|
||||
hint: String,
|
||||
warnings: Vec<String>,
|
||||
) {
|
||||
if let Some(mut operator) = world.get_resource_mut::<ActiveOperator>() {
|
||||
operator.status = Some(OperatorStatus {
|
||||
id: "physics.placement".to_string(),
|
||||
label: "Physics Placement".to_string(),
|
||||
phase,
|
||||
hint,
|
||||
warnings,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::EditorHistory;
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use crate::scene_io::SceneIo;
|
||||
use bevy::asset::{AssetApp, AssetPlugin};
|
||||
use bevy::state::app::StatesPlugin;
|
||||
use shared::{ColliderDesc, LevelObject, RigidBodyDesc};
|
||||
|
||||
fn app_with_physics() -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((
|
||||
MinimalPlugins,
|
||||
AssetPlugin::default(),
|
||||
StatesPlugin,
|
||||
TransformPlugin,
|
||||
PhysicsPlugins::default(),
|
||||
))
|
||||
.init_asset::<Mesh>()
|
||||
.init_state::<EditorMode>()
|
||||
.init_resource::<PhysicsPlacementState>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<ActiveOperator>()
|
||||
.init_resource::<SceneIo>();
|
||||
app.finish();
|
||||
app.cleanup();
|
||||
app.update();
|
||||
app.world_mut().resource_mut::<Time<Physics>>().pause();
|
||||
app
|
||||
}
|
||||
|
||||
fn spawn_placeable(world: &mut World, name: &str, transform: Transform) -> Entity {
|
||||
world
|
||||
.spawn((
|
||||
Name::new(name.to_string()),
|
||||
LevelObject,
|
||||
RigidBodyDesc::default(),
|
||||
ColliderDesc::default(),
|
||||
RigidBody::Static,
|
||||
Collider::cuboid(1.0, 1.0, 1.0),
|
||||
transform,
|
||||
))
|
||||
.id()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_missing_authoring_prerequisites_without_starting() {
|
||||
let mut app = app_with_physics();
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((Name::new("No Physics"), LevelObject, Transform::default()))
|
||||
.id();
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
let error = begin_physics_placement(app.world_mut(), [entity]).unwrap_err();
|
||||
|
||||
assert!(error.contains("add and enable a Rigid Body"));
|
||||
assert!(error.contains("add and enable a non-trigger Collider"));
|
||||
assert!(!app.world().resource::<PhysicsPlacementState>().active());
|
||||
harness.assert_blocked(app.world_mut());
|
||||
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Blocked);
|
||||
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_restores_selected_and_unrelated_motion_state_exactly() {
|
||||
let mut app = app_with_physics();
|
||||
let selected = spawn_placeable(
|
||||
app.world_mut(),
|
||||
"Selected",
|
||||
Transform::from_xyz(1.0, 4.0, 2.0),
|
||||
);
|
||||
app.world_mut().entity_mut(selected).insert((
|
||||
RigidBody::Kinematic,
|
||||
LinearVelocity(Vec3::new(1.0, 2.0, 3.0)),
|
||||
AngularVelocity(Vec3::new(0.1, 0.2, 0.3)),
|
||||
GravityScale(0.25),
|
||||
SleepingDisabled,
|
||||
));
|
||||
let unrelated = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
RigidBody::Dynamic,
|
||||
Collider::sphere(0.5),
|
||||
LinearVelocity(Vec3::X * 3.0),
|
||||
Transform::from_xyz(8.0, 2.0, 0.0),
|
||||
))
|
||||
.id();
|
||||
app.update();
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
begin_physics_placement(app.world_mut(), [selected]).unwrap();
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(selected),
|
||||
Some(&RigidBody::Dynamic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(unrelated),
|
||||
Some(&RigidBody::Static)
|
||||
);
|
||||
for _ in 0..10 {
|
||||
tick_physics_placement(app.world_mut());
|
||||
}
|
||||
assert!(
|
||||
app.world()
|
||||
.get::<Transform>(selected)
|
||||
.unwrap()
|
||||
.translation
|
||||
.y
|
||||
< 4.0
|
||||
);
|
||||
|
||||
cancel_physics_placement(app.world_mut());
|
||||
|
||||
assert_eq!(
|
||||
app.world().get::<Transform>(selected).unwrap().translation,
|
||||
Vec3::new(1.0, 4.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(selected),
|
||||
Some(&RigidBody::Kinematic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<LinearVelocity>(selected),
|
||||
Some(&LinearVelocity(Vec3::new(1.0, 2.0, 3.0)))
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<GravityScale>(selected),
|
||||
Some(&GravityScale(0.25))
|
||||
);
|
||||
assert!(app.world().get::<SleepingDisabled>(selected).is_some());
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(unrelated),
|
||||
Some(&RigidBody::Dynamic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<LinearVelocity>(unrelated),
|
||||
Some(&LinearVelocity(Vec3::X * 3.0))
|
||||
);
|
||||
assert_eq!(app.world().resource::<EditorHistory>().undo_depth(), 0);
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Canceled);
|
||||
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_physics_drop_commits_once_and_undo_restores_start_transform() {
|
||||
let mut app = app_with_physics();
|
||||
app.world_mut().spawn((
|
||||
RigidBody::Static,
|
||||
Collider::cuboid(20.0, 0.5, 20.0),
|
||||
Transform::from_xyz(0.0, -0.25, 0.0),
|
||||
));
|
||||
let start = Transform::from_xyz(0.0, 4.0, 0.0);
|
||||
let prop = spawn_placeable(app.world_mut(), "Drop Prop", start);
|
||||
app.update();
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
begin_physics_placement(app.world_mut(), [prop]).unwrap();
|
||||
for _ in 0..400 {
|
||||
tick_physics_placement(app.world_mut());
|
||||
if app.world().resource::<PhysicsPlacementState>().phase
|
||||
== PhysicsPlacementPhase::Settled
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
app.world().resource::<PhysicsPlacementState>().phase,
|
||||
PhysicsPlacementPhase::Settled
|
||||
);
|
||||
let settled = *app.world().get::<Transform>(prop).unwrap();
|
||||
assert!(settled.translation.y < 1.0, "{settled:?}");
|
||||
|
||||
commit_physics_placement(app.world_mut());
|
||||
|
||||
harness.assert_committed(app.world_mut(), 1, 0);
|
||||
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Committed);
|
||||
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
|
||||
assert_eq!(
|
||||
app.world().resource::<EditorHistory>().status,
|
||||
"Undo: Move Selection"
|
||||
);
|
||||
assert_eq!(app.world().get::<RigidBody>(prop), Some(&RigidBody::Static));
|
||||
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), settled);
|
||||
assert_undo_redo_round_trip(app.world_mut(), start, settled, |world| {
|
||||
*world.get::<Transform>(prop).unwrap()
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_op_commit_terminates_without_dirtying_or_history() {
|
||||
let mut app = app_with_physics();
|
||||
let start = Transform::from_xyz(0.0, 4.0, 0.0);
|
||||
let prop = spawn_placeable(app.world_mut(), "Static Prop", start);
|
||||
app.update();
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
begin_physics_placement(app.world_mut(), [prop]).unwrap();
|
||||
commit_physics_placement(app.world_mut());
|
||||
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Canceled);
|
||||
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
|
||||
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), start);
|
||||
assert_eq!(app.world().get::<RigidBody>(prop), Some(&RigidBody::Static));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_select_commit_is_one_transaction_and_cleans_every_preview_helper() {
|
||||
let mut app = app_with_physics();
|
||||
let starts = [
|
||||
Transform::from_xyz(-1.0, 4.0, 0.0),
|
||||
Transform::from_xyz(1.0, 6.0, 0.0),
|
||||
];
|
||||
let first = spawn_placeable(app.world_mut(), "First", starts[0]);
|
||||
let second = spawn_placeable(app.world_mut(), "Second", starts[1]);
|
||||
app.update();
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
begin_physics_placement(app.world_mut(), [first, second, first]).unwrap();
|
||||
assert_eq!(
|
||||
app.world()
|
||||
.resource::<PhysicsPlacementState>()
|
||||
.selected_count,
|
||||
2,
|
||||
"duplicate selections must collapse to one placement snapshot"
|
||||
);
|
||||
let committed = [
|
||||
Transform::from_xyz(-1.0, 0.5, 0.0),
|
||||
Transform::from_xyz(1.0, 0.5, 0.0),
|
||||
];
|
||||
app.world_mut().entity_mut(first).insert(committed[0]);
|
||||
app.world_mut().entity_mut(second).insert(committed[1]);
|
||||
|
||||
commit_physics_placement(app.world_mut());
|
||||
|
||||
harness.assert_committed(app.world_mut(), 1, 0);
|
||||
harness.assert_status(app.world(), "physics.placement", OperatorPhase::Committed);
|
||||
harness.assert_no_helpers::<PhysicsPlacementPreview>(app.world_mut());
|
||||
assert_undo_redo_round_trip(app.world_mut(), starts, committed, |world| {
|
||||
[
|
||||
*world.get::<Transform>(first).unwrap(),
|
||||
*world.get::<Transform>(second).unwrap(),
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ use crate::visualizers::EditorVisualizerProxy;
|
||||
use bevy_egui::egui;
|
||||
|
||||
use crate::viewport::material_drop::{MaterialDropSet, MaterialDropState};
|
||||
use crate::viewport::physics_placement::PhysicsPlacementState;
|
||||
use crate::viewport::scene_view_ray;
|
||||
use crate::viewport::terrain_paint::TerrainPaintState;
|
||||
use crate::viewport::terrain_sculpt::TerrainSculptState;
|
||||
@@ -54,6 +55,7 @@ struct PickTargetQueries<'w, 's> {
|
||||
material_drop: Option<Res<'w, MaterialDropState>>,
|
||||
terrain_sculpt: Res<'w, TerrainSculptState>,
|
||||
terrain_paint: Res<'w, TerrainPaintState>,
|
||||
physics_placement: Option<Res<'w, PhysicsPlacementState>>,
|
||||
viewport_ui: Res<'w, ViewportUiState>,
|
||||
}
|
||||
|
||||
@@ -129,7 +131,13 @@ fn handle_pick_events(
|
||||
for _ in click_events.read() {}
|
||||
return Ok(());
|
||||
}
|
||||
if pick_targets.terrain_sculpt.active || pick_targets.terrain_paint.active {
|
||||
if pick_targets.terrain_sculpt.active
|
||||
|| pick_targets.terrain_paint.active
|
||||
|| pick_targets
|
||||
.physics_placement
|
||||
.as_deref()
|
||||
.is_some_and(PhysicsPlacementState::active)
|
||||
{
|
||||
viewport_click.0 = None;
|
||||
for _ in click_events.read() {}
|
||||
return Ok(());
|
||||
@@ -447,6 +455,7 @@ fn sync_gizmo_targets(
|
||||
brush_mode: Res<BrushEditMode>,
|
||||
terrain_sculpt: Res<TerrainSculptState>,
|
||||
terrain_paint: Res<TerrainPaintState>,
|
||||
physics_placement: Option<Res<PhysicsPlacementState>>,
|
||||
) {
|
||||
ui_state
|
||||
.selected_entities
|
||||
@@ -457,6 +466,9 @@ fn sync_gizmo_targets(
|
||||
|| brush_mode.is_element_mode()
|
||||
|| terrain_sculpt.active
|
||||
|| terrain_paint.active
|
||||
|| physics_placement
|
||||
.as_deref()
|
||||
.is_some_and(PhysicsPlacementState::active)
|
||||
{
|
||||
for (entity, brush_element_gizmo) in &targets {
|
||||
if brush_element_gizmo.is_none() {
|
||||
|
||||
@@ -6,7 +6,7 @@ use shared::{TerrainDesc, AUTHORING_COMPONENT_TERRAIN, COMPONENT_TERRAIN_DESC};
|
||||
|
||||
use super::terrain_sculpt::{active_scene_ray, smooth_falloff, terrain_ray_hit, TerrainHit};
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::history::reflected_component_transaction;
|
||||
use crate::history::{reflected_component_transaction, EditorHistory};
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::selection::{SelectedEntity, ViewportClick};
|
||||
@@ -125,16 +125,30 @@ fn terrain_paint_input(
|
||||
viewport_click.0 = None;
|
||||
state.clamp_settings();
|
||||
let Some(entity) = state.target.or(selected.0) else {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Blocked,
|
||||
"Terrain paint stopped: target is unavailable",
|
||||
"Target unavailable",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
if selected.0 != Some(entity) {
|
||||
selected.0 = Some(entity);
|
||||
}
|
||||
if display.clean_game_view {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Terrain paint stopped for clean game view",
|
||||
"Clean game view enabled; weights restored",
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let ctx = contexts.ctx_mut()?;
|
||||
@@ -142,12 +156,11 @@ fn terrain_paint_input(
|
||||
keys.just_pressed(KeyCode::Escape) || buttons.just_pressed(MouseButton::Right);
|
||||
if cancel_requested {
|
||||
if state.is_stroking() {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
scene_io.status = "Terrain paint stroke canceled".into();
|
||||
set_status(
|
||||
cancel_active_stroke(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Weights restored",
|
||||
);
|
||||
} else {
|
||||
state.stop();
|
||||
@@ -157,14 +170,29 @@ fn terrain_paint_input(
|
||||
return Ok(());
|
||||
}
|
||||
let Ok((global, mut terrain)) = terrains.get_mut(entity) else {
|
||||
state.stroke = None;
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Blocked,
|
||||
"Terrain paint stopped: target no longer exists",
|
||||
"Target no longer exists",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
let layer_count = terrain.material_layers.len();
|
||||
if layer_count == 0 {
|
||||
if let Some(stroke) = state.stroke.take() {
|
||||
*terrain = stroke.original;
|
||||
}
|
||||
state.stop();
|
||||
scene_io.status = "Add a terrain material layer before painting".into();
|
||||
set_status(
|
||||
&mut active_operator,
|
||||
OperatorPhase::Blocked,
|
||||
"Add a material layer before painting",
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
state.active_layer = state.active_layer.min(layer_count - 1);
|
||||
@@ -227,17 +255,8 @@ fn terrain_paint_input(
|
||||
let final_terrain = terrain.clone();
|
||||
let mode = state.mode;
|
||||
commands.queue(move |world: &mut World| {
|
||||
if let Err(error) = commit_paint_stroke(world, stroke, final_terrain) {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Terrain paint commit failed: {error}");
|
||||
}
|
||||
finish_paint_stroke(world, stroke, final_terrain, mode);
|
||||
});
|
||||
scene_io.status = format!("{} terrain material weights committed", mode.label());
|
||||
set_status(
|
||||
&mut active_operator,
|
||||
OperatorPhase::Committed,
|
||||
format!("{} weights; Ctrl+Z to undo", mode.label()),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -248,10 +267,11 @@ fn commit_paint_stroke(
|
||||
stroke: TerrainPaintStroke,
|
||||
final_terrain: TerrainDesc,
|
||||
) -> Result<(), String> {
|
||||
let original = stroke.original;
|
||||
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
|
||||
actor.insert(stroke.original);
|
||||
actor.insert(original.clone());
|
||||
}
|
||||
reflected_component_transaction(
|
||||
let result = reflected_component_transaction(
|
||||
world,
|
||||
stroke.entity,
|
||||
"Paint Terrain Material",
|
||||
@@ -261,7 +281,77 @@ fn commit_paint_stroke(
|
||||
world.entity_mut(entity).insert(final_terrain);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
);
|
||||
if result.is_err() {
|
||||
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
|
||||
actor.insert(original);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn finish_paint_stroke(
|
||||
world: &mut World,
|
||||
stroke: TerrainPaintStroke,
|
||||
final_terrain: TerrainDesc,
|
||||
mode: TerrainPaintMode,
|
||||
) {
|
||||
let undo_depth = world.resource::<EditorHistory>().undo_depth();
|
||||
match commit_paint_stroke(world, stroke, final_terrain) {
|
||||
Ok(()) if world.resource::<EditorHistory>().undo_depth() > undo_depth => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("{} terrain material weights committed", mode.label());
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Committed,
|
||||
format!("{} weights; Ctrl+Z to undo", mode.label()),
|
||||
);
|
||||
}
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("{} terrain stroke made no changes", mode.label());
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Canceled,
|
||||
format!("{} stroke made no changes", mode.label()),
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Terrain paint commit failed: {error}");
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Blocked,
|
||||
format!("Commit failed: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_active_stroke(
|
||||
state: &mut TerrainPaintState,
|
||||
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
scene_io: &mut SceneIo,
|
||||
active_operator: &mut ActiveOperator,
|
||||
) {
|
||||
cancel_stroke(state, terrains);
|
||||
scene_io.status = "Terrain paint stroke canceled".into();
|
||||
set_status(active_operator, OperatorPhase::Canceled, "Weights restored");
|
||||
}
|
||||
|
||||
fn stop_tool_with_rollback(
|
||||
state: &mut TerrainPaintState,
|
||||
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
scene_io: &mut SceneIo,
|
||||
active_operator: &mut ActiveOperator,
|
||||
phase: OperatorPhase,
|
||||
message: &str,
|
||||
hint: &str,
|
||||
) {
|
||||
cancel_stroke(state, terrains);
|
||||
state.stop();
|
||||
scene_io.status = message.to_string();
|
||||
set_status(active_operator, phase, hint);
|
||||
}
|
||||
|
||||
fn cancel_stroke(
|
||||
@@ -415,7 +505,8 @@ fn draw_terrain_paint_preview(state: Res<TerrainPaintState>, mut gizmos: Gizmos)
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||
use crate::history::EditorHistory;
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use shared::{ActorKind, LevelObject};
|
||||
|
||||
#[test]
|
||||
@@ -452,8 +543,10 @@ mod tests {
|
||||
.register_type::<shared::TerrainMaterialLayer>()
|
||||
.register_type::<shared::EditorAssetRef>();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<TerrainPaintState>();
|
||||
let mut original = TerrainDesc::flat(9);
|
||||
original.material_layers = vec![Default::default(), Default::default()];
|
||||
let entity = world
|
||||
@@ -471,23 +564,121 @@ mod tests {
|
||||
);
|
||||
}
|
||||
world.entity_mut(entity).insert(final_terrain.clone());
|
||||
commit_paint_stroke(
|
||||
let stroke = TerrainPaintStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
};
|
||||
{
|
||||
let mut state = world.resource_mut::<TerrainPaintState>();
|
||||
state.start(entity, 2);
|
||||
state.stroke = Some(stroke);
|
||||
}
|
||||
let stroke = world
|
||||
.resource_mut::<TerrainPaintState>()
|
||||
.stroke
|
||||
.take()
|
||||
.unwrap();
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_paint_stroke(
|
||||
world,
|
||||
stroke,
|
||||
final_terrain.clone(),
|
||||
TerrainPaintMode::Paint,
|
||||
);
|
||||
|
||||
harness.assert_committed(world, 1, 0);
|
||||
harness.assert_status(world, "terrain.paint", OperatorPhase::Committed);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
let state = world.resource::<TerrainPaintState>();
|
||||
assert!(state.active);
|
||||
assert_eq!(state.target, Some(entity));
|
||||
assert!(!state.is_stroking());
|
||||
assert_undo_redo_round_trip(world, original, final_terrain, |world| {
|
||||
world.get::<TerrainDesc>(entity).unwrap().clone()
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_op_paint_release_terminates_without_dirtying_or_history() {
|
||||
let mut app = App::new();
|
||||
app.register_type::<ActorKind>()
|
||||
.register_type::<TerrainDesc>()
|
||||
.register_type::<shared::TerrainMaterialLayer>()
|
||||
.register_type::<shared::EditorAssetRef>();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let mut original = TerrainDesc::flat(5);
|
||||
original.material_layers = vec![Default::default(), Default::default()];
|
||||
original.ensure_material_weights();
|
||||
let entity = world
|
||||
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
|
||||
.id();
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_paint_stroke(
|
||||
world,
|
||||
TerrainPaintStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
},
|
||||
final_terrain.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
original.clone(),
|
||||
TerrainPaintMode::Erase,
|
||||
);
|
||||
|
||||
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
apply_command_undo(world);
|
||||
harness.assert_canceled(world);
|
||||
harness.assert_status(world, "terrain.paint", OperatorPhase::Canceled);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
|
||||
apply_command_redo(world);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_failure_restores_preview_and_reports_blocked_without_history() {
|
||||
let mut app = App::new();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let mut original = TerrainDesc::flat(5);
|
||||
original.material_layers = vec![Default::default(), Default::default()];
|
||||
let mut preview = original.clone();
|
||||
apply_weight_dab(
|
||||
&mut preview,
|
||||
Vec3::ZERO,
|
||||
3.0,
|
||||
0.8,
|
||||
1,
|
||||
TerrainPaintMode::Paint,
|
||||
);
|
||||
let entity = world
|
||||
.spawn((LevelObject, ActorKind::Terrain, preview.clone()))
|
||||
.id();
|
||||
let mut hierarchy = crate::ui::hierarchy_state::HierarchyPanelState::default();
|
||||
hierarchy.locked.insert(entity);
|
||||
world.insert_resource(hierarchy);
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_paint_stroke(
|
||||
world,
|
||||
TerrainPaintStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
},
|
||||
preview,
|
||||
TerrainPaintMode::Paint,
|
||||
);
|
||||
|
||||
harness.assert_blocked(world);
|
||||
harness.assert_status(world, "terrain.paint", OperatorPhase::Blocked);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(world
|
||||
.resource::<SceneIo>()
|
||||
.status
|
||||
.starts_with("Terrain paint commit failed:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -495,11 +686,21 @@ mod tests {
|
||||
fn cancel_once(
|
||||
mut state: ResMut<TerrainPaintState>,
|
||||
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
mut scene_io: ResMut<SceneIo>,
|
||||
mut active_operator: ResMut<ActiveOperator>,
|
||||
) {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
cancel_active_stroke(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
);
|
||||
}
|
||||
|
||||
let mut app = App::new();
|
||||
app.init_resource::<ActiveOperator>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<SceneIo>();
|
||||
let mut original = TerrainDesc::flat(5);
|
||||
original.material_layers = vec![Default::default(), Default::default()];
|
||||
let mut preview = original.clone();
|
||||
@@ -513,7 +714,7 @@ mod tests {
|
||||
);
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((GlobalTransform::default(), preview))
|
||||
.spawn((LevelObject, GlobalTransform::default(), preview))
|
||||
.id();
|
||||
let mut state = TerrainPaintState::default();
|
||||
state.start(entity, 2);
|
||||
@@ -523,9 +724,72 @@ mod tests {
|
||||
last_local: Vec3::ZERO,
|
||||
});
|
||||
app.insert_resource(state).add_systems(Update, cancel_once);
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
app.update();
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "terrain.paint", OperatorPhase::Canceled);
|
||||
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(!app.world().resource::<TerrainPaintState>().is_stroking());
|
||||
let state = app.world().resource::<TerrainPaintState>();
|
||||
assert!(state.active);
|
||||
assert_eq!(state.target, Some(entity));
|
||||
assert!(!state.is_stroking());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_view_interruption_restores_weights_and_terminates_tool() {
|
||||
fn interrupt_once(
|
||||
mut state: ResMut<TerrainPaintState>,
|
||||
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
mut scene_io: ResMut<SceneIo>,
|
||||
mut active_operator: ResMut<ActiveOperator>,
|
||||
) {
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Terrain paint stopped for clean game view",
|
||||
"Clean game view enabled; weights restored",
|
||||
);
|
||||
}
|
||||
|
||||
let mut app = App::new();
|
||||
app.init_resource::<ActiveOperator>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<SceneIo>();
|
||||
let mut original = TerrainDesc::flat(5);
|
||||
original.material_layers = vec![Default::default(), Default::default()];
|
||||
let mut preview = original.clone();
|
||||
apply_weight_dab(
|
||||
&mut preview,
|
||||
Vec3::ZERO,
|
||||
3.0,
|
||||
0.8,
|
||||
1,
|
||||
TerrainPaintMode::Paint,
|
||||
);
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((LevelObject, GlobalTransform::default(), preview))
|
||||
.id();
|
||||
let mut state = TerrainPaintState::default();
|
||||
state.start(entity, 2);
|
||||
state.stroke = Some(TerrainPaintStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
});
|
||||
app.insert_resource(state)
|
||||
.add_systems(Update, interrupt_once);
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
app.update();
|
||||
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "terrain.paint", OperatorPhase::Canceled);
|
||||
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(!app.world().resource::<TerrainPaintState>().active);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use bevy_egui::EguiContexts;
|
||||
use shared::{TerrainDesc, AUTHORING_COMPONENT_TERRAIN, COMPONENT_TERRAIN_DESC};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::history::reflected_component_transaction;
|
||||
use crate::history::{reflected_component_transaction, EditorHistory};
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::selection::{SelectedEntity, ViewportClick};
|
||||
@@ -143,8 +143,15 @@ fn terrain_sculpt_input(
|
||||
state.clamp_settings();
|
||||
|
||||
let Some(entity) = state.target.or(selected.0) else {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Blocked,
|
||||
"Terrain sculpt stopped: target is unavailable",
|
||||
"Target unavailable",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
if selected.0 != Some(entity) {
|
||||
@@ -152,8 +159,15 @@ fn terrain_sculpt_input(
|
||||
}
|
||||
|
||||
if display.clean_game_view {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Terrain sculpt stopped for clean game view",
|
||||
"Clean game view enabled; terrain restored",
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -163,12 +177,11 @@ fn terrain_sculpt_input(
|
||||
keys.just_pressed(KeyCode::Escape) || buttons.just_pressed(MouseButton::Right);
|
||||
if cancel_requested {
|
||||
if state.is_stroking() {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
scene_io.status = "Terrain sculpt stroke canceled".to_string();
|
||||
set_status(
|
||||
cancel_active_stroke(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Stroke canceled; terrain restored",
|
||||
);
|
||||
} else {
|
||||
state.stop();
|
||||
@@ -179,8 +192,15 @@ fn terrain_sculpt_input(
|
||||
}
|
||||
|
||||
let Ok((global, mut terrain)) = terrains.get_mut(entity) else {
|
||||
state.stroke = None;
|
||||
state.stop();
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Blocked,
|
||||
"Terrain sculpt stopped: target no longer exists",
|
||||
"Target no longer exists",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
@@ -253,18 +273,8 @@ fn terrain_sculpt_input(
|
||||
let label = sculpt_history_label(state.mode);
|
||||
let mode_label = state.mode.label();
|
||||
commands.queue(move |world: &mut World| {
|
||||
let result = commit_terrain_stroke(world, stroke, final_terrain, label);
|
||||
if let Err(error) = result {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Terrain sculpt commit failed: {error}");
|
||||
}
|
||||
finish_terrain_stroke(world, stroke, final_terrain, label, mode_label);
|
||||
});
|
||||
scene_io.status = format!("{mode_label} terrain stroke committed");
|
||||
set_status(
|
||||
&mut active_operator,
|
||||
OperatorPhase::Committed,
|
||||
format!("{mode_label} stroke; Ctrl+Z to undo"),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -276,10 +286,11 @@ fn commit_terrain_stroke(
|
||||
final_terrain: TerrainDesc,
|
||||
label: &'static str,
|
||||
) -> Result<(), String> {
|
||||
let original = stroke.original;
|
||||
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
|
||||
actor.insert(stroke.original);
|
||||
actor.insert(original.clone());
|
||||
}
|
||||
reflected_component_transaction(
|
||||
let result = reflected_component_transaction(
|
||||
world,
|
||||
stroke.entity,
|
||||
label,
|
||||
@@ -289,7 +300,82 @@ fn commit_terrain_stroke(
|
||||
world.entity_mut(entity).insert(final_terrain);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
);
|
||||
if result.is_err() {
|
||||
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
|
||||
actor.insert(original);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn finish_terrain_stroke(
|
||||
world: &mut World,
|
||||
stroke: TerrainStroke,
|
||||
final_terrain: TerrainDesc,
|
||||
label: &'static str,
|
||||
mode_label: &'static str,
|
||||
) {
|
||||
let undo_depth = world.resource::<EditorHistory>().undo_depth();
|
||||
match commit_terrain_stroke(world, stroke, final_terrain, label) {
|
||||
Ok(()) if world.resource::<EditorHistory>().undo_depth() > undo_depth => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("{mode_label} terrain stroke committed");
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Committed,
|
||||
format!("{mode_label} stroke; Ctrl+Z to undo"),
|
||||
);
|
||||
}
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("{mode_label} terrain stroke made no changes");
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Canceled,
|
||||
format!("{mode_label} stroke made no changes"),
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Terrain sculpt commit failed: {error}");
|
||||
set_status(
|
||||
&mut world.resource_mut::<ActiveOperator>(),
|
||||
OperatorPhase::Blocked,
|
||||
format!("Commit failed: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_active_stroke(
|
||||
state: &mut TerrainSculptState,
|
||||
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
scene_io: &mut SceneIo,
|
||||
active_operator: &mut ActiveOperator,
|
||||
) {
|
||||
cancel_stroke(state, terrains);
|
||||
scene_io.status = "Terrain sculpt stroke canceled".to_string();
|
||||
set_status(
|
||||
active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Stroke canceled; terrain restored",
|
||||
);
|
||||
}
|
||||
|
||||
fn stop_tool_with_rollback(
|
||||
state: &mut TerrainSculptState,
|
||||
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
scene_io: &mut SceneIo,
|
||||
active_operator: &mut ActiveOperator,
|
||||
phase: OperatorPhase,
|
||||
message: &str,
|
||||
hint: &str,
|
||||
) {
|
||||
cancel_stroke(state, terrains);
|
||||
state.stop();
|
||||
scene_io.status = message.to_string();
|
||||
set_status(active_operator, phase, hint);
|
||||
}
|
||||
|
||||
fn cancel_stroke(
|
||||
@@ -561,7 +647,8 @@ fn draw_terrain_sculpt_preview(state: Res<TerrainSculptState>, mut gizmos: Gizmo
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||
use crate::history::EditorHistory;
|
||||
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
|
||||
use shared::{ActorKind, LevelObject};
|
||||
|
||||
fn sample(terrain: &TerrainDesc, x: u32, z: u32) -> f32 {
|
||||
@@ -657,8 +744,10 @@ mod tests {
|
||||
app.register_type::<ActorKind>()
|
||||
.register_type::<TerrainDesc>();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
world.init_resource::<TerrainSculptState>();
|
||||
let original = TerrainDesc::flat(9);
|
||||
let entity = world
|
||||
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
|
||||
@@ -676,26 +765,126 @@ mod tests {
|
||||
);
|
||||
}
|
||||
world.entity_mut(entity).insert(final_terrain.clone());
|
||||
commit_terrain_stroke(
|
||||
let stroke = TerrainStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
flatten_height: 0.0,
|
||||
seed: 7,
|
||||
};
|
||||
{
|
||||
let mut state = world.resource_mut::<TerrainSculptState>();
|
||||
state.start(entity);
|
||||
state.stroke = Some(stroke);
|
||||
}
|
||||
let stroke = world
|
||||
.resource_mut::<TerrainSculptState>()
|
||||
.stroke
|
||||
.take()
|
||||
.unwrap();
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_terrain_stroke(
|
||||
world,
|
||||
stroke,
|
||||
final_terrain.clone(),
|
||||
"Raise Terrain",
|
||||
"Raise",
|
||||
);
|
||||
|
||||
harness.assert_committed(world, 1, 0);
|
||||
harness.assert_status(world, "terrain.sculpt", OperatorPhase::Committed);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
let state = world.resource::<TerrainSculptState>();
|
||||
assert!(state.active);
|
||||
assert_eq!(state.target, Some(entity));
|
||||
assert!(!state.is_stroking());
|
||||
assert_undo_redo_round_trip(world, original, final_terrain, |world| {
|
||||
world.get::<TerrainDesc>(entity).unwrap().clone()
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_op_stroke_terminates_without_dirtying_or_history() {
|
||||
let mut app = App::new();
|
||||
app.register_type::<ActorKind>()
|
||||
.register_type::<TerrainDesc>();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let original = TerrainDesc::flat(5);
|
||||
let entity = world
|
||||
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
|
||||
.id();
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_terrain_stroke(
|
||||
world,
|
||||
TerrainStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
flatten_height: 0.0,
|
||||
seed: 7,
|
||||
seed: 1,
|
||||
},
|
||||
final_terrain.clone(),
|
||||
"Raise Terrain",
|
||||
)
|
||||
.unwrap();
|
||||
original.clone(),
|
||||
"Smooth Terrain",
|
||||
"Smooth",
|
||||
);
|
||||
|
||||
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
apply_command_undo(world);
|
||||
harness.assert_canceled(world);
|
||||
harness.assert_status(world, "terrain.sculpt", OperatorPhase::Canceled);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
|
||||
apply_command_redo(world);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_failure_restores_preview_and_reports_blocked_without_history() {
|
||||
let mut app = App::new();
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<ActiveOperator>();
|
||||
world.init_resource::<EditorHistory>();
|
||||
world.init_resource::<SceneIo>();
|
||||
let original = TerrainDesc::flat(5);
|
||||
let mut preview = original.clone();
|
||||
apply_dab(
|
||||
&mut preview,
|
||||
Vec3::ZERO,
|
||||
3.0,
|
||||
0.8,
|
||||
TerrainSculptMode::Raise,
|
||||
0.0,
|
||||
11,
|
||||
);
|
||||
let entity = world
|
||||
.spawn((LevelObject, ActorKind::Terrain, preview.clone()))
|
||||
.id();
|
||||
let mut hierarchy = crate::ui::hierarchy_state::HierarchyPanelState::default();
|
||||
hierarchy.locked.insert(entity);
|
||||
world.insert_resource(hierarchy);
|
||||
let harness = OperatorInvariantHarness::capture(world);
|
||||
|
||||
finish_terrain_stroke(
|
||||
world,
|
||||
TerrainStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
flatten_height: 0.0,
|
||||
seed: 11,
|
||||
},
|
||||
preview,
|
||||
"Raise Terrain",
|
||||
"Raise",
|
||||
);
|
||||
|
||||
harness.assert_blocked(world);
|
||||
harness.assert_status(world, "terrain.sculpt", OperatorPhase::Blocked);
|
||||
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(world
|
||||
.resource::<SceneIo>()
|
||||
.status
|
||||
.starts_with("Terrain sculpt commit failed:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -703,11 +892,21 @@ mod tests {
|
||||
fn cancel_once(
|
||||
mut state: ResMut<TerrainSculptState>,
|
||||
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
mut scene_io: ResMut<SceneIo>,
|
||||
mut active_operator: ResMut<ActiveOperator>,
|
||||
) {
|
||||
cancel_stroke(&mut state, &mut terrains);
|
||||
cancel_active_stroke(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
);
|
||||
}
|
||||
|
||||
let mut app = App::new();
|
||||
app.init_resource::<ActiveOperator>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<SceneIo>();
|
||||
let original = TerrainDesc::flat(5);
|
||||
let mut preview = original.clone();
|
||||
apply_dab(
|
||||
@@ -721,7 +920,7 @@ mod tests {
|
||||
);
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((GlobalTransform::default(), preview))
|
||||
.spawn((LevelObject, GlobalTransform::default(), preview))
|
||||
.id();
|
||||
let mut state = TerrainSculptState::default();
|
||||
state.start(entity);
|
||||
@@ -733,9 +932,74 @@ mod tests {
|
||||
seed: 11,
|
||||
});
|
||||
app.insert_resource(state).add_systems(Update, cancel_once);
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
app.update();
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "terrain.sculpt", OperatorPhase::Canceled);
|
||||
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(!app.world().resource::<TerrainSculptState>().is_stroking());
|
||||
let state = app.world().resource::<TerrainSculptState>();
|
||||
assert!(state.active);
|
||||
assert_eq!(state.target, Some(entity));
|
||||
assert!(!state.is_stroking());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_view_interruption_restores_stroke_and_terminates_tool() {
|
||||
fn interrupt_once(
|
||||
mut state: ResMut<TerrainSculptState>,
|
||||
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||
mut scene_io: ResMut<SceneIo>,
|
||||
mut active_operator: ResMut<ActiveOperator>,
|
||||
) {
|
||||
stop_tool_with_rollback(
|
||||
&mut state,
|
||||
&mut terrains,
|
||||
&mut scene_io,
|
||||
&mut active_operator,
|
||||
OperatorPhase::Canceled,
|
||||
"Terrain sculpt stopped for clean game view",
|
||||
"Clean game view enabled; terrain restored",
|
||||
);
|
||||
}
|
||||
|
||||
let mut app = App::new();
|
||||
app.init_resource::<ActiveOperator>()
|
||||
.init_resource::<EditorHistory>()
|
||||
.init_resource::<SceneIo>();
|
||||
let original = TerrainDesc::flat(5);
|
||||
let mut preview = original.clone();
|
||||
apply_dab(
|
||||
&mut preview,
|
||||
Vec3::ZERO,
|
||||
3.0,
|
||||
0.8,
|
||||
TerrainSculptMode::Raise,
|
||||
0.0,
|
||||
11,
|
||||
);
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((LevelObject, GlobalTransform::default(), preview))
|
||||
.id();
|
||||
let mut state = TerrainSculptState::default();
|
||||
state.start(entity);
|
||||
state.stroke = Some(TerrainStroke {
|
||||
entity,
|
||||
original: original.clone(),
|
||||
last_local: Vec3::ZERO,
|
||||
flatten_height: 0.0,
|
||||
seed: 11,
|
||||
});
|
||||
app.insert_resource(state)
|
||||
.add_systems(Update, interrupt_once);
|
||||
let harness = OperatorInvariantHarness::capture(app.world_mut());
|
||||
|
||||
app.update();
|
||||
|
||||
harness.assert_canceled(app.world_mut());
|
||||
harness.assert_status(app.world(), "terrain.sculpt", OperatorPhase::Canceled);
|
||||
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
|
||||
assert!(!app.world().resource::<TerrainSculptState>().active);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
//! Editor-side scene visualizers for authoring/runtime entities that have no mesh.
|
||||
|
||||
use avian3d::prelude::ColliderConstructor;
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
use avian3d::prelude::{ColliderAabb, ColliderConstructor};
|
||||
use bevy::ecs::system::SystemParam;
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
AudioListenerDesc, AudioSourceDesc, AuthoringLightKind, ColliderDesc, ColliderShapeDesc,
|
||||
LevelObject, LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink,
|
||||
NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc,
|
||||
PrefabRef, ProjectSun, RaytracingExcluded, SkinnedMeshRenderer, TeamSpawn, TriggerVolume,
|
||||
WeaponSpawn,
|
||||
PrefabRef, ProjectSun, RaytracingExcluded, RigidBodyDesc, SkinnedMeshRenderer, TeamSpawn,
|
||||
TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS};
|
||||
use sim::{Player, PlayerCamera};
|
||||
@@ -16,6 +18,10 @@ use sim::{Player, PlayerCamera};
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::{scene_tools_active, EditorMode, PlayPossession};
|
||||
use crate::viewport::collider_diagnostics::{
|
||||
refresh_collider_diagnostics, ColliderDiagnosticEntry, ColliderDiagnosticsState,
|
||||
ColliderOverlayStatus,
|
||||
};
|
||||
use crate::viewport::{EditorViewportMode, ViewportDisplayMode};
|
||||
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
@@ -102,7 +108,7 @@ struct VisualizerTargetQueries<'w, 's> {
|
||||
Entity,
|
||||
(
|
||||
With<LevelObject>,
|
||||
Or<(With<PhysicsBody>, With<ColliderDesc>)>,
|
||||
Or<(With<PhysicsBody>, With<ColliderDesc>, With<RigidBodyDesc>)>,
|
||||
),
|
||||
>,
|
||||
lights: Query<'w, 's, Entity, (With<LevelObject>, With<LightDesc>)>,
|
||||
@@ -127,7 +133,15 @@ pub struct EditorVisualizersPlugin;
|
||||
impl Plugin for EditorVisualizersPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorVisualizationSettings>()
|
||||
.init_resource::<ColliderDiagnosticsState>()
|
||||
.add_systems(Startup, init_visualizer_proxy_assets)
|
||||
.add_systems(
|
||||
Update,
|
||||
refresh_collider_diagnostics
|
||||
.before(sync_visualizer_proxies)
|
||||
.before(draw_visualizers)
|
||||
.before(draw_split_collider_visualizers),
|
||||
)
|
||||
.add_systems(Update, sync_visualizer_proxies)
|
||||
.add_systems(
|
||||
Update,
|
||||
@@ -135,6 +149,7 @@ impl Plugin for EditorVisualizersPlugin {
|
||||
draw_visualizers,
|
||||
draw_audio_visualizers,
|
||||
draw_split_collider_visualizers,
|
||||
draw_missing_collider_visualizers,
|
||||
draw_post_process_volume_gizmos,
|
||||
draw_navigation_visualizers,
|
||||
)
|
||||
@@ -145,6 +160,52 @@ impl Plugin for EditorVisualizersPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_missing_collider_visualizers(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
diagnostics: Res<ColliderDiagnosticsState>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut gizmos: Gizmos,
|
||||
missing: Query<
|
||||
(Entity, &GlobalTransform),
|
||||
(
|
||||
With<LevelObject>,
|
||||
With<RigidBodyDesc>,
|
||||
Without<ColliderDesc>,
|
||||
Without<PhysicsBody>,
|
||||
),
|
||||
>,
|
||||
) {
|
||||
let collider_mode = *viewport_mode == EditorViewportMode::Collider;
|
||||
if !(collider_mode || settings.enabled && settings.show_colliders) {
|
||||
return;
|
||||
}
|
||||
for (entity, global) in &missing {
|
||||
let color = collider_overlay_color(
|
||||
diagnostics.entry(entity),
|
||||
selected.0 == Some(entity),
|
||||
collider_mode,
|
||||
);
|
||||
let center = global.translation();
|
||||
let radius = if selected.0 == Some(entity) {
|
||||
0.48
|
||||
} else {
|
||||
0.34
|
||||
};
|
||||
draw_box(
|
||||
&mut gizmos,
|
||||
center,
|
||||
global.rotation(),
|
||||
Vec3::splat(radius),
|
||||
color,
|
||||
);
|
||||
for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
|
||||
let direction = global.rotation() * axis * radius * 1.35;
|
||||
gizmos.line(center - direction, center + direction, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_navigation_visualizers(
|
||||
state: Res<crate::ui::navigation_inspector::NavigationEditorState>,
|
||||
mut gizmos: Gizmos,
|
||||
@@ -556,17 +617,7 @@ fn draw_visualizers(
|
||||
|
||||
if settings.show_colliders || collider_mode {
|
||||
for (entity, body, global) in &colliders {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
if collider_mode {
|
||||
Color::srgba(0.65, 1.0, 0.55, 1.0)
|
||||
} else {
|
||||
Color::srgba(0.55, 1.0, 0.45, 0.95)
|
||||
}
|
||||
} else if collider_mode {
|
||||
Color::srgba(0.35, 1.0, 0.45, 0.9)
|
||||
} else {
|
||||
Color::srgba(0.25, 0.9, 0.35, 0.55)
|
||||
};
|
||||
let color = collider_overlay_color(None, selected.0 == Some(entity), collider_mode);
|
||||
draw_collider(&mut gizmos, global, &body.collider, color);
|
||||
}
|
||||
}
|
||||
@@ -679,11 +730,18 @@ fn draw_visualizers(
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "collider overlays combine authoring, runtime bounds, selection, and viewport state"
|
||||
)]
|
||||
fn draw_split_collider_visualizers(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
diagnostics: Res<ColliderDiagnosticsState>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut gizmos: Gizmos,
|
||||
children: Query<&Children>,
|
||||
runtime_aabbs: Query<&ColliderAabb>,
|
||||
colliders: Query<
|
||||
(Entity, &ColliderDesc, &GlobalTransform),
|
||||
(With<LevelObject>, Without<PhysicsBody>),
|
||||
@@ -697,15 +755,78 @@ fn draw_split_collider_visualizers(
|
||||
return;
|
||||
}
|
||||
for (entity, collider, global) in &colliders {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(0.65, 1.0, 0.55, 1.0)
|
||||
} else if collider_mode {
|
||||
Color::srgba(0.35, 1.0, 0.45, 0.9)
|
||||
} else {
|
||||
Color::srgba(0.25, 0.9, 0.35, 0.55)
|
||||
};
|
||||
let color = collider_overlay_color(
|
||||
diagnostics.entry(entity),
|
||||
selected.0 == Some(entity),
|
||||
collider_mode,
|
||||
);
|
||||
let drew_runtime_mesh = matches!(collider.shape, ColliderShapeDesc::StaticMesh { .. })
|
||||
&& draw_runtime_collider_bounds(&mut gizmos, entity, &children, &runtime_aabbs, color);
|
||||
if !drew_runtime_mesh {
|
||||
draw_collider_desc(&mut gizmos, global, collider, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collider_overlay_color(
|
||||
entry: Option<&ColliderDiagnosticEntry>,
|
||||
selected: bool,
|
||||
collider_mode: bool,
|
||||
) -> Color {
|
||||
let status = entry
|
||||
.map(|entry| entry.overlay_status)
|
||||
.unwrap_or(ColliderOverlayStatus::Valid);
|
||||
let (rgb, base_alpha): (Vec3, f32) = match status {
|
||||
ColliderOverlayStatus::Valid => (Vec3::new(0.25, 0.92, 0.43), 0.72),
|
||||
ColliderOverlayStatus::Trigger => (Vec3::new(0.18, 0.82, 1.0), 0.78),
|
||||
ColliderOverlayStatus::Disabled => (Vec3::new(0.52, 0.56, 0.62), 0.42),
|
||||
ColliderOverlayStatus::Warning => (Vec3::new(1.0, 0.68, 0.18), 0.9),
|
||||
ColliderOverlayStatus::Error => (Vec3::new(1.0, 0.24, 0.3), 0.96),
|
||||
};
|
||||
let alpha = if selected {
|
||||
1.0
|
||||
} else if collider_mode {
|
||||
base_alpha.max(0.82)
|
||||
} else {
|
||||
base_alpha * 0.72
|
||||
};
|
||||
let rgb = if selected {
|
||||
rgb.lerp(Vec3::ONE, 0.18)
|
||||
} else {
|
||||
rgb
|
||||
};
|
||||
Color::srgba(rgb.x, rgb.y, rgb.z, alpha)
|
||||
}
|
||||
|
||||
fn draw_runtime_collider_bounds(
|
||||
gizmos: &mut Gizmos,
|
||||
root: Entity,
|
||||
children: &Query<&Children>,
|
||||
aabbs: &Query<&ColliderAabb>,
|
||||
color: Color,
|
||||
) -> bool {
|
||||
let mut pending = vec![root];
|
||||
let mut drew = false;
|
||||
while let Some(entity) = pending.pop() {
|
||||
if let Ok(aabb) = aabbs.get(entity) {
|
||||
let min = aabb.min;
|
||||
let max = aabb.max;
|
||||
if min.is_finite() && max.is_finite() && min.cmplt(max).all() {
|
||||
draw_box(
|
||||
gizmos,
|
||||
(min + max) * 0.5,
|
||||
Quat::IDENTITY,
|
||||
(max - min) * 0.5,
|
||||
color,
|
||||
);
|
||||
drew = true;
|
||||
}
|
||||
}
|
||||
if let Ok(entity_children) = children.get(entity) {
|
||||
pending.extend(entity_children.iter());
|
||||
}
|
||||
}
|
||||
drew
|
||||
}
|
||||
|
||||
fn draw_post_process_volume_gizmos(
|
||||
@@ -741,6 +862,8 @@ fn draw_collider(
|
||||
collider: &ColliderConstructor,
|
||||
color: Color,
|
||||
) {
|
||||
let (scale, rotation, translation) = global.to_scale_rotation_translation();
|
||||
let scale = scale.abs();
|
||||
match collider {
|
||||
ColliderConstructor::Cuboid {
|
||||
x_length,
|
||||
@@ -748,27 +871,21 @@ fn draw_collider(
|
||||
z_length,
|
||||
} => draw_box(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
|
||||
translation,
|
||||
rotation,
|
||||
Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
|
||||
color,
|
||||
),
|
||||
ColliderConstructor::Sphere { radius } => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
*radius,
|
||||
color,
|
||||
)
|
||||
.resolution(24);
|
||||
draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
|
||||
}
|
||||
ColliderConstructor::Capsule { radius, height } => {
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
*radius,
|
||||
*height,
|
||||
translation,
|
||||
rotation,
|
||||
*radius * scale.x.max(scale.z),
|
||||
*height * scale.y,
|
||||
color,
|
||||
);
|
||||
}
|
||||
@@ -790,9 +907,8 @@ fn draw_collider_desc(
|
||||
collider: &ColliderDesc,
|
||||
color: Color,
|
||||
) {
|
||||
if !collider.enabled {
|
||||
return;
|
||||
}
|
||||
let (scale, rotation, translation) = global.to_scale_rotation_translation();
|
||||
let scale = scale.abs();
|
||||
match &collider.shape {
|
||||
ColliderShapeDesc::Cuboid {
|
||||
x_length,
|
||||
@@ -800,40 +916,57 @@ fn draw_collider_desc(
|
||||
z_length,
|
||||
} => draw_box(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
|
||||
translation,
|
||||
rotation,
|
||||
Vec3::new(*x_length, *y_length, *z_length) * scale * 0.5,
|
||||
color,
|
||||
),
|
||||
ColliderShapeDesc::Sphere { radius } => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
*radius,
|
||||
color,
|
||||
)
|
||||
.resolution(24);
|
||||
draw_ellipsoid(gizmos, translation, rotation, scale * *radius, color);
|
||||
}
|
||||
ColliderShapeDesc::Capsule { radius, height } => {
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
*radius,
|
||||
*height,
|
||||
translation,
|
||||
rotation,
|
||||
*radius * scale.x.max(scale.z),
|
||||
*height * scale.y,
|
||||
color,
|
||||
);
|
||||
}
|
||||
ColliderShapeDesc::StaticMesh { .. } => {
|
||||
draw_box(gizmos, translation, rotation, Vec3::splat(0.24), color);
|
||||
gizmos.line(
|
||||
translation - rotation * Vec3::splat(0.34),
|
||||
translation + rotation * Vec3::splat(0.34),
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_ellipsoid(gizmos: &mut Gizmos, center: Vec3, rotation: Quat, radii: Vec3, color: Color) {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
0.35,
|
||||
.ellipse(
|
||||
Isometry3d::new(center, rotation),
|
||||
Vec2::new(radii.x, radii.z),
|
||||
color,
|
||||
)
|
||||
.resolution(16);
|
||||
}
|
||||
}
|
||||
.resolution(32);
|
||||
gizmos
|
||||
.ellipse(
|
||||
Isometry3d::new(center, rotation * Quat::from_rotation_x(FRAC_PI_2)),
|
||||
Vec2::new(radii.x, radii.y),
|
||||
color,
|
||||
)
|
||||
.resolution(32);
|
||||
gizmos
|
||||
.ellipse(
|
||||
Isometry3d::new(center, rotation * Quat::from_rotation_z(FRAC_PI_2)),
|
||||
Vec2::new(radii.y, radii.z),
|
||||
color,
|
||||
)
|
||||
.resolution(32);
|
||||
}
|
||||
|
||||
fn draw_light(
|
||||
|
||||
@@ -55,6 +55,7 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
|
||||
| [0038](adr/0038-non-blocking-native-dialog-broker.md) | Worker-owned native waits with one-shot main-thread workflow completion |
|
||||
| [0039](adr/0039-inline-height-grid-terrain-foundation.md) | Inline authored height grids with deterministic runtime-only chunk hydration |
|
||||
| [0040](adr/0040-terrain-material-layer-weights.md) | Four-channel terrain material layers, compact normalized weights, and raster transport |
|
||||
| [0041](adr/0041-transactional-editor-physics-placement.md) | Paused editor physics ownership and transactional gravity placement |
|
||||
|
||||
## Editor framework
|
||||
|
||||
@@ -82,10 +83,15 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
|
||||
| [editor/collaborative-file-safety.md](editor/collaborative-file-safety.md) | Guarded authored writes, compact Git/read-only status, conflict recovery, and ownership providers |
|
||||
| [editor/native-dialogs.md](editor/native-dialogs.md) | Non-blocking native dialog acquisition and main-thread result application |
|
||||
| [editor/terrain.md](editor/terrain.md) | Terrain schema, inspector workflow, chunk hydration, collision, and follow-on boundaries |
|
||||
| [editor/physics-placement.md](editor/physics-placement.md) | Transactional gravity placement, diagnostics, isolation, and undo workflow |
|
||||
| [editor/collider-authoring.md](editor/collider-authoring.md) | Collider shape authoring, hydration diagnostics, semantic overlays, and placement prerequisites |
|
||||
| [editor/evaluations/material-renderer-foundation/](editor/evaluations/material-renderer-foundation/) | Live screenshots and acceptance results for the renderer/material/component foundation |
|
||||
| [editor/evaluations/terrain-sculpt-tools/](editor/evaluations/terrain-sculpt-tools/) | Live screenshot and acceptance results for modal terrain sculpt tools |
|
||||
| [editor/evaluations/terrain-material-layers/](editor/evaluations/terrain-material-layers/) | Live screenshot and acceptance results for terrain material assignment, blending, painting, and history |
|
||||
| [editor/evaluations/physics-placement/](editor/evaluations/physics-placement/) | Live screenshot and acceptance results for physics settling, cancel, commit, undo, and redo |
|
||||
| [editor/evaluations/collider-diagnostics/](editor/evaluations/collider-diagnostics/) | Live screenshot and acceptance results for collider overlays, diagnostics, shape history, and placement preflight |
|
||||
| [editor/evaluations/navigation-authoring/](editor/evaluations/navigation-authoring/) | Live screenshots and acceptance results for navigation authoring and runtime parity |
|
||||
| [editor/evaluations/operator-invariants/](editor/evaluations/operator-invariants/) | Source acceptance results for production operator lifecycle, rollback, cleanup, and undo/redo invariants |
|
||||
| [editor/evaluations/production-readiness/](editor/evaluations/production-readiness/) | Current versioned production gate, evidence matrix, candidate commands, soak protocol, and independent sign-off requirements |
|
||||
|
||||
## Working plans (not canonical long-term)
|
||||
@@ -109,6 +115,7 @@ Detailed milestone and feature plans live in [`.cursor/plans/`](../.cursor/plans
|
||||
| `production_readiness_acceptance_*.plan.md` | Release-candidate evidence matrix, blocker sequence, clean-checkout checks, soak, budgets, and independent sign-off |
|
||||
| `material_library_and_targeted_drop_*.plan.md` | Dedicated Material Library, exact viewport slot/primitive/brush targeting, hover preview, cancel, and grouped history |
|
||||
| `terrain_material_layers_*.plan.md` | Terrain shared-material layers, normalized weights, blended hydration, and modal painting |
|
||||
| `operator_invariants_completion_*.plan.md` | Production operator dispatch, interruption, rollback, cleanup, and undo/redo acceptance |
|
||||
|
||||
## Crate responsibilities (quick reference)
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ from its draw or skeleton representation.
|
||||
user decision to reassign or discard.
|
||||
- Legacy primitive/actor `MaterialDesc` paths remain compatibility paths until their consumers move
|
||||
to renderer slots; new mesh-renderer work uses shared references.
|
||||
- Runtime property blocks have no editor promotion workflow yet.
|
||||
- `MaterialPropertyBlocks` currently define the runtime-only schema and persistence exclusion, but
|
||||
renderer application and the editor promote-to-instance transaction are not implemented. Gitea
|
||||
#53 owns that complete workflow; callers must not treat the component as visibly applied yet.
|
||||
- Material graph authoring, nested instances, blended/transmissive materials, and a generalized
|
||||
per-renderer property-block inspector are outside this decision.
|
||||
@@ -0,0 +1,44 @@
|
||||
# ADR 0041: Transactional Editor Physics Placement
|
||||
|
||||
## Status
|
||||
|
||||
Accepted
|
||||
|
||||
## Context
|
||||
|
||||
The editor and game share one Bevy world and one Avian physics instance. Authored rigid
|
||||
bodies are hydrated in Edit mode so collider visualization and queries remain available,
|
||||
but advancing the shared simulation while editing mutates scene transforms outside history.
|
||||
A physics-placement tool must use the real runtime colliders while preventing unrelated
|
||||
dynamic bodies, PIE state, or authored physics settings from changing.
|
||||
|
||||
Running a second physics world would duplicate hydration, imported-mesh collider cooking,
|
||||
and hierarchy mapping. Advancing the existing world without isolation would make placement
|
||||
dependent on every other movable body in the scene and would violate cancel safety.
|
||||
|
||||
## Decision
|
||||
|
||||
The editor owns Avian's `Time<Physics>` clock:
|
||||
|
||||
- normal Edit mode and paused Play mode keep physics paused;
|
||||
- active Play mode unpauses physics;
|
||||
- paused Play single-step advances the physics clock by one fixed tick;
|
||||
- the placement tool advances bounded 120 Hz steps while Edit mode remains paused.
|
||||
|
||||
Physics placement is a transactional preview in the shared world. It snapshots the selected
|
||||
bodies' local transforms and runtime motion components, temporarily makes them dynamic, and
|
||||
temporarily makes every other movable rigid body static. Static bodies and all colliders stay
|
||||
in the same world, preserving production collision fidelity. Commit restores every temporary
|
||||
runtime override and writes only the final local transforms through one grouped history
|
||||
command. Cancel restores the full snapshot and writes no history.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Edit mode no longer permits authored dynamic bodies to drift outside undo history.
|
||||
- Placement uses the exact hydrated collider geometry used by PIE and the standalone game.
|
||||
- Kinematic and dynamic non-selected bodies behave as fixed collision surfaces during the
|
||||
preview; simulating interacting piles is deliberately outside this tool's contract.
|
||||
- A placement session cannot cross the Edit/Play boundary and is cancelled on mode exit.
|
||||
- Future editor physics previews should reuse this clock ownership and transactional-session
|
||||
model instead of introducing independent ad hoc simulation loops.
|
||||
|
||||
@@ -26,6 +26,8 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
||||
| [collaborative-file-safety.md](collaborative-file-safety.md) | Exact authored-file revisions, Git/read-only status, conflict recovery, and optional ownership providers |
|
||||
| [native-dialogs.md](native-dialogs.md) | Non-blocking file/folder/confirmation acquisition and main-thread result application |
|
||||
| [terrain.md](terrain.md) | Inline height-grid terrain, chunk hydration, collision, inspector workflow, and fixtures |
|
||||
| [physics-placement.md](physics-placement.md) | Transactional gravity placement, prerequisites, isolation, commit/cancel, and undo |
|
||||
| [collider-authoring.md](collider-authoring.md) | Collider shape editing, shared health diagnostics, overlays, hydration status, and placement reuse |
|
||||
| [evaluations/](evaluations/) | Acceptance evidence records and native Gitea attachment publishing policy |
|
||||
| [evaluations/material-renderer-foundation/](evaluations/material-renderer-foundation/) | Live screenshots and verification record for the renderer/material/component foundation |
|
||||
| [evaluations/material-library-targeted-drop/](evaluations/material-library-targeted-drop/) | Live screenshot and verification record for the docked Material Library and exact reversible surface drops |
|
||||
@@ -34,7 +36,10 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
||||
| [evaluations/terrain-foundation/](evaluations/terrain-foundation/) | Live screenshot and verification record for height-grid terrain schema and chunk hydration |
|
||||
| [evaluations/terrain-sculpt-tools/](evaluations/terrain-sculpt-tools/) | Live screenshot and verification record for modal sculpt controls, footprint, and stroke history |
|
||||
| [evaluations/terrain-material-layers/](evaluations/terrain-material-layers/) | Live screenshot and verification record for blended layers, assignment, painting, and history |
|
||||
| [evaluations/physics-placement/](evaluations/physics-placement/) | Live screenshot and verification record for multi-prop settling, cancel, commit, undo, and redo |
|
||||
| [evaluations/collider-diagnostics/](evaluations/collider-diagnostics/) | Live screenshot and verification record for semantic collider overlays, health linking, shape switching, and placement reuse |
|
||||
| [evaluations/navigation-authoring/](evaluations/navigation-authoring/) | Live screenshots and verification record for navigation authoring and runtime parity |
|
||||
| [evaluations/operator-invariants/](evaluations/operator-invariants/) | Source acceptance record for production operator lifecycle, rollback, cleanup, and undo/redo invariants |
|
||||
| [evaluations/production-readiness/](evaluations/production-readiness/) | Current #50 release-candidate matrix and required clean-checkout, soak, performance, limitation, and independent-signoff evidence |
|
||||
|
||||
## Subsystems (code → doc)
|
||||
@@ -44,6 +49,8 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
||||
| `lib.rs` / `EditorPluginGroup` | Ordered plugin bundle, lib/bin split | ADR 0008, architecture.md |
|
||||
| `shared::components::BrushDesc` / `shared::hydration::brushes` | Persisted brush authoring data and generated runtime mesh hydration | brushes.md, ADR 0021 |
|
||||
| `shared::components::TerrainDesc` / `shared::hydration::terrain` / `blacksite_surface` | Persisted height/layer grids, generated chunks, and raster blending | terrain.md, ADR 0039, ADR 0040 |
|
||||
| `viewport/physics_placement.rs` / `play/state.rs` | Paused Edit physics and transactional gravity placement | physics-placement.md, ADR 0041 |
|
||||
| `viewport/collider_diagnostics.rs` / `viewport/visualizers.rs` / `ui/inspector.rs` | Shared collider health, semantic overlays, and undoable shape authoring | collider-authoring.md |
|
||||
| `scene/` | Level I/O, tabs, composition materialization, schema, viewport render-target setup | architecture.md, multi-scene-composition.md, ADR 0026 |
|
||||
| `viewport/` | Camera, selection, gizmos, render views | architecture.md |
|
||||
| `play/` | PIE session, editor mode state | architecture.md |
|
||||
@@ -86,8 +93,8 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
||||
- **Brush authoring** — `ActorKind::Brush + BrushDesc` stores persisted convex blockout faces, validates authored geometry in the inspector and Window → Brush Diagnostics, and hydrates active valid brushes into generated mesh children. See [brushes.md](brushes.md).
|
||||
- **Draw Brush** — `B`, toolbar pencil, or command `brush.draw` enters a floor-polygon draw mode. LMB places snapped points, Backspace removes the last point, Enter locks the outline for height editing, mouse up/down adjusts height, and Enter/LMB creates additive prism brushes through history. Esc/right-click cancels. Simple concave outlines decompose into convex brush parts; self-intersections remain blocked.
|
||||
- **Brush edit modes** — with a brush selected, `1`/`2`/`3`/`4` enter vertex, edge, face, and clip element modes. Element modes show brush handles in the viewport, own LMB picking, support Shift multi-select, show a mode badge, and Esc returns to object mode. Vertex/edge/face selections use the standard `W`/`E`/`R` gizmo at the element pivot and commit undoable `SetBrush` edits. Clip previews a bounds-based half-brush and commits with Enter; command-palette intersect, convex merge, and subtract operations use the same preview/commit lifecycle for conservative cuboid/prism blockout.
|
||||
- **Collider split** — imported mesh collision lives in a separate `ColliderDesc::StaticMesh` plus optional `RigidBodyDesc`; renderer slots own only render visibility, shadows, mesh, and material references.
|
||||
- **Material assets and renderer slots** — Material and direct-base Material Instance documents are shared assets. `StaticMeshRenderer` and `SkinnedMeshRenderer` each own stable material slots with imported source defaults and explicit shared assignments; Clear returns to the source default, while reimported missing slots retain overrides as orphans instead of matching by name. Runtime-only property blocks never mutate or persist into the shared asset. Custom Surface evaluators use the same constrained ABI for raster and Solari-eligible non-deformed geometry; skinned/morph geometry is deliberately excluded from Solari until deformed BLAS updates exist. See [material-system.md](material-system.md), [ADR 0035](../adr/0035-shared-material-assets-and-renderer-slots.md), and [ADR 0036](../adr/0036-surface-abi-and-solari-parity.md).
|
||||
- **Collider split and health** — imported mesh collision lives in a separate `ColliderDesc::StaticMesh` plus optional `RigidBodyDesc`; renderer slots own only render visibility, shadows, mesh, and material references. Inspector, viewport, Diagnostics, and physics placement share one authored/runtime health result; see [collider-authoring.md](collider-authoring.md).
|
||||
- **Material assets and renderer slots** — Material and direct-base Material Instance documents are shared assets. `StaticMeshRenderer` and `SkinnedMeshRenderer` each own stable material slots with imported source defaults and explicit shared assignments; Clear returns to the source default, while reimported missing slots retain overrides as orphans instead of matching by name. The property-block schema is runtime-only and persistence-excluded, while renderer application/promotion remains #53. Custom Surface evaluators use the same constrained ABI for raster and Solari-eligible non-deformed geometry; skinned/morph geometry is deliberately excluded from Solari until #54 adds deformed BLAS updates. See [material-system.md](material-system.md), [ADR 0035](../adr/0035-shared-material-assets-and-renderer-slots.md), and [ADR 0036](../adr/0036-surface-abi-and-solari-parity.md).
|
||||
- **Prefab authoring** — shared `PrefabOverrides` targets generated actors by nested anchor chain plus stable `ActorId`, and applies reflected property/component plus same-layer structural operations in editor and game hydration. The editor supports scoped Revert and transactional **Apply to source** with three-way conflict checks, exact-file undo guards, and recoverable changed/broken/conflict states. `HydratedPrefabMember` keeps generated content out of owner serialization; linked-root saves retain local structure as variants. **Unpack Layer** preserves nested links, while **Convert to Local** recursively removes them. See [prefab-authoring.md](prefab-authoring.md) and [ADR 0027](../adr/0027-stable-prefab-ownership-and-variants.md).
|
||||
- **Visual language** uses a near-black industrial shell, a compact Blacksite identity mark, restrained amber actions/primary selection, cyan secondary selection, semantic status colors, stable grouped controls, and shared elevated viewport chips. Primary/secondary selection roles remain consistent across hierarchy rows, viewport x-ray shells/corner brackets, the selection HUD, and transform interactions. See [visual-language.md](visual-language.md).
|
||||
- **Hierarchy** shows authored objects plus useful runtime context (`Player`, `PlayerCamera`, Project Sun). Ordinary runtime rows remain read-only; generated prefab rows expose override-aware inspection and same-layer remove/reparent actions while rejecting cross-instance/layer and composition-boundary drops. Locks prevent selection, gizmos, drag participation, structural targets, and mutating context actions. Authored reparenting preserves world placement and records parent/local-transform/manual-order changes as one undoable command.
|
||||
|
||||
@@ -24,6 +24,7 @@ Native-only dependencies (`rfd`, BRP HTTP) stay in `editor`. `settings`, `shared
|
||||
| `ProjectSettingsPlugin` | Load `assets/project.ron`, emit changes, sync `SimTuning` |
|
||||
| `ProjectIoPlugin` | User prefs, workspace metadata, window title inputs |
|
||||
| `EditorStatePlugin` | `EditorMode` (Edit/Play), `PlayPossession`, camera/input gating |
|
||||
| `PhysicsPlacementPlugin` | Paused Edit physics plus isolated transactional gravity placement |
|
||||
| `ViewportPlugin` | Grid, focus, bookmarks, snap settings |
|
||||
| `EditorCameraPlugin` | Fly camera; FX applied via `render_view` + `viewport_camera` sync |
|
||||
| `ActorIconsPlugin` | Selectable actor root billboard icons |
|
||||
@@ -181,11 +182,19 @@ stateDiagram-v2
|
||||
|----------|---------|-------------------|-----------------|
|
||||
| `SimEnabled` | false | true | true |
|
||||
| `GameInputEnabled` | false | true | false |
|
||||
| `Time<Physics>` | paused | running | running |
|
||||
| Editor camera active | true | false | true |
|
||||
| Player camera active | false | true | false |
|
||||
|
||||
On play enter/exit the editor snapshots **player sim state only** (transform, velocity, jump timers). Authored scene entities are not rolled back so in-play edits persist when stopping PIE.
|
||||
|
||||
Paused Play also pauses `Time<Physics>`; **F7** advances that clock by exactly one 64 Hz sim tick.
|
||||
Edit mode keeps the clock paused. `viewport/physics_placement.rs` may advance bounded 120 Hz
|
||||
preview steps while selected bodies are temporarily dynamic and every other movable body is
|
||||
temporarily static. Commit records only final local transforms through grouped history; cancel and
|
||||
the Edit-to-Play boundary restore the complete runtime snapshot. See
|
||||
[physics-placement.md](physics-placement.md) and [ADR 0041](../adr/0041-transactional-editor-physics-placement.md).
|
||||
|
||||
## Scene authoring flow
|
||||
|
||||
1. User edits entities with `LevelObject` + reflectable components from `shared`.
|
||||
@@ -236,13 +245,16 @@ On play enter/exit the editor snapshots **player sim state only** (transform, ve
|
||||
|
||||
Structural edits (spawn, delete, transform, rename) go through `EditorHistory` command objects in `history.rs`.
|
||||
User-facing actions route through the operator lifecycle in `operators.rs`: begin, preview,
|
||||
commit, cancel, disabled reason, and status text. The first bridge wraps command-palette and queued
|
||||
editor commands as immediate operators, while existing `EditorHistory` commands remain the undo
|
||||
payload. Asset placement, mesh-subasset placement, texture apply, and material apply actions now
|
||||
use immediate operators from `assets::operators`; texture/material changes across a selection use
|
||||
one `SetMaterialGroup` command. Draw Brush, brush CSG, clip, and element gizmo paths publish the
|
||||
same preview/commit/cancel phases. `operators/test_harness.rs` verifies authored deltas, dirty
|
||||
state, helper cleanup, undo grouping, and undo/redo restoration; see
|
||||
commit, cancel, disabled reason, stable ID, and status text. Registered commands return typed
|
||||
`OperatorAction::Commit` or `OperatorAction::ContinuePreview`, so immediate commands finish while
|
||||
Draw Brush and CSG retain modal Preview ownership; validation failures terminate instead of leaving
|
||||
stale status. Existing `EditorHistory` commands remain the undo payload. Group Selection is one
|
||||
atomic command that remaps its transient group identity on every redo without reparenting unrelated
|
||||
siblings. Lighting reset and Project Sun changes use one grouped light command. Asset placement,
|
||||
assignment, exact material drops, brush tools, terrain strokes, physics placement, and the real
|
||||
transform tracker all publish terminal lifecycle state. `operators/test_harness.rs` verifies semantic
|
||||
projections, dirty-state preservation, stable IDs, helper cleanup, undo grouping, repeated undo/redo,
|
||||
and automatic interruption rollback; see
|
||||
[operator-regression-testing.md](operator-regression-testing.md).
|
||||
|
||||
PIE stop restores player simulation state only; authored `LevelObject` edits made during PIE remain in the scene.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Collider Authoring And Diagnostics
|
||||
|
||||
`ColliderDesc` is the saved collision shape. `RigidBodyDesc` independently controls authored body
|
||||
motion, while Avian `Collider` and `RigidBody` components are hydrated runtime state. Collider
|
||||
health compares both sides of that boundary so editor tools do not treat authored-but-unavailable
|
||||
collision as ready.
|
||||
|
||||
## Inspector Workflow
|
||||
|
||||
The Collider component card reports its shape, health, and hydration state. Box, sphere, capsule,
|
||||
and static mesh shapes can be switched from the Shape menu. Primitive conversions retain the
|
||||
previous shape's useful extents; each completed switch uses `SetCollider` history and is one undo
|
||||
operation. Invalid shapes expose a reset action. Static mesh sources can be selected or replaced
|
||||
with the actor's renderer meshes.
|
||||
|
||||
Dimensions are clamped to positive values in normal inspector editing. Project validation still
|
||||
rejects hand-edited or migrated non-finite/zero dimensions and empty mesh source lists.
|
||||
|
||||
## Viewport Contract
|
||||
|
||||
Collider view hides render meshes and emphasizes authored collision using semantic status colors:
|
||||
|
||||
| Color | State |
|
||||
|-------|-------|
|
||||
| Green | Valid hydrated solid collider |
|
||||
| Cyan | Valid hydrated trigger |
|
||||
| Gray | Disabled or inactive collider |
|
||||
| Amber | Stale hydration or oversized collider |
|
||||
| Red | Missing or invalid collider |
|
||||
|
||||
Box, sphere/ellipsoid, and capsule wireframes include actor world scale. Static mesh collision uses
|
||||
the cooked runtime collider bounds when available. A rigid body with no collider receives a red
|
||||
spatial marker, so missing collision remains discoverable with meshes hidden. The lower-left HUD
|
||||
summarizes scene health and identifies the selected collider's shape and hydration state.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
The shared health service reports:
|
||||
|
||||
- missing/inactive/disabled collider authoring;
|
||||
- non-positive or non-finite primitive dimensions;
|
||||
- empty, unresolved, or registry-stale static mesh references;
|
||||
- valid authoring that has not produced a runtime collider;
|
||||
- primitive colliders exceeding 1,000 meters on any world-space axis.
|
||||
|
||||
The 1,000-meter warning is conservative rather than a save blocker. Large worlds should split
|
||||
collision into spatially bounded actors to keep broad-phase behavior predictable. Diagnostics can
|
||||
select the affected actor; static mesh fields retain their asset-browser locate action.
|
||||
|
||||
Physics Placement consumes the same errors plus its stricter non-trigger and hydrated rigid-body
|
||||
requirements. See [physics-placement.md](physics-placement.md).
|
||||
|
||||
`assets/levels/collider_diagnostics_showcase.scn.ron` contains valid box, scaled sphere, capsule,
|
||||
trigger, disabled, and missing-collider states for visual acceptance. Invalid, oversized, and stale
|
||||
asset cases live in unit fixtures so the committed project remains release-valid.
|
||||
@@ -10,6 +10,7 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
|
||||
| Monolithic `hydrate_authoring_entities` | Done | `crates/shared/src/hydration/*` modules |
|
||||
| Optional / inferred `ActorKind` as long-term save path | Done | Schema v2 + migration; save validates |
|
||||
| Hydrated components in committed `.scn.ron` | CI | `scene::validate_scene_authoring_only` + `repo_editor_scene_has_no_hydrated_components` |
|
||||
| Production mutation without commit/cancel/failure/undo invariants | Done | Shared operator harness plus typed history projections cover palette, asset, brush, terrain, physics, grouping, lighting, material-drop, and transform paths; see [evaluation](evaluations/operator-invariants/) |
|
||||
| Dual FBX thumbnail ad-hoc path (parallel to unified pipeline) | Partial | Phase 5 `assets/thumbnails/` refactor |
|
||||
| `failed_keys` thumbnail cache without retry API | Partial | `asset_thumbnails.rs`; Phase 5 `ThumbnailState` |
|
||||
|
||||
@@ -21,7 +22,7 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
|
||||
| P1 | `ActorKind` required; `validate_actor` on save |
|
||||
| P2 | No runtime components in default inspector |
|
||||
| P3 | `HierarchySiblingIndex`; no undefined sibling order |
|
||||
| P6 | `ActorInspectorSection` registry; command palette commands; BRP authoring policy |
|
||||
| P6 | `ActorInspectorSection` registry; typed immediate/modal command dispatch; BRP authoring policy; production mutation invariants |
|
||||
| P7 | ADRs 0009–0012 indexed; CI `shared` + `scene` + `editor` checks |
|
||||
|
||||
## Manual verification (release)
|
||||
@@ -29,3 +30,4 @@ Living checklist for the production editor program ([ADR 0012](../adr/0012-zero-
|
||||
- [ ] R1–R6 rendering/inspector scenarios ([roadmap.md](roadmap.md))
|
||||
- [ ] Save/load roundtrip: hierarchy, lights, materials unchanged
|
||||
- [ ] PIE 60s stop: project lighting profile unchanged unless scene overrides edited
|
||||
- [ ] Rerun the [operator invariant matrix](operator-regression-testing.md) from the nominated release-candidate commit
|
||||
@@ -0,0 +1,24 @@
|
||||
# Collider Diagnostics Acceptance
|
||||
|
||||
Issue: Gitea #26 (`BS-JD-305`)
|
||||
|
||||
## Evidence
|
||||
|
||||

|
||||
|
||||
The native Wayland editor loaded `assets/levels/collider_diagnostics_showcase.scn.ron` and entered
|
||||
Collider view. The captured frame shows shape overlays with meshes hidden, the scene health HUD,
|
||||
the selectable Diagnostics window, and the selected trigger's hydrated status in the inspector.
|
||||
|
||||
## Live Results
|
||||
|
||||
- Box, scaled sphere/ellipsoid, and capsule overlays matched authored transforms and dimensions.
|
||||
- Green ready, cyan trigger, gray disabled, and red missing states were visually distinct.
|
||||
- The HUD reported `4 ready / 1 disabled / 0 warning / 1 invalid` and followed selection.
|
||||
- The Diagnostics panel linked the missing finding back to its actor.
|
||||
- Switching the valid box to sphere preserved useful extents and produced `Undo: Set Collider`;
|
||||
undo restored the box.
|
||||
- Physics Placement rejected the missing-collider actor with the shared collider-health messages.
|
||||
- Scene switching and editor shutdown completed without a panic or runtime validation error.
|
||||
|
||||
Packaged verification remains deferred by current project instruction.
|
||||
Binary file not shown.
@@ -65,7 +65,7 @@ Additional captures:
|
||||
| Dedicated static/skinned ownership | Pass | Separate authored/hydrated renderer types; rigged/animated manifests are rejected by static hydration |
|
||||
| Pose lifecycle | Pass | Explicit stable default clip; transform and morph-weight baseline restore on stop, controller removal, preview reset, and PIE exit |
|
||||
| Renderer material slots | Pass | Stable named IDs, imported fallback, explicit assignment, orphan retention, and in-place material patching |
|
||||
| Material assets/instances | Pass | Versioned shared assets, direct-base sparse instances, transient property blocks, Apply/Revert/Create Instance |
|
||||
| Material assets/instances | Pass | Versioned shared assets, direct-base sparse instances, Apply/Revert/Create Instance; property-block runtime application/promotion is isolated in #53 |
|
||||
| Texture parameters | Pass | Project-wide picker includes imported texture subassets; base/schema/stored/instance slots share browse, drop, reject, and clear behavior |
|
||||
| Component lifecycle | Pass | Stable registry IDs, reflected transactions/history, persistence allowlist, independent active state, and compatible composition |
|
||||
| Surface raster/Solari semantics | Pass for eligible geometry | Shared ABI packing, evaluator, textures, normal/emissive/unlit values, and cutout predicate |
|
||||
@@ -92,5 +92,6 @@ Additional captures:
|
||||
Bevy 0.19's maintained Solari path does not expose dynamic post-morph/post-skin vertex buffers and
|
||||
BLAS updates. Skinned and morph-deformed actors therefore remain visible in raster but are omitted
|
||||
from ray tracing with an actionable diagnostic. This is safer than tracing a stale bind-pose ghost;
|
||||
dynamic deformed BLAS support remains future work and the corresponding Gitea acceptance item stays
|
||||
open.
|
||||
dynamic deformed BLAS support is the independently scoped Gitea #54. Runtime property-block
|
||||
application and promotion are independently scoped in #53; this foundation record does not claim
|
||||
either follow-up.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Operator Invariants Evaluation
|
||||
|
||||
Date: 2026-07-12
|
||||
|
||||
Gitea issue:
|
||||
[`#33`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33)
|
||||
|
||||
This acceptance record covers the source-level production operator contract. It does not nominate a
|
||||
release candidate or replace the clean-checkout rerun required by production-readiness gate G3.
|
||||
|
||||
## Accepted Coverage
|
||||
|
||||
- Registered commands distinguish immediate completion from modal Preview ownership; validation
|
||||
failures terminate with their stable command ID. Palette execution and cancellation fully dismiss
|
||||
the palette instead of leaving an empty title bar.
|
||||
- Group Selection is one history transaction and preserves unrelated hierarchy rows through repeated
|
||||
undo/redo even though the transient group entity is respawned. Newly spawned and redone group
|
||||
actors own their visibility hierarchy before viewport icon children attach.
|
||||
- Reset Lighting and Project Sun changes are grouped, undoable light transactions.
|
||||
- Asset/sub-asset placement; material/texture/audio/animation assignment; and exact viewport material
|
||||
drops cover commit, block/failure, cancel where applicable, and semantic undo/redo projections.
|
||||
- Draw Brush, CSG, clip, and element-gizmo paths exercise production modal finalizers and helper
|
||||
cleanup.
|
||||
- Terrain sculpt/paint cover multi-dab commit, failure rollback, cancel, clean-view interruption, and
|
||||
resource cleanup.
|
||||
- Physics placement covers prerequisite block, exact cancel, real settle commit, multi-selection
|
||||
grouping, helper cleanup, undo, and redo.
|
||||
- The transform tracker covers continuous multi-target grouping and no-op release termination.
|
||||
|
||||
## Verification
|
||||
|
||||
The publication worktree passed:
|
||||
|
||||
- `cargo test -p editor --lib --no-fail-fast`: 245 passed, 0 failed.
|
||||
- `cargo clippy -p editor --lib --tests -- -D warnings`.
|
||||
- `cargo fmt --all -- --check`.
|
||||
- `cargo test --workspace --all-targets --no-fail-fast`.
|
||||
- `cargo clippy --workspace --all-targets -- -D warnings`.
|
||||
- `cargo validate-levels --project .`: 62 dependencies, 5 expected non-blocking findings, 0 blocking
|
||||
errors.
|
||||
|
||||
The Gitea closure comment records these results with the exact publication commit.
|
||||
|
||||
## Native Editor Follow-up
|
||||
|
||||
A native-editor replay on 2026-07-13 loaded the collider diagnostics scene, exercised Draw Brush
|
||||
Preview/cancel, and grouped two hierarchy actors through undo/redo. The replay exposed two issues
|
||||
that source-only checks did not make visible: command execution left a collapsed palette title bar,
|
||||
and the viewport icon child briefly inherited from a group actor without Bevy visibility hierarchy
|
||||
components. Both paths now have focused regression assertions; a rebuilt replay dismissed the
|
||||
palette completely and emitted no hierarchy warning.
|
||||
|
||||
No screenshot is required for this ticket: the accepted surface is lifecycle, rollback, cleanup, and
|
||||
history behavior exercised through headless production entry points. Live command/status checks add
|
||||
confidence but are not substituted for semantic assertions. Packaged-runtime testing remains
|
||||
deferred by project-owner request.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Physics Placement Evaluation
|
||||
|
||||
Date: 2026-07-12
|
||||
|
||||

|
||||
|
||||
The native Wayland editor is shown with the committed
|
||||
`assets/levels/physics_placement_showcase.scn.ron` fixture. Placement Prop A, B, and C were
|
||||
multi-selected and released from three different heights through the hand/down-arrow action in the
|
||||
existing horizontal viewport toolbar.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- All three props used the hydrated Avian cuboid colliders and settled on Placement Floor after
|
||||
1.5 simulated seconds.
|
||||
- During preview the HUD reported selection count, simulated time, and Settled state; transform
|
||||
gizmos and viewport picking did not compete with the modal tool.
|
||||
- Escape restored every starting transform and left history empty.
|
||||
- A second run committed with Enter as exactly one `Undo: Move Selection` entry.
|
||||
- Ctrl+Z restored all three elevated starting transforms; Ctrl+Y restored the settled transforms.
|
||||
- Opening the fixture immediately after the terrain showcase no longer panicked on a stale
|
||||
generated terrain-material binding; the scene-switch regression is covered in
|
||||
`blacksite_surface`.
|
||||
- The runtime log contained no physics-placement, scene-load, render-pipeline, or GPU validation
|
||||
error after the stale-binding fix.
|
||||
|
||||
Packaged-runtime tests remain intentionally deferred by project-owner request.
|
||||
|
||||
Binary file not shown.
@@ -31,13 +31,13 @@ another commit, a dirty worktree, or an older package do not transfer to the can
|
||||
| ID | Requirement | State | Current evidence and gap |
|
||||
|----|-------------|-------|--------------------------|
|
||||
| G1 | Project create/open/resume, scene authoring, autosave/recovery, hierarchy, prefab, and asset integrity pass | Partial | Project/recovery/session/multi-scene/prefab implementations are documented in [project launcher](../../project-launcher.md), [session recovery](../../session-recovery.md), [multi-scene composition](../../multi-scene-composition.md), and [prefab authoring](../../prefab-authoring.md). Collaborative file safety `#49` and non-blocking native dialogs `#52` passed live acceptance. Candidate-specific end-to-end reruns remain. |
|
||||
| G2 | Brush, material, terrain, physics placement, animation, audio, navigation, PIE, and build/package samples pass | Fail | Animation, audio, navigation, Material Library, targeted material drops, and build foundations are implemented. Renderer foundation `#51` remains open on deformed Solari geometry; terrain `#22`-`#24`, physics placement `#25`, and brush acceptance `#37` remain incomplete. Packaged testing is owner-deferred. |
|
||||
| G3 | Undo/redo/cancel invariants and helper cleanup cover every production mutation path | Partial | The reusable harness and current tool coverage are documented in [operator regression testing](../../operator-regression-testing.md). Gitea `#33` remains open for terrain-stroke and physics-settle fixtures after those tools exist. |
|
||||
| G2 | Brush, material, terrain, physics placement, animation, audio, navigation, PIE, and build/package samples pass | Fail | Animation, audio, navigation, renderer/material foundation `#51`, Material Library, targeted material drops, terrain `#22`-`#24`, physics placement `#25`, and build foundations are implemented with source/live fixtures. Brush acceptance `#37` remains incomplete. Packaged testing is owner-deferred. |
|
||||
| G3 | Undo/redo/cancel invariants and helper cleanup cover every production mutation path | Partial | Source implementation and focused evidence are complete in [operator regression testing](../../operator-regression-testing.md) and the [operator-invariants evaluation](../operator-invariants/); Gitea `#33` is ready to close. A clean, exact-candidate rerun is still required for `Pass`. |
|
||||
| G4 | Representative project completes an eight-hour soak without unbounded memory/target growth or unrecoverable failure | Missing | No candidate soak log, resource timeline, failure ledger, or target-growth measurement exists. |
|
||||
| G5 | Cold start, scene open/save, asset refresh, common manipulation, and package-build budgets are documented and measured | Missing | Gitea `#34` is open; no ratified budgets or candidate measurement record exists. |
|
||||
| G6 | Headless content validation and CI are green from a clean checkout | Missing | [CI configuration](../../../../.github/workflows/ci.yml) exists and local source/headless checks have passed during feature work, but no clean-checkout candidate run is linked. The current Gitea server does not expose an Actions run endpoint for this repository. |
|
||||
| G7 | First-hour UX and recovery QA are signed off by someone other than the implementer | External | No independent sign-off exists. Gitea `#36` remains open; historical H1-H6 implementation-pass notes do not count. |
|
||||
| G8 | Known limitations have severity/workaround and no P0 blocker remains | Fail | Limitations are distributed across feature docs rather than one candidate ledger. Open P0 work includes `#32`, `#33`, and `#51`; `#50` cannot close while a gate-relevant P0 remains. Roadmap audit `#35`, Material Library `#16`, targeted drops `#18`, collaborative safety `#49`, and dialog responsiveness `#52` are closed. |
|
||||
| G8 | Known limitations have severity/workaround and no P0 blocker remains | Fail | Limitations are distributed across feature docs rather than one candidate ledger. The remaining open P0 implementation blocker is `#32`; `#50` cannot close while it remains. Operator invariants `#33`, renderer foundation `#51`, roadmap audit `#35`, Material Library `#16`, targeted drops `#18`, collaborative safety `#49`, and dialog responsiveness `#52` are complete. Property-block application `#53` is P1; dynamic deformed Solari geometry `#54` is a documented P2 limitation with Forward/raster fallback. |
|
||||
|
||||
## Deliverables
|
||||
|
||||
@@ -56,9 +56,10 @@ another commit, a dirty worktree, or an older package do not transfer to the can
|
||||
| Hierarchy parenting and prefab structure | Implemented | Not rerun |
|
||||
| Multi-scene composition | Implemented | Not rerun |
|
||||
| Brush blockout/edit/CSG | Implemented foundation; `#37` open | Not signed off |
|
||||
| Material catalog and assignment | Material Library and exact targeted drops accepted; `#51` open only on deformed Solari geometry | Not rerun as one candidate |
|
||||
| Terrain authoring | `#22`-`#24` open | Blocked |
|
||||
| Physics placement | `#25` open | Blocked |
|
||||
| Material catalog and assignment | Renderer/material foundation `#51`, Material Library, and exact targeted drops accepted; optional property-block promotion is `#53` | Not rerun as one candidate |
|
||||
| Terrain authoring | `#22`-`#24` source/live acceptance complete; M3 closed | Pass; packaged-runtime acceptance owner-deferred |
|
||||
| Physics placement | `#25` source/live acceptance complete | Pass; packaged-runtime acceptance owner-deferred |
|
||||
| Collider authoring and diagnostics | `#26` source/live acceptance complete | Pass; packaged-runtime acceptance owner-deferred |
|
||||
| Animation | Implemented | Not rerun |
|
||||
| Audio | Implemented | Not rerun |
|
||||
| Navigation | Implemented | Not rerun |
|
||||
|
||||
@@ -13,12 +13,17 @@ and [ADR 0036](../adr/0036-surface-abi-and-solari-parity.md).
|
||||
| Material instance | Overrides over one direct base material | Yes, under `assets/materials/` |
|
||||
| Renderer material slot | A stable reference on one static or skinned renderer | Yes, in scenes/prefabs |
|
||||
| Imported source material | Read-only default supplied by model import | Yes, as the slot fallback |
|
||||
| Material property block | Temporary per-renderer/per-slot runtime overrides | No |
|
||||
| Material property block | Reserved runtime-only per-renderer/per-slot override schema; application/promotion tracked by Gitea #53 | No |
|
||||
|
||||
A renderer slot stores a `MaterialRef`, not a copy of the material. The registry UUID and subasset
|
||||
ID identify the target; the cached path is only a loading hint. A material instance may reference a
|
||||
material, but may not reference another instance.
|
||||
|
||||
`MaterialPropertyBlocks` are excluded from authored persistence, but they are not yet consumed by
|
||||
renderer binding. Runtime application and the transactional **Promote to Material Instance**
|
||||
workflow are tracked by Gitea #53. Use an ordinary direct-base Material Instance for reusable
|
||||
variations until that issue closes.
|
||||
|
||||
## Assign materials
|
||||
|
||||
Open **Window > Material Library** for the cross-folder Material/Material Instance catalog. It
|
||||
@@ -88,6 +93,11 @@ handle in place. Standard and custom Surface changes therefore propagate to ever
|
||||
or skinned renderer slot without reloading geometry, joints, or the current animation pose. Invalid
|
||||
Surface edits retain the last-good evaluator generation and emit diagnostics.
|
||||
|
||||
Renderer and terrain material bindings target generated draw entities. Scene switches may remove
|
||||
those entities between binding discovery and deferred command application, so binding replacement
|
||||
uses fallible entity commands and treats that stale-target race as normal lifecycle cleanup rather
|
||||
than an editor-fatal error.
|
||||
|
||||
## Custom Surface evaluators
|
||||
|
||||
A custom shader schema may reference evaluator WGSL. Evaluators return material properties through
|
||||
@@ -125,7 +135,8 @@ The standard material path remains unchanged for materials without a custom eval
|
||||
Skinned meshes and morph-deformed meshes are currently excluded from Solari. This prevents rays
|
||||
from tracing their undeformed source/bind pose while raster shows the animated pose. They remain
|
||||
visible in raster, and Rendering diagnostics report the deformed exclusion. Dynamic deformed
|
||||
vertex/BLAS updates are future work.
|
||||
vertex/BLAS updates are tracked independently by Gitea #54 with animation, ray-hit, fallback,
|
||||
memory, and update-cost acceptance.
|
||||
|
||||
Surface ABI v1 does not support blended transparency, transmission/refraction, custom vertex
|
||||
displacement, or arbitrary pipeline stages.
|
||||
|
||||
@@ -11,11 +11,13 @@ Every production operator test must cover the paths it exposes:
|
||||
|
||||
| Path | Required proof |
|
||||
|------|----------------|
|
||||
| Commit | Expected authored entity delta, exact undo-group delta, dirty state, committed phase |
|
||||
| Cancel or commit failure | No authored entity delta, no new history, prior dirty state, canceled phase |
|
||||
| Commit | Expected authored projection, exact undo-group delta, dirty state, stable operator ID, committed phase |
|
||||
| Zero-history commit | Authored projection and prior dirty state remain unchanged |
|
||||
| Cancel or commit failure | Exact authored projection restored, no new history, prior dirty state, stable operator ID, terminal canceled/blocked phase |
|
||||
| Blocked start | Commit closure never runs; authored state, history, and dirty state are unchanged |
|
||||
| Preview failure | Cancel finalizer runs, authored state is restored, and helpers are removed |
|
||||
| Preview helpers | No helper component remains after commit or cancel |
|
||||
| Undoable commit | `assert_undo_redo_round_trip` restores both initial and committed projections |
|
||||
| Undoable commit | `assert_undo_redo_round_trip` restores both initial and committed semantic projections |
|
||||
| Continuous edit | The entire interaction creates one history command, not one per frame or target |
|
||||
|
||||
The harness intentionally fails with the invariant name in the assertion message. Tests may add
|
||||
@@ -26,12 +28,12 @@ domain assertions, but should not replace these shared lifecycle checks.
|
||||
1. Build a minimal `World` with `ActiveOperator`, `EditorHistory`, and `SceneIo`. Add tool-specific
|
||||
selection/resources and `SelectedEntity` when history helpers update selection.
|
||||
2. Capture `OperatorInvariantHarness` immediately before starting the operation.
|
||||
3. Run the real operator entry point or the same production commit/cancel function used by its
|
||||
input system.
|
||||
3. Run the real dispatch path or production finalizer used by the input system. Do not duplicate its
|
||||
state transition in the test.
|
||||
4. Call `assert_committed`, `assert_canceled`, or `assert_blocked` with the expected authored and
|
||||
undo deltas.
|
||||
undo deltas, then `assert_status` with the stable operator ID and terminal phase.
|
||||
5. For helpers, call `assert_no_helpers::<ToolHelper>`. For undoable work, project the meaningful
|
||||
state through `assert_undo_redo_round_trip`.
|
||||
state through `assert_undo_redo_round_trip`; use `assert_projection_unchanged` for no-op paths.
|
||||
|
||||
Do not satisfy a lifecycle test by constructing an `EditorCommand` and checking only its label.
|
||||
The test must mutate a world and prove restoration.
|
||||
@@ -40,15 +42,17 @@ The test must mutate a world and prove restoration.
|
||||
|
||||
| Workflow | Coverage |
|
||||
|----------|----------|
|
||||
| Generic `EditorOperator` | Commit cleanup, commit failure rollback, blocked no-op |
|
||||
| Asset placement | Commit, dirty state, single undo, authored spawn round trip |
|
||||
| Sub-asset placement | Missing dependency commit failure leaves no side effects |
|
||||
| Texture/material assignment | Multi-actor grouped undo; missing material failure; empty-selection block |
|
||||
| Draw Brush | Full modal-state cancel; decomposed multi-brush grouped commit and round trip |
|
||||
| Brush CSG | Pending-preview cancel; merge commit/deletion grouped round trip |
|
||||
| Brush clip and element gizmo | Clip grouped geometry round trip; Escape rollback and helper cleanup |
|
||||
| Transform gizmo finalization | Multi-target continuous edit grouped into one undo command |
|
||||
| Generic `EditorOperator` | Commit cleanup, preview/commit failure rollback, blocked no-op, terminal ID/phase |
|
||||
| Palette and registered commands | Typed immediate commit versus modal preview ownership; Enter/click/Escape dismissal cannot be overwritten by stale window state; failed CSG start terminates |
|
||||
| Selection and scene commands | Atomic Group Selection across repeated undo/redo; spawned group actors have an immediate Bevy visibility hierarchy; grouped Reset Lighting and Project Sun history |
|
||||
| Asset workflows | Asset/sub-asset placement; material/texture group assignment; audio/animation assignment and incompatible targets |
|
||||
| Viewport material drop | Exact renderer slot/primitive/brush-face preview, cancel, commit, cleanup, undo, and redo |
|
||||
| Draw Brush and CSG | Modal cancel; decomposed commit; CSG validation/read-only block, cancel, grouped commit, and deleted-brush restoration |
|
||||
| Brush clip and element gizmo | Production finalizers, geometry round trip, Escape rollback, and helper cleanup |
|
||||
| Terrain sculpt and paint | Multi-dab grouped commit, no-op release, commit failure rollback, cancel, clean-view interruption, and resource cleanup |
|
||||
| Physics placement | Prerequisite block, no-op commit, exact cancel, real settle commit, multi-selection grouping, helper cleanup, undo, and redo |
|
||||
| Transform gizmo finalization | Actual tracker finalizer, continuous multi-target grouping, no-op release, and missing-primary survivor rollback |
|
||||
|
||||
Terrain strokes and physics-settle sessions are roadmap tools, not current production operators.
|
||||
Their implementation tickets must add harness fixtures before those tools can pass their own exit
|
||||
gates; Gitea issue BS-JD-502 remains the umbrella until that coverage exists.
|
||||
The shared harness covers formal operators and multi-frame modal paths. Atomic inspector and history
|
||||
mutations that do not own `ActiveOperator` use focused typed history tests with equivalent semantic
|
||||
projection and undo/redo assertions.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Physics Placement
|
||||
|
||||
The Physics Placement tool releases selected authored props into the same Avian collision world
|
||||
used by Play mode. It is intended for arranging loose objects on floors, terrain, brushes, and
|
||||
other hydrated colliders without hand-tuning every final transform.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Select one or more mutable level objects. Each object needs an enabled **Rigid Body** and an
|
||||
enabled, non-trigger **Collider** component.
|
||||
2. Press the hand/down-arrow button in the existing horizontal Scene viewport toolbar.
|
||||
3. The selected props become dynamic and fall under gravity. The viewport HUD reports simulation
|
||||
time and whether the group is still moving, settled, or stopped at the preview limit.
|
||||
4. Press the check button to commit the current transforms, or **Escape** / the X button to cancel.
|
||||
**Enter** commits after the group has settled.
|
||||
|
||||
Commit creates one `Move Selection` undo entry for the whole group. Cancel restores the exact
|
||||
pre-placement local transforms and runtime motion components and creates no history entry.
|
||||
|
||||
## Isolation And Diagnostics
|
||||
|
||||
Normal Edit mode keeps Avian physics paused, so authored dynamic bodies cannot drift outside
|
||||
history. During placement, every non-selected dynamic or kinematic body is temporarily treated as
|
||||
a static collision surface. The tool restores those bodies exactly when the preview ends. Entering
|
||||
Play mode cancels an active placement preview.
|
||||
|
||||
The start action is non-destructive when prerequisites are missing. It consumes the shared
|
||||
[collider health service](collider-authoring.md), so the viewport, inspector, Diagnostics panel,
|
||||
and placement status agree about missing, invalid, stale, disabled, or trigger collision. A
|
||||
ten-second simulated-time limit stops unstable previews while
|
||||
leaving explicit commit and cancel available.
|
||||
|
||||
`assets/levels/physics_placement_showcase.scn.ron` is the committed acceptance fixture. Select
|
||||
**Placement Prop A**, **B**, and **C** together, start physics placement, and verify that the three
|
||||
different shapes settle on **Placement Floor** as one commit/cancel transaction.
|
||||
|
||||
The clock and transaction boundary are specified by
|
||||
[ADR 0041](../adr/0041-transactional-editor-physics-placement.md).
|
||||
@@ -57,6 +57,8 @@ Phased work for the in-process editor (`crates/editor`). Status reflects the cur
|
||||
| Clean game-view overlay | Done | `G` hides editor chrome, grid, visualizers, proxies, gizmos, and selection outlines |
|
||||
| Tab cycle overlapping picks | Done | `ViewportPickStack` + Tab in viewport |
|
||||
| Multi-viewport | Scaffolded | Primary viewport state is separated from render ownership; secondary viewports remain future work |
|
||||
| Physics placement | Done | Existing horizontal toolbar action; real Avian settling, prerequisite diagnostics, exact cancel, grouped undo, and isolated non-selected bodies |
|
||||
| Collider authoring diagnostics | Done | World-scale shape overlays, semantic health colors, stale/missing/invalid/oversized findings, undoable shape switching, and shared placement preflight |
|
||||
|
||||
## Phase 2b — Advanced rendering
|
||||
|
||||
@@ -132,6 +134,7 @@ Phased work for the in-process editor (`crates/editor`). Status reflects the cur
|
||||
| `ActorInspectorSection` registry | Done | `ext/extensibility.rs` + `game_inspector.rs` |
|
||||
| Command registry | Done | Play, lighting reset, group, focus |
|
||||
| Command palette (Ctrl+P) | Done | Executes registered commands |
|
||||
| Typed operator dispatch and mutation invariants | Done | Immediate commands commit, modal commands retain Preview ownership, and production asset/brush/terrain/physics/history paths pass the shared lifecycle and undo contract ([testing guide](operator-regression-testing.md), [Gitea #33](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/33)) |
|
||||
| `EditorPlugin` trait | Done | `register_editor_plugin`; dogfood panel from `game::editor_ext` |
|
||||
| Undo: `SetActorKind`, add/remove component | Done | `SetActorKind` + `AddComponent` / `RemoveComponent` |
|
||||
| BRP authoring-only policy | Done | [brp.md](brp.md) |
|
||||
|
||||
Reference in new issue
Block a user