Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
293811aecd | ||
|
|
ed21bcc52d | ||
|
|
577d8dcb27 | ||
|
|
ba59f57a5a | ||
|
|
d038cf3670 | ||
|
|
61be2440bd | ||
|
|
3794faa4aa | ||
|
|
02247f029a | ||
|
|
3931de1f0a | ||
|
|
f2ad88fd03 | ||
|
|
5a82a9ee29 |
No files matched your search
@@ -21,9 +21,23 @@ performance, soak, regression, and first-hour workflows must pass against a repr
|
|||||||
`#43`; M6 implementation is complete.
|
`#43`; M6 implementation is complete.
|
||||||
4. Completed: authoritative content validation `#45` and the validation-gated packaging/Build
|
4. Completed: authoritative content validation `#45` and the validation-gated packaging/Build
|
||||||
workflow `#44`.
|
workflow `#44`.
|
||||||
5. Completed: audio source/listener/bus authoring and spatial preview passed production acceptance
|
5. Completed: audio `#47`, animation `#46`, and navigation `#48` passed production acceptance.
|
||||||
in `#47`. Next: animation `#46`, navigation `#48`, source-control safety `#49`, then readiness
|
Source-control safety `#49` has complete implementation and source/headless acceptance; live
|
||||||
gate `#50`.
|
visual acceptance remains before the readiness gate `#50`.
|
||||||
|
|
||||||
|
## Implemented Slice - Collaborative Authored-File Safety
|
||||||
|
|
||||||
|
- Exact BLAKE3 baselines for scene tabs, staged Material/Material Instance documents, and Project
|
||||||
|
Settings.
|
||||||
|
- One guarded atomic publication path for scene save/export, prefab source Apply/history, and
|
||||||
|
editable materials, including missing-file and immediate pre-rename race protection.
|
||||||
|
- Non-destructive background Git porcelain scanning with optional off-thread ownership providers;
|
||||||
|
Git/provider absence is quiet.
|
||||||
|
- Compact active-scene and selected-asset state plus Reload, metadata comparison, Save As, and
|
||||||
|
Cancel conflict recovery. No force-overwrite action exists.
|
||||||
|
- Focused race, read-only, provider-lock, parser, non-repository, modal-render, scene, and material
|
||||||
|
tests pass. Live debug-editor visual acceptance remains pending for a desktop-capable QA session;
|
||||||
|
packaged acceptance remains owner-deferred.
|
||||||
|
|
||||||
## M6 - Reliability, Recovery, And Project Workflow
|
## M6 - Reliability, Recovery, And Project Workflow
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Material Library And Targeted Viewport Drop
|
||||||
|
|
||||||
|
Working implementation plan for Gitea issues
|
||||||
|
[`#16`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/16) and
|
||||||
|
[`#18`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/18).
|
||||||
|
The shared Material/Material Instance and stable renderer-slot foundation from `#51` is already
|
||||||
|
present; this slice completes the production-facing catalog and drag/drop workflow.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Implemented on `codex/material-library-targeted-drop` after collaborative-safety `#49` was
|
||||||
|
published and integrated into `main`. Focused and full source-only verification plus live editor
|
||||||
|
acceptance are green; ticket evidence remains before `#16` / `#18` close.
|
||||||
|
|
||||||
|
## Resolved Gaps
|
||||||
|
|
||||||
|
- The dockable Material Library now provides cross-folder Material/Instance catalog, usage counts,
|
||||||
|
health, creation, thumbnails, drag sources, and the guarded existing details editors.
|
||||||
|
- Viewport Material/Texture drops resolve the surface under the pointer and never broaden to the
|
||||||
|
current selection or every renderer slot.
|
||||||
|
- `HydratedRendererMaterialBinding` identifies the exact static/skinned renderer slot; primitives
|
||||||
|
and stable brush-face IDs use their authored component paths.
|
||||||
|
- Unsupported, locked, linked, missing, and payload-incompatible targets reject with an explicit
|
||||||
|
reason and no scene mutation.
|
||||||
|
- Hover previews are reversible, target changes restore the prior snapshot, and release records one
|
||||||
|
typed operator/history transaction.
|
||||||
|
- Viewport pointer tracking remains active while another egui widget owns the drag, so exact target
|
||||||
|
resolution cannot stall at the viewport boundary.
|
||||||
|
- Visibility hierarchy setup now precedes generated hydration content, preventing Bevy parent/child
|
||||||
|
visibility warnings when brush draws are created after scene load.
|
||||||
|
|
||||||
|
## Material Library
|
||||||
|
|
||||||
|
1. Add a dockable `Material Library` panel, opened from Window and placed in the existing bottom dock
|
||||||
|
without adding another permanent toolbar.
|
||||||
|
2. Present project Materials and Material Instances with search, Material/Instance filter, thumbnail
|
||||||
|
grid/list modes, base/dependency health, and source-control status.
|
||||||
|
3. Add a scene-usage section that counts renderer-slot, primitive, and brush-face references and can
|
||||||
|
select/locate users. Do not revive ambiguous hidden scene-local material clones.
|
||||||
|
4. Reuse the existing guarded Material/Instance drafts for Apply, Revert, Create Instance, and
|
||||||
|
texture-parameter editing. Shared-file edits remain explicit; scene assignment changes use
|
||||||
|
history.
|
||||||
|
5. Material and Instance cells are first-class drag sources and preserve the current pointer-following
|
||||||
|
visual identity.
|
||||||
|
|
||||||
|
## Targeted Drop Contract
|
||||||
|
|
||||||
|
Introduce a frame-updated `ViewportAssetDropTarget` resolved by the existing mesh-picking path:
|
||||||
|
|
||||||
|
- A hydrated static/skinned draw maps through `HydratedRendererMaterialBinding` to the authored actor
|
||||||
|
and exact stable slot ID.
|
||||||
|
- A primitive maps to its authored actor-level `MaterialDesc`.
|
||||||
|
- A brush performs authored face intersection and identifies the stable face ID.
|
||||||
|
- An authored but unsupported target remains a visible invalid target with a specific reason.
|
||||||
|
- Empty space remains placement-only for placeable assets and invalid for Material/Texture payloads.
|
||||||
|
|
||||||
|
Payload matrix:
|
||||||
|
|
||||||
|
| Payload | Renderer slot | Primitive | Brush face |
|
||||||
|
|---------|---------------|-----------|------------|
|
||||||
|
| Material / Material Instance | Assign exact hit slot; one-slot actors may assign directly | Replace actor material reference/values | Replace the hit face material reference |
|
||||||
|
| Texture | Reject with guidance to create/edit a Material Instance | Set base-color texture | Set hit-face base-color texture/material binding |
|
||||||
|
|
||||||
|
An explicit `Apply All Slots` command remains available from the renderer inspector/library usage
|
||||||
|
menu; a viewport hit never silently broadens from one slot to all slots.
|
||||||
|
|
||||||
|
## Preview, Commit, And Cancel
|
||||||
|
|
||||||
|
1. Start a persistent drop-preview session when a supported Material/Texture payload enters the
|
||||||
|
viewport. Snapshot only the target's affected authored state.
|
||||||
|
2. Apply a transient visual preview without pushing history or marking the scene dirty.
|
||||||
|
3. When the pointer changes target, restore the previous snapshot before previewing the new target.
|
||||||
|
4. On release, restore the transient state first, then commit exactly one typed history/operator
|
||||||
|
transaction to the identified slot, primitive, or face.
|
||||||
|
5. On Escape, drag cancellation, leaving the viewport, invalid target, or missing source, restore the
|
||||||
|
exact snapshot and remove every preview/helper marker.
|
||||||
|
6. The drag card and target outline name the payload, actor, slot/face, action, and invalid reason.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Focused tests cover exact multi-slot assignment/undo, brush-face-only preview/restore, primitive
|
||||||
|
Material/Texture resolution, renderer Texture rejection, Material Library filtering, and scene
|
||||||
|
usage counts.
|
||||||
|
- Source checks include editor all-target check, focused tests, and strict editor Clippy.
|
||||||
|
- Live acceptance covered the docked catalog, search/type/usage filters, grid/list views, resolved
|
||||||
|
Material Instance thumbnails, exact primitive preview, green actor/surface feedback, one-step
|
||||||
|
commit/undo, and Escape rollback. The same relaunch produced no hydration hierarchy warnings.
|
||||||
|
- Static/skinned exact-slot, brush-face, locked/linked, incompatible Texture, and non-dirty preview
|
||||||
|
contracts remain covered by focused automated tests; shared-asset file creation was deliberately
|
||||||
|
not invoked during live QA to avoid adding throwaway authored files.
|
||||||
|
- Full verification passed: workspace all-target check, strict workspace Clippy, all workspace tests,
|
||||||
|
strict editor Clippy with both `dev` and `hot-reload`, level validation with zero blockers, and
|
||||||
|
navigation artifact freshness. Packaged testing remains deferred until the project owner requests
|
||||||
|
it again.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Non-Blocking Native Dialogs
|
||||||
|
|
||||||
|
Working implementation plan for the production-readiness defect discovered during live acceptance
|
||||||
|
of collaborative file safety. Opening an `rfd` picker synchronously from an egui/Bevy system stops
|
||||||
|
window event processing long enough for Hyprland to report Blacksite as unresponsive.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
1. Add one project-level native-dialog broker with a typed intent, one active dialog, background
|
||||||
|
native work, and a main-thread result queue.
|
||||||
|
2. Convert scene open/save-as, asset import/export, prefab save/source selection, subscene selection,
|
||||||
|
conflict Save As, diagnostics export, and project-launcher folder selection to the broker.
|
||||||
|
3. Keep destructive or stateful application logic on the Bevy main thread after a path result is
|
||||||
|
received. Background work may only own the native dialog and its returned paths.
|
||||||
|
4. Show a stable pending state and reject duplicate dialog requests while a picker is active.
|
||||||
|
5. Replace blocking native dirty-scene confirmation dialogs with an editor-owned modal when the
|
||||||
|
scene-transition state machine can preserve the original action exactly.
|
||||||
|
|
||||||
|
## Contract
|
||||||
|
|
||||||
|
- The editor continues rendering and processing compositor pings while a native dialog is open.
|
||||||
|
- Cancel returns a typed empty result and does not mutate editor state.
|
||||||
|
- A result is applied once to the intent that created it; stale or duplicate results cannot run.
|
||||||
|
- Paths are validated at the same ownership boundary as before. The dialog broker does not read,
|
||||||
|
write, import, save, or canonicalize project content.
|
||||||
|
- Existing collaborative revision guards remain authoritative after Save As selection.
|
||||||
|
- Project-launcher dialogs use the same broker before the full editor plugin group is active.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Focused tests cover request exclusivity, cancel, one-shot result delivery, and typed intent
|
||||||
|
preservation.
|
||||||
|
- Source-only workspace formatting, check, strict Clippy, and tests run; packaged acceptance remains
|
||||||
|
deferred by project-owner direction.
|
||||||
|
- Native Wayland QA opens representative file, folder, and Save As dialogs under Hyprland and
|
||||||
|
confirms the Blacksite window remains responsive without an unresponsive-application prompt.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Production-Readiness Acceptance Gate
|
||||||
|
|
||||||
|
Working plan for Gitea issue
|
||||||
|
[`#50`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/50).
|
||||||
|
This gate is broader than the M7 feature list: it proves the complete daily authoring, content,
|
||||||
|
recovery, performance, and release workflow against one exact release-candidate commit.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Audit in progress. The versioned acceptance matrix exists, but no release candidate is nominated and
|
||||||
|
the gate is not signed off. Packaged/release testing remains explicitly deferred until the project
|
||||||
|
owner requests it again.
|
||||||
|
|
||||||
|
## Sequence
|
||||||
|
|
||||||
|
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`.
|
||||||
|
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.
|
||||||
|
6. Run the eight-hour soak and measured performance protocol, consolidate limitations by severity
|
||||||
|
and workaround, and obtain independent first-hour/recovery sign-off.
|
||||||
|
7. Post the signed Gitea milestone comment linking the exact commit and immutable evidence. Close
|
||||||
|
`#50` only when every required row passes and no P0 blocker remains.
|
||||||
|
|
||||||
|
## Gate Rules
|
||||||
|
|
||||||
|
- Feature presence is not acceptance evidence.
|
||||||
|
- A local dirty worktree is not a release candidate.
|
||||||
|
- Results from another commit or an old package do not transfer to the candidate.
|
||||||
|
- Deferred, missing, partial, and implementer-only evidence are not passes.
|
||||||
|
- Every failure records an owner ticket or a concrete rerun condition.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Source-Control Status And Collaborative File Safety
|
||||||
|
|
||||||
|
Working implementation plan for Gitea issue
|
||||||
|
[`#49`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/49).
|
||||||
|
This is the final M7 implementation slice before the production-readiness acceptance gate.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Implementation, focused source tests, full editor tests, strict editor clippy, and headless checks
|
||||||
|
are complete. Live debug-editor visual acceptance remains pending for a desktop-capable QA session.
|
||||||
|
Packaged/release acceptance is explicitly deferred until the project owner requests another
|
||||||
|
packaged pass.
|
||||||
|
|
||||||
|
## Outcome
|
||||||
|
|
||||||
|
External edits cannot be silently overwritten by the editor, common Git/read-only/ownership states
|
||||||
|
are visible without dominating the shell, and projects without Git or an ownership provider behave
|
||||||
|
normally.
|
||||||
|
|
||||||
|
## Implementation Sequence
|
||||||
|
|
||||||
|
1. Add exact file revisions, comparison metadata, guarded atomic replacement, and deterministic
|
||||||
|
pre-rename race coverage.
|
||||||
|
2. Capture baselines for scene tabs, material/material-instance drafts, and Project Settings;
|
||||||
|
protect prefab source Apply and exact-file undo/redo with the same guard.
|
||||||
|
3. Add a non-destructive asynchronous Git scanner and optional ownership-provider registry.
|
||||||
|
4. Add compact active-scene and selected-asset status plus a recovery modal with reload, compare
|
||||||
|
metadata, save-as, and cancel.
|
||||||
|
5. Cover missing/present/read-only/external-change races, porcelain parsing, provider absence, and
|
||||||
|
document-specific conflict recovery with focused source tests.
|
||||||
|
6. Run format, strict affected-crate clippy, source tests, headless validation, and live debug-editor
|
||||||
|
QA. Do not run packaged tests until requested by the project owner.
|
||||||
|
|
||||||
|
## Acceptance Gates
|
||||||
|
|
||||||
|
- A loaded authored file changed by another process is never replaced by Save, Apply to source, or
|
||||||
|
prefab source history.
|
||||||
|
- File creation is also conditional: a file that appears after a save-as baseline is captured is
|
||||||
|
not overwritten.
|
||||||
|
- Conflict and read-only UI identifies the path and recovery choices without a force-overwrite
|
||||||
|
escape hatch.
|
||||||
|
- Active-scene and selected-asset Git status remain compact and explain themselves on hover.
|
||||||
|
- Git absence, a non-repository project, and an empty provider registry are quiet normal states.
|
||||||
|
- Git commands are read-only and never alter index, worktree, commits, branches, or locks.
|
||||||
|
- Provider state can block an authored write without coupling core editor code to a vendor.
|
||||||
|
- Source tests simulate a writer changing the target immediately before rename and prove the old or
|
||||||
|
external content survives.
|
||||||
|
|
||||||
|
## Deliberate Boundaries
|
||||||
|
|
||||||
|
- Generated registries, imports, thumbnails, navigation bakes, recovery snapshots, and packages are
|
||||||
|
regenerative/system-owned and do not open authored-file recovery UI.
|
||||||
|
- V1 compares metadata rather than rendering a text diff; external diff-tool integration is future
|
||||||
|
work.
|
||||||
|
- V1 observes ownership/locks. Acquiring, releasing, or stealing locks belongs in a provider-specific
|
||||||
|
follow-up.
|
||||||
|
- Git status is project-local and advisory. The content revision guard remains authoritative even
|
||||||
|
when Git is absent or stale.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Terrain Authoring Foundation
|
||||||
|
|
||||||
|
Working implementation plan for Gitea
|
||||||
|
[`#22`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/22).
|
||||||
|
This establishes the persistent and hydrated terrain contract required by sculpting `#23`, layer
|
||||||
|
painting `#24`, physics placement `#25`, and the regression pack `#32`.
|
||||||
|
|
||||||
|
## Authored Contract
|
||||||
|
|
||||||
|
- Add reflected `TerrainDesc` authoring data with a version, square height-grid resolution, inline
|
||||||
|
finite heights, horizontal sample spacing, vertical scale, chunk quad size, optional shared
|
||||||
|
Material/Material Instance reference, collider generation, and shadow flags.
|
||||||
|
- V1 stores the compact height grid in the scene so save/recovery/history/prefab behavior is exact.
|
||||||
|
A later external heightmap asset migration must be explicit and versioned rather than silently
|
||||||
|
changing ownership.
|
||||||
|
- Validate resolution, exact sample count, finite values, positive scale, and chunk bounds before
|
||||||
|
hydration or publication.
|
||||||
|
|
||||||
|
## Hydration
|
||||||
|
|
||||||
|
- Partition the grid into deterministic non-overlapping quad chunks with shared boundary samples.
|
||||||
|
- Generate triangle-list meshes with normals, UVs, U32 indices, and tangents; each generated child
|
||||||
|
carries owner/chunk coordinates and remains runtime-only.
|
||||||
|
- Use the authored shared material when resolvable and an explicit terrain fallback otherwise.
|
||||||
|
- Optionally attach `ColliderConstructor::TrimeshFromMesh` per chunk.
|
||||||
|
- Rebuild only the owning terrain's generated chunks when descriptor/material/active state changes;
|
||||||
|
disabling/removing terrain cleans every generated child.
|
||||||
|
|
||||||
|
## Editor Integration
|
||||||
|
|
||||||
|
- Register Terrain as a stable authoring component and ActorKind with conflicts against primitive,
|
||||||
|
brush, static renderer, and skinned renderer geometry sources.
|
||||||
|
- Add an inspector for resolution, world scale, chunk size, collider/shadow state, material summary,
|
||||||
|
validation, and a guarded flat-grid resize action. All mutations are one typed history step.
|
||||||
|
- Include terrain bounds in selection framing and generated chunks in authored-parent picking.
|
||||||
|
- Expose Add Terrain through the existing component shelf; no new permanent toolbar is added.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Tests cover descriptor validation, deterministic chunk coverage/mesh topology, hydration and
|
||||||
|
cleanup, generated-child stripping, serialization, and history round-trip.
|
||||||
|
- Source-only workspace format/check/strict-Clippy/tests and level validation run. Packaged tests
|
||||||
|
remain deferred by project-owner direction.
|
||||||
|
- Live native-Wayland acceptance creates or loads a terrain actor, verifies chunk rendering and
|
||||||
|
selection/inspection, changes scale/chunking, exercises undo/redo, and inspects a saved scene to
|
||||||
|
confirm generated chunks are absent.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Terrain Sculpt Tools (#23)
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- Add a modal terrain sculpt operator for raise, lower, flatten, smooth, and deterministic noise.
|
||||||
|
- Keep activation and brush settings in the existing horizontal viewport toolbar.
|
||||||
|
- Track a terrain-local cursor hit and render a world-space brush footprint preview.
|
||||||
|
- Apply live stroke previews while preserving one history entry per completed stroke.
|
||||||
|
- Restore the exact pre-stroke height grid on Escape or right-click.
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
1. Add pure heightfield sampling, ray-hit, falloff, and brush-dab functions with focused tests.
|
||||||
|
2. Add editor-only terrain sculpt state and viewport input/preview systems.
|
||||||
|
3. Commit strokes through the reflected component transaction after restoring the pre-stroke snapshot.
|
||||||
|
4. Add compact terrain controls to the existing viewport toolbar and update operator hints.
|
||||||
|
5. Document controls and validation evidence in the terrain editor guide and root checklist.
|
||||||
|
|
||||||
|
## Acceptance
|
||||||
|
|
||||||
|
- All five modes visibly modify terrain.
|
||||||
|
- The brush ring follows the actual terrain surface.
|
||||||
|
- Escape and right-click cancel without dirtying history.
|
||||||
|
- Mouse release creates exactly one undoable transaction regardless of dab count.
|
||||||
|
- Formatting, editor/shared checks, focused tests, and live editor QA pass.
|
||||||
@@ -152,6 +152,9 @@ deep-stale variants.
|
|||||||
| Asset Browser project/file views | Browse `assets/`, search/filter/sort models, textures, materials, audio clips, levels, and prefabs; switch grid/list; expand model subassets; inspect file details; audition audio; drag supported assets/submeshes into the viewport |
|
| Asset Browser project/file views | Browse `assets/`, search/filter/sort models, textures, materials, audio clips, levels, and prefabs; switch grid/list; expand model subassets; inspect file details; audition audio; drag supported assets/submeshes into the viewport |
|
||||||
| Drag audio clip into viewport | Create an authored audio source; when an audio source is selected, assign the clip instead |
|
| Drag audio clip into viewport | Create an authored audio source; when an audio source is selected, assign the clip instead |
|
||||||
| Asset Browser context/details actions | Apply textures/materials, regenerate thumbnails, reimport models, place assets/submeshes, or move file assets to `assets/.trash/` |
|
| Asset Browser context/details actions | Apply textures/materials, regenerate thumbnails, reimport models, place assets/submeshes, or move file assets to `assets/.trash/` |
|
||||||
|
| Window → Material Library | Search/filter project Materials and Material Instances, inspect scene usage and dependency health, create/edit shared assets, and drag them into the viewport |
|
||||||
|
| Drag Material/Instance onto viewport surface | Preview and assign the exact renderer slot, primitive, or brush face under the pointer; release commits one undo step, while Escape/right-click/outside restores the preview |
|
||||||
|
| Drag Texture onto viewport surface | Set a primitive base-color texture or exact brush face; renderer slots reject loose textures and direct you to a Material Instance |
|
||||||
| Static/Skinned Mesh Renderer material slots | Assign a shared Material/Material Instance per slot; Browse/Select/Locate the reference, or Clear the override to restore the imported source material |
|
| Static/Skinned Mesh Renderer material slots | Assign a shared Material/Material Instance per slot; Browse/Select/Locate the reference, or Clear the override to restore the imported source material |
|
||||||
| `Ctrl+P` | Centered command palette; search human labels or stable command IDs, use arrow keys to select, Enter to run |
|
| `Ctrl+P` | Centered command palette; search human labels or stable command IDs, use arrow keys to select, Enter to run |
|
||||||
| `F7` | While paused in Play: advance one sim tick |
|
| `F7` | While paused in Play: advance one sim tick |
|
||||||
@@ -160,11 +163,15 @@ deep-stale variants.
|
|||||||
| Drag actor between rows / onto Scene Root (Hierarchy, Manual sort) | Reorder siblings / unparent to the root |
|
| Drag actor between rows / onto Scene Root (Hierarchy, Manual sort) | Reorder siblings / unparent to the root |
|
||||||
| Hierarchy lock | Excludes the actor from selection, gizmos, multi-drag, structural drops, and mutating context actions |
|
| Hierarchy lock | Excludes the actor from selection, gizmos, multi-drag, structural drops, and mutating context actions |
|
||||||
| Hierarchy context | Group selection, create authored local children below linked prefab roots, remove/reparent generated members through same-layer structural overrides, or unparent |
|
| Hierarchy context | Group selection, create authored local children below linked prefab roots, remove/reparent generated members through same-layer structural overrides, or unparent |
|
||||||
| File menu | New, Open, transactional Save/Save As, recovery restore/keep-copy/discard when available, Import Assets, Export Selection, Save Selection As Prefab (including linked-root variants), Recent Scenes |
|
| File menu | New, non-blocking native Open/Save As, recovery restore/keep-copy/discard when available, Import Assets, Export Selection, Save Selection As Prefab (including linked-root variants), Recent Scenes |
|
||||||
|
| Status strip / Asset Details source-state chip | Inspect compact clean, modified, untracked, conflicted, read-only, and optional ownership status; hover for the source path and provider details |
|
||||||
|
| Authored File Not Saved dialog | Resolve an external edit, read-only target, or ownership lock with Reload, Compare Metadata, Save As, or Cancel; the editor never offers force overwrite |
|
||||||
| Main toolbar, right side | Switch or close independent scene tabs, create an untitled tab, and manage loaded/locked composed subscenes |
|
| Main toolbar, right side | Switch or close independent scene tabs, create an untitled tab, and manage loaded/locked composed subscenes |
|
||||||
| Prefab Instance inspector | Inspect/recover source health, Apply/Revert overrides by scope, Apply overrides to source, create a variant, **Unpack Layer**, or recursively **Convert to Local** |
|
| Prefab Instance inspector | Inspect/recover source health, Apply/Revert overrides by scope, Apply overrides to source, create a variant, **Unpack Layer**, or recursively **Convert to Local** |
|
||||||
| Inspector component card | Collapse with caret, toggle active with status dot, or use triple-dot menu for reset/copy/paste/move/remove actions |
|
| Inspector component card | Collapse with caret, toggle active with status dot, or use triple-dot menu for reset/copy/paste/move/remove actions |
|
||||||
| Inspector footer → Add Component | Expands an inline search shelf for registered authoring, rendering, physics, gameplay, and volume components with descriptions, availability hints, and undo |
|
| Inspector footer → Add Component | Expands an inline search shelf for registered authoring, rendering, physics, gameplay, and volume components with descriptions, availability hints, and undo |
|
||||||
|
| 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 |
|
||||||
| Audio Source / Listener inspector | Assign and audition clips; edit gain, pitch, loop/autoplay, spatial blend, attenuation, bus, listener priority, and ear gap |
|
| 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 |
|
| Edit → Project Settings… | Edit `assets/project.ron` rendering, audio buses, physics, and input |
|
||||||
|
|
||||||
@@ -261,6 +268,13 @@ Viewport shortcut keys require the pointer to be in the viewport and are suspend
|
|||||||
without changing the scene.
|
without changing the scene.
|
||||||
- Runtime-only handles/colliders are not serialized directly, keeping scenes stable and portable.
|
- Runtime-only handles/colliders are not serialized directly, keeping scenes stable and portable.
|
||||||
- Editor-only cameras and helper roots are filtered from selection, hierarchy, and scene save.
|
- Editor-only cameras and helper roots are filtered from selection, hierarchy, and scene save.
|
||||||
|
- Loaded scenes, prefab source Apply/history, Materials, Material Instances, and Project Settings
|
||||||
|
retain exact BLAKE3 disk revisions. Save verifies the revision again immediately before atomic
|
||||||
|
replacement; an external edit, create race, read-only target, or provider lock leaves the
|
||||||
|
existing file untouched and opens the collaborative recovery dialog. Git status is observational
|
||||||
|
and optional. See the
|
||||||
|
[collaborative file-safety guide](docs/editor/collaborative-file-safety.md) and
|
||||||
|
[ADR 0037](docs/adr/0037-collaborative-authored-file-safety.md).
|
||||||
- **PIE restores player sim only** (transform, velocity, jump state) when you stop Play; authored
|
- **PIE restores player sim only** (transform, velocity, jump state) when you stop Play; authored
|
||||||
`LevelObject` edits made during PIE **remain** in the scene (the level may show as dirty).
|
`LevelObject` edits made during PIE **remain** in the scene (the level may show as dirty).
|
||||||
- Play mode swaps the unified viewport between the player camera (possessed) and editor fly camera
|
- Play mode swaps the unified viewport between the player camera (possessed) and editor fly camera
|
||||||
@@ -323,6 +337,16 @@ identity, project and active-scene paths, dirty flags, aggregate validation coun
|
|||||||
state, and the bounded Scene I/O log. It excludes scene and asset contents, environment values,
|
state, and the bounded Scene I/O log. It excludes scene and asset contents, environment values,
|
||||||
host/user identity, credentials, access tokens, and modal tool state.
|
host/user identity, credentials, access tokens, and modal tool state.
|
||||||
|
|
||||||
|
### External file changes and read-only assets
|
||||||
|
|
||||||
|
The active scene status strip and selected asset header show compact Git/read-only/ownership state
|
||||||
|
when available. If Save or Apply detects a different disk revision, Blacksite leaves that revision
|
||||||
|
untouched and opens **Authored File Not Saved**. Use **Compare Metadata** to inspect both revisions,
|
||||||
|
**Save As** to preserve the editor copy elsewhere, **Reload** to take the disk version, or **Cancel**
|
||||||
|
to keep the local draft unsaved. Git and ownership providers are optional; the status scanner never
|
||||||
|
stages, commits, resets, checks out, restores, or discards files. See
|
||||||
|
[collaborative-file-safety.md](docs/editor/collaborative-file-safety.md).
|
||||||
|
|
||||||
## Cursor / VSCode Setup
|
## Cursor / VSCode Setup
|
||||||
|
|
||||||
The `.vscode/` folder is preconfigured:
|
The `.vscode/` folder is preconfigured:
|
||||||
@@ -346,6 +370,7 @@ The `.vscode/` folder is preconfigured:
|
|||||||
- [ADR 0016: Unified Rendering Contract](docs/adr/0016-unified-rendering-contract.md)
|
- [ADR 0016: Unified Rendering Contract](docs/adr/0016-unified-rendering-contract.md)
|
||||||
- [ADR 0017: Normalized Static Mesh Assets](docs/adr/0017-normalized-static-mesh-assets.md)
|
- [ADR 0017: Normalized Static Mesh Assets](docs/adr/0017-normalized-static-mesh-assets.md)
|
||||||
- [ADR 0034: Registry-driven Authoring Components](docs/adr/0034-registry-driven-authoring-components.md)
|
- [ADR 0034: Registry-driven Authoring Components](docs/adr/0034-registry-driven-authoring-components.md)
|
||||||
|
- [ADR 0037: Collaborative Authored-File Safety](docs/adr/0037-collaborative-authored-file-safety.md)
|
||||||
|
|
||||||
## Project Layout
|
## Project Layout
|
||||||
|
|
||||||
@@ -375,6 +400,9 @@ crates/
|
|||||||
- [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels
|
- [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels
|
||||||
- [x] Delete, duplicate, rename, and structural/material undo-redo
|
- [x] Delete, duplicate, rename, and structural/material undo-redo
|
||||||
- [x] Native Bevy scene New/Open/Save/Save As with dirty title tracking
|
- [x] Native Bevy scene New/Open/Save/Save As with dirty title tracking
|
||||||
|
- [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] 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] Asset import, static mesh/prefab placement, texture assignment, and selection export
|
||||||
- [x] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
|
- [x] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
|
||||||
- [x] Unified viewport render-to-texture target + Play session bootstrap
|
- [x] Unified viewport render-to-texture target + Play session bootstrap
|
||||||
@@ -393,6 +421,7 @@ crates/
|
|||||||
- [x] Audio source/listener authoring, non-dirty spatial audition, viewport icons/range gizmos, stable buses, PIE/runtime parity, device diagnostics, and shared release validation ([ADR 0030](docs/adr/0030-audio-authoring-and-bus-schema.md); production acceptance completed in [Gitea #47](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/47))
|
- [x] Audio source/listener authoring, non-dirty spatial audition, viewport icons/range gizmos, stable buses, PIE/runtime parity, device diagnostics, and shared release validation ([ADR 0030](docs/adr/0030-audio-authoring-and-bus-schema.md); production acceptance completed in [Gitea #47](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/47))
|
||||||
- [x] glTF/GLB skeletal animation manifests, stable controller states, non-dirty preview, PIE/runtime hydration, and exact-signature compatibility validation ([ADR 0031](docs/adr/0031-animation-authoring-runtime-contract.md); production acceptance completed in [Gitea #46](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/46))
|
- [x] glTF/GLB skeletal animation manifests, stable controller states, non-dirty preview, PIE/runtime hydration, and exact-signature compatibility validation ([ADR 0031](docs/adr/0031-animation-authoring-runtime-contract.md); production acceptance completed in [Gitea #46](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/46))
|
||||||
- [x] Navigation bounds/obstacles/areas/links, persisted validation samples, composed-source resolution, deterministic stale-checked bake artifacts, viewport path preview, headless bake, and shared game/runtime query API ([ADR 0032](docs/adr/0032-versioned-navigation-bake-and-runtime-query.md); [evaluation](docs/editor/evaluations/navigation-authoring/); [Gitea #48](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/48))
|
- [x] Navigation bounds/obstacles/areas/links, persisted validation samples, composed-source resolution, deterministic stale-checked bake artifacts, viewport path preview, headless bake, and shared game/runtime query API ([ADR 0032](docs/adr/0032-versioned-navigation-bake-and-runtime-query.md); [evaluation](docs/editor/evaluations/navigation-authoring/); [Gitea #48](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/48))
|
||||||
|
- [x] Exact authored-file revision guards for scenes, prefab source Apply/history, Materials, Material Instances, and Project Settings; compact observational Git/read-only/ownership state; and explicit Reload/Compare Metadata/Save As/Cancel recovery without force overwrite ([ADR 0037](docs/adr/0037-collaborative-authored-file-safety.md), [collaboration guide](docs/editor/collaborative-file-safety.md), [Gitea #49](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/49))
|
||||||
- [x] Prefab instances (`PrefabInstance`) + save-as-prefab + unpack
|
- [x] Prefab instances (`PrefabInstance`) + save-as-prefab + unpack
|
||||||
- [x] Independent dirty-tab close confirmation and all-tab save guard when switching projects
|
- [x] Independent dirty-tab close confirmation and all-tab save guard when switching projects
|
||||||
- [x] Transactional scene writes + bounded user-local recovery snapshots ([ADR 0023](docs/adr/0023-transactional-scene-persistence-and-recovery.md))
|
- [x] Transactional scene writes + bounded user-local recovery snapshots ([ADR 0023](docs/adr/0023-transactional-scene-persistence-and-recovery.md))
|
||||||
@@ -413,6 +442,7 @@ crates/
|
|||||||
- [x] FBX/glTF model import + normalized static/skinned renderer routing; explicit generic scene-instance load via `bevy_ufbx` / `ModelRef`
|
- [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] 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 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] 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 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))
|
- [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))
|
||||||
- [x] Shared project validation: editor Diagnostics and `cargo validate-levels --json` use one owner-attributed dependency/finding report across project settings, registry/import artifacts, materials, shaders, scenes, prefabs, brushes, and colliders; valid/missing/cyclic/incompatible fixtures fail on blocking content errors ([ADR 0028](docs/adr/0028-authoritative-project-content-validation.md), [Gitea #45](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/45))
|
- [x] Shared project validation: editor Diagnostics and `cargo validate-levels --json` use one owner-attributed dependency/finding report across project settings, registry/import artifacts, materials, shaders, scenes, prefabs, brushes, and colliders; valid/missing/cyclic/incompatible fixtures fail on blocking content errors ([ADR 0028](docs/adr/0028-authoritative-project-content-validation.md), [Gitea #45](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/45))
|
||||||
@@ -455,7 +485,7 @@ crates/
|
|||||||
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
|
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
|
||||||
authoring UI coverage and production-acceptance gaps are tracked in
|
authoring UI coverage and production-acceptance gaps are tracked in
|
||||||
[prefab-authoring.md](docs/editor/prefab-authoring.md).
|
[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/`. In the Asset Browser, select a Material and use **Create Instance** for sparse inherited variants. Static and skinned renderers own stable per-draw material slots, with explicit assignments taking precedence over imported source defaults; 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. 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).
|
||||||
- Per-field reflect undo for all components remains future work; typed `shared` inspectors cover the common authoring path.
|
- 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,
|
- 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.
|
material graphs, lighting profiles) can be added without changing the scene format foundation.
|
||||||
|
|||||||
@@ -269,6 +269,24 @@
|
|||||||
),
|
),
|
||||||
dependencies: [],
|
dependencies: [],
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
id: ("1b25d451-7b54-41d6-af00-d2e6950f502d"),
|
||||||
|
path: "assets/levels/terrain_authoring_showcase.scn.ron",
|
||||||
|
label: "terrain_authoring_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: ("dc13ce01-c7ce-43c5-974c-0e659ae49ab9"),
|
id: ("dc13ce01-c7ce-43c5-974c-0e659ae49ab9"),
|
||||||
path: "assets/levels/editor_scene 2.scn.ron",
|
path: "assets/levels/editor_scene 2.scn.ron",
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
(schema_version: 4, resources: {}, entities: {
|
||||||
|
1: (components: {
|
||||||
|
"bevy_ecs::name::Name": "Terrain Showcase",
|
||||||
|
"bevy_transform::components::transform::Transform": (
|
||||||
|
translation: (0.0, 0.0, 0.0),
|
||||||
|
rotation: (0.0, 0.0, 0.0, 1.0),
|
||||||
|
scale: (1.0, 1.0, 1.0),
|
||||||
|
),
|
||||||
|
"shared::components::ActorId": ("terrain-showcase-main"),
|
||||||
|
"shared::components::ActorKind": Terrain,
|
||||||
|
"shared::components::EditorVisibility": (visible: true),
|
||||||
|
"shared::components::HierarchySiblingIndex": (0),
|
||||||
|
"shared::components::LevelObject": (),
|
||||||
|
"shared::components::TerrainDesc": (
|
||||||
|
schema_version: 1,
|
||||||
|
resolution: 5,
|
||||||
|
heights: [
|
||||||
|
0.00, 0.00, 0.05, 0.00, 0.00,
|
||||||
|
0.00, 0.15, 0.30, 0.10, 0.00,
|
||||||
|
0.05, 0.35, 0.80, 0.25, 0.05,
|
||||||
|
0.00, 0.20, 0.40, 0.15, 0.00,
|
||||||
|
0.00, 0.00, 0.05, 0.00, 0.00,
|
||||||
|
],
|
||||||
|
sample_spacing: 2.0,
|
||||||
|
height_scale: 3.0,
|
||||||
|
chunk_quads: 2,
|
||||||
|
base_material: Some((
|
||||||
|
asset_id: "cc2769da-c9a5-4cb3-866a-cc81d0688ee2",
|
||||||
|
sub_asset_id: "material:instance",
|
||||||
|
label: "surface_tint_instance",
|
||||||
|
source_path: Some("assets/materials/surface_tint_instance.ron"),
|
||||||
|
)),
|
||||||
|
generate_colliders: true,
|
||||||
|
cast_shadows: true,
|
||||||
|
receive_shadows: true,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
2: (components: {
|
||||||
|
"bevy_ecs::name::Name": "Terrain Sun",
|
||||||
|
"bevy_transform::components::transform::Transform": (
|
||||||
|
translation: (0.0, 8.0, 0.0),
|
||||||
|
rotation: (0.1691, -0.0670, 0.7244, 0.6648),
|
||||||
|
scale: (1.0, 1.0, 1.0),
|
||||||
|
),
|
||||||
|
"shared::components::ActorId": ("terrain-showcase-sun"),
|
||||||
|
"shared::components::ActorKind": Light,
|
||||||
|
"shared::components::EditorVisibility": (visible: true),
|
||||||
|
"shared::components::HierarchySiblingIndex": (1),
|
||||||
|
"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,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
})
|
||||||
@@ -16,10 +16,7 @@ pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String>
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
|
pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
|
||||||
let asset = load_material_asset(catalog_path)?;
|
shared::load_resolved_material_from_path(catalog_path).map(|(desc, _)| desc)
|
||||||
let mut desc = asset.material;
|
|
||||||
desc.material_asset_path = Some(catalog_path.to_string());
|
|
||||||
Ok(desc)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_material_asset_to_selection(
|
pub fn apply_material_asset_to_selection(
|
||||||
@@ -110,7 +107,7 @@ pub fn apply_material_asset_to_selection(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRenderer) {
|
pub(crate) fn ensure_static_material_slots(renderer: &mut shared::StaticMeshRenderer) {
|
||||||
for part in &mut renderer.slots {
|
for part in &mut renderer.slots {
|
||||||
if part.material_slot_id.0.trim().is_empty() {
|
if part.material_slot_id.0.trim().is_empty() {
|
||||||
part.material_slot_id = if part.id.0.trim().is_empty() {
|
part.material_slot_id = if part.id.0.trim().is_empty() {
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ pub mod thumbnails;
|
|||||||
pub use catalog::*;
|
pub use catalog::*;
|
||||||
pub use thumbnails::{
|
pub use thumbnails::{
|
||||||
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
|
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
|
||||||
prefetch_folder_thumbnails, AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState,
|
prefetch_asset_thumbnails, prefetch_folder_thumbnails, AssetThumbnailCache,
|
||||||
ThumbnailStudio, ThumbnailsPlugin,
|
ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Refreshes both generated contracts derived from one imported model source.
|
/// Refreshes both generated contracts derived from one imported model source.
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ use crate::asset_db::{ensure_asset_record, AssetRegistry};
|
|||||||
use crate::history::{
|
use crate::history::{
|
||||||
capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply,
|
capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply,
|
||||||
};
|
};
|
||||||
|
use crate::native_dialog::NativeDialogBroker;
|
||||||
use crate::ui::inspector::{
|
use crate::ui::inspector::{
|
||||||
apply_component_card_response, component_card, component_card_context, property_row,
|
apply_component_card_response, component_card, component_card_context, property_row,
|
||||||
ComponentCardOptions,
|
ComponentCardOptions,
|
||||||
@@ -751,13 +752,44 @@ fn relink_prefab_source(world: &mut World, entity: Entity) {
|
|||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let Some(path) = rfd::FileDialog::new()
|
let directory = project_root.join("assets/prefabs");
|
||||||
.set_directory(project_root.join("assets/prefabs"))
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
|
move || {
|
||||||
|
rfd::FileDialog::new()
|
||||||
|
.set_directory(directory)
|
||||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||||
.pick_file()
|
.pick_file()
|
||||||
else {
|
},
|
||||||
|
move |world, path| {
|
||||||
|
let Some(path) = path else {
|
||||||
|
world
|
||||||
|
.resource_mut::<crate::scene_io::SceneIo>()
|
||||||
|
.set_status("Prefab relink cancelled");
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
finish_relink_prefab_source(world, entity, project_root, path);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
world
|
||||||
|
.resource_mut::<crate::scene_io::SceneIo>()
|
||||||
|
.set_status(match result {
|
||||||
|
Ok(()) => "Choose a prefab source".into(),
|
||||||
|
Err(error) => format!("Prefab relink unavailable: {error}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_relink_prefab_source(
|
||||||
|
world: &mut World,
|
||||||
|
entity: Entity,
|
||||||
|
project_root: PathBuf,
|
||||||
|
path: PathBuf,
|
||||||
|
) {
|
||||||
|
if world.get_entity(entity).is_err() {
|
||||||
|
world
|
||||||
|
.resource_mut::<crate::scene_io::SceneIo>()
|
||||||
|
.set_status("Prefab relink failed: the initiating actor no longer exists");
|
||||||
|
return;
|
||||||
|
}
|
||||||
let Ok(path) = path.canonicalize() else {
|
let Ok(path) = path.canonicalize() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -1248,6 +1280,10 @@ fn apply_prefab_scope_to_source(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let before_snapshot = crate::collaboration::FileSnapshot::from_loaded_bytes(
|
||||||
|
&source_path,
|
||||||
|
before_source.as_bytes(),
|
||||||
|
);
|
||||||
let mut document = match SceneDocument::from_ron_text(&before_source) {
|
let mut document = match SceneDocument::from_ron_text(&before_source) {
|
||||||
Ok(document) => document,
|
Ok(document) => document,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -1361,7 +1397,13 @@ fn apply_prefab_scope_to_source(
|
|||||||
}
|
}
|
||||||
let after_source = document.to_ron_text()?;
|
let after_source = document.to_ron_text()?;
|
||||||
scene::validate_prefab_graph_text(&after_source, &source_path, &project_root)?;
|
scene::validate_prefab_graph_text(&after_source, &source_path, &project_root)?;
|
||||||
crate::scene::recovery::atomic_write(&source_path, after_source.as_bytes())?;
|
crate::collaboration::publish_authored_file(
|
||||||
|
world,
|
||||||
|
&source_path,
|
||||||
|
after_source.as_bytes(),
|
||||||
|
&before_snapshot,
|
||||||
|
crate::collaboration::FileWriteIntent::PrefabSource { instance_root },
|
||||||
|
)?;
|
||||||
Ok::<_, String>(after_source)
|
Ok::<_, String>(after_source)
|
||||||
})();
|
})();
|
||||||
let after_source = match apply_result {
|
let after_source = match apply_result {
|
||||||
@@ -2607,6 +2649,22 @@ fn retry_prefab_source(world: &mut World, entity: Entity) {
|
|||||||
"Prefab source queued for reload".into();
|
"Prefab source queued for reload".into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn reload_prefab_source_after_file_conflict(
|
||||||
|
world: &mut World,
|
||||||
|
instance_root: Entity,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
if world.get::<PrefabInstance>(instance_root).is_none() {
|
||||||
|
return Err("the prefab instance no longer exists".into());
|
||||||
|
}
|
||||||
|
retry_prefab_source(world, instance_root);
|
||||||
|
let status = world.resource::<crate::scene_io::SceneIo>().status.clone();
|
||||||
|
if status.starts_with("Prefab retry failed") {
|
||||||
|
Err(status)
|
||||||
|
} else {
|
||||||
|
Ok(status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn prefab_member_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
pub fn prefab_member_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||||
let Some((instance_root, target)) = prefab_member_override_target(world, entity) else {
|
let Some((instance_root, target)) = prefab_member_override_target(world, entity) else {
|
||||||
ui.label(egui::RichText::new("Prefab target unavailable").color(ERROR));
|
ui.label(egui::RichText::new("Prefab target unavailable").color(ERROR));
|
||||||
@@ -3258,6 +3316,38 @@ mod tests {
|
|||||||
assert_eq!(read_overrides(&instance), PrefabOverrides::default());
|
assert_eq!(read_overrides(&instance), PrefabOverrides::default());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collaboration_reload_restarts_prefab_hydration_without_dropping_overrides() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-prefab-collaboration-reload-{}",
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
));
|
||||||
|
let source_path = root.join("assets/prefabs/base.scn.ron");
|
||||||
|
std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&source_path, prefab_source("mesh", None)).unwrap();
|
||||||
|
let mut world = prefab_test_world(&root);
|
||||||
|
let mut instance = PrefabInstance::new("base", "assets/prefabs/base.scn.ron");
|
||||||
|
instance.overrides_ron = encode_prefab_overrides(&PrefabOverrides {
|
||||||
|
source_revision: Some("previous".into()),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let instance_root = world.spawn((instance.clone(), HydratedPrefabReady)).id();
|
||||||
|
|
||||||
|
let status = reload_prefab_source_after_file_conflict(&mut world, instance_root).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(status, "Prefab source queued for reload");
|
||||||
|
assert_eq!(
|
||||||
|
world
|
||||||
|
.get::<PrefabInstance>(instance_root)
|
||||||
|
.map(|current| ¤t.overrides_ron),
|
||||||
|
Some(&instance.overrides_ron)
|
||||||
|
);
|
||||||
|
assert!(world.get::<HydratedPrefabReady>(instance_root).is_none());
|
||||||
|
assert!(world.get::<PrefabRef>(instance_root).is_some());
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn nested_unpack_fold_is_transactional_when_a_later_link_is_invalid() {
|
fn nested_unpack_fold_is_transactional_when_a_later_link_is_invalid() {
|
||||||
let mut world = World::new();
|
let mut world = World::new();
|
||||||
|
|||||||
@@ -188,18 +188,24 @@ impl AssetThumbnailCache {
|
|||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let material = match shared::MaterialAsset::load_from_path(&path) {
|
let material = match shared::load_resolved_material_from_path(&path) {
|
||||||
Ok(asset) => asset,
|
Ok((material, _)) => material,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
self.mark_studio_failed(&key, &error, true);
|
self.mark_studio_failed(&key, &error, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let label = shared::MaterialAsset::load_from_path(&path)
|
||||||
|
.map(|asset| asset.label)
|
||||||
|
.or_else(|_| {
|
||||||
|
shared::MaterialInstanceAsset::load_from_path(&path).map(|asset| asset.label)
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|_| "Material".into());
|
||||||
if studio.enqueue_source(
|
if studio.enqueue_source(
|
||||||
key.clone(),
|
key.clone(),
|
||||||
ThumbnailJobSource::MaterialAsset {
|
ThumbnailJobSource::MaterialAsset {
|
||||||
label: material.label.clone(),
|
label,
|
||||||
material: Box::new(material.material),
|
material: Box::new(material),
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
self.studio_pending.insert(key);
|
self.studio_pending.insert(key);
|
||||||
@@ -482,6 +488,37 @@ pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
|
|||||||
.prefetched_folder = Some(folder.to_string());
|
.prefetched_folder = Some(folder.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Requests thumbnails for an explicit cross-folder asset set.
|
||||||
|
pub fn prefetch_asset_thumbnails(world: &mut World, assets: &[EditorAsset]) {
|
||||||
|
let requests = assets
|
||||||
|
.iter()
|
||||||
|
.filter_map(|asset| {
|
||||||
|
Some((
|
||||||
|
asset_cache_key(asset),
|
||||||
|
asset.path.clone()?,
|
||||||
|
asset.kind.clone(),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let asset_server = world.resource::<AssetServer>().clone();
|
||||||
|
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
|
||||||
|
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
|
||||||
|
for (key, path, kind) in requests {
|
||||||
|
match kind {
|
||||||
|
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
|
||||||
|
EditorAssetKind::Model => {
|
||||||
|
cache.request_model(key, path, &asset_server, &mut studio)
|
||||||
|
}
|
||||||
|
EditorAssetKind::Material => {
|
||||||
|
cache.request_material_asset(key, path, &mut studio)
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
pub fn invalidate_on_catalog_refresh(world: &mut World) {
|
pub fn invalidate_on_catalog_refresh(world: &mut World) {
|
||||||
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
|
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
|
||||||
if !world.contains_resource::<ThumbnailStudio>() {
|
if !world.contains_resource::<ThumbnailStudio>() {
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ mod sources;
|
|||||||
mod studio;
|
mod studio;
|
||||||
|
|
||||||
pub use cache::{
|
pub use cache::{
|
||||||
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
|
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
|
||||||
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
|
prefetch_folder_thumbnails, AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot,
|
||||||
|
ThumbnailState,
|
||||||
};
|
};
|
||||||
pub use job::{ThumbnailJob, ThumbnailJobSource};
|
pub use job::{ThumbnailJob, ThumbnailJobSource};
|
||||||
pub use sources::{
|
pub use sources::{
|
||||||
|
|||||||
@@ -1570,7 +1570,7 @@ pub fn set_scene_composition_with_history(world: &mut World, new: SceneCompositi
|
|||||||
pub fn apply_command_undo(world: &mut World) {
|
pub fn apply_command_undo(world: &mut World) {
|
||||||
let candidate = world.resource::<EditorHistory>().undo_stack.last().cloned();
|
let candidate = world.resource::<EditorHistory>().undo_stack.last().cloned();
|
||||||
if let Some(candidate) = candidate {
|
if let Some(candidate) = candidate {
|
||||||
if let Err(error) = prepare_prefab_source_history(&candidate, true) {
|
if let Err(error) = prepare_prefab_source_history(world, &candidate, true) {
|
||||||
world.resource_mut::<EditorHistory>().status = format!("Undo blocked: {error}");
|
world.resource_mut::<EditorHistory>().status = format!("Undo blocked: {error}");
|
||||||
world
|
world
|
||||||
.resource_mut::<SceneIo>()
|
.resource_mut::<SceneIo>()
|
||||||
@@ -1591,7 +1591,7 @@ pub fn apply_command_undo(world: &mut World) {
|
|||||||
pub fn apply_command_redo(world: &mut World) {
|
pub fn apply_command_redo(world: &mut World) {
|
||||||
let candidate = world.resource::<EditorHistory>().redo_stack.last().cloned();
|
let candidate = world.resource::<EditorHistory>().redo_stack.last().cloned();
|
||||||
if let Some(candidate) = candidate {
|
if let Some(candidate) = candidate {
|
||||||
if let Err(error) = prepare_prefab_source_history(&candidate, false) {
|
if let Err(error) = prepare_prefab_source_history(world, &candidate, false) {
|
||||||
world.resource_mut::<EditorHistory>().status = format!("Redo blocked: {error}");
|
world.resource_mut::<EditorHistory>().status = format!("Redo blocked: {error}");
|
||||||
world
|
world
|
||||||
.resource_mut::<SceneIo>()
|
.resource_mut::<SceneIo>()
|
||||||
@@ -1609,8 +1609,13 @@ pub fn apply_command_redo(world: &mut World) {
|
|||||||
mark_dirty(world);
|
mark_dirty(world);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<(), String> {
|
fn prepare_prefab_source_history(
|
||||||
|
world: &mut World,
|
||||||
|
command: &EditorCommand,
|
||||||
|
undo: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
let EditorCommand::ApplyPrefabToSource {
|
let EditorCommand::ApplyPrefabToSource {
|
||||||
|
entity,
|
||||||
source_path,
|
source_path,
|
||||||
before_source,
|
before_source,
|
||||||
after_source,
|
after_source,
|
||||||
@@ -1624,15 +1629,18 @@ fn prepare_prefab_source_history(command: &EditorCommand, undo: bool) -> Result<
|
|||||||
} else {
|
} else {
|
||||||
(before_source, after_source)
|
(before_source, after_source)
|
||||||
};
|
};
|
||||||
let current = std::fs::read_to_string(source_path)
|
let expected =
|
||||||
.map_err(|error| format!("could not read {}: {error}", source_path.display()))?;
|
crate::collaboration::FileSnapshot::from_loaded_bytes(source_path, expected.as_bytes());
|
||||||
if ¤t != expected {
|
crate::collaboration::publish_authored_file(
|
||||||
return Err(format!(
|
world,
|
||||||
"{} changed outside this history command",
|
source_path,
|
||||||
source_path.display()
|
replacement.as_bytes(),
|
||||||
));
|
&expected,
|
||||||
}
|
crate::collaboration::FileWriteIntent::PrefabSourceHistory {
|
||||||
crate::scene::recovery::atomic_write(source_path, replacement.as_bytes())
|
instance_root: *entity,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
fn undo_command(world: &mut World, command: &mut EditorCommand) {
|
||||||
|
|||||||
@@ -22,8 +22,10 @@ pub use ext::extensibility;
|
|||||||
pub use ext::hot_reload;
|
pub use ext::hot_reload;
|
||||||
pub use play::net_editor;
|
pub use play::net_editor;
|
||||||
pub use play::state;
|
pub use play::state;
|
||||||
|
pub use project::collaboration;
|
||||||
pub use project::diagnostics_bundle;
|
pub use project::diagnostics_bundle;
|
||||||
pub use project::launcher;
|
pub use project::launcher;
|
||||||
|
pub use project::native_dialog;
|
||||||
pub use project::project_io;
|
pub use project::project_io;
|
||||||
pub use project::session;
|
pub use project::session;
|
||||||
pub use project::settings_ui;
|
pub use project::settings_ui;
|
||||||
@@ -36,10 +38,12 @@ pub use viewport::brush_edit;
|
|||||||
pub use viewport::brush_tool;
|
pub use viewport::brush_tool;
|
||||||
pub use viewport::camera;
|
pub use viewport::camera;
|
||||||
pub use viewport::gizmos;
|
pub use viewport::gizmos;
|
||||||
|
pub use viewport::material_drop;
|
||||||
pub use viewport::render_view;
|
pub use viewport::render_view;
|
||||||
pub use viewport::rendering_diagnostics;
|
pub use viewport::rendering_diagnostics;
|
||||||
pub use viewport::selection;
|
pub use viewport::selection;
|
||||||
pub use viewport::selection_outline;
|
pub use viewport::selection_outline;
|
||||||
|
pub use viewport::terrain_sculpt;
|
||||||
pub use viewport::visualizers;
|
pub use viewport::visualizers;
|
||||||
|
|
||||||
use bevy::app::PluginGroupBuilder;
|
use bevy::app::PluginGroupBuilder;
|
||||||
@@ -61,9 +65,12 @@ use extensibility::ExtensibilityPlugin;
|
|||||||
use gizmos::EditorGizmoPlugin;
|
use gizmos::EditorGizmoPlugin;
|
||||||
use history::EditorHistoryPlugin;
|
use history::EditorHistoryPlugin;
|
||||||
use infra::EditorInfraPlugin;
|
use infra::EditorInfraPlugin;
|
||||||
|
use material_drop::MaterialDropPlugin;
|
||||||
use operators::OperatorPlugin;
|
use operators::OperatorPlugin;
|
||||||
use play::audio_preview::AudioPreviewPlugin;
|
use play::audio_preview::AudioPreviewPlugin;
|
||||||
use play::PlaySessionPlugin;
|
use play::PlaySessionPlugin;
|
||||||
|
use project::collaboration::CollaborationPlugin;
|
||||||
|
use project::native_dialog::NativeDialogPlugin;
|
||||||
use project_io::ProjectIoPlugin;
|
use project_io::ProjectIoPlugin;
|
||||||
use render_view::RenderViewPlugin;
|
use render_view::RenderViewPlugin;
|
||||||
use scene_io::SceneIoPlugin;
|
use scene_io::SceneIoPlugin;
|
||||||
@@ -73,6 +80,7 @@ use selection_outline::SelectionOutlinePlugin;
|
|||||||
use session::EditorSessionPlugin;
|
use session::EditorSessionPlugin;
|
||||||
use settings_ui::SettingsUiPlugin;
|
use settings_ui::SettingsUiPlugin;
|
||||||
use state::EditorStatePlugin;
|
use state::EditorStatePlugin;
|
||||||
|
use terrain_sculpt::TerrainSculptPlugin;
|
||||||
use ui::EditorUiPlugin;
|
use ui::EditorUiPlugin;
|
||||||
use viewport::ViewportPlugin;
|
use viewport::ViewportPlugin;
|
||||||
use visualizers::EditorVisualizersPlugin;
|
use visualizers::EditorVisualizersPlugin;
|
||||||
@@ -86,6 +94,7 @@ impl PluginGroup for EditorPluginGroup {
|
|||||||
let group = PluginGroupBuilder::start::<Self>()
|
let group = PluginGroupBuilder::start::<Self>()
|
||||||
.add(EditorInfraPlugin)
|
.add(EditorInfraPlugin)
|
||||||
.add(ProjectIoPlugin)
|
.add(ProjectIoPlugin)
|
||||||
|
.add(NativeDialogPlugin)
|
||||||
.add(scene_schema::SceneSchemaPlugin)
|
.add(scene_schema::SceneSchemaPlugin)
|
||||||
.add(net_editor::NetEditorPlugin)
|
.add(net_editor::NetEditorPlugin)
|
||||||
.add(AssetDbPlugin)
|
.add(AssetDbPlugin)
|
||||||
@@ -102,15 +111,18 @@ impl PluginGroup for EditorPluginGroup {
|
|||||||
.add(BrushCsgPlugin)
|
.add(BrushCsgPlugin)
|
||||||
.add(BrushEditPlugin)
|
.add(BrushEditPlugin)
|
||||||
.add(BrushToolPlugin)
|
.add(BrushToolPlugin)
|
||||||
|
.add(TerrainSculptPlugin)
|
||||||
.add(EditorCameraPlugin)
|
.add(EditorCameraPlugin)
|
||||||
.add(AudioPreviewPlugin)
|
.add(AudioPreviewPlugin)
|
||||||
.add(ActorIconsPlugin)
|
.add(ActorIconsPlugin)
|
||||||
|
.add(MaterialDropPlugin)
|
||||||
.add(EditorSelectionPlugin)
|
.add(EditorSelectionPlugin)
|
||||||
.add(SelectionOutlinePlugin)
|
.add(SelectionOutlinePlugin)
|
||||||
.add(EditorGizmoPlugin)
|
.add(EditorGizmoPlugin)
|
||||||
.add(EditorVisualizersPlugin)
|
.add(EditorVisualizersPlugin)
|
||||||
.add(EditorHistoryPlugin)
|
.add(EditorHistoryPlugin)
|
||||||
.add(SceneIoPlugin)
|
.add(SceneIoPlugin)
|
||||||
|
.add(CollaborationPlugin)
|
||||||
.add(EditorUiPlugin)
|
.add(EditorUiPlugin)
|
||||||
.add(EditorSessionPlugin)
|
.add(EditorSessionPlugin)
|
||||||
.add(brp::BrpPlugin);
|
.add(brp::BrpPlugin);
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -13,6 +13,7 @@ use settings::{
|
|||||||
PROJECT_TEMPLATE_VERSION,
|
PROJECT_TEMPLATE_VERSION,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::native_dialog::{NativeDialogBroker, NativeDialogPlugin};
|
||||||
use crate::project_io::UserPreferences;
|
use crate::project_io::UserPreferences;
|
||||||
use crate::scene::recovery::atomic_write;
|
use crate::scene::recovery::atomic_write;
|
||||||
use crate::ui::theme::{
|
use crate::ui::theme::{
|
||||||
@@ -91,6 +92,7 @@ pub fn run_project_launcher() {
|
|||||||
..default()
|
..default()
|
||||||
}))
|
}))
|
||||||
.add_plugins(EguiPlugin::default())
|
.add_plugins(EguiPlugin::default())
|
||||||
|
.add_plugins(NativeDialogPlugin)
|
||||||
.init_resource::<ProjectLauncherUi>()
|
.init_resource::<ProjectLauncherUi>()
|
||||||
.add_systems(Startup, spawn_project_launcher_camera)
|
.add_systems(Startup, spawn_project_launcher_camera)
|
||||||
.add_systems(EguiPrimaryContextPass, project_launcher_ui_system);
|
.add_systems(EguiPrimaryContextPass, project_launcher_ui_system);
|
||||||
@@ -208,9 +210,24 @@ fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLau
|
|||||||
egui::RichText::new("Select a root containing assets/project.ron").color(TEXT_DIM),
|
egui::RichText::new("Select a root containing assets/project.ron").color(TEXT_DIM),
|
||||||
);
|
);
|
||||||
ui.add_space(8.0);
|
ui.add_space(8.0);
|
||||||
if ui.button("Browse Existing...").clicked() {
|
let dialog_pending = world.resource::<NativeDialogBroker>().is_pending();
|
||||||
if let Some(root) = rfd::FileDialog::new().pick_folder() {
|
if ui
|
||||||
open_project_from_launcher(world, state, root);
|
.add_enabled(!dialog_pending, egui::Button::new("Browse Existing..."))
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| rfd::FileDialog::new().pick_folder(),
|
||||||
|
|world, root| {
|
||||||
|
let Some(root) = root else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
world.resource_scope(|world, mut state: Mut<ProjectLauncherUi>| {
|
||||||
|
open_project_from_launcher(world, &mut state, root);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if let Err(error) = result {
|
||||||
|
state.status = Some(format!("Project browser unavailable: {error}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,8 +256,23 @@ fn launcher_actions(world: &mut World, ui: &mut egui::Ui, state: &mut ProjectLau
|
|||||||
)
|
)
|
||||||
.truncate(),
|
.truncate(),
|
||||||
);
|
);
|
||||||
if ui.button("Choose Empty Folder...").clicked() {
|
if ui
|
||||||
state.sandbox_destination = rfd::FileDialog::new().pick_folder();
|
.add_enabled(!dialog_pending, egui::Button::new("Choose Empty Folder..."))
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| rfd::FileDialog::new().pick_folder(),
|
||||||
|
|world, destination| {
|
||||||
|
if let Some(destination) = destination {
|
||||||
|
world
|
||||||
|
.resource_mut::<ProjectLauncherUi>()
|
||||||
|
.sandbox_destination = Some(destination);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if let Err(error) = result {
|
||||||
|
state.status = Some(format!("Folder browser unavailable: {error}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let can_create =
|
let can_create =
|
||||||
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
|
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
//! Project workspace I/O, settings UI, and recent-level sync.
|
//! Project workspace I/O, settings UI, and recent-level sync.
|
||||||
|
|
||||||
|
pub mod collaboration;
|
||||||
pub mod diagnostics_bundle;
|
pub mod diagnostics_bundle;
|
||||||
pub mod launcher;
|
pub mod launcher;
|
||||||
|
pub mod native_dialog;
|
||||||
pub mod project_io;
|
pub mod project_io;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod settings_ui;
|
pub mod settings_ui;
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
//! Non-blocking bridge between native dialogs and main-thread editor workflows.
|
||||||
|
|
||||||
|
use std::sync::mpsc::{self, Receiver, Sender};
|
||||||
|
use std::sync::{
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
Arc, Mutex,
|
||||||
|
};
|
||||||
|
|
||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
type MainThreadCompletion = Box<dyn FnOnce(&mut World) + Send + 'static>;
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
pub struct NativeDialogBroker {
|
||||||
|
sender: Sender<MainThreadCompletion>,
|
||||||
|
receiver: Mutex<Receiver<MainThreadCompletion>>,
|
||||||
|
pending: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for NativeDialogBroker {
|
||||||
|
fn default() -> Self {
|
||||||
|
let (sender, receiver) = mpsc::channel();
|
||||||
|
Self {
|
||||||
|
sender,
|
||||||
|
receiver: Mutex::new(receiver),
|
||||||
|
pending: Arc::new(AtomicUsize::new(0)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NativeDialogBroker {
|
||||||
|
pub fn is_pending(&self) -> bool {
|
||||||
|
self.pending.load(Ordering::Acquire) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request<T, D, C>(&self, dialog: D, completion: C) -> Result<(), &'static str>
|
||||||
|
where
|
||||||
|
T: Send + 'static,
|
||||||
|
D: FnOnce() -> T + Send + 'static,
|
||||||
|
C: FnOnce(&mut World, T) + Send + 'static,
|
||||||
|
{
|
||||||
|
if self
|
||||||
|
.pending
|
||||||
|
.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
return Err("another native dialog is already open");
|
||||||
|
}
|
||||||
|
|
||||||
|
let sender = self.sender.clone();
|
||||||
|
let pending = Arc::clone(&self.pending);
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let result = dialog();
|
||||||
|
let callback: MainThreadCompletion = Box::new(move |world| completion(world, result));
|
||||||
|
if sender.send(callback).is_err() {
|
||||||
|
pending.store(0, Ordering::Release);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NativeDialogPlugin;
|
||||||
|
|
||||||
|
impl Plugin for NativeDialogPlugin {
|
||||||
|
fn build(&self, app: &mut App) {
|
||||||
|
app.init_resource::<NativeDialogBroker>()
|
||||||
|
.add_systems(Update, drain_native_dialog_results);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain_native_dialog_results(world: &mut World) {
|
||||||
|
let callbacks: Vec<_> = {
|
||||||
|
let broker = world.resource::<NativeDialogBroker>();
|
||||||
|
broker
|
||||||
|
.receiver
|
||||||
|
.lock()
|
||||||
|
.expect("native dialog receiver poisoned")
|
||||||
|
.try_iter()
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
for callback in callbacks {
|
||||||
|
world
|
||||||
|
.resource::<NativeDialogBroker>()
|
||||||
|
.pending
|
||||||
|
.store(0, Ordering::Release);
|
||||||
|
callback(world);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[derive(Resource, Default)]
|
||||||
|
struct ResultValue(Option<u32>);
|
||||||
|
|
||||||
|
#[derive(Resource, Default)]
|
||||||
|
struct FrameCount(u32);
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn request_is_exclusive_and_completion_runs_once() {
|
||||||
|
let mut app = App::new();
|
||||||
|
app.add_plugins(NativeDialogPlugin)
|
||||||
|
.init_resource::<ResultValue>();
|
||||||
|
app.world()
|
||||||
|
.resource::<NativeDialogBroker>()
|
||||||
|
.request(
|
||||||
|
|| 42,
|
||||||
|
|world, value| world.resource_mut::<ResultValue>().0 = Some(value),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(app
|
||||||
|
.world()
|
||||||
|
.resource::<NativeDialogBroker>()
|
||||||
|
.request(|| 7, |_, _| {})
|
||||||
|
.is_err());
|
||||||
|
|
||||||
|
for _ in 0..100 {
|
||||||
|
app.update();
|
||||||
|
if app.world().resource::<ResultValue>().0.is_some() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::thread::yield_now();
|
||||||
|
}
|
||||||
|
assert_eq!(app.world().resource::<ResultValue>().0, Some(42));
|
||||||
|
app.update();
|
||||||
|
assert_eq!(app.world().resource::<ResultValue>().0, Some(42));
|
||||||
|
assert!(!app.world().resource::<NativeDialogBroker>().is_pending());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blocked_dialog_worker_does_not_block_app_frames() {
|
||||||
|
let mut app = App::new();
|
||||||
|
app.add_plugins(NativeDialogPlugin)
|
||||||
|
.init_resource::<ResultValue>()
|
||||||
|
.init_resource::<FrameCount>()
|
||||||
|
.add_systems(Update, |mut frames: ResMut<FrameCount>| frames.0 += 1);
|
||||||
|
let (release_sender, release_receiver) = mpsc::channel();
|
||||||
|
app.world()
|
||||||
|
.resource::<NativeDialogBroker>()
|
||||||
|
.request(
|
||||||
|
move || {
|
||||||
|
release_receiver
|
||||||
|
.recv()
|
||||||
|
.expect("test release sender dropped")
|
||||||
|
},
|
||||||
|
|world, value| world.resource_mut::<ResultValue>().0 = Some(value),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for _ in 0..8 {
|
||||||
|
app.update();
|
||||||
|
}
|
||||||
|
assert_eq!(app.world().resource::<FrameCount>().0, 8);
|
||||||
|
assert_eq!(app.world().resource::<ResultValue>().0, None);
|
||||||
|
assert!(app.world().resource::<NativeDialogBroker>().is_pending());
|
||||||
|
|
||||||
|
release_sender.send(73).unwrap();
|
||||||
|
for _ in 0..100 {
|
||||||
|
app.update();
|
||||||
|
if app.world().resource::<ResultValue>().0.is_some() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::thread::yield_now();
|
||||||
|
}
|
||||||
|
assert_eq!(app.world().resource::<ResultValue>().0, Some(73));
|
||||||
|
assert!(app.world().resource::<FrameCount>().0 > 8);
|
||||||
|
assert!(!app.world().resource::<NativeDialogBroker>().is_pending());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,28 @@
|
|||||||
//! Editor-only Project Settings panel (egui). Data lives in the `settings` crate.
|
//! Editor-only Project Settings panel (egui). Data lives in the `settings` crate.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
use bevy_egui::egui;
|
use bevy_egui::egui;
|
||||||
use game_hot::sync_project_sun_from_settings;
|
use game_hot::sync_project_sun_from_settings;
|
||||||
use settings::{
|
use settings::{
|
||||||
load_project_settings_from_path, save_project_settings, sync_sim_tuning, ExposureMode,
|
save_project_settings_to_string, sync_sim_tuning, ExposureMode, ProjectSettings,
|
||||||
ProjectSettings, ProjectSettingsChanged, ProjectSettingsIo,
|
ProjectSettingsChanged, ProjectSettingsIo,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::project::collaboration::{
|
||||||
|
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
|
||||||
|
FileWriteIntent,
|
||||||
|
};
|
||||||
|
use crate::scene_io::SceneIo;
|
||||||
|
|
||||||
/// Whether the Project Settings window is visible (editor UI state only).
|
/// Whether the Project Settings window is visible (editor UI state only).
|
||||||
#[derive(Resource, Debug, Default)]
|
#[derive(Resource, Debug, Default)]
|
||||||
pub struct ProjectSettingsPanel {
|
pub struct ProjectSettingsPanel {
|
||||||
pub open: bool,
|
pub open: bool,
|
||||||
pub draft: Option<ProjectSettings>,
|
pub draft: Option<ProjectSettings>,
|
||||||
|
disk_snapshot: Option<FileSnapshot>,
|
||||||
|
save_error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SettingsUiPlugin;
|
pub struct SettingsUiPlugin;
|
||||||
@@ -39,11 +49,23 @@ pub fn project_settings_window(
|
|||||||
) {
|
) {
|
||||||
if !panel.open {
|
if !panel.open {
|
||||||
panel.draft = None;
|
panel.draft = None;
|
||||||
|
panel.disk_snapshot = None;
|
||||||
|
panel.save_error = None;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if panel.draft.is_none() {
|
if panel.draft.is_none() {
|
||||||
panel.draft = Some(world.resource::<ProjectSettings>().clone());
|
panel.draft = Some(world.resource::<ProjectSettings>().clone());
|
||||||
|
let io = world.resource::<ProjectSettingsIo>();
|
||||||
|
panel.disk_snapshot = Some(
|
||||||
|
io.loaded_source
|
||||||
|
.as_deref()
|
||||||
|
.map(|source| {
|
||||||
|
FileSnapshot::from_loaded_bytes(Path::new(&io.path), source.as_bytes())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(FileSnapshot::missing),
|
||||||
|
);
|
||||||
|
panel.save_error = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut open = panel.open;
|
let mut open = panel.open;
|
||||||
@@ -51,17 +73,33 @@ pub fn project_settings_window(
|
|||||||
.open(&mut open)
|
.open(&mut open)
|
||||||
.default_width(420.0)
|
.default_width(420.0)
|
||||||
.show(ctx, |ui| {
|
.show(ctx, |ui| {
|
||||||
let Some(draft) = panel.draft.as_mut() else {
|
let ProjectSettingsPanel {
|
||||||
|
draft: Some(draft),
|
||||||
|
disk_snapshot,
|
||||||
|
save_error,
|
||||||
|
..
|
||||||
|
} = panel
|
||||||
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let io_path = world.resource::<ProjectSettingsIo>().path.clone();
|
let io_path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||||
let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty;
|
let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty;
|
||||||
draw_project_settings_form(world, ui, draft, &io_path, &mut io_dirty);
|
draw_project_settings_form(
|
||||||
|
world,
|
||||||
|
ui,
|
||||||
|
draft,
|
||||||
|
&io_path,
|
||||||
|
&mut io_dirty,
|
||||||
|
disk_snapshot,
|
||||||
|
save_error,
|
||||||
|
);
|
||||||
world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty;
|
world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty;
|
||||||
});
|
});
|
||||||
panel.open = open;
|
panel.open = open;
|
||||||
if !open {
|
if !open {
|
||||||
panel.draft = None;
|
panel.draft = None;
|
||||||
|
panel.disk_snapshot = None;
|
||||||
|
panel.save_error = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,12 +109,26 @@ fn draw_project_settings_form(
|
|||||||
draft: &mut ProjectSettings,
|
draft: &mut ProjectSettings,
|
||||||
io_path: &str,
|
io_path: &str,
|
||||||
io_dirty: &mut bool,
|
io_dirty: &mut bool,
|
||||||
|
disk_snapshot: &mut Option<FileSnapshot>,
|
||||||
|
save_error: &mut Option<String>,
|
||||||
) {
|
) {
|
||||||
let caps = world
|
let caps = world
|
||||||
.get_resource::<settings::RenderingCapabilities>()
|
.get_resource::<settings::RenderingCapabilities>()
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.small(egui::RichText::new(io_path).monospace());
|
||||||
|
if let Some(state) = world.get_resource::<CollaborationState>() {
|
||||||
|
let status = state.file_status(Path::new(io_path));
|
||||||
|
let _ = file_status_indicator_ui(ui, &status, Path::new(io_path));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(error) = save_error.as_deref() {
|
||||||
|
ui.colored_label(crate::ui::theme::ERROR, error);
|
||||||
|
}
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
ui.collapsing("Global Illumination", |ui| {
|
ui.collapsing("Global Illumination", |ui| {
|
||||||
egui::ComboBox::from_label("GiMode")
|
egui::ComboBox::from_label("GiMode")
|
||||||
.selected_text(format!("{:?}", draft.rendering.gi_mode))
|
.selected_text(format!("{:?}", draft.rendering.gi_mode))
|
||||||
@@ -335,25 +387,116 @@ fn draw_project_settings_form(
|
|||||||
.clicked()
|
.clicked()
|
||||||
{
|
{
|
||||||
commit_project_settings(world, draft);
|
commit_project_settings(world, draft);
|
||||||
|
*io_dirty = true;
|
||||||
let settings = world.resource::<ProjectSettings>().clone();
|
let settings = world.resource::<ProjectSettings>().clone();
|
||||||
|
let Some(expected) = disk_snapshot.clone() else {
|
||||||
|
let error = "Project settings disk baseline is unavailable; reload before saving";
|
||||||
|
*save_error = Some(error.into());
|
||||||
|
world.resource_mut::<SceneIo>().set_status(error);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match persist_project_settings(world, &settings, &expected) {
|
||||||
|
Ok((snapshot, source)) => {
|
||||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||||
if let Err(error) = save_project_settings(&settings, &mut io) {
|
io.dirty = false;
|
||||||
warn!("Save project settings failed: {error}");
|
io.loaded_source = Some(source);
|
||||||
} else {
|
*disk_snapshot = Some(snapshot);
|
||||||
|
*save_error = None;
|
||||||
*io_dirty = false;
|
*io_dirty = false;
|
||||||
|
world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status(format!("Saved project settings to {io_path}"));
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Save project settings failed: {error}");
|
||||||
|
*save_error = Some(error.clone());
|
||||||
|
world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status(format!("Save project settings failed: {error}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ui.button("Revert from disk").clicked() {
|
if ui.button("Revert from disk").clicked() {
|
||||||
*draft = load_project_settings_from_path(io_path);
|
match read_project_settings_document(Path::new(io_path)) {
|
||||||
|
Ok((settings, source, snapshot)) => {
|
||||||
|
*draft = settings;
|
||||||
commit_project_settings(world, draft);
|
commit_project_settings(world, draft);
|
||||||
world.resource_mut::<ProjectSettingsIo>().dirty = false;
|
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||||
|
io.dirty = false;
|
||||||
|
io.loaded_source = Some(source);
|
||||||
|
*disk_snapshot = Some(snapshot);
|
||||||
|
*save_error = None;
|
||||||
*io_dirty = false;
|
*io_dirty = false;
|
||||||
}
|
}
|
||||||
|
Err(error) => {
|
||||||
|
*save_error = Some(error.clone());
|
||||||
|
world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status(format!("Revert project settings failed: {error}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if *io_dirty {
|
if *io_dirty {
|
||||||
ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW));
|
ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn persist_project_settings(
|
||||||
|
world: &mut World,
|
||||||
|
settings: &ProjectSettings,
|
||||||
|
expected: &FileSnapshot,
|
||||||
|
) -> Result<(FileSnapshot, String), String> {
|
||||||
|
let path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||||
|
let source = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
|
||||||
|
let snapshot = publish_authored_file(
|
||||||
|
world,
|
||||||
|
Path::new(&path),
|
||||||
|
source.as_bytes(),
|
||||||
|
expected,
|
||||||
|
FileWriteIntent::ProjectSettings,
|
||||||
|
)?;
|
||||||
|
Ok((snapshot, source))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_project_settings_document(
|
||||||
|
path: &Path,
|
||||||
|
) -> Result<(ProjectSettings, String, FileSnapshot), String> {
|
||||||
|
let source = std::fs::read_to_string(path)
|
||||||
|
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
|
||||||
|
let settings: ProjectSettings = ron::from_str(&source)
|
||||||
|
.map_err(|error| format!("invalid project settings in {}: {error}", path.display()))?;
|
||||||
|
let snapshot = FileSnapshot::from_loaded_bytes(path, source.as_bytes());
|
||||||
|
Ok((settings, source, snapshot))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn reload_project_settings_after_file_conflict(
|
||||||
|
world: &mut World,
|
||||||
|
path: &Path,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let active_path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||||
|
if Path::new(&active_path) != path {
|
||||||
|
return Err("the project settings conflict no longer matches the active manifest".into());
|
||||||
|
}
|
||||||
|
let (settings, source, snapshot) = read_project_settings_document(path)?;
|
||||||
|
commit_project_settings(world, &settings);
|
||||||
|
{
|
||||||
|
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||||
|
io.dirty = false;
|
||||||
|
io.loaded_source = Some(source);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut panel = world.resource_mut::<ProjectSettingsPanel>();
|
||||||
|
panel.draft = Some(settings);
|
||||||
|
panel.disk_snapshot = Some(snapshot);
|
||||||
|
panel.save_error = None;
|
||||||
|
}
|
||||||
|
Ok(format!("Reloaded project settings from {}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn project_settings_conflict_copy_saved(world: &mut World) {
|
||||||
|
world.resource_mut::<ProjectSettingsPanel>().save_error = None;
|
||||||
|
}
|
||||||
|
|
||||||
fn commit_project_settings(world: &mut World, draft: &ProjectSettings) {
|
fn commit_project_settings(world: &mut World, draft: &ProjectSettings) {
|
||||||
let previous = world.resource::<ProjectSettings>().rendering.gi_mode;
|
let previous = world.resource::<ProjectSettings>().rendering.gi_mode;
|
||||||
*world.resource_mut::<ProjectSettings>() = draft.clone();
|
*world.resource_mut::<ProjectSettings>() = draft.clone();
|
||||||
@@ -406,3 +549,35 @@ fn apply_project_settings_changes(
|
|||||||
// Full stack refresh runs next frame via `render_view::sync_project_render_view`
|
// Full stack refresh runs next frame via `render_view::sync_project_render_view`
|
||||||
// when `ProjectSettings` changes.
|
// when `ProjectSettings` changes.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn project_settings_save_refuses_an_external_revision() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-project-settings-external-write-{}",
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
));
|
||||||
|
let path = root.join("assets/project.ron");
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
let loaded = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
|
||||||
|
std::fs::write(&path, &loaded).unwrap();
|
||||||
|
let expected = FileSnapshot::from_loaded_bytes(&path, loaded.as_bytes());
|
||||||
|
let mut world = World::new();
|
||||||
|
world.insert_resource(ProjectSettingsIo {
|
||||||
|
path: path.to_string_lossy().into_owned(),
|
||||||
|
loaded_source: Some(loaded),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
world.insert_resource(SceneIo::default());
|
||||||
|
std::fs::write(&path, b"external").unwrap();
|
||||||
|
|
||||||
|
let result = persist_project_settings(&mut world, &ProjectSettings::default(), &expected);
|
||||||
|
|
||||||
|
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||||
|
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,17 +13,20 @@ pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
|||||||
atomic_write_with_pre_rename(path, bytes, || Ok(()))
|
atomic_write_with_pre_rename(path, bytes, || Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn atomic_write_with_pre_rename(
|
pub(crate) fn atomic_write_with_pre_rename<E>(
|
||||||
path: &Path,
|
path: &Path,
|
||||||
bytes: &[u8],
|
bytes: &[u8],
|
||||||
before_rename: impl FnOnce() -> Result<(), String>,
|
before_rename: impl FnOnce() -> Result<(), E>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), E>
|
||||||
|
where
|
||||||
|
E: From<String>,
|
||||||
|
{
|
||||||
let parent = path
|
let parent = path
|
||||||
.parent()
|
.parent()
|
||||||
.filter(|parent| !parent.as_os_str().is_empty())
|
.filter(|parent| !parent.as_os_str().is_empty())
|
||||||
.unwrap_or_else(|| Path::new("."));
|
.unwrap_or_else(|| Path::new("."));
|
||||||
fs::create_dir_all(parent)
|
fs::create_dir_all(parent)
|
||||||
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
|
.map_err(|error| E::from(format!("could not create {}: {error}", parent.display())))?;
|
||||||
|
|
||||||
let file_name = path
|
let file_name = path
|
||||||
.file_name()
|
.file_name()
|
||||||
@@ -40,18 +43,21 @@ fn atomic_write_with_pre_rename(
|
|||||||
.create_new(true)
|
.create_new(true)
|
||||||
.write(true)
|
.write(true)
|
||||||
.open(&temporary)
|
.open(&temporary)
|
||||||
.map_err(|error| format!("could not create {}: {error}", temporary.display()))?;
|
.map_err(|error| {
|
||||||
file.write_all(bytes)
|
E::from(format!("could not create {}: {error}", temporary.display()))
|
||||||
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
|
})?;
|
||||||
|
file.write_all(bytes).map_err(|error| {
|
||||||
|
E::from(format!("could not write {}: {error}", temporary.display()))
|
||||||
|
})?;
|
||||||
file.sync_all()
|
file.sync_all()
|
||||||
.map_err(|error| format!("could not sync {}: {error}", temporary.display()))?;
|
.map_err(|error| E::from(format!("could not sync {}: {error}", temporary.display())))?;
|
||||||
before_rename()?;
|
before_rename()?;
|
||||||
fs::rename(&temporary, path).map_err(|error| {
|
fs::rename(&temporary, path).map_err(|error| {
|
||||||
format!(
|
E::from(format!(
|
||||||
"could not replace {} with {}: {error}",
|
"could not replace {} with {}: {error}",
|
||||||
path.display(),
|
path.display(),
|
||||||
temporary.display()
|
temporary.display()
|
||||||
)
|
))
|
||||||
})?;
|
})?;
|
||||||
sync_parent_directory(parent);
|
sync_parent_directory(parent);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
+501
-115
@@ -23,8 +23,10 @@ use shared::{
|
|||||||
|
|
||||||
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
|
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
|
||||||
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
|
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
|
||||||
|
use crate::native_dialog::NativeDialogBroker;
|
||||||
|
use crate::project::collaboration::{publish_authored_file, FileSnapshot, FileWriteIntent};
|
||||||
use crate::scene::recovery::{
|
use crate::scene::recovery::{
|
||||||
atomic_write, default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
|
default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
|
||||||
write_recovery_snapshot,
|
write_recovery_snapshot,
|
||||||
};
|
};
|
||||||
use crate::selection::SelectedEntity;
|
use crate::selection::SelectedEntity;
|
||||||
@@ -60,6 +62,7 @@ pub struct SceneTab {
|
|||||||
pub dirty: bool,
|
pub dirty: bool,
|
||||||
snapshot: String,
|
snapshot: String,
|
||||||
recovery_snapshot: Option<PathBuf>,
|
recovery_snapshot: Option<PathBuf>,
|
||||||
|
disk_snapshot: Option<FileSnapshot>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SceneTab {
|
impl SceneTab {
|
||||||
@@ -80,8 +83,6 @@ pub struct SceneIo {
|
|||||||
pub request: Option<SceneIoRequest>,
|
pub request: Option<SceneIoRequest>,
|
||||||
pub status: String,
|
pub status: String,
|
||||||
pub dirty: bool,
|
pub dirty: bool,
|
||||||
/// When set, the next I/O request needs unsaved-changes confirmation.
|
|
||||||
pub pending_request: Option<SceneIoRequest>,
|
|
||||||
/// Newest recovery snapshot that is newer than the active authored scene.
|
/// Newest recovery snapshot that is newer than the active authored scene.
|
||||||
pub recovery_snapshot: Option<PathBuf>,
|
pub recovery_snapshot: Option<PathBuf>,
|
||||||
/// Bounded in-session audit trail for scene persistence and recovery operations.
|
/// Bounded in-session audit trail for scene persistence and recovery operations.
|
||||||
@@ -117,7 +118,6 @@ impl Default for SceneIo {
|
|||||||
request: None,
|
request: None,
|
||||||
status: "Ready".to_string(),
|
status: "Ready".to_string(),
|
||||||
dirty: false,
|
dirty: false,
|
||||||
pending_request: None,
|
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
events: VecDeque::new(),
|
events: VecDeque::new(),
|
||||||
tabs: vec![SceneTab {
|
tabs: vec![SceneTab {
|
||||||
@@ -126,6 +126,7 @@ impl Default for SceneIo {
|
|||||||
dirty: false,
|
dirty: false,
|
||||||
snapshot: String::new(),
|
snapshot: String::new(),
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
|
disk_snapshot: None,
|
||||||
}],
|
}],
|
||||||
active_tab: 0,
|
active_tab: 0,
|
||||||
change_revision: 0,
|
change_revision: 0,
|
||||||
@@ -252,9 +253,14 @@ fn load_startup_scene(world: &mut World) {
|
|||||||
let path = active_path.unwrap_or(default_path);
|
let path = active_path.unwrap_or(default_path);
|
||||||
|
|
||||||
match load_level(world, &path) {
|
match load_level(world, &path) {
|
||||||
Ok(()) => {
|
Ok(disk_snapshot) => {
|
||||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
{
|
||||||
world.resource_mut::<SceneIo>().mark_clean();
|
let mut io = world.resource_mut::<SceneIo>();
|
||||||
|
io.active_path = Some(path.clone());
|
||||||
|
let active_tab = io.active_tab;
|
||||||
|
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||||
|
io.mark_clean();
|
||||||
|
}
|
||||||
remember_path(world, path.clone());
|
remember_path(world, path.clone());
|
||||||
world.resource_mut::<EditorHistory>().clear();
|
world.resource_mut::<EditorHistory>().clear();
|
||||||
refresh_recovery_notice(world, &path);
|
refresh_recovery_notice(world, &path);
|
||||||
@@ -283,40 +289,16 @@ fn load_startup_scene(world: &mut World) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn process_scene_io_requests(world: &mut World) {
|
fn process_scene_io_requests(world: &mut World) {
|
||||||
let request = {
|
let Some(request) = world.resource_mut::<SceneIo>().request.take() else {
|
||||||
let mut io = world.resource_mut::<SceneIo>();
|
|
||||||
if let Some(pending) = io.pending_request.take() {
|
|
||||||
pending
|
|
||||||
} else {
|
|
||||||
match io.request.take() {
|
|
||||||
Some(req) if io.has_unsaved_tabs() && needs_dirty_confirm(&req) => {
|
|
||||||
io.pending_request = Some(req);
|
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
Some(req) => req,
|
|
||||||
None => return,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if world.resource::<SceneIo>().has_unsaved_tabs() && needs_dirty_confirm(&request) {
|
if matches!(request, SceneIoRequest::SwitchProject)
|
||||||
match confirm_discard_or_save() {
|
&& world.resource::<SceneIo>().has_unsaved_tabs()
|
||||||
DirtyConfirm::Save => {
|
{
|
||||||
let save_status = save_all_tabs(world);
|
request_switch_project_confirmation(world);
|
||||||
if save_status.starts_with("Save failed") || save_status.ends_with("cancelled") {
|
|
||||||
world.resource_mut::<SceneIo>().set_status(save_status);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
DirtyConfirm::Discard => {}
|
|
||||||
DirtyConfirm::Cancel => {
|
|
||||||
world
|
|
||||||
.resource_mut::<SceneIo>()
|
|
||||||
.set_status("Operation cancelled");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let status = match request {
|
let status = match request {
|
||||||
SceneIoRequest::New => new_scene_tab(world),
|
SceneIoRequest::New => new_scene_tab(world),
|
||||||
@@ -340,16 +322,6 @@ fn process_scene_io_requests(world: &mut World) {
|
|||||||
world.resource_mut::<SceneIo>().set_status(status);
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
}
|
}
|
||||||
|
|
||||||
enum DirtyConfirm {
|
|
||||||
Save,
|
|
||||||
Discard,
|
|
||||||
Cancel,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn needs_dirty_confirm(request: &SceneIoRequest) -> bool {
|
|
||||||
matches!(request, SceneIoRequest::SwitchProject)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn switch_project(world: &mut World) -> String {
|
fn switch_project(world: &mut World) -> String {
|
||||||
match crate::launcher::spawn_project_launcher_process() {
|
match crate::launcher::spawn_project_launcher_process() {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
@@ -360,20 +332,42 @@ fn switch_project(world: &mut World) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn confirm_discard_or_save() -> DirtyConfirm {
|
fn request_switch_project_confirmation(world: &mut World) {
|
||||||
use rfd::{MessageButtons, MessageDialog, MessageLevel};
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
match MessageDialog::new()
|
|| {
|
||||||
|
rfd::MessageDialog::new()
|
||||||
.set_title("Unsaved Changes")
|
.set_title("Unsaved Changes")
|
||||||
.set_description("The scene has unsaved changes. Save before continuing?")
|
.set_description("The scene has unsaved changes. Save before continuing?")
|
||||||
.set_level(MessageLevel::Warning)
|
.set_level(rfd::MessageLevel::Warning)
|
||||||
.set_buttons(MessageButtons::YesNoCancel)
|
.set_buttons(rfd::MessageButtons::YesNoCancel)
|
||||||
.show()
|
.show()
|
||||||
{
|
},
|
||||||
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
|
|world, decision| match decision {
|
||||||
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
|
rfd::MessageDialogResult::Yes => {
|
||||||
_ => DirtyConfirm::Cancel,
|
let status = save_all_tabs(world);
|
||||||
|
if status == "Saved all modified scene tabs" {
|
||||||
|
let status = switch_project(world);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
} else {
|
||||||
|
world.resource_mut::<SceneIo>().set_status(format!(
|
||||||
|
"Project switch paused until every scene is saved: {status}"
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
rfd::MessageDialogResult::No => {
|
||||||
|
let status = switch_project(world);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
}
|
||||||
|
_ => world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status("Project switch cancelled"),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(match result {
|
||||||
|
Ok(()) => "Waiting for unsaved-scene confirmation".into(),
|
||||||
|
Err(error) => format!("Project switch unavailable: {error}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn open_recent(world: &mut World, index: usize) -> String {
|
fn open_recent(world: &mut World, index: usize) -> String {
|
||||||
let path = world.resource::<SceneIo>().recent_paths.get(index).cloned();
|
let path = world.resource::<SceneIo>().recent_paths.get(index).cloned();
|
||||||
@@ -396,7 +390,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
|
|||||||
return format!("Open failed: could not preserve active scene: {error}");
|
return format!("Open failed: could not preserve active scene: {error}");
|
||||||
}
|
}
|
||||||
match load_level(world, &path) {
|
match load_level(world, &path) {
|
||||||
Ok(()) => {
|
Ok(disk_snapshot) => {
|
||||||
let id = world.resource_mut::<SceneIo>().allocate_tab_id();
|
let id = world.resource_mut::<SceneIo>().allocate_tab_id();
|
||||||
{
|
{
|
||||||
let mut io = world.resource_mut::<SceneIo>();
|
let mut io = world.resource_mut::<SceneIo>();
|
||||||
@@ -406,6 +400,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
|
|||||||
dirty: false,
|
dirty: false,
|
||||||
snapshot: String::new(),
|
snapshot: String::new(),
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
|
disk_snapshot: Some(disk_snapshot),
|
||||||
});
|
});
|
||||||
io.active_tab = io.tabs.len() - 1;
|
io.active_tab = io.tabs.len() - 1;
|
||||||
io.active_path = Some(path.clone());
|
io.active_path = Some(path.clone());
|
||||||
@@ -442,6 +437,7 @@ fn new_scene_tab(world: &mut World) -> String {
|
|||||||
dirty: false,
|
dirty: false,
|
||||||
snapshot: String::new(),
|
snapshot: String::new(),
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
|
disk_snapshot: None,
|
||||||
});
|
});
|
||||||
io.active_tab = io.tabs.len() - 1;
|
io.active_tab = io.tabs.len() - 1;
|
||||||
io.active_path = None;
|
io.active_path = None;
|
||||||
@@ -523,18 +519,14 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if world.resource::<SceneIo>().dirty {
|
if world.resource::<SceneIo>().dirty {
|
||||||
match confirm_close_scene() {
|
request_close_scene_confirmation(world);
|
||||||
DirtyConfirm::Save => {
|
return "Waiting for close-scene confirmation".to_string();
|
||||||
let status = save_active_or_prompt(world);
|
|
||||||
if status.starts_with("Save failed") || status.ends_with("cancelled") {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DirtyConfirm::Discard => {}
|
|
||||||
DirtyConfirm::Cancel => return "Close scene cancelled".to_string(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
finish_close_scene_tab(world)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_close_scene_tab(world: &mut World) -> String {
|
||||||
if world.resource::<SceneIo>().tabs.len() == 1 {
|
if world.resource::<SceneIo>().tabs.len() == 1 {
|
||||||
clear_scene_world(world);
|
clear_scene_world(world);
|
||||||
world.insert_resource(SceneComposition {
|
world.insert_resource(SceneComposition {
|
||||||
@@ -550,6 +542,7 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
|
|||||||
dirty: false,
|
dirty: false,
|
||||||
snapshot: String::new(),
|
snapshot: String::new(),
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
|
disk_snapshot: None,
|
||||||
}];
|
}];
|
||||||
io.active_tab = 0;
|
io.active_tab = 0;
|
||||||
io.active_path = None;
|
io.active_path = None;
|
||||||
@@ -607,18 +600,36 @@ fn reload_active_composition(world: &mut World) -> String {
|
|||||||
"Reloaded active scene composition".to_string()
|
"Reloaded active scene composition".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn confirm_close_scene() -> DirtyConfirm {
|
fn request_close_scene_confirmation(world: &mut World) {
|
||||||
use rfd::{MessageButtons, MessageDialog, MessageLevel};
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
match MessageDialog::new()
|
|| {
|
||||||
|
rfd::MessageDialog::new()
|
||||||
.set_title("Close Scene")
|
.set_title("Close Scene")
|
||||||
.set_description("This scene tab has unsaved changes. Save before closing it?")
|
.set_description("This scene tab has unsaved changes. Save before closing it?")
|
||||||
.set_level(MessageLevel::Warning)
|
.set_level(rfd::MessageLevel::Warning)
|
||||||
.set_buttons(MessageButtons::YesNoCancel)
|
.set_buttons(rfd::MessageButtons::YesNoCancel)
|
||||||
.show()
|
.show()
|
||||||
{
|
},
|
||||||
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
|
|world, decision| {
|
||||||
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
|
let status = match decision {
|
||||||
_ => DirtyConfirm::Cancel,
|
rfd::MessageDialogResult::Yes => {
|
||||||
|
let save_status = save_active_or_prompt(world);
|
||||||
|
if save_status.starts_with("Saved ") {
|
||||||
|
finish_close_scene_tab(world)
|
||||||
|
} else {
|
||||||
|
format!("Close scene paused until it is saved: {save_status}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rfd::MessageDialogResult::No => finish_close_scene_tab(world),
|
||||||
|
_ => "Close scene cancelled".to_string(),
|
||||||
|
};
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if let Err(error) = result {
|
||||||
|
world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status(format!("Close scene unavailable: {error}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -683,20 +694,51 @@ fn save_selection_as_prefab(world: &mut World) -> String {
|
|||||||
return "Select level objects to save as prefab".to_string();
|
return "Select level objects to save as prefab".to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(path) = rfd::FileDialog::new()
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.set_directory("assets/prefabs")
|
.set_directory("assets/prefabs")
|
||||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||||
.set_file_name("prefab.scn.ron")
|
.set_file_name("prefab.scn.ron")
|
||||||
.save_file()
|
.save_file()
|
||||||
else {
|
},
|
||||||
|
move |world, path| {
|
||||||
|
let status = finish_save_selection_as_prefab(world, selection, path);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose a destination for the prefab".to_string(),
|
||||||
|
Err(error) => format!("Save prefab unavailable: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_save_selection_as_prefab(
|
||||||
|
world: &mut World,
|
||||||
|
selection: Vec<Entity>,
|
||||||
|
path: Option<PathBuf>,
|
||||||
|
) -> String {
|
||||||
|
let Some(path) = path else {
|
||||||
return "Save prefab cancelled".to_string();
|
return "Save prefab cancelled".to_string();
|
||||||
};
|
};
|
||||||
|
let expected = match FileSnapshot::capture(&path) {
|
||||||
|
Ok(expected) => expected,
|
||||||
|
Err(error) => return format!("Save prefab failed: {error}"),
|
||||||
|
};
|
||||||
|
|
||||||
if ensure_unique_actor_ids(world, &selection) > 0 {
|
if ensure_unique_actor_ids(world, &selection) > 0 {
|
||||||
world.resource_mut::<SceneIo>().mark_dirty();
|
world.resource_mut::<SceneIo>().mark_dirty();
|
||||||
}
|
}
|
||||||
|
|
||||||
match save_prefab_entities(world, &path, selection) {
|
match save_prefab_entities(
|
||||||
|
world,
|
||||||
|
&path,
|
||||||
|
selection,
|
||||||
|
SceneWriteContext::Standalone {
|
||||||
|
expected,
|
||||||
|
description: "prefab copy",
|
||||||
|
},
|
||||||
|
) {
|
||||||
Ok(count) => {
|
Ok(count) => {
|
||||||
world.resource_mut::<EditorAssets>().refresh();
|
world.resource_mut::<EditorAssets>().refresh();
|
||||||
format!(
|
format!(
|
||||||
@@ -775,6 +817,7 @@ fn save_prefab_entities(
|
|||||||
world: &mut World,
|
world: &mut World,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
entities: Vec<Entity>,
|
entities: Vec<Entity>,
|
||||||
|
write_context: SceneWriteContext,
|
||||||
) -> Result<usize, String> {
|
) -> Result<usize, String> {
|
||||||
let count = entities.len();
|
let count = entities.len();
|
||||||
let original_actor_ids: Vec<_> = entities
|
let original_actor_ids: Vec<_> = entities
|
||||||
@@ -791,7 +834,7 @@ fn save_prefab_entities(
|
|||||||
.clone(),
|
.clone(),
|
||||||
);
|
);
|
||||||
scene::validate_prefab_graph_text(&text, path, &project_root)?;
|
scene::validate_prefab_graph_text(&text, path, &project_root)?;
|
||||||
atomic_write(path, text.as_bytes())?;
|
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||||
Ok(count)
|
Ok(count)
|
||||||
})();
|
})();
|
||||||
if result.is_err() {
|
if result.is_err() {
|
||||||
@@ -821,7 +864,7 @@ pub fn save_active_or_prompt_world(world: &mut World) -> String {
|
|||||||
fn save_active_or_prompt(world: &mut World) -> String {
|
fn save_active_or_prompt(world: &mut World) -> String {
|
||||||
let path = world.resource::<SceneIo>().active_path.clone();
|
let path = world.resource::<SceneIo>().active_path.clone();
|
||||||
match path {
|
match path {
|
||||||
Some(path) => match save_level(world, &path) {
|
Some(path) => match save_level(world, &path, SceneWriteContext::Active) {
|
||||||
Ok(count) => {
|
Ok(count) => {
|
||||||
world.resource_mut::<SceneIo>().mark_clean();
|
world.resource_mut::<SceneIo>().mark_clean();
|
||||||
remember_path(world, path.clone());
|
remember_path(world, path.clone());
|
||||||
@@ -835,16 +878,35 @@ fn save_active_or_prompt(world: &mut World) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn save_with_dialog(world: &mut World) -> String {
|
fn save_with_dialog(world: &mut World) -> String {
|
||||||
let Some(path) = rfd::FileDialog::new()
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.set_directory("assets/levels")
|
.set_directory("assets/levels")
|
||||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||||
.set_file_name("editor_scene.scn.ron")
|
.set_file_name("editor_scene.scn.ron")
|
||||||
.save_file()
|
.save_file()
|
||||||
else {
|
},
|
||||||
|
|world, path| {
|
||||||
|
let status = finish_save_with_dialog(world, path);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose a scene destination".to_string(),
|
||||||
|
Err(error) => format!("Save unavailable: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_save_with_dialog(world: &mut World, path: Option<PathBuf>) -> String {
|
||||||
|
let Some(path) = path else {
|
||||||
return "Save cancelled".to_string();
|
return "Save cancelled".to_string();
|
||||||
};
|
};
|
||||||
|
let expected = match FileSnapshot::capture(&path) {
|
||||||
|
Ok(expected) => expected,
|
||||||
|
Err(error) => return format!("Save failed: {error}"),
|
||||||
|
};
|
||||||
|
|
||||||
match save_level(world, &path) {
|
match save_level(world, &path, SceneWriteContext::ActiveSaveAs { expected }) {
|
||||||
Ok(count) => {
|
Ok(count) => {
|
||||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||||
world.resource_mut::<SceneIo>().mark_clean();
|
world.resource_mut::<SceneIo>().mark_clean();
|
||||||
@@ -857,31 +919,51 @@ fn save_with_dialog(world: &mut World) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn open_with_dialog(world: &mut World) -> String {
|
fn open_with_dialog(world: &mut World) -> String {
|
||||||
let Some(path) = rfd::FileDialog::new()
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.set_directory("assets/levels")
|
.set_directory("assets/levels")
|
||||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||||
.pick_file()
|
.pick_file()
|
||||||
else {
|
},
|
||||||
return "Open cancelled".to_string();
|
|world, path| {
|
||||||
};
|
let status = path.map_or_else(
|
||||||
|
|| "Open cancelled".to_string(),
|
||||||
open_path(world, path)
|
|path| open_path(world, path),
|
||||||
|
);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose a scene to open".to_string(),
|
||||||
|
Err(error) => format!("Open unavailable: {error}"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn import_with_dialog(world: &mut World) -> String {
|
fn import_with_dialog(world: &mut World) -> String {
|
||||||
let Some(paths) = rfd::FileDialog::new()
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
|
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
|
||||||
.pick_files()
|
.pick_files()
|
||||||
else {
|
},
|
||||||
return "Import cancelled".to_string();
|
|world, paths| {
|
||||||
};
|
let status = match paths {
|
||||||
|
None => "Import cancelled".to_string(),
|
||||||
match import_external_assets(&paths) {
|
Some(paths) => match import_external_assets(&paths) {
|
||||||
Ok(count) => {
|
Ok(count) => {
|
||||||
world.resource_mut::<EditorAssets>().refresh();
|
world.resource_mut::<EditorAssets>().refresh();
|
||||||
format!("Imported {count} asset(s)")
|
format!("Imported {count} asset(s)")
|
||||||
}
|
}
|
||||||
Err(err) => format!("Import failed: {err}"),
|
Err(err) => format!("Import failed: {err}"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose assets to import".to_string(),
|
||||||
|
Err(error) => format!("Import unavailable: {error}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -893,16 +975,46 @@ fn export_selection_with_dialog(world: &mut World) -> String {
|
|||||||
return "Selected entity is not an authored level object".to_string();
|
return "Selected entity is not an authored level object".to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(path) = rfd::FileDialog::new()
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
|| {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.set_directory("assets/levels")
|
.set_directory("assets/levels")
|
||||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||||
.set_file_name("selection.scn.ron")
|
.set_file_name("selection.scn.ron")
|
||||||
.save_file()
|
.save_file()
|
||||||
else {
|
},
|
||||||
|
move |world, path| {
|
||||||
|
let status = finish_export_selection(world, entity, path);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose an export destination".to_string(),
|
||||||
|
Err(error) => format!("Export unavailable: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_export_selection(world: &mut World, entity: Entity, path: Option<PathBuf>) -> String {
|
||||||
|
let Some(path) = path else {
|
||||||
return "Export cancelled".to_string();
|
return "Export cancelled".to_string();
|
||||||
};
|
};
|
||||||
|
if snapshot_entity(world, entity).is_none() {
|
||||||
|
return "Export failed: the initiating selection no longer exists".to_string();
|
||||||
|
}
|
||||||
|
let expected = match FileSnapshot::capture(&path) {
|
||||||
|
Ok(expected) => expected,
|
||||||
|
Err(error) => return format!("Export failed: {error}"),
|
||||||
|
};
|
||||||
|
|
||||||
match save_standalone_entities(world, &path, vec![entity]) {
|
match save_standalone_entities(
|
||||||
|
world,
|
||||||
|
&path,
|
||||||
|
vec![entity],
|
||||||
|
SceneWriteContext::Standalone {
|
||||||
|
expected,
|
||||||
|
description: "selection export",
|
||||||
|
},
|
||||||
|
) {
|
||||||
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
|
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
|
||||||
Err(err) => format!("Export failed: {err}"),
|
Err(err) => format!("Export failed: {err}"),
|
||||||
}
|
}
|
||||||
@@ -934,12 +1046,16 @@ fn clear_scene_world(world: &mut World) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
|
fn save_level(
|
||||||
|
world: &mut World,
|
||||||
|
path: &Path,
|
||||||
|
write_context: SceneWriteContext,
|
||||||
|
) -> Result<usize, String> {
|
||||||
let entities = authored_scene_entities(world);
|
let entities = authored_scene_entities(world);
|
||||||
if is_prefab_document(path) {
|
if is_prefab_document(path) {
|
||||||
save_prefab_entities(world, path, entities)
|
save_prefab_entities(world, path, entities, write_context)
|
||||||
} else {
|
} else {
|
||||||
save_entities(world, path, entities)
|
save_entities(world, path, entities, write_context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -997,6 +1113,9 @@ fn format_actor_validation(err: ActorValidationError) -> String {
|
|||||||
ActorValidationError::InvalidBrushGeometry(message) => {
|
ActorValidationError::InvalidBrushGeometry(message) => {
|
||||||
format!("Save failed: invalid brush geometry: {message}")
|
format!("Save failed: invalid brush geometry: {message}")
|
||||||
}
|
}
|
||||||
|
ActorValidationError::InvalidTerrain(message) => {
|
||||||
|
format!("Save failed: invalid terrain: {message}")
|
||||||
|
}
|
||||||
ActorValidationError::StaticMeshMissingPrimitive => {
|
ActorValidationError::StaticMeshMissingPrimitive => {
|
||||||
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
|
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
|
||||||
.into()
|
.into()
|
||||||
@@ -1131,10 +1250,15 @@ fn format_actor_validation(err: ActorValidationError) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_entities(world: &mut World, path: &Path, entities: Vec<Entity>) -> Result<usize, String> {
|
fn save_entities(
|
||||||
|
world: &mut World,
|
||||||
|
path: &Path,
|
||||||
|
entities: Vec<Entity>,
|
||||||
|
write_context: SceneWriteContext,
|
||||||
|
) -> Result<usize, String> {
|
||||||
let count = entities.len();
|
let count = entities.len();
|
||||||
let text = serialize_entities(world, entities)?;
|
let text = serialize_entities(world, entities)?;
|
||||||
atomic_write(path, text.as_bytes())?;
|
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1142,13 +1266,108 @@ fn save_standalone_entities(
|
|||||||
world: &mut World,
|
world: &mut World,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
entities: Vec<Entity>,
|
entities: Vec<Entity>,
|
||||||
|
write_context: SceneWriteContext,
|
||||||
) -> Result<usize, String> {
|
) -> Result<usize, String> {
|
||||||
let count = entities.len();
|
let count = entities.len();
|
||||||
let text = serialize_standalone_entities(world, entities)?;
|
let text = serialize_standalone_entities(world, entities)?;
|
||||||
atomic_write(path, text.as_bytes())?;
|
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum SceneWriteContext {
|
||||||
|
Active,
|
||||||
|
ActiveSaveAs {
|
||||||
|
expected: FileSnapshot,
|
||||||
|
},
|
||||||
|
Standalone {
|
||||||
|
expected: FileSnapshot,
|
||||||
|
description: &'static str,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_scene_text(
|
||||||
|
world: &mut World,
|
||||||
|
path: &Path,
|
||||||
|
bytes: &[u8],
|
||||||
|
entity_count: usize,
|
||||||
|
context: SceneWriteContext,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match context {
|
||||||
|
SceneWriteContext::Active | SceneWriteContext::ActiveSaveAs { .. } => {
|
||||||
|
let (tab_id, expected) = match context {
|
||||||
|
SceneWriteContext::Active => active_scene_write_baseline(world, path)?,
|
||||||
|
SceneWriteContext::ActiveSaveAs { expected } => {
|
||||||
|
(active_scene_tab_id(world)?, expected)
|
||||||
|
}
|
||||||
|
SceneWriteContext::Standalone { .. } => unreachable!(),
|
||||||
|
};
|
||||||
|
let snapshot = publish_authored_file(
|
||||||
|
world,
|
||||||
|
path,
|
||||||
|
bytes,
|
||||||
|
&expected,
|
||||||
|
FileWriteIntent::Scene {
|
||||||
|
tab_id,
|
||||||
|
entity_count,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
let mut io = world.resource_mut::<SceneIo>();
|
||||||
|
let Some(tab) = io.tabs.iter_mut().find(|tab| tab.id == tab_id) else {
|
||||||
|
return Err("saved scene tab no longer exists".into());
|
||||||
|
};
|
||||||
|
tab.disk_snapshot = Some(snapshot);
|
||||||
|
}
|
||||||
|
SceneWriteContext::Standalone {
|
||||||
|
expected,
|
||||||
|
description,
|
||||||
|
} => {
|
||||||
|
publish_authored_file(
|
||||||
|
world,
|
||||||
|
path,
|
||||||
|
bytes,
|
||||||
|
&expected,
|
||||||
|
FileWriteIntent::Standalone {
|
||||||
|
description: description.into(),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_scene_write_baseline(
|
||||||
|
world: &World,
|
||||||
|
destination: &Path,
|
||||||
|
) -> Result<(u64, FileSnapshot), String> {
|
||||||
|
let io = world.resource::<SceneIo>();
|
||||||
|
let tab = io
|
||||||
|
.tabs
|
||||||
|
.get(io.active_tab)
|
||||||
|
.ok_or_else(|| "active scene tab is missing".to_string())?;
|
||||||
|
if io.active_path.as_deref() != Some(destination) || tab.path.as_deref() != Some(destination) {
|
||||||
|
return Err(format!(
|
||||||
|
"{} is not the active scene destination; use Save As",
|
||||||
|
destination.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let expected = tab.disk_snapshot.clone().ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"scene disk baseline is unavailable for {}; reload it or use Save As",
|
||||||
|
destination.display()
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok((tab.id, expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_scene_tab_id(world: &World) -> Result<u64, String> {
|
||||||
|
let io = world.resource::<SceneIo>();
|
||||||
|
io.tabs
|
||||||
|
.get(io.active_tab)
|
||||||
|
.map(|tab| tab.id)
|
||||||
|
.ok_or_else(|| "active scene tab is missing".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
fn serialize_entities(world: &mut World, entities: Vec<Entity>) -> Result<String, String> {
|
fn serialize_entities(world: &mut World, entities: Vec<Entity>) -> Result<String, String> {
|
||||||
serialize_entities_inner_with_resources(world, entities, true)
|
serialize_entities_inner_with_resources(world, entities, true)
|
||||||
}
|
}
|
||||||
@@ -1430,7 +1649,7 @@ fn restore_recovery(world: &mut World) -> String {
|
|||||||
return "No scene recovery snapshot is available".to_string();
|
return "No scene recovery snapshot is available".to_string();
|
||||||
};
|
};
|
||||||
match load_level(world, &snapshot) {
|
match load_level(world, &snapshot) {
|
||||||
Ok(()) => {
|
Ok(_) => {
|
||||||
mark_recovery_restored(&mut world.resource_mut::<SceneIo>(), active_path);
|
mark_recovery_restored(&mut world.resource_mut::<SceneIo>(), active_path);
|
||||||
world.resource_mut::<EditorHistory>().clear();
|
world.resource_mut::<EditorHistory>().clear();
|
||||||
format!(
|
format!(
|
||||||
@@ -1463,16 +1682,40 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|
|||||||
|| "recovered_scene.scn.ron".to_string(),
|
|| "recovered_scene.scn.ron".to_string(),
|
||||||
|stem| format!("{stem}.recovered.scn.ron"),
|
|stem| format!("{stem}.recovered.scn.ron"),
|
||||||
);
|
);
|
||||||
let Some(destination) = rfd::FileDialog::new()
|
let directory = directory.to_path_buf();
|
||||||
|
let request = world.resource::<NativeDialogBroker>().request(
|
||||||
|
move || {
|
||||||
|
rfd::FileDialog::new()
|
||||||
.set_directory(directory)
|
.set_directory(directory)
|
||||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||||
.set_file_name(file_name)
|
.set_file_name(file_name)
|
||||||
.save_file()
|
.save_file()
|
||||||
else {
|
},
|
||||||
|
move |world, destination| {
|
||||||
|
let status = finish_save_recovery_copy(world, snapshot, destination);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(status);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match request {
|
||||||
|
Ok(()) => "Choose a destination for the recovery copy".to_string(),
|
||||||
|
Err(error) => format!("Save recovery copy unavailable: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_save_recovery_copy(
|
||||||
|
world: &mut World,
|
||||||
|
snapshot: PathBuf,
|
||||||
|
destination: Option<PathBuf>,
|
||||||
|
) -> String {
|
||||||
|
let Some(destination) = destination else {
|
||||||
return "Save recovery copy cancelled".to_string();
|
return "Save recovery copy cancelled".to_string();
|
||||||
};
|
};
|
||||||
|
let expected = match FileSnapshot::capture(&destination) {
|
||||||
|
Ok(expected) => expected,
|
||||||
|
Err(error) => return format!("Save recovery copy failed: {error}"),
|
||||||
|
};
|
||||||
|
|
||||||
match write_recovery_copy(&snapshot, &destination) {
|
match write_recovery_copy(world, &snapshot, &destination, &expected) {
|
||||||
Ok(()) => format!(
|
Ok(()) => format!(
|
||||||
"Saved recovery copy {} from {}",
|
"Saved recovery copy {} from {}",
|
||||||
destination.display(),
|
destination.display(),
|
||||||
@@ -1482,10 +1725,24 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_recovery_copy(snapshot: &Path, destination: &Path) -> Result<(), String> {
|
fn write_recovery_copy(
|
||||||
|
world: &mut World,
|
||||||
|
snapshot: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
expected: &FileSnapshot,
|
||||||
|
) -> Result<(), String> {
|
||||||
let bytes = std::fs::read(snapshot)
|
let bytes = std::fs::read(snapshot)
|
||||||
.map_err(|error| format!("could not read {}: {error}", snapshot.display()))?;
|
.map_err(|error| format!("could not read {}: {error}", snapshot.display()))?;
|
||||||
atomic_write(destination, &bytes)
|
publish_authored_file(
|
||||||
|
world,
|
||||||
|
destination,
|
||||||
|
&bytes,
|
||||||
|
expected,
|
||||||
|
FileWriteIntent::Standalone {
|
||||||
|
description: "recovery scene copy".into(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mark_recovery_restored(io: &mut SceneIo, active_path: Option<PathBuf>) {
|
fn mark_recovery_restored(io: &mut SceneIo, active_path: Option<PathBuf>) {
|
||||||
@@ -1522,14 +1779,79 @@ fn discard_recovery(world: &mut World) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_level(world: &mut World, path: &Path) -> Result<(), String> {
|
fn load_level(world: &mut World, path: &Path) -> Result<FileSnapshot, String> {
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
return Err(format!("{} does not exist yet", path.display()));
|
return Err(format!("{} does not exist yet", path.display()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let text = std::fs::read_to_string(path)
|
let text = std::fs::read_to_string(path)
|
||||||
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
|
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
|
||||||
load_level_text(world, Some(path), &text)
|
let disk_snapshot = FileSnapshot::from_loaded_bytes(path, text.as_bytes());
|
||||||
|
load_level_text(world, Some(path), &text)?;
|
||||||
|
Ok(disk_snapshot)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn reload_scene_after_file_conflict(
|
||||||
|
world: &mut World,
|
||||||
|
tab_id: u64,
|
||||||
|
path: &Path,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let active_matches = {
|
||||||
|
let io = world.resource::<SceneIo>();
|
||||||
|
io.tabs
|
||||||
|
.get(io.active_tab)
|
||||||
|
.is_some_and(|tab| tab.id == tab_id)
|
||||||
|
};
|
||||||
|
if !active_matches {
|
||||||
|
return Err("the scene conflict no longer belongs to the active tab".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let disk_snapshot = load_level(world, path)?;
|
||||||
|
{
|
||||||
|
let mut io = world.resource_mut::<SceneIo>();
|
||||||
|
io.active_path = Some(path.to_path_buf());
|
||||||
|
io.recovery_snapshot = None;
|
||||||
|
let active_tab = io.active_tab;
|
||||||
|
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||||
|
io.mark_clean();
|
||||||
|
}
|
||||||
|
world.resource_mut::<EditorHistory>().clear();
|
||||||
|
remember_path(world, path.to_path_buf());
|
||||||
|
refresh_recovery_notice(world, path);
|
||||||
|
capture_active_tab(world)?;
|
||||||
|
Ok(format!("Reloaded {} from disk", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn adopt_scene_conflict_save_as(
|
||||||
|
world: &mut World,
|
||||||
|
tab_id: u64,
|
||||||
|
path: PathBuf,
|
||||||
|
disk_snapshot: FileSnapshot,
|
||||||
|
entity_count: usize,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let active_matches = {
|
||||||
|
let io = world.resource::<SceneIo>();
|
||||||
|
io.tabs
|
||||||
|
.get(io.active_tab)
|
||||||
|
.is_some_and(|tab| tab.id == tab_id)
|
||||||
|
};
|
||||||
|
if !active_matches {
|
||||||
|
return Err("the scene conflict no longer belongs to the active tab".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut io = world.resource_mut::<SceneIo>();
|
||||||
|
io.active_path = Some(path.clone());
|
||||||
|
let active_tab = io.active_tab;
|
||||||
|
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
|
||||||
|
io.mark_clean();
|
||||||
|
}
|
||||||
|
remember_path(world, path.clone());
|
||||||
|
retire_scene_recovery(world, &path);
|
||||||
|
Ok(format!(
|
||||||
|
"Saved {entity_count} level entities to {}",
|
||||||
|
path.display()
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_level_text(world: &mut World, path: Option<&Path>, text: &str) -> Result<(), String> {
|
fn load_level_text(world: &mut World, path: Option<&Path>, text: &str) -> Result<(), String> {
|
||||||
@@ -1979,6 +2301,7 @@ mod tests {
|
|||||||
dirty: true,
|
dirty: true,
|
||||||
snapshot: "dirty inactive tab".to_string(),
|
snapshot: "dirty inactive tab".to_string(),
|
||||||
recovery_snapshot: None,
|
recovery_snapshot: None,
|
||||||
|
disk_snapshot: None,
|
||||||
});
|
});
|
||||||
assert!(
|
assert!(
|
||||||
io.has_unsaved_tabs(),
|
io.has_unsaved_tabs(),
|
||||||
@@ -1993,6 +2316,61 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn active_scene_write_refuses_an_external_revision() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-scene-external-write-{}",
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
));
|
||||||
|
let path = root.join("assets/levels/main.scn.ron");
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&path, b"loaded").unwrap();
|
||||||
|
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
|
||||||
|
let mut io = SceneIo {
|
||||||
|
active_path: Some(path.clone()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
io.tabs[0].path = Some(path.clone());
|
||||||
|
io.tabs[0].disk_snapshot = Some(disk_snapshot);
|
||||||
|
let mut world = World::new();
|
||||||
|
world.insert_resource(io);
|
||||||
|
std::fs::write(&path, b"external").unwrap();
|
||||||
|
|
||||||
|
let result = publish_scene_text(&mut world, &path, b"editor", 1, SceneWriteContext::Active);
|
||||||
|
|
||||||
|
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||||
|
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||||
|
assert!(world.resource::<SceneIo>().dirty);
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scene_save_as_refuses_a_file_created_after_destination_selection() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-scene-save-as-race-{}",
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
));
|
||||||
|
let path = root.join("assets/levels/new.scn.ron");
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
let expected = FileSnapshot::missing();
|
||||||
|
let mut world = World::new();
|
||||||
|
world.init_resource::<SceneIo>();
|
||||||
|
std::fs::write(&path, b"external").unwrap();
|
||||||
|
|
||||||
|
let result = publish_scene_text(
|
||||||
|
&mut world,
|
||||||
|
&path,
|
||||||
|
b"editor",
|
||||||
|
1,
|
||||||
|
SceneWriteContext::ActiveSaveAs { expected },
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(result.unwrap_err().contains("changed outside Blacksite"));
|
||||||
|
assert_eq!(std::fs::read(&path).unwrap(), b"external");
|
||||||
|
assert!(world.resource::<SceneIo>().dirty);
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn composition_edits_participate_in_undo_and_redo() {
|
fn composition_edits_participate_in_undo_and_redo() {
|
||||||
let mut app = App::new();
|
let mut app = App::new();
|
||||||
@@ -2770,8 +3148,13 @@ mod tests {
|
|||||||
.insert_resource(crate::ui::hierarchy_state::HierarchyPanelState::default());
|
.insert_resource(crate::ui::hierarchy_state::HierarchyPanelState::default());
|
||||||
app.world_mut().init_resource::<SceneIo>();
|
app.world_mut().init_resource::<SceneIo>();
|
||||||
|
|
||||||
load_level(app.world_mut(), &prefab_path).unwrap();
|
let expected = load_level(app.world_mut(), &prefab_path).unwrap();
|
||||||
save_level(app.world_mut(), &prefab_path).unwrap();
|
save_level(
|
||||||
|
app.world_mut(),
|
||||||
|
&prefab_path,
|
||||||
|
SceneWriteContext::ActiveSaveAs { expected },
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
scene::validate_prefab_graph(&prefab_path, &root).unwrap();
|
scene::validate_prefab_graph(&prefab_path, &root).unwrap();
|
||||||
let document =
|
let document =
|
||||||
@@ -2813,8 +3196,11 @@ mod tests {
|
|||||||
let destination = root.join("kept.scn.ron");
|
let destination = root.join("kept.scn.ron");
|
||||||
std::fs::create_dir_all(&root).unwrap();
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
std::fs::write(&snapshot, b"recovered scene bytes").unwrap();
|
std::fs::write(&snapshot, b"recovered scene bytes").unwrap();
|
||||||
|
let expected = FileSnapshot::missing();
|
||||||
|
let mut world = World::new();
|
||||||
|
world.init_resource::<SceneIo>();
|
||||||
|
|
||||||
write_recovery_copy(&snapshot, &destination).unwrap();
|
write_recovery_copy(&mut world, &snapshot, &destination, &expected).unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
std::fs::read(&destination).unwrap(),
|
std::fs::read(&destination).unwrap(),
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
|
|||||||
ActorKind::StaticMesh
|
ActorKind::StaticMesh
|
||||||
| ActorKind::SkinnedMesh
|
| ActorKind::SkinnedMesh
|
||||||
| ActorKind::Brush
|
| ActorKind::Brush
|
||||||
|
| ActorKind::Terrain
|
||||||
| ActorKind::ImportedModel
|
| ActorKind::ImportedModel
|
||||||
| ActorKind::Light
|
| ActorKind::Light
|
||||||
| ActorKind::Empty
|
| ActorKind::Empty
|
||||||
@@ -143,6 +144,7 @@ fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
|
|||||||
ActorKind::StaticMesh
|
ActorKind::StaticMesh
|
||||||
| ActorKind::SkinnedMesh
|
| ActorKind::SkinnedMesh
|
||||||
| ActorKind::Brush
|
| ActorKind::Brush
|
||||||
|
| ActorKind::Terrain
|
||||||
| ActorKind::ImportedModel => icons::CUBE,
|
| ActorKind::ImportedModel => icons::CUBE,
|
||||||
ActorKind::Light => icons::LIGHTBULB,
|
ActorKind::Light => icons::LIGHTBULB,
|
||||||
ActorKind::PrefabAnchor => icons::PACKAGE,
|
ActorKind::PrefabAnchor => icons::PACKAGE,
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ use crate::assets::{
|
|||||||
AssetSelection, AssetSubAssetKind, EditorAsset, EditorAssetKind, EditorAssets, ASSETS_ROOT,
|
AssetSelection, AssetSubAssetKind, EditorAsset, EditorAssetKind, EditorAssets, ASSETS_ROOT,
|
||||||
BUILTINS_FOLDER,
|
BUILTINS_FOLDER,
|
||||||
};
|
};
|
||||||
|
use crate::project::collaboration::{
|
||||||
|
file_status_indicator_ui, publish_authored_file, CollaborationState, FileSnapshot,
|
||||||
|
FileWriteIntent,
|
||||||
|
};
|
||||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||||
|
|
||||||
use super::state::{
|
use super::state::{
|
||||||
@@ -1851,13 +1855,13 @@ fn details_panel(world: &mut World, ui: &mut egui::Ui, selected_entities: &Selec
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn top_level_asset_details_panel(
|
pub(crate) fn top_level_asset_details_panel(
|
||||||
world: &mut World,
|
world: &mut World,
|
||||||
ui: &mut egui::Ui,
|
ui: &mut egui::Ui,
|
||||||
selected_entities: &SelectedEntities,
|
selected_entities: &SelectedEntities,
|
||||||
asset: &EditorAsset,
|
asset: &EditorAsset,
|
||||||
) {
|
) {
|
||||||
asset_details_header(ui, asset);
|
asset_details_header(world, ui, asset);
|
||||||
ui.add_space(8.0);
|
ui.add_space(8.0);
|
||||||
detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in"));
|
detail_row(ui, "Path", asset.path.as_deref().unwrap_or("Built-in"));
|
||||||
detail_row(ui, "Folder", asset.folder_path.as_str());
|
detail_row(ui, "Folder", asset.folder_path.as_str());
|
||||||
@@ -1946,7 +1950,7 @@ fn top_level_asset_details_panel(
|
|||||||
asset_action_buttons(world, ui, selected_entities, asset);
|
asset_action_buttons(world, ui, selected_entities, asset);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) {
|
fn asset_details_header(world: &World, ui: &mut egui::Ui, asset: &EditorAsset) {
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
ui.label(
|
ui.label(
|
||||||
egui::RichText::new(kind_icon(&asset.kind).as_str())
|
egui::RichText::new(kind_icon(&asset.kind).as_str())
|
||||||
@@ -1959,6 +1963,13 @@ fn asset_details_header(ui: &mut egui::Ui, asset: &EditorAsset) {
|
|||||||
ui.vertical(|ui| {
|
ui.vertical(|ui| {
|
||||||
ui.strong(asset.label.as_str());
|
ui.strong(asset.label.as_str());
|
||||||
ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM));
|
ui.small(egui::RichText::new(kind_label(&asset.kind)).color(TEXT_DIM));
|
||||||
|
if let (Some(state), Some(path)) = (
|
||||||
|
world.get_resource::<CollaborationState>(),
|
||||||
|
asset.path.as_deref(),
|
||||||
|
) {
|
||||||
|
let status = state.file_status(Path::new(path));
|
||||||
|
let _ = file_status_indicator_ui(ui, &status, Path::new(path));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -2434,10 +2445,19 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
|
|||||||
if !needs_load {
|
if !needs_load {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let draft = match MaterialAsset::load_from_path(path) {
|
let loaded = fs::read_to_string(path)
|
||||||
Ok(asset) => MaterialAssetDraft {
|
.map_err(|error| format!("could not read {path}: {error}"))
|
||||||
|
.and_then(|text| {
|
||||||
|
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
|
||||||
|
ron::from_str::<MaterialAsset>(&text)
|
||||||
|
.map(|asset| (asset, snapshot))
|
||||||
|
.map_err(|error| format!("invalid material RON in {path}: {error}"))
|
||||||
|
});
|
||||||
|
let draft = match loaded {
|
||||||
|
Ok((asset, disk_snapshot)) => MaterialAssetDraft {
|
||||||
path: path.to_string(),
|
path: path.to_string(),
|
||||||
asset,
|
asset,
|
||||||
|
disk_snapshot,
|
||||||
error: None,
|
error: None,
|
||||||
},
|
},
|
||||||
Err(error) => MaterialAssetDraft {
|
Err(error) => MaterialAssetDraft {
|
||||||
@@ -2450,6 +2470,8 @@ fn ensure_material_draft(world: &mut World, path: &str, fallback_label: &str) {
|
|||||||
render_state: shared::MaterialRenderState::default(),
|
render_state: shared::MaterialRenderState::default(),
|
||||||
material: MaterialDesc::default(),
|
material: MaterialDesc::default(),
|
||||||
},
|
},
|
||||||
|
disk_snapshot: FileSnapshot::capture(Path::new(path))
|
||||||
|
.unwrap_or_else(|_| FileSnapshot::missing()),
|
||||||
error: Some(error),
|
error: Some(error),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -2467,17 +2489,23 @@ fn save_material_draft(world: &mut World) {
|
|||||||
let result = ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
let result = ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
||||||
.map_err(|error| format!("could not serialize material {}: {error}", draft.path))
|
.map_err(|error| format!("could not serialize material {}: {error}", draft.path))
|
||||||
.and_then(|text| {
|
.and_then(|text| {
|
||||||
fs::write(&draft.path, text)
|
publish_authored_file(
|
||||||
.map_err(|error| format!("could not write material {}: {error}", draft.path))
|
world,
|
||||||
|
Path::new(&draft.path),
|
||||||
|
text.as_bytes(),
|
||||||
|
&draft.disk_snapshot,
|
||||||
|
FileWriteIntent::Material,
|
||||||
|
)
|
||||||
});
|
});
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(disk_snapshot) => {
|
||||||
if let Some(current) = world
|
if let Some(current) = world
|
||||||
.resource_mut::<AssetBrowserUiState>()
|
.resource_mut::<AssetBrowserUiState>()
|
||||||
.material_draft
|
.material_draft
|
||||||
.as_mut()
|
.as_mut()
|
||||||
{
|
{
|
||||||
current.error = None;
|
current.error = None;
|
||||||
|
current.disk_snapshot = disk_snapshot;
|
||||||
}
|
}
|
||||||
world.resource_mut::<EditorAssets>().refresh();
|
world.resource_mut::<EditorAssets>().refresh();
|
||||||
invalidate_on_catalog_refresh(world);
|
invalidate_on_catalog_refresh(world);
|
||||||
@@ -2496,7 +2524,11 @@ fn save_material_draft(world: &mut World) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_material_instance_from_base(world: &mut World, base_path: &str, base_label: &str) {
|
pub(crate) fn create_material_instance_from_base(
|
||||||
|
world: &mut World,
|
||||||
|
base_path: &str,
|
||||||
|
base_label: &str,
|
||||||
|
) {
|
||||||
let base_reference = world
|
let base_reference = world
|
||||||
.get_resource_mut::<crate::asset_db::AssetRegistry>()
|
.get_resource_mut::<crate::asset_db::AssetRegistry>()
|
||||||
.ok_or_else(|| "Asset registry is unavailable".to_string())
|
.ok_or_else(|| "Asset registry is unavailable".to_string())
|
||||||
@@ -2556,8 +2588,13 @@ fn create_material_instance_from_base(world: &mut World, base_path: &str, base_l
|
|||||||
let result = ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default())
|
let result = ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default())
|
||||||
.map_err(|error| format!("could not serialize material instance: {error}"))
|
.map_err(|error| format!("could not serialize material instance: {error}"))
|
||||||
.and_then(|text| {
|
.and_then(|text| {
|
||||||
fs::write(&path, text)
|
publish_authored_file(
|
||||||
.map_err(|error| format!("could not write {}: {error}", path.display()))
|
world,
|
||||||
|
&path,
|
||||||
|
text.as_bytes(),
|
||||||
|
&FileSnapshot::missing(),
|
||||||
|
FileWriteIntent::MaterialInstance,
|
||||||
|
)
|
||||||
});
|
});
|
||||||
if let Err(error) = result {
|
if let Err(error) = result {
|
||||||
world.resource_mut::<SceneIo>().status = error;
|
world.resource_mut::<SceneIo>().status = error;
|
||||||
@@ -2845,10 +2882,19 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
|
|||||||
if !needs_load {
|
if !needs_load {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let draft = match MaterialInstanceAsset::load_from_path(path) {
|
let loaded = fs::read_to_string(path)
|
||||||
Ok(asset) => MaterialInstanceAssetDraft {
|
.map_err(|error| format!("could not read {path}: {error}"))
|
||||||
|
.and_then(|text| {
|
||||||
|
let snapshot = FileSnapshot::from_loaded_bytes(Path::new(path), text.as_bytes());
|
||||||
|
ron::from_str::<MaterialInstanceAsset>(&text)
|
||||||
|
.map(|asset| (asset, snapshot))
|
||||||
|
.map_err(|error| format!("invalid material-instance RON in {path}: {error}"))
|
||||||
|
});
|
||||||
|
let draft = match loaded {
|
||||||
|
Ok((asset, disk_snapshot)) => MaterialInstanceAssetDraft {
|
||||||
path: path.to_string(),
|
path: path.to_string(),
|
||||||
asset,
|
asset,
|
||||||
|
disk_snapshot,
|
||||||
error: None,
|
error: None,
|
||||||
},
|
},
|
||||||
Err(error) => MaterialInstanceAssetDraft {
|
Err(error) => MaterialInstanceAssetDraft {
|
||||||
@@ -2860,6 +2906,8 @@ fn ensure_material_instance_draft(world: &mut World, path: &str, fallback_label:
|
|||||||
parameters: Vec::new(),
|
parameters: Vec::new(),
|
||||||
textures: Vec::new(),
|
textures: Vec::new(),
|
||||||
},
|
},
|
||||||
|
disk_snapshot: FileSnapshot::capture(Path::new(path))
|
||||||
|
.unwrap_or_else(|_| FileSnapshot::missing()),
|
||||||
error: Some(error),
|
error: Some(error),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -2884,18 +2932,24 @@ fn save_material_instance_draft(world: &mut World) {
|
|||||||
ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
ron::ser::to_string_pretty(&draft.asset, ron::ser::PrettyConfig::default())
|
||||||
.map_err(|error| format!("could not serialize material instance: {error}"))
|
.map_err(|error| format!("could not serialize material instance: {error}"))
|
||||||
.and_then(|text| {
|
.and_then(|text| {
|
||||||
fs::write(&draft.path, text)
|
publish_authored_file(
|
||||||
.map_err(|error| format!("could not write {}: {error}", draft.path))
|
world,
|
||||||
|
Path::new(&draft.path),
|
||||||
|
text.as_bytes(),
|
||||||
|
&draft.disk_snapshot,
|
||||||
|
FileWriteIntent::MaterialInstance,
|
||||||
|
)
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(disk_snapshot) => {
|
||||||
if let Some(current) = world
|
if let Some(current) = world
|
||||||
.resource_mut::<AssetBrowserUiState>()
|
.resource_mut::<AssetBrowserUiState>()
|
||||||
.material_instance_draft
|
.material_instance_draft
|
||||||
.as_mut()
|
.as_mut()
|
||||||
{
|
{
|
||||||
current.error = None;
|
current.error = None;
|
||||||
|
current.disk_snapshot = disk_snapshot;
|
||||||
}
|
}
|
||||||
world.resource_mut::<EditorAssets>().refresh();
|
world.resource_mut::<EditorAssets>().refresh();
|
||||||
invalidate_on_catalog_refresh(world);
|
invalidate_on_catalog_refresh(world);
|
||||||
@@ -4380,10 +4434,181 @@ fn dedup_strings(values: &mut Vec<String>) {
|
|||||||
values.retain(|value| seen.insert(value.clone()));
|
values.retain(|value| seen.insert(value.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_material_conflict_destination(
|
||||||
|
world: &World,
|
||||||
|
destination: &Path,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
|
||||||
|
let root = root.canonicalize().unwrap_or(root);
|
||||||
|
let absolute = if destination.is_absolute() {
|
||||||
|
destination.to_path_buf()
|
||||||
|
} else {
|
||||||
|
root.join(destination)
|
||||||
|
};
|
||||||
|
let absolute = absolute
|
||||||
|
.parent()
|
||||||
|
.and_then(|parent| parent.canonicalize().ok())
|
||||||
|
.and_then(|parent| destination.file_name().map(|name| parent.join(name)))
|
||||||
|
.unwrap_or(absolute);
|
||||||
|
let relative = absolute.strip_prefix(&root).map_err(|_| {
|
||||||
|
format!(
|
||||||
|
"Material assets must stay inside {}",
|
||||||
|
root.join("assets").display()
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if !relative.starts_with("assets") {
|
||||||
|
return Err(format!(
|
||||||
|
"Material assets must stay inside {}",
|
||||||
|
root.join("assets").display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(relative.to_string_lossy().replace('\\', "/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn reload_material_after_file_conflict(
|
||||||
|
world: &mut World,
|
||||||
|
path: &Path,
|
||||||
|
intent: &FileWriteIntent,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let path = path.to_string_lossy();
|
||||||
|
{
|
||||||
|
let mut state = world.resource_mut::<AssetBrowserUiState>();
|
||||||
|
match intent {
|
||||||
|
FileWriteIntent::Material => {
|
||||||
|
if state
|
||||||
|
.material_draft
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|draft| draft.path == path)
|
||||||
|
{
|
||||||
|
state.material_draft = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FileWriteIntent::MaterialInstance => {
|
||||||
|
if state
|
||||||
|
.material_instance_draft
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|draft| draft.path == path)
|
||||||
|
{
|
||||||
|
state.material_instance_draft = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Err("the conflict is not an editable material document".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
world.resource_mut::<EditorAssets>().refresh();
|
||||||
|
invalidate_on_catalog_refresh(world);
|
||||||
|
Ok(format!("Reloaded {} from disk", path))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn adopt_material_conflict_save_as(
|
||||||
|
world: &mut World,
|
||||||
|
original_path: &Path,
|
||||||
|
catalog_path: String,
|
||||||
|
disk_snapshot: FileSnapshot,
|
||||||
|
intent: &FileWriteIntent,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let original_path = original_path.to_string_lossy();
|
||||||
|
{
|
||||||
|
let mut state = world.resource_mut::<AssetBrowserUiState>();
|
||||||
|
match intent {
|
||||||
|
FileWriteIntent::Material => {
|
||||||
|
if let Some(draft) = state
|
||||||
|
.material_draft
|
||||||
|
.as_mut()
|
||||||
|
.filter(|draft| draft.path == original_path)
|
||||||
|
{
|
||||||
|
draft.path.clone_from(&catalog_path);
|
||||||
|
draft.disk_snapshot = disk_snapshot;
|
||||||
|
draft.error = None;
|
||||||
|
} else {
|
||||||
|
let asset = MaterialAsset::load_from_path(&catalog_path)?;
|
||||||
|
state.material_draft = Some(MaterialAssetDraft {
|
||||||
|
path: catalog_path.clone(),
|
||||||
|
asset,
|
||||||
|
disk_snapshot,
|
||||||
|
error: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FileWriteIntent::MaterialInstance => {
|
||||||
|
if let Some(draft) = state
|
||||||
|
.material_instance_draft
|
||||||
|
.as_mut()
|
||||||
|
.filter(|draft| draft.path == original_path)
|
||||||
|
{
|
||||||
|
draft.path.clone_from(&catalog_path);
|
||||||
|
draft.disk_snapshot = disk_snapshot;
|
||||||
|
draft.error = None;
|
||||||
|
} else {
|
||||||
|
let asset = MaterialInstanceAsset::load_from_path(&catalog_path)?;
|
||||||
|
state.material_instance_draft = Some(MaterialInstanceAssetDraft {
|
||||||
|
path: catalog_path.clone(),
|
||||||
|
asset,
|
||||||
|
disk_snapshot,
|
||||||
|
error: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Err("the conflict is not an editable material document".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut assets = world.resource_mut::<EditorAssets>();
|
||||||
|
assets.refresh();
|
||||||
|
assets.select(AssetSelection::File(catalog_path.clone()));
|
||||||
|
}
|
||||||
|
invalidate_on_catalog_refresh(world);
|
||||||
|
Ok(format!("Saved material copy to {catalog_path}"))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn material_apply_refuses_an_external_revision() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-material-external-write-{}",
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
));
|
||||||
|
let path = root.join("assets/materials/test.ron");
|
||||||
|
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
fs::write(&path, b"loaded").unwrap();
|
||||||
|
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
|
||||||
|
let draft = MaterialAssetDraft {
|
||||||
|
path: path.to_string_lossy().into_owned(),
|
||||||
|
asset: MaterialAsset {
|
||||||
|
schema_version: shared::MATERIAL_ASSET_SCHEMA_VERSION,
|
||||||
|
label: "Test".into(),
|
||||||
|
shader: None,
|
||||||
|
shader_ref: None,
|
||||||
|
render_state: shared::MaterialRenderState::default(),
|
||||||
|
material: MaterialDesc::default(),
|
||||||
|
},
|
||||||
|
disk_snapshot,
|
||||||
|
error: None,
|
||||||
|
};
|
||||||
|
let state = AssetBrowserUiState {
|
||||||
|
material_draft: Some(draft),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut world = World::new();
|
||||||
|
world.insert_resource(state);
|
||||||
|
world.insert_resource(SceneIo::default());
|
||||||
|
fs::write(&path, b"external").unwrap();
|
||||||
|
|
||||||
|
save_material_draft(&mut world);
|
||||||
|
|
||||||
|
assert_eq!(fs::read(&path).unwrap(), b"external");
|
||||||
|
assert!(world
|
||||||
|
.resource::<AssetBrowserUiState>()
|
||||||
|
.material_draft
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|draft| draft.error.as_deref())
|
||||||
|
.is_some_and(|error| error.contains("changed outside Blacksite")));
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn audio_filter_matches_only_audio_clips() {
|
fn audio_filter_matches_only_audio_clips() {
|
||||||
let audio = EditorAsset {
|
let audio = EditorAsset {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use shared::{MaterialAsset, MaterialInstanceAsset};
|
|||||||
|
|
||||||
use crate::asset_db::ImportSettings;
|
use crate::asset_db::ImportSettings;
|
||||||
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
|
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
|
||||||
|
use crate::project::collaboration::FileSnapshot;
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub(crate) enum AssetBrowserView {
|
pub(crate) enum AssetBrowserView {
|
||||||
@@ -69,6 +70,7 @@ pub(crate) struct ImportSettingsDraft {
|
|||||||
pub(crate) struct MaterialAssetDraft {
|
pub(crate) struct MaterialAssetDraft {
|
||||||
pub(crate) path: String,
|
pub(crate) path: String,
|
||||||
pub(crate) asset: MaterialAsset,
|
pub(crate) asset: MaterialAsset,
|
||||||
|
pub(crate) disk_snapshot: FileSnapshot,
|
||||||
pub(crate) error: Option<String>,
|
pub(crate) error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +78,7 @@ pub(crate) struct MaterialAssetDraft {
|
|||||||
pub(crate) struct MaterialInstanceAssetDraft {
|
pub(crate) struct MaterialInstanceAssetDraft {
|
||||||
pub(crate) path: String,
|
pub(crate) path: String,
|
||||||
pub(crate) asset: MaterialInstanceAsset,
|
pub(crate) asset: MaterialInstanceAsset,
|
||||||
|
pub(crate) disk_snapshot: FileSnapshot,
|
||||||
pub(crate) error: Option<String>,
|
pub(crate) error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -373,6 +373,27 @@ impl Default for EditorComponentRegistry {
|
|||||||
],
|
],
|
||||||
hydration_effect: "Hydrates into generated brush mesh children.",
|
hydration_effect: "Hydrates into generated brush mesh children.",
|
||||||
},
|
},
|
||||||
|
EditorComponentDescriptor {
|
||||||
|
id: shared::AUTHORING_COMPONENT_TERRAIN,
|
||||||
|
type_name: "shared::components::TerrainDesc",
|
||||||
|
display_name: "Terrain",
|
||||||
|
category: EditorComponentCategory::Authoring,
|
||||||
|
addable: true,
|
||||||
|
removable: true,
|
||||||
|
reorderable: true,
|
||||||
|
hidden: false,
|
||||||
|
icon: icons::MOUNTAINS.as_str(),
|
||||||
|
description: "Creates chunked height-grid terrain with optional collision.",
|
||||||
|
search_terms: &["terrain", "landscape", "heightmap", "ground", "chunk"],
|
||||||
|
recommended: &[],
|
||||||
|
conflicts_with: &[
|
||||||
|
"shared::components::Primitive",
|
||||||
|
"shared::components::BrushDesc",
|
||||||
|
"shared::components::StaticMeshRenderer",
|
||||||
|
"shared::animation::SkinnedMeshRenderer",
|
||||||
|
],
|
||||||
|
hydration_effect: "Hydrates into generated render and collider chunks.",
|
||||||
|
},
|
||||||
EditorComponentDescriptor {
|
EditorComponentDescriptor {
|
||||||
id: shared::AUTHORING_COMPONENT_MATERIAL,
|
id: shared::AUTHORING_COMPONENT_MATERIAL,
|
||||||
type_name: "shared::components::MaterialDesc",
|
type_name: "shared::components::MaterialDesc",
|
||||||
|
|||||||
@@ -36,7 +36,10 @@ impl PanelNodes {
|
|||||||
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
|
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
|
||||||
EditorTab::Hierarchy => self.hierarchy(),
|
EditorTab::Hierarchy => self.hierarchy(),
|
||||||
EditorTab::Inspector => self.inspector(),
|
EditorTab::Inspector => self.inspector(),
|
||||||
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => self.bottom(),
|
EditorTab::AssetBrowser
|
||||||
|
| EditorTab::MaterialLibrary
|
||||||
|
| EditorTab::Build
|
||||||
|
| EditorTab::Toolbar => self.bottom(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,20 +54,22 @@ impl PanelNodes {
|
|||||||
EditorTab::Viewport | EditorTab::GameView => nodes.main_view = path.node.0,
|
EditorTab::Viewport | EditorTab::GameView => nodes.main_view = path.node.0,
|
||||||
EditorTab::Hierarchy => nodes.hierarchy = path.node.0,
|
EditorTab::Hierarchy => nodes.hierarchy = path.node.0,
|
||||||
EditorTab::Inspector => nodes.inspector = path.node.0,
|
EditorTab::Inspector => nodes.inspector = path.node.0,
|
||||||
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => {
|
EditorTab::AssetBrowser
|
||||||
nodes.bottom = path.node.0
|
| EditorTab::MaterialLibrary
|
||||||
}
|
| EditorTab::Build
|
||||||
|
| EditorTab::Toolbar => nodes.bottom = path.node.0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
nodes
|
nodes
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const PANEL_TABS: [EditorTab; 5] = [
|
pub const PANEL_TABS: [EditorTab; 6] = [
|
||||||
EditorTab::Viewport,
|
EditorTab::Viewport,
|
||||||
EditorTab::Hierarchy,
|
EditorTab::Hierarchy,
|
||||||
EditorTab::Inspector,
|
EditorTab::Inspector,
|
||||||
EditorTab::AssetBrowser,
|
EditorTab::AssetBrowser,
|
||||||
|
EditorTab::MaterialLibrary,
|
||||||
EditorTab::Build,
|
EditorTab::Build,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -74,6 +79,7 @@ pub fn tab_label(tab: &EditorTab) -> &'static str {
|
|||||||
EditorTab::Hierarchy => "Hierarchy",
|
EditorTab::Hierarchy => "Hierarchy",
|
||||||
EditorTab::Inspector => "Inspector",
|
EditorTab::Inspector => "Inspector",
|
||||||
EditorTab::AssetBrowser => "Asset Browser",
|
EditorTab::AssetBrowser => "Asset Browser",
|
||||||
|
EditorTab::MaterialLibrary => "Material Library",
|
||||||
EditorTab::Build => "Build",
|
EditorTab::Build => "Build",
|
||||||
EditorTab::Toolbar => "Toolbar (legacy)",
|
EditorTab::Toolbar => "Toolbar (legacy)",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,6 +205,7 @@ fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
|
|||||||
.map(|kind| match kind {
|
.map(|kind| match kind {
|
||||||
ActorKind::Empty => 0,
|
ActorKind::Empty => 0,
|
||||||
ActorKind::Brush
|
ActorKind::Brush
|
||||||
|
| ActorKind::Terrain
|
||||||
| ActorKind::StaticMesh
|
| ActorKind::StaticMesh
|
||||||
| ActorKind::SkinnedMesh
|
| ActorKind::SkinnedMesh
|
||||||
| ActorKind::ImportedModel => 1,
|
| ActorKind::ImportedModel => 1,
|
||||||
@@ -468,6 +469,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
|
|||||||
match kind {
|
match kind {
|
||||||
ActorKind::Empty => icons::FOLDER.as_str(),
|
ActorKind::Empty => icons::FOLDER.as_str(),
|
||||||
ActorKind::Brush => icons::CUBE.as_str(),
|
ActorKind::Brush => icons::CUBE.as_str(),
|
||||||
|
ActorKind::Terrain => icons::MOUNTAINS.as_str(),
|
||||||
ActorKind::StaticMesh => icons::CUBE.as_str(),
|
ActorKind::StaticMesh => icons::CUBE.as_str(),
|
||||||
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
|
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
|
||||||
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
|
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ use shared::{
|
|||||||
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
|
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
|
||||||
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
|
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
|
||||||
PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc,
|
PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc,
|
||||||
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TriggerVolume,
|
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TerrainDesc,
|
||||||
WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
|
TriggerVolume, WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
|
||||||
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC,
|
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC,
|
||||||
COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
|
COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
|
||||||
COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_NAVIGATION_AREA,
|
COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_NAVIGATION_AREA,
|
||||||
@@ -25,8 +25,8 @@ use shared::{
|
|||||||
COMPONENT_OBJECTIVE_MARKER, COMPONENT_PHYSICS_BODY, COMPONENT_PLAYER_SPAWN,
|
COMPONENT_OBJECTIVE_MARKER, COMPONENT_PHYSICS_BODY, COMPONENT_PLAYER_SPAWN,
|
||||||
COMPONENT_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE,
|
COMPONENT_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE,
|
||||||
COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER,
|
COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER,
|
||||||
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TRIGGER_VOLUME,
|
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TERRAIN_DESC,
|
||||||
COMPONENT_WEAPON_SPAWN,
|
COMPONENT_TRIGGER_VOLUME, COMPONENT_WEAPON_SPAWN,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::history::{
|
use crate::history::{
|
||||||
@@ -1110,6 +1110,7 @@ fn draw_authoring_component_by_type(
|
|||||||
COMPONENT_STATIC_MESH_RENDERER => static_mesh_renderer_ui(world, ui, entity),
|
COMPONENT_STATIC_MESH_RENDERER => static_mesh_renderer_ui(world, ui, entity),
|
||||||
COMPONENT_SKINNED_MESH_RENDERER => skinned_mesh_renderer_ui(world, ui, entity),
|
COMPONENT_SKINNED_MESH_RENDERER => skinned_mesh_renderer_ui(world, ui, entity),
|
||||||
COMPONENT_BRUSH_DESC => brush_editor_ui(world, ui, entity),
|
COMPONENT_BRUSH_DESC => brush_editor_ui(world, ui, entity),
|
||||||
|
COMPONENT_TERRAIN_DESC => terrain_editor_ui(world, ui, entity),
|
||||||
COMPONENT_PRIMITIVE => primitive_editor_ui(world, ui, entity),
|
COMPONENT_PRIMITIVE => primitive_editor_ui(world, ui, entity),
|
||||||
COMPONENT_MATERIAL_DESC => material_editor_ui(world, ui, entity),
|
COMPONENT_MATERIAL_DESC => material_editor_ui(world, ui, entity),
|
||||||
COMPONENT_LIGHT_DESC => light_editor_ui(world, ui, entity),
|
COMPONENT_LIGHT_DESC => light_editor_ui(world, ui, entity),
|
||||||
@@ -3494,6 +3495,128 @@ fn brush_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn terrain_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||||
|
let Some(mut terrain) = world.get::<TerrainDesc>(entity).cloned() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let original = terrain.clone();
|
||||||
|
let mut changed = false;
|
||||||
|
let mut requested_resolution = terrain.resolution;
|
||||||
|
let card = component_card_context(
|
||||||
|
world,
|
||||||
|
entity,
|
||||||
|
ComponentCardOptions::removable(COMPONENT_TERRAIN_DESC, "Terrain", icons::MOUNTAINS),
|
||||||
|
);
|
||||||
|
let card_response = component_card(ui, &card, |ui| {
|
||||||
|
property_row(ui, "Grid", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut requested_resolution)
|
||||||
|
.range(2..=1025)
|
||||||
|
.suffix(" samples"),
|
||||||
|
);
|
||||||
|
if ui
|
||||||
|
.add_enabled(
|
||||||
|
requested_resolution != terrain.resolution,
|
||||||
|
egui::Button::new("Resize Flat"),
|
||||||
|
)
|
||||||
|
.on_hover_text("Replaces the current height grid with a flat grid")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
let replacement = TerrainDesc::flat(requested_resolution);
|
||||||
|
terrain.resolution = replacement.resolution;
|
||||||
|
terrain.heights = replacement.heights;
|
||||||
|
terrain.chunk_quads = terrain.chunk_quads.min(terrain.resolution - 1).max(1);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
property_row(ui, "Sample Spacing", |ui| {
|
||||||
|
changed |= ui
|
||||||
|
.add(
|
||||||
|
egui::DragValue::new(&mut terrain.sample_spacing)
|
||||||
|
.range(0.01..=1000.0)
|
||||||
|
.speed(0.1)
|
||||||
|
.suffix(" m"),
|
||||||
|
)
|
||||||
|
.changed();
|
||||||
|
});
|
||||||
|
property_row(ui, "Height Scale", |ui| {
|
||||||
|
changed |= ui
|
||||||
|
.add(
|
||||||
|
egui::DragValue::new(&mut terrain.height_scale)
|
||||||
|
.range(0.01..=10000.0)
|
||||||
|
.speed(0.1)
|
||||||
|
.suffix(" m"),
|
||||||
|
)
|
||||||
|
.changed();
|
||||||
|
});
|
||||||
|
property_row(ui, "Chunk Size", |ui| {
|
||||||
|
changed |= ui
|
||||||
|
.add(
|
||||||
|
egui::DragValue::new(&mut terrain.chunk_quads)
|
||||||
|
.range(1..=terrain.resolution.saturating_sub(1))
|
||||||
|
.suffix(" quads"),
|
||||||
|
)
|
||||||
|
.changed();
|
||||||
|
});
|
||||||
|
property_row(ui, "Collision", |ui| {
|
||||||
|
changed |= ui
|
||||||
|
.checkbox(&mut terrain.generate_colliders, "Generate")
|
||||||
|
.changed();
|
||||||
|
});
|
||||||
|
property_row(ui, "Shadows", |ui| {
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
changed |= ui.checkbox(&mut terrain.cast_shadows, "Cast").changed();
|
||||||
|
changed |= ui
|
||||||
|
.checkbox(&mut terrain.receive_shadows, "Receive")
|
||||||
|
.changed();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
property_row(ui, "Base Material", |ui| {
|
||||||
|
ui.label(
|
||||||
|
terrain
|
||||||
|
.base_material
|
||||||
|
.as_ref()
|
||||||
|
.map(|material| material.label.as_str())
|
||||||
|
.filter(|label| !label.is_empty())
|
||||||
|
.unwrap_or("Terrain fallback"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
match terrain.validate() {
|
||||||
|
Ok(()) => {
|
||||||
|
ui.label(
|
||||||
|
egui::RichText::new(format!(
|
||||||
|
"{} heights • {}×{} chunks",
|
||||||
|
terrain.heights.len(),
|
||||||
|
(terrain.resolution - 1).div_ceil(terrain.chunk_quads),
|
||||||
|
(terrain.resolution - 1).div_ceil(terrain.chunk_quads)
|
||||||
|
))
|
||||||
|
.color(super::theme::SUCCESS),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
ui.label(egui::RichText::new(error).color(super::theme::ERROR));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
apply_component_card_response(world, entity, card_response);
|
||||||
|
|
||||||
|
if changed && terrain != original {
|
||||||
|
let _ = reflected_component_transaction(
|
||||||
|
world,
|
||||||
|
entity,
|
||||||
|
"Edit Terrain",
|
||||||
|
shared::AUTHORING_COMPONENT_TERRAIN,
|
||||||
|
COMPONENT_TERRAIN_DESC,
|
||||||
|
move |world, entity| {
|
||||||
|
world.entity_mut(entity).insert(terrain);
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn brush_validation_ui(ui: &mut egui::Ui, brush: &BrushDesc) {
|
fn brush_validation_ui(ui: &mut egui::Ui, brush: &BrushDesc) {
|
||||||
let report = validate_brush(brush);
|
let report = validate_brush(brush);
|
||||||
if report.diagnostics.is_empty() {
|
if report.diagnostics.is_empty() {
|
||||||
|
|||||||
@@ -32,8 +32,11 @@ pub fn default_dock_layout() -> DockLayoutSnapshot {
|
|||||||
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
|
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
|
||||||
let [main_view_node, hierarchy_node] =
|
let [main_view_node, hierarchy_node] =
|
||||||
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
|
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
|
||||||
let [main_view_node, bottom_node] =
|
let [main_view_node, bottom_node] = tree.split_below(
|
||||||
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]);
|
main_view_node,
|
||||||
|
0.88,
|
||||||
|
vec![EditorTab::AssetBrowser, EditorTab::MaterialLibrary],
|
||||||
|
);
|
||||||
|
|
||||||
let panel_nodes = PanelNodes {
|
let panel_nodes = PanelNodes {
|
||||||
main_view: main_view_node.0,
|
main_view: main_view_node.0,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -13,6 +13,7 @@ pub mod hierarchy_ops;
|
|||||||
pub mod hierarchy_state;
|
pub mod hierarchy_state;
|
||||||
pub(crate) mod inspector;
|
pub(crate) mod inspector;
|
||||||
mod layout;
|
mod layout;
|
||||||
|
mod material_library;
|
||||||
mod menu;
|
mod menu;
|
||||||
pub(crate) mod navigation_inspector;
|
pub(crate) mod navigation_inspector;
|
||||||
mod play_controls;
|
mod play_controls;
|
||||||
@@ -39,6 +40,10 @@ use crate::project_io::UserPreferences;
|
|||||||
use crate::selection::SelectedEntity;
|
use crate::selection::SelectedEntity;
|
||||||
use crate::state::EditorMode;
|
use crate::state::EditorMode;
|
||||||
|
|
||||||
|
pub(crate) use asset_browser::{
|
||||||
|
adopt_material_conflict_save_as, reload_material_after_file_conflict,
|
||||||
|
validate_material_conflict_destination,
|
||||||
|
};
|
||||||
pub use build::BuildPanel;
|
pub use build::BuildPanel;
|
||||||
pub use diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel};
|
pub use diagnostics::{BrushDiagnosticsPanel, DiagnosticsPanel};
|
||||||
pub use layout::LayoutSaveTimer;
|
pub use layout::LayoutSaveTimer;
|
||||||
@@ -71,6 +76,9 @@ pub struct UiState {
|
|||||||
last_mode_tab: Option<EditorMode>,
|
last_mode_tab: Option<EditorMode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Resource, Default)]
|
||||||
|
struct DockTabRequest(Option<EditorTab>);
|
||||||
|
|
||||||
pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool {
|
pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool {
|
||||||
ctx.egui_wants_keyboard_input()
|
ctx.egui_wants_keyboard_input()
|
||||||
}
|
}
|
||||||
@@ -183,6 +191,10 @@ impl UiState {
|
|||||||
.show_inside(root_ui, &mut viewer);
|
.show_inside(root_ui, &mut viewer);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if let Some(tab) = world.resource_mut::<DockTabRequest>().0.take() {
|
||||||
|
dock_tabs::open_and_focus_tab(&mut self.dock_state, tab, &self.panel_nodes);
|
||||||
|
}
|
||||||
|
|
||||||
self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
|
self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
|
||||||
|
|
||||||
mark_layout_dirty_if_changed(
|
mark_layout_dirty_if_changed(
|
||||||
@@ -215,6 +227,8 @@ impl UiState {
|
|||||||
project_settings_window(world, ctx, &mut panel);
|
project_settings_window(world, ctx, &mut panel);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
crate::collaboration::file_conflict_modal(world, ctx);
|
||||||
|
|
||||||
if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
|
if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
|
||||||
world.resource_mut::<ViewportUiState>().shortcuts_open = true;
|
world.resource_mut::<ViewportUiState>().shortcuts_open = true;
|
||||||
}
|
}
|
||||||
@@ -277,6 +291,7 @@ pub enum EditorTab {
|
|||||||
Inspector,
|
Inspector,
|
||||||
Toolbar,
|
Toolbar,
|
||||||
AssetBrowser,
|
AssetBrowser,
|
||||||
|
MaterialLibrary,
|
||||||
Build,
|
Build,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,6 +307,9 @@ impl Plugin for EditorUiPlugin {
|
|||||||
.init_resource::<component_registry::EditorComponentRegistry>()
|
.init_resource::<component_registry::EditorComponentRegistry>()
|
||||||
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||||
.init_resource::<asset_browser::AssetBrowserUiState>()
|
.init_resource::<asset_browser::AssetBrowserUiState>()
|
||||||
|
.init_resource::<material_library::MaterialLibraryState>()
|
||||||
|
.init_resource::<material_library::MaterialLibraryCatalog>()
|
||||||
|
.init_resource::<DockTabRequest>()
|
||||||
.init_resource::<inspector::InspectorClipboard>()
|
.init_resource::<inspector::InspectorClipboard>()
|
||||||
.init_resource::<inspector::InspectorPanelState>()
|
.init_resource::<inspector::InspectorPanelState>()
|
||||||
.init_resource::<animation_inspector::AnimationInspectorState>()
|
.init_resource::<animation_inspector::AnimationInspectorState>()
|
||||||
@@ -309,6 +327,10 @@ impl Plugin for EditorUiPlugin {
|
|||||||
apply_ui_state_from_prefs
|
apply_ui_state_from_prefs
|
||||||
.after(crate::project_io::load_user_preferences_on_startup),
|
.after(crate::project_io::load_user_preferences_on_startup),
|
||||||
)
|
)
|
||||||
|
.add_systems(
|
||||||
|
EguiPrimaryContextPass,
|
||||||
|
material_library::refresh_material_library_catalog.before(show_ui_system),
|
||||||
|
)
|
||||||
.add_systems(EguiPrimaryContextPass, show_ui_system)
|
.add_systems(EguiPrimaryContextPass, show_ui_system)
|
||||||
.add_systems(
|
.add_systems(
|
||||||
Update,
|
Update,
|
||||||
@@ -415,6 +437,9 @@ impl egui_dock::TabViewer for TabViewer<'_> {
|
|||||||
EditorTab::AssetBrowser => {
|
EditorTab::AssetBrowser => {
|
||||||
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities);
|
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities);
|
||||||
}
|
}
|
||||||
|
EditorTab::MaterialLibrary => {
|
||||||
|
material_library::material_library_ui(self.world, ui, self.selected_entities);
|
||||||
|
}
|
||||||
EditorTab::Build => build::build_ui(self.world, ui),
|
EditorTab::Build => build::build_ui(self.world, ui),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -426,6 +451,7 @@ impl egui_dock::TabViewer for TabViewer<'_> {
|
|||||||
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
|
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
|
||||||
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
|
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
|
||||||
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
|
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
|
||||||
|
EditorTab::MaterialLibrary => (icons::PALETTE, "Material Library"),
|
||||||
EditorTab::Build => (icons::HAMMER, "Build"),
|
EditorTab::Build => (icons::HAMMER, "Build"),
|
||||||
};
|
};
|
||||||
tab_title(icon, label)
|
tab_title(icon, label)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
|||||||
use egui_phosphor_icons::icons;
|
use egui_phosphor_icons::icons;
|
||||||
use shared::{SceneComposition, SubsceneReference};
|
use shared::{SceneComposition, SubsceneReference};
|
||||||
|
|
||||||
|
use crate::native_dialog::NativeDialogBroker;
|
||||||
use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest};
|
use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest};
|
||||||
use crate::selection::SelectedEntity;
|
use crate::selection::SelectedEntity;
|
||||||
|
|
||||||
@@ -195,19 +196,47 @@ fn composition_menu(
|
|||||||
|
|
||||||
ui.separator();
|
ui.separator();
|
||||||
if ui
|
if ui
|
||||||
.add_enabled(editing, egui::Button::new("Add Subscene..."))
|
.add_enabled(
|
||||||
|
editing && !world.resource::<NativeDialogBroker>().is_pending(),
|
||||||
|
egui::Button::new("Add Subscene..."),
|
||||||
|
)
|
||||||
.clicked()
|
.clicked()
|
||||||
{
|
{
|
||||||
match choose_subscene(world, &composition) {
|
let project_root =
|
||||||
Ok(Some(reference)) => {
|
PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
|
||||||
composition.subscenes.push(reference);
|
let directory = project_root.join("assets/levels");
|
||||||
changed = true;
|
let result = world.resource::<NativeDialogBroker>().request(
|
||||||
|
move || {
|
||||||
|
rfd::FileDialog::new()
|
||||||
|
.set_directory(directory)
|
||||||
|
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||||
|
.pick_file()
|
||||||
|
},
|
||||||
|
move |world, path| {
|
||||||
|
let Some(path) = path else {
|
||||||
|
world
|
||||||
|
.resource_mut::<SceneIo>()
|
||||||
|
.set_status("Add subscene cancelled");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let current = world.resource::<SceneComposition>().clone();
|
||||||
|
match validate_subscene_choice(&project_root, ¤t, path) {
|
||||||
|
Ok(reference) => {
|
||||||
|
let mut updated = current;
|
||||||
|
updated.subscenes.push(reference);
|
||||||
|
crate::history::set_scene_composition_with_history(world, updated);
|
||||||
|
world.resource_mut::<SceneIo>().set_status("Subscene added");
|
||||||
}
|
}
|
||||||
Ok(None) => {}
|
|
||||||
Err(error) => world
|
Err(error) => world
|
||||||
.resource_mut::<SceneIo>()
|
.resource_mut::<SceneIo>()
|
||||||
.set_status(format!("Add subscene failed: {error}")),
|
.set_status(format!("Add subscene failed: {error}")),
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
world.resource_mut::<SceneIo>().set_status(match result {
|
||||||
|
Ok(()) => "Choose a scene to compose".into(),
|
||||||
|
Err(error) => format!("Add subscene unavailable: {error}"),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if changed {
|
if changed {
|
||||||
@@ -218,20 +247,14 @@ fn composition_menu(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn choose_subscene(
|
fn validate_subscene_choice(
|
||||||
world: &World,
|
project_root: &Path,
|
||||||
composition: &SceneComposition,
|
composition: &SceneComposition,
|
||||||
) -> Result<Option<SubsceneReference>, String> {
|
path: PathBuf,
|
||||||
let project_root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root)
|
) -> Result<SubsceneReference, String> {
|
||||||
|
let project_root = project_root
|
||||||
.canonicalize()
|
.canonicalize()
|
||||||
.map_err(|error| format!("could not resolve project root: {error}"))?;
|
.map_err(|error| format!("could not resolve project root: {error}"))?;
|
||||||
let Some(path) = rfd::FileDialog::new()
|
|
||||||
.set_directory(project_root.join("assets/levels"))
|
|
||||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
|
||||||
.pick_file()
|
|
||||||
else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
let path = path
|
let path = path
|
||||||
.canonicalize()
|
.canonicalize()
|
||||||
.map_err(|error| format!("could not resolve {}: {error}", path.display()))?;
|
.map_err(|error| format!("could not resolve {}: {error}", path.display()))?;
|
||||||
@@ -251,12 +274,12 @@ fn choose_subscene(
|
|||||||
{
|
{
|
||||||
return Err(format!("{relative} is already composed"));
|
return Err(format!("{relative} is already composed"));
|
||||||
}
|
}
|
||||||
Ok(Some(SubsceneReference {
|
Ok(SubsceneReference {
|
||||||
id: uuid::Uuid::new_v4().to_string(),
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
path: relative,
|
path: relative,
|
||||||
visible: true,
|
visible: true,
|
||||||
locked: true,
|
locked: true,
|
||||||
}))
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) {
|
fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use egui_phosphor_icons::icons;
|
|||||||
|
|
||||||
use crate::history::EditorHistory;
|
use crate::history::EditorHistory;
|
||||||
use crate::operators::ActiveOperator;
|
use crate::operators::ActiveOperator;
|
||||||
|
use crate::project::collaboration::{file_status_indicator_ui, CollaborationState};
|
||||||
use crate::scene_io::SceneIo;
|
use crate::scene_io::SceneIo;
|
||||||
use crate::state::{EditorMode, PlayPaused};
|
use crate::state::{EditorMode, PlayPaused};
|
||||||
|
|
||||||
@@ -47,6 +48,16 @@ pub fn status_bar_ui(
|
|||||||
.on_hover_text(status);
|
.on_hover_text(status);
|
||||||
},
|
},
|
||||||
|ui| {
|
|ui| {
|
||||||
|
if let (Some(state), Some(path)) = (
|
||||||
|
world.get_resource::<CollaborationState>(),
|
||||||
|
world.resource::<SceneIo>().active_path.as_deref(),
|
||||||
|
) {
|
||||||
|
let status = state.file_status(path);
|
||||||
|
if status.indicator().is_some() {
|
||||||
|
let _ = file_status_indicator_ui(ui, &status, path);
|
||||||
|
ui.separator();
|
||||||
|
}
|
||||||
|
}
|
||||||
let (mode_icon, mode_label, mode_color) = match mode {
|
let (mode_icon, mode_label, mode_color) = match mode {
|
||||||
EditorMode::Editing => (icons::PENCIL_SIMPLE, "EDIT", ACCENT),
|
EditorMode::Editing => (icons::PENCIL_SIMPLE, "EDIT", ACCENT),
|
||||||
EditorMode::Playing => {
|
EditorMode::Playing => {
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ use egui_phosphor_icons::icons;
|
|||||||
use transform_gizmo_bevy::prelude::GizmoOptions;
|
use transform_gizmo_bevy::prelude::GizmoOptions;
|
||||||
|
|
||||||
use crate::assets::operators::{
|
use crate::assets::operators::{
|
||||||
apply_material_operator, apply_texture_operator, assign_animation_clip_operator,
|
assign_animation_clip_operator, assign_audio_clip_operator, place_asset_operator,
|
||||||
assign_audio_clip_operator, place_asset_operator, place_subasset_operator,
|
place_subasset_operator,
|
||||||
};
|
};
|
||||||
use crate::assets::thumbnails::kind_icon;
|
use crate::assets::thumbnails::kind_icon;
|
||||||
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
|
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
|
||||||
@@ -20,9 +20,10 @@ use crate::state::PlayPossession;
|
|||||||
use crate::viewport::actor_icons::ActorIconSettings;
|
use crate::viewport::actor_icons::ActorIconSettings;
|
||||||
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
|
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
|
||||||
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
|
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
|
||||||
|
use crate::viewport::terrain_sculpt::{TerrainSculptMode, TerrainSculptState};
|
||||||
use crate::viewport::{
|
use crate::viewport::{
|
||||||
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
|
material_drop::is_surface_asset_selection, snap_translation, viewport_ground_position,
|
||||||
ViewportSettings,
|
EditorViewportMode, MaterialDropState, ViewportDisplayMode, ViewportSettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::helpers::{
|
use super::helpers::{
|
||||||
@@ -30,7 +31,8 @@ use super::helpers::{
|
|||||||
};
|
};
|
||||||
use super::theme::{
|
use super::theme::{
|
||||||
overlay_chip_frame, viewport_toolbar_frame, ACCENT, ACCENT_HOVER, AXIS_X, AXIS_Y, AXIS_Z,
|
overlay_chip_frame, viewport_toolbar_frame, ACCENT, ACCENT_HOVER, AXIS_X, AXIS_Y, AXIS_Z,
|
||||||
BORDER, BORDER_STRONG, ELEVATED_BG, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED, WARNING,
|
BORDER, BORDER_STRONG, ELEVATED_BG, ERROR, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED,
|
||||||
|
WARNING,
|
||||||
};
|
};
|
||||||
use super::widgets::{
|
use super::widgets::{
|
||||||
icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent,
|
icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent,
|
||||||
@@ -40,6 +42,7 @@ use super::widgets::{
|
|||||||
pub struct ViewportUiState {
|
pub struct ViewportUiState {
|
||||||
pub options_open: bool,
|
pub options_open: bool,
|
||||||
pub shortcuts_open: bool,
|
pub shortcuts_open: bool,
|
||||||
|
pub toolbar_rect: Option<egui::Rect>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const VIEWPORT_TOOLTIP: &str = "RMB + WASD/QE: fly | MMB: pan | Scroll: dolly\nW/E/R: gizmo | X: world/local | F: focus | G: game view | Ctrl+G: grid\nTab: cycle overlapping picks | Play/Pause/Stop: main toolbar (F5 / F6)";
|
const VIEWPORT_TOOLTIP: &str = "RMB + WASD/QE: fly | MMB: pan | Scroll: dolly\nW/E/R: gizmo | X: world/local | F: focus | G: game view | Ctrl+G: grid\nTab: cycle overlapping picks | Play/Pause/Stop: main toolbar (F5 / F6)";
|
||||||
@@ -69,9 +72,17 @@ pub fn viewport_tab_ui(
|
|||||||
|
|
||||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||||
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
|
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
|
||||||
*viewport_pointer_pos = response
|
// A drag source owns egui's interaction response, so `Response::hover_pos()`
|
||||||
.interact_pointer_pos()
|
// is intentionally empty while an asset is dragged over the viewport. The
|
||||||
.or_else(|| response.hover_pos())
|
// global pointer position remains available and is the correct input for
|
||||||
|
// drag previews and exact surface targeting.
|
||||||
|
*viewport_pointer_pos = ui
|
||||||
|
.input(|input| {
|
||||||
|
input
|
||||||
|
.pointer
|
||||||
|
.interact_pos()
|
||||||
|
.or_else(|| input.pointer.hover_pos())
|
||||||
|
})
|
||||||
.filter(|pos| rect.contains(*pos));
|
.filter(|pos| rect.contains(*pos));
|
||||||
*pointer_in_viewport = viewport_pointer_pos.is_some();
|
*pointer_in_viewport = viewport_pointer_pos.is_some();
|
||||||
|
|
||||||
@@ -137,6 +148,7 @@ pub fn viewport_tab_ui(
|
|||||||
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
||||||
scene_view_selection_hud(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_brush_draw_hints(world, ui.ctx(), rect);
|
||||||
|
scene_view_terrain_sculpt_hints(world, ui.ctx(), rect);
|
||||||
scene_view_render_badge(world, ui.ctx(), rect);
|
scene_view_render_badge(world, ui.ctx(), rect);
|
||||||
scene_view_brush_mode_badge(world, ui.ctx(), rect);
|
scene_view_brush_mode_badge(world, ui.ctx(), rect);
|
||||||
scene_view_volume_hud(world, ui.ctx(), rect);
|
scene_view_volume_hud(world, ui.ctx(), rect);
|
||||||
@@ -295,6 +307,48 @@ fn scene_view_brush_draw_hints(world: &World, ctx: &egui::Context, scene_rect: e
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn scene_view_terrain_sculpt_hints(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||||
|
let Some(tool) = world.get_resource::<TerrainSculptState>() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if !tool.active {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
egui::Area::new(egui::Id::new("scene_view_terrain_sculpt_hints"))
|
||||||
|
.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(
|
||||||
|
egui::RichText::new(format!("Terrain {}", tool.mode.label()))
|
||||||
|
.color(SELECTION)
|
||||||
|
.strong(),
|
||||||
|
);
|
||||||
|
ui.label(
|
||||||
|
egui::RichText::new(format!("R {:.1}m", tool.radius))
|
||||||
|
.color(TEXT_DIM)
|
||||||
|
.monospace()
|
||||||
|
.small(),
|
||||||
|
);
|
||||||
|
ui.label(
|
||||||
|
egui::RichText::new(format!("S {:.2}m", tool.strength))
|
||||||
|
.color(SUCCESS)
|
||||||
|
.monospace()
|
||||||
|
.small(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.add_space(4.0);
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
key_hint(ui, "LMB Drag", "Sculpt");
|
||||||
|
key_hint(ui, "Esc", "Cancel stroke / close");
|
||||||
|
key_hint(ui, "RMB", "Cancel stroke / close");
|
||||||
|
key_hint(ui, "Ctrl+Z", "Undo stroke");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn key_hint(ui: &mut egui::Ui, key: &str, label: &str) {
|
fn key_hint(ui: &mut egui::Ui, key: &str, label: &str) {
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.label(
|
ui.label(
|
||||||
@@ -483,8 +537,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) {
|
||||||
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
||||||
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
||||||
|
let terrain_selected = world
|
||||||
|
.resource::<crate::selection::SelectedEntity>()
|
||||||
|
.0
|
||||||
|
.filter(|entity| world.get::<shared::TerrainDesc>(*entity).is_some());
|
||||||
|
|
||||||
egui::Area::new(egui::Id::new("scene_view_toolbar"))
|
let toolbar_response = egui::Area::new(egui::Id::new("scene_view_toolbar"))
|
||||||
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
|
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
|
||||||
.interactable(true)
|
.interactable(true)
|
||||||
.show(ctx, |ui| {
|
.show(ctx, |ui| {
|
||||||
@@ -613,6 +671,83 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let sculpt_active = world.resource::<TerrainSculptState>().active;
|
||||||
|
if terrain_selected.is_some() || sculpt_active {
|
||||||
|
ui.separator();
|
||||||
|
let stroking = world.resource::<TerrainSculptState>().is_stroking();
|
||||||
|
let sculpt_button_clicked = tool_button_accent(
|
||||||
|
ui,
|
||||||
|
icons::MOUNTAINS,
|
||||||
|
sculpt_active,
|
||||||
|
if sculpt_active {
|
||||||
|
"Close terrain sculpt tool"
|
||||||
|
} else {
|
||||||
|
"Sculpt selected terrain"
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.clicked();
|
||||||
|
if sculpt_button_clicked {
|
||||||
|
world.resource_mut::<ViewportClick>().0 = None;
|
||||||
|
}
|
||||||
|
if sculpt_button_clicked && !stroking {
|
||||||
|
let state = &mut *world.resource_mut::<TerrainSculptState>();
|
||||||
|
if state.active {
|
||||||
|
state.stop();
|
||||||
|
} else if let Some(entity) = terrain_selected {
|
||||||
|
state.start(entity);
|
||||||
|
}
|
||||||
|
let active = state.active;
|
||||||
|
if active {
|
||||||
|
world.resource_mut::<BrushToolState>().cancel();
|
||||||
|
world
|
||||||
|
.resource_mut::<crate::operators::ActiveOperator>()
|
||||||
|
.status = Some(crate::operators::OperatorStatus {
|
||||||
|
id: "terrain.sculpt".to_string(),
|
||||||
|
label: "Terrain Sculpt".to_string(),
|
||||||
|
phase: crate::operators::OperatorPhase::Preview,
|
||||||
|
hint: "LMB drag sculpts; Esc or RMB cancels".to_string(),
|
||||||
|
warnings: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sculpt_active {
|
||||||
|
let mut mode = world.resource::<TerrainSculptState>().mode;
|
||||||
|
for candidate in [
|
||||||
|
TerrainSculptMode::Raise,
|
||||||
|
TerrainSculptMode::Lower,
|
||||||
|
TerrainSculptMode::Flatten,
|
||||||
|
TerrainSculptMode::Smooth,
|
||||||
|
TerrainSculptMode::Noise,
|
||||||
|
] {
|
||||||
|
ui.selectable_value(&mut mode, candidate, candidate.label())
|
||||||
|
.on_hover_text(format!("{} terrain", candidate.label()));
|
||||||
|
}
|
||||||
|
let mut radius = world.resource::<TerrainSculptState>().radius;
|
||||||
|
let mut strength = world.resource::<TerrainSculptState>().strength;
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut radius)
|
||||||
|
.range(0.25..=128.0)
|
||||||
|
.speed(0.1)
|
||||||
|
.prefix("R ")
|
||||||
|
.suffix(" m"),
|
||||||
|
)
|
||||||
|
.on_hover_text("Brush radius");
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut strength)
|
||||||
|
.range(0.01..=20.0)
|
||||||
|
.speed(0.05)
|
||||||
|
.prefix("S ")
|
||||||
|
.suffix(" m"),
|
||||||
|
)
|
||||||
|
.on_hover_text("Height strength per dab");
|
||||||
|
let mut state = world.resource_mut::<TerrainSculptState>();
|
||||||
|
state.mode = mode;
|
||||||
|
state.radius = radius;
|
||||||
|
state.strength = strength;
|
||||||
|
state.clamp_settings();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||||
if tool_button(
|
if tool_button(
|
||||||
ui,
|
ui,
|
||||||
@@ -640,6 +775,13 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let toolbar_clicked = toolbar_response.response.contains_pointer()
|
||||||
|
&& ctx.input(|input| input.pointer.button_clicked(egui::PointerButton::Primary));
|
||||||
|
if toolbar_clicked {
|
||||||
|
world.resource_mut::<ViewportClick>().0 = None;
|
||||||
|
}
|
||||||
|
world.resource_mut::<ViewportUiState>().toolbar_rect = Some(toolbar_response.response.rect);
|
||||||
|
|
||||||
if options_open {
|
if options_open {
|
||||||
scene_options_popover(world, ctx, scene_rect, &mut options_open);
|
scene_options_popover(world, ctx, scene_rect, &mut options_open);
|
||||||
}
|
}
|
||||||
@@ -820,11 +962,44 @@ fn viewport_asset_drop_ui(
|
|||||||
.resource::<EditorAssets>()
|
.resource::<EditorAssets>()
|
||||||
.dragging_selection()
|
.dragging_selection()
|
||||||
.cloned();
|
.cloned();
|
||||||
let drag_descriptor = drag_selection
|
let surface_drag = drag_selection
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|selection| is_surface_asset_selection(world, selection));
|
||||||
|
let mut drag_descriptor = drag_selection
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|selection| asset_drag_descriptor(world, selection, selected));
|
.and_then(|selection| asset_drag_descriptor(world, selection, selected));
|
||||||
let over_viewport = pointer_pos.is_some_and(|pos| viewport_rect.contains(pos));
|
let over_viewport = pointer_pos.is_some_and(|pos| viewport_rect.contains(pos));
|
||||||
|
let surface_feedback = surface_drag
|
||||||
|
.then(|| world.get_resource::<MaterialDropState>())
|
||||||
|
.flatten()
|
||||||
|
.and_then(MaterialDropState::feedback)
|
||||||
|
.cloned();
|
||||||
|
if surface_drag && over_viewport {
|
||||||
|
if let Some((_, _, action)) = drag_descriptor.as_mut() {
|
||||||
|
*action = surface_feedback
|
||||||
|
.as_ref()
|
||||||
|
.map(|feedback| feedback.action.clone())
|
||||||
|
.unwrap_or_else(|| "Finding an assignable surface".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let drop_valid = (surface_drag && over_viewport)
|
||||||
|
.then(|| surface_feedback.as_ref().map(|feedback| feedback.valid))
|
||||||
|
.flatten();
|
||||||
|
let highlight_color = match drop_valid {
|
||||||
|
Some(true) => SUCCESS,
|
||||||
|
Some(false) => ERROR,
|
||||||
|
None => ACCENT_HOVER,
|
||||||
|
};
|
||||||
|
|
||||||
|
let drag_visual_state = if !over_viewport {
|
||||||
|
AssetDragVisualState::Outside
|
||||||
|
} else {
|
||||||
|
match drop_valid {
|
||||||
|
Some(true) => AssetDragVisualState::Valid,
|
||||||
|
Some(false) => AssetDragVisualState::Invalid,
|
||||||
|
None => AssetDragVisualState::Targeted,
|
||||||
|
}
|
||||||
|
};
|
||||||
if let (Some(pointer), Some((icon, label, action))) = (pointer_pos, drag_descriptor.as_ref()) {
|
if let (Some(pointer), Some((icon, label, action))) = (pointer_pos, drag_descriptor.as_ref()) {
|
||||||
draw_asset_drag_preview(
|
draw_asset_drag_preview(
|
||||||
ui,
|
ui,
|
||||||
@@ -833,7 +1008,7 @@ fn viewport_asset_drop_ui(
|
|||||||
*icon,
|
*icon,
|
||||||
label,
|
label,
|
||||||
action,
|
action,
|
||||||
over_viewport,
|
drag_visual_state,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -841,7 +1016,7 @@ fn viewport_asset_drop_ui(
|
|||||||
ui.painter().rect_stroke(
|
ui.painter().rect_stroke(
|
||||||
viewport_rect.shrink(2.0),
|
viewport_rect.shrink(2.0),
|
||||||
0.0,
|
0.0,
|
||||||
egui::Stroke::new(2.0, ACCENT_HOVER),
|
egui::Stroke::new(2.0, highlight_color),
|
||||||
egui::StrokeKind::Inside,
|
egui::StrokeKind::Inside,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -851,6 +1026,11 @@ fn viewport_asset_drop_ui(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if surface_drag && over_viewport {
|
||||||
|
// The Last-schedule surface-drop session owns exact hit resolution and commit.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
|
if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
|
||||||
world.resource_mut::<EditorAssets>().clear_drag();
|
world.resource_mut::<EditorAssets>().clear_drag();
|
||||||
return;
|
return;
|
||||||
@@ -903,26 +1083,6 @@ fn viewport_asset_drop_ui(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let AssetSelection::SubAsset {
|
|
||||||
kind: AssetSubAssetKind::Texture,
|
|
||||||
source_path: Some(path),
|
|
||||||
label,
|
|
||||||
..
|
|
||||||
} = &selection
|
|
||||||
{
|
|
||||||
let asset = crate::assets::EditorAsset {
|
|
||||||
label: label.clone(),
|
|
||||||
path: Some(path.clone()),
|
|
||||||
folder_path: std::path::Path::new(path)
|
|
||||||
.parent()
|
|
||||||
.map(|parent| parent.to_string_lossy().replace('\\', "/"))
|
|
||||||
.unwrap_or_else(|| crate::assets::ASSETS_ROOT.to_string()),
|
|
||||||
kind: crate::assets::EditorAssetKind::Texture,
|
|
||||||
};
|
|
||||||
apply_texture_operator(world, asset, selected);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let asset = {
|
let asset = {
|
||||||
let assets = world.resource::<EditorAssets>();
|
let assets = world.resource::<EditorAssets>();
|
||||||
assets.asset_for_selection(&selection).cloned()
|
assets.asset_for_selection(&selection).cloned()
|
||||||
@@ -943,18 +1103,6 @@ fn viewport_asset_drop_ui(
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
match asset.kind {
|
|
||||||
crate::assets::EditorAssetKind::Texture => {
|
|
||||||
apply_texture_operator(world, asset, selected);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
crate::assets::EditorAssetKind::Material => {
|
|
||||||
apply_material_operator(world, asset, selected);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
place_asset_operator(world, asset, placement);
|
place_asset_operator(world, asset, placement);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -996,11 +1144,11 @@ fn asset_drag_descriptor(
|
|||||||
AssetSelection::SubAsset {
|
AssetSelection::SubAsset {
|
||||||
kind: AssetSubAssetKind::Texture,
|
kind: AssetSubAssetKind::Texture,
|
||||||
..
|
..
|
||||||
} if !selected.is_empty() => "Apply texture to selection",
|
} => "Drop onto a primitive or brush face",
|
||||||
AssetSelection::SubAsset {
|
AssetSelection::SubAsset {
|
||||||
kind: AssetSubAssetKind::Material,
|
kind: AssetSubAssetKind::Material,
|
||||||
..
|
..
|
||||||
} if !selected.is_empty() => "Apply material to selection",
|
} => "Drop onto an exact renderer slot",
|
||||||
AssetSelection::SubAsset {
|
AssetSelection::SubAsset {
|
||||||
kind: AssetSubAssetKind::Skeleton,
|
kind: AssetSubAssetKind::Skeleton,
|
||||||
..
|
..
|
||||||
@@ -1020,12 +1168,8 @@ fn asset_drag_descriptor(
|
|||||||
..
|
..
|
||||||
} => "Create animated actor",
|
} => "Create animated actor",
|
||||||
_ => match asset.kind {
|
_ => match asset.kind {
|
||||||
crate::assets::EditorAssetKind::Texture if !selected.is_empty() => {
|
crate::assets::EditorAssetKind::Texture => "Drop onto a primitive or brush face",
|
||||||
"Apply texture to selection"
|
crate::assets::EditorAssetKind::Material => "Drop onto a renderable surface",
|
||||||
}
|
|
||||||
crate::assets::EditorAssetKind::Material if !selected.is_empty() => {
|
|
||||||
"Apply material to selection"
|
|
||||||
}
|
|
||||||
crate::assets::EditorAssetKind::AudioClip
|
crate::assets::EditorAssetKind::AudioClip
|
||||||
if selected
|
if selected
|
||||||
.as_slice()
|
.as_slice()
|
||||||
@@ -1041,6 +1185,29 @@ fn asset_drag_descriptor(
|
|||||||
Some((icon, label, action.to_string()))
|
Some((icon, label, action.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum AssetDragVisualState {
|
||||||
|
Outside,
|
||||||
|
Targeted,
|
||||||
|
Valid,
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssetDragVisualState {
|
||||||
|
fn over_viewport(self) -> bool {
|
||||||
|
self != Self::Outside
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(self) -> egui::Color32 {
|
||||||
|
match self {
|
||||||
|
Self::Outside => TEXT_DIM,
|
||||||
|
Self::Targeted => ACCENT_HOVER,
|
||||||
|
Self::Valid => SUCCESS,
|
||||||
|
Self::Invalid => ERROR,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn draw_asset_drag_preview(
|
fn draw_asset_drag_preview(
|
||||||
ui: &egui::Ui,
|
ui: &egui::Ui,
|
||||||
viewport_rect: egui::Rect,
|
viewport_rect: egui::Rect,
|
||||||
@@ -1048,39 +1215,41 @@ fn draw_asset_drag_preview(
|
|||||||
icon: egui_phosphor_icons::Icon,
|
icon: egui_phosphor_icons::Icon,
|
||||||
label: &str,
|
label: &str,
|
||||||
action: &str,
|
action: &str,
|
||||||
over_viewport: bool,
|
visual_state: AssetDragVisualState,
|
||||||
) {
|
) {
|
||||||
|
let over_viewport = visual_state.over_viewport();
|
||||||
|
let highlight_color = visual_state.color();
|
||||||
if over_viewport {
|
if over_viewport {
|
||||||
let painter = ui.painter();
|
let painter = ui.painter();
|
||||||
painter.circle_filled(pointer, 3.0, ACCENT_HOVER);
|
painter.circle_filled(pointer, 3.0, highlight_color);
|
||||||
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, ACCENT_HOVER));
|
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, highlight_color));
|
||||||
painter.line_segment(
|
painter.line_segment(
|
||||||
[
|
[
|
||||||
pointer - egui::vec2(17.0, 0.0),
|
pointer - egui::vec2(17.0, 0.0),
|
||||||
pointer - egui::vec2(7.0, 0.0),
|
pointer - egui::vec2(7.0, 0.0),
|
||||||
],
|
],
|
||||||
egui::Stroke::new(1.5, ACCENT_HOVER),
|
egui::Stroke::new(1.5, highlight_color),
|
||||||
);
|
);
|
||||||
painter.line_segment(
|
painter.line_segment(
|
||||||
[
|
[
|
||||||
pointer + egui::vec2(7.0, 0.0),
|
pointer + egui::vec2(7.0, 0.0),
|
||||||
pointer + egui::vec2(17.0, 0.0),
|
pointer + egui::vec2(17.0, 0.0),
|
||||||
],
|
],
|
||||||
egui::Stroke::new(1.5, ACCENT_HOVER),
|
egui::Stroke::new(1.5, highlight_color),
|
||||||
);
|
);
|
||||||
painter.line_segment(
|
painter.line_segment(
|
||||||
[
|
[
|
||||||
pointer - egui::vec2(0.0, 17.0),
|
pointer - egui::vec2(0.0, 17.0),
|
||||||
pointer - egui::vec2(0.0, 7.0),
|
pointer - egui::vec2(0.0, 7.0),
|
||||||
],
|
],
|
||||||
egui::Stroke::new(1.5, ACCENT_HOVER),
|
egui::Stroke::new(1.5, highlight_color),
|
||||||
);
|
);
|
||||||
painter.line_segment(
|
painter.line_segment(
|
||||||
[
|
[
|
||||||
pointer + egui::vec2(0.0, 7.0),
|
pointer + egui::vec2(0.0, 7.0),
|
||||||
pointer + egui::vec2(0.0, 17.0),
|
pointer + egui::vec2(0.0, 17.0),
|
||||||
],
|
],
|
||||||
egui::Stroke::new(1.5, ACCENT_HOVER),
|
egui::Stroke::new(1.5, highlight_color),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1101,7 +1270,7 @@ fn draw_asset_drag_preview(
|
|||||||
ui.set_width(228.0);
|
ui.set_width(228.0);
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.label(phosphor_icon(icon, 20.0).color(if over_viewport {
|
ui.label(phosphor_icon(icon, 20.0).color(if over_viewport {
|
||||||
ACCENT_HOVER
|
highlight_color
|
||||||
} else {
|
} else {
|
||||||
TEXT_DIM
|
TEXT_DIM
|
||||||
}));
|
}));
|
||||||
@@ -1116,7 +1285,7 @@ fn draw_asset_drag_preview(
|
|||||||
})
|
})
|
||||||
.size(11.0)
|
.size(11.0)
|
||||||
.color(if over_viewport {
|
.color(if over_viewport {
|
||||||
ACCENT_HOVER
|
highlight_color
|
||||||
} else {
|
} else {
|
||||||
TEXT_MUTED
|
TEXT_MUTED
|
||||||
}),
|
}),
|
||||||
@@ -1152,9 +1321,9 @@ fn draw_asset_drag_preview(
|
|||||||
),
|
),
|
||||||
] {
|
] {
|
||||||
ui.painter()
|
ui.painter()
|
||||||
.line_segment([a, a + b], egui::Stroke::new(3.0, ACCENT_HOVER));
|
.line_segment([a, a + b], egui::Stroke::new(3.0, highlight_color));
|
||||||
ui.painter()
|
ui.painter()
|
||||||
.line_segment([a, a + c], egui::Stroke::new(3.0, ACCENT_HOVER));
|
.line_segment([a, a + c], egui::Stroke::new(3.0, highlight_color));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -631,6 +631,10 @@ fn icon_for_actor_components(components: ActorIconComponents) -> ActorIconSpec {
|
|||||||
image: ActorIconImage::Mesh,
|
image: ActorIconImage::Mesh,
|
||||||
category: ActorIconCategory::Mesh,
|
category: ActorIconCategory::Mesh,
|
||||||
},
|
},
|
||||||
|
ActorKind::Terrain => ActorIconSpec {
|
||||||
|
image: ActorIconImage::Mesh,
|
||||||
|
category: ActorIconCategory::Mesh,
|
||||||
|
},
|
||||||
ActorKind::StaticMesh => {
|
ActorKind::StaticMesh => {
|
||||||
if components.has_primitive || components.has_static_mesh_renderer {
|
if components.has_primitive || components.has_static_mesh_renderer {
|
||||||
ActorIconSpec {
|
ActorIconSpec {
|
||||||
|
|||||||
@@ -1047,6 +1047,17 @@ fn pick_face(
|
|||||||
best
|
best
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn pick_brush_face_id(
|
||||||
|
brush: &BrushDesc,
|
||||||
|
transform: &GlobalTransform,
|
||||||
|
ray: Ray3d,
|
||||||
|
) -> Option<(ComponentInstanceId, f32)> {
|
||||||
|
let (BrushElementKey::Face { face }, distance) = pick_face(brush, transform, ray)? else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
Some((face, distance))
|
||||||
|
}
|
||||||
|
|
||||||
fn world_vertices(face: &BrushFaceDesc, transform: &GlobalTransform) -> Vec<Vec3> {
|
fn world_vertices(face: &BrushFaceDesc, transform: &GlobalTransform) -> Vec<Vec3> {
|
||||||
face.vertices
|
face.vertices
|
||||||
.iter()
|
.iter()
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -6,11 +6,13 @@ pub mod brush_edit;
|
|||||||
pub mod brush_tool;
|
pub mod brush_tool;
|
||||||
pub mod camera;
|
pub mod camera;
|
||||||
pub mod gizmos;
|
pub mod gizmos;
|
||||||
|
pub mod material_drop;
|
||||||
mod panel;
|
mod panel;
|
||||||
pub mod render_view;
|
pub mod render_view;
|
||||||
pub mod rendering_diagnostics;
|
pub mod rendering_diagnostics;
|
||||||
pub mod selection;
|
pub mod selection;
|
||||||
pub mod selection_outline;
|
pub mod selection_outline;
|
||||||
|
pub mod terrain_sculpt;
|
||||||
pub mod viewport_mode;
|
pub mod viewport_mode;
|
||||||
pub mod visualizers;
|
pub mod visualizers;
|
||||||
|
|
||||||
@@ -21,5 +23,7 @@ pub use brush_csg::{
|
|||||||
};
|
};
|
||||||
pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
|
pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
|
||||||
pub use brush_tool::{BrushToolPlugin, BrushToolState};
|
pub use brush_tool::{BrushToolPlugin, BrushToolState};
|
||||||
|
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
|
||||||
pub use panel::*;
|
pub use panel::*;
|
||||||
|
pub use terrain_sculpt::{TerrainSculptMode, TerrainSculptPlugin, TerrainSculptState};
|
||||||
pub use viewport_mode::EditorViewportMode;
|
pub use viewport_mode::EditorViewportMode;
|
||||||
@@ -14,6 +14,7 @@ use crate::ui::helpers::ensure_player_spawn_for_edit;
|
|||||||
use crate::ui::hierarchy_ops::is_entity_locked;
|
use crate::ui::hierarchy_ops::is_entity_locked;
|
||||||
use crate::ui::hierarchy_state::HierarchyPanelState;
|
use crate::ui::hierarchy_state::HierarchyPanelState;
|
||||||
use crate::ui::UiState;
|
use crate::ui::UiState;
|
||||||
|
use crate::ui::ViewportUiState;
|
||||||
use crate::viewport::actor_icons::ActorIconProxy;
|
use crate::viewport::actor_icons::ActorIconProxy;
|
||||||
use crate::viewport::brush_edit::{BrushEditMode, BrushElementGizmo};
|
use crate::viewport::brush_edit::{BrushEditMode, BrushElementGizmo};
|
||||||
use crate::viewport::brush_tool::BrushToolState;
|
use crate::viewport::brush_tool::BrushToolState;
|
||||||
@@ -21,7 +22,9 @@ use crate::viewport::ViewportDisplayMode;
|
|||||||
use crate::visualizers::EditorVisualizerProxy;
|
use crate::visualizers::EditorVisualizerProxy;
|
||||||
use bevy_egui::egui;
|
use bevy_egui::egui;
|
||||||
|
|
||||||
|
use crate::viewport::material_drop::{MaterialDropSet, MaterialDropState};
|
||||||
use crate::viewport::scene_view_ray;
|
use crate::viewport::scene_view_ray;
|
||||||
|
use crate::viewport::terrain_sculpt::TerrainSculptState;
|
||||||
|
|
||||||
#[derive(Resource, Default, Debug, Clone, Copy)]
|
#[derive(Resource, Default, Debug, Clone, Copy)]
|
||||||
pub struct SelectedEntity(pub Option<Entity>);
|
pub struct SelectedEntity(pub Option<Entity>);
|
||||||
@@ -47,6 +50,9 @@ struct PickTargetQueries<'w, 's> {
|
|||||||
icon_proxies: Query<'w, 's, &'static ActorIconProxy>,
|
icon_proxies: Query<'w, 's, &'static ActorIconProxy>,
|
||||||
parents: Query<'w, 's, &'static ChildOf>,
|
parents: Query<'w, 's, &'static ChildOf>,
|
||||||
editor_only: Query<'w, 's, (), With<EditorOnly>>,
|
editor_only: Query<'w, 's, (), With<EditorOnly>>,
|
||||||
|
material_drop: Option<Res<'w, MaterialDropState>>,
|
||||||
|
terrain_sculpt: Res<'w, TerrainSculptState>,
|
||||||
|
viewport_ui: Res<'w, ViewportUiState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Plugin for EditorSelectionPlugin {
|
impl Plugin for EditorSelectionPlugin {
|
||||||
@@ -68,6 +74,7 @@ impl Plugin for EditorSelectionPlugin {
|
|||||||
Last,
|
Last,
|
||||||
(handle_pick_events, cycle_overlapping_viewport_pick)
|
(handle_pick_events, cycle_overlapping_viewport_pick)
|
||||||
.chain()
|
.chain()
|
||||||
|
.after(MaterialDropSet)
|
||||||
.run_if(scene_tools_active),
|
.run_if(scene_tools_active),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -110,6 +117,29 @@ fn handle_pick_events(
|
|||||||
gizmo_targets: Query<&GizmoTarget>,
|
gizmo_targets: Query<&GizmoTarget>,
|
||||||
hierarchy: Option<Res<HierarchyPanelState>>,
|
hierarchy: Option<Res<HierarchyPanelState>>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
|
if ui_state.viewport_pointer_pos.is_some_and(|pointer| {
|
||||||
|
pick_targets
|
||||||
|
.viewport_ui
|
||||||
|
.toolbar_rect
|
||||||
|
.is_some_and(|rect| rect.contains(pointer))
|
||||||
|
}) {
|
||||||
|
viewport_click.0 = None;
|
||||||
|
for _ in click_events.read() {}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if pick_targets.terrain_sculpt.active {
|
||||||
|
viewport_click.0 = None;
|
||||||
|
for _ in click_events.read() {}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if pick_targets
|
||||||
|
.material_drop
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(MaterialDropState::captures_viewport_input)
|
||||||
|
{
|
||||||
|
viewport_click.0 = None;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
if ui_state.pointer_in_viewport
|
if ui_state.pointer_in_viewport
|
||||||
&& !buttons.any_pressed([MouseButton::Right, MouseButton::Middle])
|
&& !buttons.any_pressed([MouseButton::Right, MouseButton::Middle])
|
||||||
&& keys.just_pressed(KeyCode::Escape)
|
&& keys.just_pressed(KeyCode::Escape)
|
||||||
@@ -209,6 +239,10 @@ fn handle_pick_events(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[expect(
|
||||||
|
clippy::too_many_arguments,
|
||||||
|
reason = "selection cycling reads independent viewport input ownership resources"
|
||||||
|
)]
|
||||||
fn cycle_overlapping_viewport_pick(
|
fn cycle_overlapping_viewport_pick(
|
||||||
mut ui_state: ResMut<UiState>,
|
mut ui_state: ResMut<UiState>,
|
||||||
mut selected: ResMut<SelectedEntity>,
|
mut selected: ResMut<SelectedEntity>,
|
||||||
@@ -216,7 +250,18 @@ fn cycle_overlapping_viewport_pick(
|
|||||||
keys: Res<ButtonInput<KeyCode>>,
|
keys: Res<ButtonInput<KeyCode>>,
|
||||||
buttons: Res<ButtonInput<MouseButton>>,
|
buttons: Res<ButtonInput<MouseButton>>,
|
||||||
display: Res<ViewportDisplayMode>,
|
display: Res<ViewportDisplayMode>,
|
||||||
|
material_drop: Option<Res<MaterialDropState>>,
|
||||||
|
terrain_sculpt: Res<TerrainSculptState>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
|
if terrain_sculpt.active {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if material_drop
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(MaterialDropState::captures_viewport_input)
|
||||||
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
if display.clean_game_view {
|
if display.clean_game_view {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -397,13 +442,14 @@ fn sync_gizmo_targets(
|
|||||||
hierarchy: Option<Res<HierarchyPanelState>>,
|
hierarchy: Option<Res<HierarchyPanelState>>,
|
||||||
display: Res<ViewportDisplayMode>,
|
display: Res<ViewportDisplayMode>,
|
||||||
brush_mode: Res<BrushEditMode>,
|
brush_mode: Res<BrushEditMode>,
|
||||||
|
terrain_sculpt: Res<TerrainSculptState>,
|
||||||
) {
|
) {
|
||||||
ui_state
|
ui_state
|
||||||
.selected_entities
|
.selected_entities
|
||||||
.retain(|entity| transforms.contains(entity) && !editor_only.contains(entity));
|
.retain(|entity| transforms.contains(entity) && !editor_only.contains(entity));
|
||||||
selected.0 = ui_state.selected_entities.as_slice().first().copied();
|
selected.0 = ui_state.selected_entities.as_slice().first().copied();
|
||||||
|
|
||||||
if display.clean_game_view || brush_mode.is_element_mode() {
|
if display.clean_game_view || brush_mode.is_element_mode() || terrain_sculpt.active {
|
||||||
for (entity, brush_element_gizmo) in &targets {
|
for (entity, brush_element_gizmo) in &targets {
|
||||||
if brush_element_gizmo.is_none() {
|
if brush_element_gizmo.is_none() {
|
||||||
commands.entity(entity).remove::<GizmoTarget>();
|
commands.entity(entity).remove::<GizmoTarget>();
|
||||||
@@ -456,6 +502,7 @@ mod tests {
|
|||||||
.init_resource::<SelectedEntity>()
|
.init_resource::<SelectedEntity>()
|
||||||
.init_resource::<ViewportDisplayMode>()
|
.init_resource::<ViewportDisplayMode>()
|
||||||
.init_resource::<BrushEditMode>()
|
.init_resource::<BrushEditMode>()
|
||||||
|
.init_resource::<TerrainSculptState>()
|
||||||
.add_systems(Update, sync_gizmo_targets);
|
.add_systems(Update, sync_gizmo_targets);
|
||||||
|
|
||||||
app.update();
|
app.update();
|
||||||
@@ -470,4 +517,26 @@ mod tests {
|
|||||||
assert!(app.world().get::<GizmoTarget>(first).is_some());
|
assert!(app.world().get::<GizmoTarget>(first).is_some());
|
||||||
assert!(app.world().get::<GizmoTarget>(second).is_none());
|
assert!(app.world().get::<GizmoTarget>(second).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn terrain_sculpt_owns_pointer_without_transform_gizmo() {
|
||||||
|
let mut app = App::new();
|
||||||
|
let terrain = app
|
||||||
|
.world_mut()
|
||||||
|
.spawn((LevelObject, Transform::default(), GizmoTarget::default()))
|
||||||
|
.id();
|
||||||
|
let mut ui_state = UiState::default_layout();
|
||||||
|
ui_state.selected_entities.select_replace(terrain);
|
||||||
|
let mut sculpt = TerrainSculptState::default();
|
||||||
|
sculpt.start(terrain);
|
||||||
|
app.insert_resource(ui_state)
|
||||||
|
.insert_resource(sculpt)
|
||||||
|
.init_resource::<SelectedEntity>()
|
||||||
|
.init_resource::<ViewportDisplayMode>()
|
||||||
|
.init_resource::<BrushEditMode>()
|
||||||
|
.add_systems(Update, sync_gizmo_targets);
|
||||||
|
|
||||||
|
app.update();
|
||||||
|
assert!(app.world().get::<GizmoTarget>(terrain).is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,741 @@
|
|||||||
|
//! Modal terrain height sculpting with one history transaction per pointer stroke.
|
||||||
|
|
||||||
|
use bevy::prelude::*;
|
||||||
|
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::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||||
|
use crate::scene_io::SceneIo;
|
||||||
|
use crate::selection::{SelectedEntity, ViewportClick};
|
||||||
|
use crate::state::scene_tools_active;
|
||||||
|
use crate::ui::UiState;
|
||||||
|
use crate::viewport::{scene_view_ray, ViewportDisplayMode};
|
||||||
|
|
||||||
|
const MIN_RADIUS: f32 = 0.25;
|
||||||
|
const MAX_RADIUS: f32 = 128.0;
|
||||||
|
const MIN_STRENGTH: f32 = 0.01;
|
||||||
|
const MAX_STRENGTH: f32 = 20.0;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub enum TerrainSculptMode {
|
||||||
|
#[default]
|
||||||
|
Raise,
|
||||||
|
Lower,
|
||||||
|
Flatten,
|
||||||
|
Smooth,
|
||||||
|
Noise,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerrainSculptMode {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Raise => "Raise",
|
||||||
|
Self::Lower => "Lower",
|
||||||
|
Self::Flatten => "Flatten",
|
||||||
|
Self::Smooth => "Smooth",
|
||||||
|
Self::Noise => "Noise",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
struct TerrainHit {
|
||||||
|
entity: Entity,
|
||||||
|
local: Vec3,
|
||||||
|
world: Vec3,
|
||||||
|
world_rotation: Quat,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct TerrainStroke {
|
||||||
|
entity: Entity,
|
||||||
|
original: TerrainDesc,
|
||||||
|
last_local: Vec3,
|
||||||
|
flatten_height: f32,
|
||||||
|
seed: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Resource, Debug, Clone)]
|
||||||
|
pub struct TerrainSculptState {
|
||||||
|
pub active: bool,
|
||||||
|
pub mode: TerrainSculptMode,
|
||||||
|
pub radius: f32,
|
||||||
|
/// Approximate world-space height delta per dab.
|
||||||
|
pub strength: f32,
|
||||||
|
hover: Option<TerrainHit>,
|
||||||
|
stroke: Option<TerrainStroke>,
|
||||||
|
target: Option<Entity>,
|
||||||
|
next_seed: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TerrainSculptState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
active: false,
|
||||||
|
mode: TerrainSculptMode::Raise,
|
||||||
|
radius: 4.0,
|
||||||
|
strength: 0.35,
|
||||||
|
hover: None,
|
||||||
|
stroke: None,
|
||||||
|
target: None,
|
||||||
|
next_seed: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerrainSculptState {
|
||||||
|
pub fn start(&mut self, target: Entity) {
|
||||||
|
self.active = true;
|
||||||
|
self.target = Some(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
self.active = false;
|
||||||
|
self.hover = None;
|
||||||
|
self.target = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_stroking(&self) -> bool {
|
||||||
|
self.stroke.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clamp_settings(&mut self) {
|
||||||
|
self.radius = self.radius.clamp(MIN_RADIUS, MAX_RADIUS);
|
||||||
|
self.strength = self.strength.clamp(MIN_STRENGTH, MAX_STRENGTH);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TerrainSculptPlugin;
|
||||||
|
|
||||||
|
impl Plugin for TerrainSculptPlugin {
|
||||||
|
fn build(&self, app: &mut App) {
|
||||||
|
app.init_resource::<TerrainSculptState>().add_systems(
|
||||||
|
Update,
|
||||||
|
(terrain_sculpt_input, draw_terrain_sculpt_preview)
|
||||||
|
.chain()
|
||||||
|
.run_if(scene_tools_active),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn terrain_sculpt_input(
|
||||||
|
mut commands: Commands,
|
||||||
|
mut state: ResMut<TerrainSculptState>,
|
||||||
|
mut selected: ResMut<SelectedEntity>,
|
||||||
|
keys: Res<ButtonInput<KeyCode>>,
|
||||||
|
buttons: Res<ButtonInput<MouseButton>>,
|
||||||
|
mut contexts: EguiContexts,
|
||||||
|
ui_state: Res<UiState>,
|
||||||
|
display: Res<ViewportDisplayMode>,
|
||||||
|
cameras: Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
|
||||||
|
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||||
|
mut viewport_click: ResMut<ViewportClick>,
|
||||||
|
mut scene_io: ResMut<SceneIo>,
|
||||||
|
mut active_operator: ResMut<ActiveOperator>,
|
||||||
|
) -> Result {
|
||||||
|
if !state.active {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
viewport_click.0 = None;
|
||||||
|
state.clamp_settings();
|
||||||
|
|
||||||
|
let Some(entity) = state.target.or(selected.0) else {
|
||||||
|
cancel_stroke(&mut state, &mut terrains);
|
||||||
|
state.stop();
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if selected.0 != Some(entity) {
|
||||||
|
selected.0 = Some(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
if display.clean_game_view {
|
||||||
|
cancel_stroke(&mut state, &mut terrains);
|
||||||
|
state.stop();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let ctx = contexts.ctx_mut()?;
|
||||||
|
let pointer_over_ui = ctx.egui_wants_pointer_input();
|
||||||
|
let cancel_requested =
|
||||||
|
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(
|
||||||
|
&mut active_operator,
|
||||||
|
OperatorPhase::Canceled,
|
||||||
|
"Stroke canceled; terrain restored",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
state.stop();
|
||||||
|
scene_io.status = "Terrain sculpt tool closed".to_string();
|
||||||
|
set_status(&mut active_operator, OperatorPhase::Canceled, "Tool closed");
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok((global, mut terrain)) = terrains.get_mut(entity) else {
|
||||||
|
state.stroke = None;
|
||||||
|
state.stop();
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let hit = ui_state
|
||||||
|
.viewport_pointer_pos
|
||||||
|
.and_then(|pointer| active_scene_ray(&cameras, pointer, ui_state.viewport_rect))
|
||||||
|
.and_then(|ray| terrain_ray_hit(entity, &terrain, global, ray));
|
||||||
|
state.hover = hit;
|
||||||
|
|
||||||
|
if buttons.just_pressed(MouseButton::Left) && !pointer_over_ui {
|
||||||
|
if let Some(hit) = state.hover.filter(|hit| hit.entity == entity) {
|
||||||
|
let flatten_height =
|
||||||
|
sample_height_bilinear(&terrain, hit.local.x, hit.local.z).unwrap_or_default();
|
||||||
|
let seed = state.next_seed;
|
||||||
|
state.next_seed = state.next_seed.wrapping_add(1).max(1);
|
||||||
|
state.stroke = Some(TerrainStroke {
|
||||||
|
entity,
|
||||||
|
original: terrain.clone(),
|
||||||
|
last_local: hit.local,
|
||||||
|
flatten_height,
|
||||||
|
seed,
|
||||||
|
});
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
hit.local,
|
||||||
|
state.radius,
|
||||||
|
state.strength,
|
||||||
|
state.mode,
|
||||||
|
flatten_height,
|
||||||
|
seed,
|
||||||
|
);
|
||||||
|
set_status(
|
||||||
|
&mut active_operator,
|
||||||
|
OperatorPhase::Preview,
|
||||||
|
format!("{} stroke in progress", state.mode.label()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if buttons.pressed(MouseButton::Left) {
|
||||||
|
let radius = state.radius;
|
||||||
|
let strength = state.strength;
|
||||||
|
let mode = state.mode;
|
||||||
|
if let (Some(hit), Some(stroke)) = (state.hover, state.stroke.as_mut()) {
|
||||||
|
if hit.entity == stroke.entity {
|
||||||
|
let step = (radius * 0.2).max(terrain.sample_spacing * 0.25);
|
||||||
|
let delta = hit.local - stroke.last_local;
|
||||||
|
let distance = Vec2::new(delta.x, delta.z).length();
|
||||||
|
if distance >= step {
|
||||||
|
let count = (distance / step).floor() as usize;
|
||||||
|
for index in 1..=count {
|
||||||
|
let point = stroke.last_local + delta * (index as f32 / count as f32);
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
point,
|
||||||
|
radius,
|
||||||
|
strength,
|
||||||
|
mode,
|
||||||
|
stroke.flatten_height,
|
||||||
|
stroke.seed,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
stroke.last_local = hit.local;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if buttons.just_released(MouseButton::Left) {
|
||||||
|
if let Some(stroke) = state.stroke.take() {
|
||||||
|
let final_terrain = terrain.clone();
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_terrain_stroke(
|
||||||
|
world: &mut World,
|
||||||
|
stroke: TerrainStroke,
|
||||||
|
final_terrain: TerrainDesc,
|
||||||
|
label: &'static str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if let Ok(mut actor) = world.get_entity_mut(stroke.entity) {
|
||||||
|
actor.insert(stroke.original);
|
||||||
|
}
|
||||||
|
reflected_component_transaction(
|
||||||
|
world,
|
||||||
|
stroke.entity,
|
||||||
|
label,
|
||||||
|
AUTHORING_COMPONENT_TERRAIN,
|
||||||
|
COMPONENT_TERRAIN_DESC,
|
||||||
|
move |world, entity| {
|
||||||
|
world.entity_mut(entity).insert(final_terrain);
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cancel_stroke(
|
||||||
|
state: &mut TerrainSculptState,
|
||||||
|
terrains: &mut Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||||
|
) {
|
||||||
|
let Some(stroke) = state.stroke.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Ok((_, mut terrain)) = terrains.get_mut(stroke.entity) {
|
||||||
|
*terrain = stroke.original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_status(active: &mut ActiveOperator, phase: OperatorPhase, hint: impl Into<String>) {
|
||||||
|
active.status = Some(OperatorStatus {
|
||||||
|
id: "terrain.sculpt".to_string(),
|
||||||
|
label: "Terrain Sculpt".to_string(),
|
||||||
|
phase,
|
||||||
|
hint: hint.into(),
|
||||||
|
warnings: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sculpt_history_label(mode: TerrainSculptMode) -> &'static str {
|
||||||
|
match mode {
|
||||||
|
TerrainSculptMode::Raise => "Raise Terrain",
|
||||||
|
TerrainSculptMode::Lower => "Lower Terrain",
|
||||||
|
TerrainSculptMode::Flatten => "Flatten Terrain",
|
||||||
|
TerrainSculptMode::Smooth => "Smooth Terrain",
|
||||||
|
TerrainSculptMode::Noise => "Noise Terrain",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_scene_ray(
|
||||||
|
cameras: &Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
|
||||||
|
pointer: bevy_egui::egui::Pos2,
|
||||||
|
scene_rect: bevy_egui::egui::Rect,
|
||||||
|
) -> Option<Ray3d> {
|
||||||
|
let (camera, transform) = cameras
|
||||||
|
.iter()
|
||||||
|
.find(|(camera, _)| camera.is_active)
|
||||||
|
.or_else(|| cameras.iter().next())?;
|
||||||
|
scene_view_ray(camera, transform, pointer, scene_rect)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terrain_ray_hit(
|
||||||
|
entity: Entity,
|
||||||
|
terrain: &TerrainDesc,
|
||||||
|
global: &GlobalTransform,
|
||||||
|
ray: Ray3d,
|
||||||
|
) -> Option<TerrainHit> {
|
||||||
|
let world_from_local = global.affine();
|
||||||
|
let local_from_world = world_from_local.inverse();
|
||||||
|
let origin = local_from_world.transform_point3(ray.origin);
|
||||||
|
let direction = local_from_world.transform_vector3(ray.direction.as_vec3());
|
||||||
|
let local = ray_heightfield_intersection(terrain, origin, direction)?;
|
||||||
|
Some(TerrainHit {
|
||||||
|
entity,
|
||||||
|
local,
|
||||||
|
world: world_from_local.transform_point3(local),
|
||||||
|
world_rotation: global.rotation(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ray_heightfield_intersection(
|
||||||
|
terrain: &TerrainDesc,
|
||||||
|
origin: Vec3,
|
||||||
|
direction: Vec3,
|
||||||
|
) -> Option<Vec3> {
|
||||||
|
if terrain.validate().is_err() || direction.length_squared() <= f32::EPSILON {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let horizontal_speed = Vec2::new(direction.x, direction.z).length();
|
||||||
|
if horizontal_speed <= 1.0e-6 {
|
||||||
|
if direction.y.abs() <= 1.0e-6 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let height = sample_height_bilinear(terrain, origin.x, origin.z)?;
|
||||||
|
let t = (height - origin.y) / direction.y;
|
||||||
|
return (t >= 0.0).then_some(origin + direction * t);
|
||||||
|
}
|
||||||
|
let half_extent = (terrain.resolution - 1) as f32 * terrain.sample_spacing * 0.5;
|
||||||
|
let (mut start, mut end) = (0.0_f32, f32::INFINITY);
|
||||||
|
for (origin_axis, direction_axis) in [(origin.x, direction.x), (origin.z, direction.z)] {
|
||||||
|
if direction_axis.abs() <= 1.0e-6 {
|
||||||
|
if origin_axis < -half_extent || origin_axis > half_extent {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let a = (-half_extent - origin_axis) / direction_axis;
|
||||||
|
let b = (half_extent - origin_axis) / direction_axis;
|
||||||
|
start = start.max(a.min(b));
|
||||||
|
end = end.min(a.max(b));
|
||||||
|
}
|
||||||
|
if end < start || end < 0.0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
start = start.max(0.0);
|
||||||
|
|
||||||
|
let span = (end - start).max(0.0);
|
||||||
|
let steps = ((span * horizontal_speed) / (terrain.sample_spacing * 0.4))
|
||||||
|
.ceil()
|
||||||
|
.clamp(1.0, 8192.0) as usize;
|
||||||
|
let surface_delta = |t: f32| {
|
||||||
|
let point = origin + direction * t;
|
||||||
|
sample_height_bilinear(terrain, point.x, point.z).map(|height| point.y - height)
|
||||||
|
};
|
||||||
|
let mut previous_t = start;
|
||||||
|
let mut previous = surface_delta(start)?;
|
||||||
|
if previous.abs() <= 1.0e-4 {
|
||||||
|
return Some(origin + direction * start);
|
||||||
|
}
|
||||||
|
for step in 1..=steps {
|
||||||
|
let t = start + span * (step as f32 / steps as f32);
|
||||||
|
let current = surface_delta(t)?;
|
||||||
|
if current.signum() != previous.signum() || current.abs() <= 1.0e-4 {
|
||||||
|
let (mut low, mut high) = (previous_t, t);
|
||||||
|
let low_sign = previous.signum();
|
||||||
|
for _ in 0..14 {
|
||||||
|
let middle = (low + high) * 0.5;
|
||||||
|
let delta = surface_delta(middle)?;
|
||||||
|
if delta.signum() == low_sign {
|
||||||
|
low = middle;
|
||||||
|
} else {
|
||||||
|
high = middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hit_t = (low + high) * 0.5;
|
||||||
|
return Some(origin + direction * hit_t);
|
||||||
|
}
|
||||||
|
previous_t = t;
|
||||||
|
previous = current;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample_height_bilinear(terrain: &TerrainDesc, local_x: f32, local_z: f32) -> Option<f32> {
|
||||||
|
let half_extent = (terrain.resolution - 1) as f32 * terrain.sample_spacing * 0.5;
|
||||||
|
let x = (local_x + half_extent) / terrain.sample_spacing;
|
||||||
|
let z = (local_z + half_extent) / terrain.sample_spacing;
|
||||||
|
let max = (terrain.resolution - 1) as f32;
|
||||||
|
if x < 0.0 || z < 0.0 || x > max || z > max {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let x0 = x.floor() as u32;
|
||||||
|
let z0 = z.floor() as u32;
|
||||||
|
let x1 = (x0 + 1).min(terrain.resolution - 1);
|
||||||
|
let z1 = (z0 + 1).min(terrain.resolution - 1);
|
||||||
|
let sample = |sx: u32, sz: u32| {
|
||||||
|
terrain.heights[(sz * terrain.resolution + sx) as usize] * terrain.height_scale
|
||||||
|
};
|
||||||
|
let top = sample(x0, z0).lerp(sample(x1, z0), x - x0 as f32);
|
||||||
|
let bottom = sample(x0, z1).lerp(sample(x1, z1), x - x0 as f32);
|
||||||
|
Some(top.lerp(bottom, z - z0 as f32))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_dab(
|
||||||
|
terrain: &mut TerrainDesc,
|
||||||
|
center: Vec3,
|
||||||
|
radius: f32,
|
||||||
|
strength: f32,
|
||||||
|
mode: TerrainSculptMode,
|
||||||
|
flatten_height: f32,
|
||||||
|
seed: u32,
|
||||||
|
) {
|
||||||
|
let radius = radius.max(MIN_RADIUS);
|
||||||
|
let resolution = terrain.resolution;
|
||||||
|
let half_extent = (resolution - 1) as f32 * terrain.sample_spacing * 0.5;
|
||||||
|
let source = terrain.heights.clone();
|
||||||
|
let normalized_strength = strength / terrain.height_scale.max(0.01);
|
||||||
|
for z in 0..resolution {
|
||||||
|
for x in 0..resolution {
|
||||||
|
let sample_position = Vec2::new(
|
||||||
|
x as f32 * terrain.sample_spacing - half_extent,
|
||||||
|
z as f32 * terrain.sample_spacing - half_extent,
|
||||||
|
);
|
||||||
|
let distance = sample_position.distance(Vec2::new(center.x, center.z));
|
||||||
|
if distance > radius {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let falloff = smooth_falloff(distance / radius);
|
||||||
|
let index = (z * resolution + x) as usize;
|
||||||
|
let current = source[index];
|
||||||
|
let next = match mode {
|
||||||
|
TerrainSculptMode::Raise => current + normalized_strength * falloff,
|
||||||
|
TerrainSculptMode::Lower => current - normalized_strength * falloff,
|
||||||
|
TerrainSculptMode::Flatten => {
|
||||||
|
let target = flatten_height / terrain.height_scale.max(0.01);
|
||||||
|
current.lerp(target, (normalized_strength * falloff).clamp(0.0, 1.0))
|
||||||
|
}
|
||||||
|
TerrainSculptMode::Smooth => {
|
||||||
|
let average = neighbor_average(&source, resolution, x, z);
|
||||||
|
current.lerp(average, (normalized_strength * falloff).clamp(0.0, 1.0))
|
||||||
|
}
|
||||||
|
TerrainSculptMode::Noise => {
|
||||||
|
current + signed_noise(x, z, seed) * normalized_strength * falloff
|
||||||
|
}
|
||||||
|
};
|
||||||
|
terrain.heights[index] = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn smooth_falloff(normalized_distance: f32) -> f32 {
|
||||||
|
let t = (1.0 - normalized_distance).clamp(0.0, 1.0);
|
||||||
|
t * t * (3.0 - 2.0 * t)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn neighbor_average(heights: &[f32], resolution: u32, x: u32, z: u32) -> f32 {
|
||||||
|
let mut sum = 0.0;
|
||||||
|
let mut count = 0;
|
||||||
|
for dz in -1_i32..=1 {
|
||||||
|
for dx in -1_i32..=1 {
|
||||||
|
let sx = x as i32 + dx;
|
||||||
|
let sz = z as i32 + dz;
|
||||||
|
if sx >= 0 && sz >= 0 && sx < resolution as i32 && sz < resolution as i32 {
|
||||||
|
sum += heights[(sz as u32 * resolution + sx as u32) as usize];
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum / count as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signed_noise(x: u32, z: u32, seed: u32) -> f32 {
|
||||||
|
let mut value = x
|
||||||
|
.wrapping_mul(0x9e37_79b9)
|
||||||
|
.wrapping_add(z.wrapping_mul(0x85eb_ca6b))
|
||||||
|
.wrapping_add(seed.wrapping_mul(0xc2b2_ae35));
|
||||||
|
value ^= value >> 16;
|
||||||
|
value = value.wrapping_mul(0x7feb_352d);
|
||||||
|
value ^= value >> 15;
|
||||||
|
value = value.wrapping_mul(0x846c_a68b);
|
||||||
|
value ^= value >> 16;
|
||||||
|
(value as f32 / u32::MAX as f32) * 2.0 - 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_terrain_sculpt_preview(state: Res<TerrainSculptState>, mut gizmos: Gizmos) {
|
||||||
|
if !state.active {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(hit) = state.hover else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let color = match state.mode {
|
||||||
|
TerrainSculptMode::Raise => Color::srgba(0.30, 0.92, 0.58, 0.95),
|
||||||
|
TerrainSculptMode::Lower => Color::srgba(0.96, 0.36, 0.32, 0.95),
|
||||||
|
TerrainSculptMode::Flatten => Color::srgba(0.32, 0.72, 1.0, 0.95),
|
||||||
|
TerrainSculptMode::Smooth => Color::srgba(0.72, 0.56, 1.0, 0.95),
|
||||||
|
TerrainSculptMode::Noise => Color::srgba(1.0, 0.76, 0.28, 0.95),
|
||||||
|
};
|
||||||
|
let rotation = hit.world_rotation * Quat::from_rotation_x(std::f32::consts::FRAC_PI_2);
|
||||||
|
gizmos
|
||||||
|
.circle(
|
||||||
|
Isometry3d::new(hit.world + Vec3::Y * 0.03, rotation),
|
||||||
|
state.radius,
|
||||||
|
color,
|
||||||
|
)
|
||||||
|
.resolution(48);
|
||||||
|
gizmos.sphere(
|
||||||
|
Isometry3d::from_translation(hit.world + Vec3::Y * 0.035),
|
||||||
|
0.06,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||||
|
use shared::{ActorKind, LevelObject};
|
||||||
|
|
||||||
|
fn sample(terrain: &TerrainDesc, x: u32, z: u32) -> f32 {
|
||||||
|
terrain.heights[(z * terrain.resolution + x) as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vertical_ray_hits_heightfield_surface() {
|
||||||
|
let mut terrain = TerrainDesc::flat(3);
|
||||||
|
terrain.height_scale = 2.0;
|
||||||
|
terrain.heights[4] = 1.0;
|
||||||
|
let hit = ray_heightfield_intersection(&terrain, Vec3::new(0.0, 5.0, 0.0), Vec3::NEG_Y)
|
||||||
|
.expect("ray should hit center sample");
|
||||||
|
assert!((hit.y - 2.0).abs() < 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn raise_and_lower_only_touch_brush_footprint() {
|
||||||
|
let mut terrain = TerrainDesc::flat(5);
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
Vec3::ZERO,
|
||||||
|
1.1,
|
||||||
|
1.0,
|
||||||
|
TerrainSculptMode::Raise,
|
||||||
|
0.0,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
assert!(sample(&terrain, 2, 2) > 0.0);
|
||||||
|
assert_eq!(sample(&terrain, 0, 0), 0.0);
|
||||||
|
let raised = sample(&terrain, 2, 2);
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
Vec3::ZERO,
|
||||||
|
1.1,
|
||||||
|
1.0,
|
||||||
|
TerrainSculptMode::Lower,
|
||||||
|
0.0,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
assert!(sample(&terrain, 2, 2) < raised);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flatten_and_smooth_converge_toward_targets() {
|
||||||
|
let mut terrain = TerrainDesc::flat(3);
|
||||||
|
terrain.height_scale = 1.0;
|
||||||
|
terrain.heights[4] = 4.0;
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
Vec3::ZERO,
|
||||||
|
2.0,
|
||||||
|
1.0,
|
||||||
|
TerrainSculptMode::Smooth,
|
||||||
|
0.0,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
assert!(sample(&terrain, 1, 1) < 4.0);
|
||||||
|
apply_dab(
|
||||||
|
&mut terrain,
|
||||||
|
Vec3::ZERO,
|
||||||
|
2.0,
|
||||||
|
0.5,
|
||||||
|
TerrainSculptMode::Flatten,
|
||||||
|
2.0,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
assert!(sample(&terrain, 1, 1) > 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noise_is_deterministic_for_stroke_seed() {
|
||||||
|
let mut first = TerrainDesc::flat(5);
|
||||||
|
let mut second = first.clone();
|
||||||
|
for terrain in [&mut first, &mut second] {
|
||||||
|
apply_dab(
|
||||||
|
terrain,
|
||||||
|
Vec3::ZERO,
|
||||||
|
3.0,
|
||||||
|
0.4,
|
||||||
|
TerrainSculptMode::Noise,
|
||||||
|
0.0,
|
||||||
|
42,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(first.heights, second.heights);
|
||||||
|
assert!(first.heights.iter().any(|height| *height != 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn many_dabs_commit_as_one_undoable_stroke() {
|
||||||
|
let mut app = App::new();
|
||||||
|
app.register_type::<ActorKind>()
|
||||||
|
.register_type::<TerrainDesc>();
|
||||||
|
let world = app.world_mut();
|
||||||
|
world.init_resource::<EditorHistory>();
|
||||||
|
world.init_resource::<SceneIo>();
|
||||||
|
let original = TerrainDesc::flat(9);
|
||||||
|
let entity = world
|
||||||
|
.spawn((LevelObject, ActorKind::Terrain, original.clone()))
|
||||||
|
.id();
|
||||||
|
let mut final_terrain = original.clone();
|
||||||
|
for x in [-2.0, 0.0, 2.0] {
|
||||||
|
apply_dab(
|
||||||
|
&mut final_terrain,
|
||||||
|
Vec3::new(x, 0.0, 0.0),
|
||||||
|
2.5,
|
||||||
|
0.4,
|
||||||
|
TerrainSculptMode::Raise,
|
||||||
|
0.0,
|
||||||
|
7,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
world.entity_mut(entity).insert(final_terrain.clone());
|
||||||
|
commit_terrain_stroke(
|
||||||
|
world,
|
||||||
|
TerrainStroke {
|
||||||
|
entity,
|
||||||
|
original: original.clone(),
|
||||||
|
last_local: Vec3::ZERO,
|
||||||
|
flatten_height: 0.0,
|
||||||
|
seed: 7,
|
||||||
|
},
|
||||||
|
final_terrain.clone(),
|
||||||
|
"Raise Terrain",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(world.resource::<EditorHistory>().undo_depth(), 1);
|
||||||
|
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||||
|
apply_command_undo(world);
|
||||||
|
assert_eq!(world.get::<TerrainDesc>(entity), Some(&original));
|
||||||
|
apply_command_redo(world);
|
||||||
|
assert_eq!(world.get::<TerrainDesc>(entity), Some(&final_terrain));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cancel_restores_exact_pre_stroke_descriptor() {
|
||||||
|
fn cancel_once(
|
||||||
|
mut state: ResMut<TerrainSculptState>,
|
||||||
|
mut terrains: Query<(&GlobalTransform, &mut TerrainDesc)>,
|
||||||
|
) {
|
||||||
|
cancel_stroke(&mut state, &mut terrains);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut app = App::new();
|
||||||
|
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((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, cancel_once);
|
||||||
|
|
||||||
|
app.update();
|
||||||
|
assert_eq!(app.world().get::<TerrainDesc>(entity), Some(&original));
|
||||||
|
assert!(!app.world().resource::<TerrainSculptState>().is_stroking());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -94,7 +94,7 @@ mod hot {
|
|||||||
ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities,
|
ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities,
|
||||||
SimTuning,
|
SimTuning,
|
||||||
};
|
};
|
||||||
use shared::{InspectorOrder, LevelObject, LightDesc, ProjectSun};
|
use shared::{AuthoringComponentStates, InspectorOrder, LevelObject, LightDesc, ProjectSun};
|
||||||
use sim::{
|
use sim::{
|
||||||
CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState,
|
CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState,
|
||||||
Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity,
|
Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity,
|
||||||
|
|||||||
@@ -175,6 +175,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
|
|||||||
match kind {
|
match kind {
|
||||||
ActorKind::Empty => "Empty",
|
ActorKind::Empty => "Empty",
|
||||||
ActorKind::Brush => "Brush",
|
ActorKind::Brush => "Brush",
|
||||||
|
ActorKind::Terrain => "Terrain",
|
||||||
ActorKind::StaticMesh => "StaticMesh",
|
ActorKind::StaticMesh => "StaticMesh",
|
||||||
ActorKind::SkinnedMesh => "SkinnedMesh",
|
ActorKind::SkinnedMesh => "SkinnedMesh",
|
||||||
ActorKind::ImportedModel => "ImportedModel",
|
ActorKind::ImportedModel => "ImportedModel",
|
||||||
|
|||||||
@@ -227,17 +227,22 @@ impl Default for InputSettings {
|
|||||||
|
|
||||||
/// Loads settings from disk, falling back to defaults.
|
/// Loads settings from disk, falling back to defaults.
|
||||||
pub fn load_project_settings_from_path(path: &str) -> ProjectSettings {
|
pub fn load_project_settings_from_path(path: &str) -> ProjectSettings {
|
||||||
|
load_project_settings_with_source(path).0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads settings plus the exact source text used when the file was readable.
|
||||||
|
pub fn load_project_settings_with_source(path: &str) -> (ProjectSettings, Option<String>) {
|
||||||
match std::fs::read_to_string(path) {
|
match std::fs::read_to_string(path) {
|
||||||
Ok(contents) => match ron::from_str(&contents) {
|
Ok(contents) => match ron::from_str(&contents) {
|
||||||
Ok(settings) => settings,
|
Ok(settings) => (settings, Some(contents)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
warn!("Failed to parse {path}: {error}; using defaults");
|
warn!("Failed to parse {path}: {error}; using defaults");
|
||||||
ProjectSettings::default()
|
(ProjectSettings::default(), Some(contents))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
warn!("Could not read {path}: {error}; using defaults");
|
warn!("Could not read {path}: {error}; using defaults");
|
||||||
ProjectSettings::default()
|
(ProjectSettings::default(), None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,6 +271,27 @@ mod tests {
|
|||||||
assert_eq!(parsed.rendering.gi_mode, settings.rendering.gi_mode);
|
assert_eq!(parsed.rendering.gi_mode, settings.rendering.gi_mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settings_load_returns_the_exact_source_for_revision_guards() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-settings-source-{}",
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
));
|
||||||
|
let path = root.join("project.ron");
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
let source = save_project_settings_to_string(&ProjectSettings::default()).unwrap();
|
||||||
|
std::fs::write(&path, &source).unwrap();
|
||||||
|
|
||||||
|
let (settings, loaded_source) = load_project_settings_with_source(path.to_str().unwrap());
|
||||||
|
|
||||||
|
assert_eq!(settings.name, ProjectSettings::default().name);
|
||||||
|
assert_eq!(loaded_source.as_deref(), Some(source.as_str()));
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn legacy_manifest_defaults_project_identity_fields() {
|
fn legacy_manifest_defaults_project_identity_fields() {
|
||||||
let legacy = r#"(
|
let legacy = r#"(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
load_project_settings_from_path, save_project_settings_to_string, PhysicsSettings,
|
load_project_settings_with_source, save_project_settings_to_string, PhysicsSettings,
|
||||||
ProjectSettings, DEFAULT_PROJECT_PATH,
|
ProjectSettings, DEFAULT_PROJECT_PATH,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -56,6 +56,8 @@ impl SimTuning {
|
|||||||
pub struct ProjectSettingsIo {
|
pub struct ProjectSettingsIo {
|
||||||
pub path: String,
|
pub path: String,
|
||||||
pub dirty: bool,
|
pub dirty: bool,
|
||||||
|
/// Exact source loaded or last saved by this process; collaboration guards hash it.
|
||||||
|
pub loaded_source: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ProjectSettingsIo {
|
impl Default for ProjectSettingsIo {
|
||||||
@@ -63,6 +65,7 @@ impl Default for ProjectSettingsIo {
|
|||||||
Self {
|
Self {
|
||||||
path: DEFAULT_PROJECT_PATH.into(),
|
path: DEFAULT_PROJECT_PATH.into(),
|
||||||
dirty: false,
|
dirty: false,
|
||||||
|
loaded_source: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,8 +94,9 @@ impl Plugin for ProjectSettingsPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_settings(mut commands: Commands, io: Res<ProjectSettingsIo>) {
|
fn load_settings(mut commands: Commands, mut io: ResMut<ProjectSettingsIo>) {
|
||||||
let settings = load_project_settings_from_path(&io.path);
|
let (settings, source) = load_project_settings_with_source(&io.path);
|
||||||
|
io.loaded_source = source;
|
||||||
let tuning = SimTuning::from_physics(&settings.physics);
|
let tuning = SimTuning::from_physics(&settings.physics);
|
||||||
commands.insert_resource(settings);
|
commands.insert_resource(settings);
|
||||||
commands.insert_resource(tuning);
|
commands.insert_resource(tuning);
|
||||||
@@ -103,13 +107,17 @@ pub fn sync_sim_tuning(settings: &ProjectSettings, mut tuning: ResMut<SimTuning>
|
|||||||
*tuning = SimTuning::from_physics(&settings.physics);
|
*tuning = SimTuning::from_physics(&settings.physics);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Persists settings to the path in [`ProjectSettingsIo`].
|
/// Low-level unconditional persistence for non-editor callers.
|
||||||
|
///
|
||||||
|
/// The editor uses its guarded authored-file publication path instead so external revisions cannot
|
||||||
|
/// be overwritten.
|
||||||
pub fn save_project_settings(
|
pub fn save_project_settings(
|
||||||
settings: &ProjectSettings,
|
settings: &ProjectSettings,
|
||||||
io: &mut ProjectSettingsIo,
|
io: &mut ProjectSettingsIo,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let text = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
|
let text = save_project_settings_to_string(settings).map_err(|error| error.to_string())?;
|
||||||
std::fs::write(&io.path, text).map_err(|error| error.to_string())?;
|
std::fs::write(&io.path, &text).map_err(|error| error.to_string())?;
|
||||||
|
io.loaded_source = Some(text);
|
||||||
io.dirty = false;
|
io.dirty = false;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,7 @@ use crate::{
|
|||||||
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
|
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
|
||||||
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
|
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
|
||||||
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
|
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
|
||||||
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TerrainDesc, TriggerVolume, WeaponSpawn,
|
||||||
AUDIO_CLIP_SUB_ASSET_ID,
|
AUDIO_CLIP_SUB_ASSET_ID,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -31,6 +31,9 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
|
|||||||
if entity.get::<BrushDesc>().is_some() {
|
if entity.get::<BrushDesc>().is_some() {
|
||||||
return Some(ActorKind::Brush);
|
return Some(ActorKind::Brush);
|
||||||
}
|
}
|
||||||
|
if entity.get::<TerrainDesc>().is_some() {
|
||||||
|
return Some(ActorKind::Terrain);
|
||||||
|
}
|
||||||
if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
|
if entity.get::<Primitive>().is_some() || entity.get::<StaticMeshRenderer>().is_some() {
|
||||||
return Some(ActorKind::StaticMesh);
|
return Some(ActorKind::StaticMesh);
|
||||||
}
|
}
|
||||||
@@ -84,6 +87,7 @@ pub enum ActorValidationError {
|
|||||||
BrushHasLight,
|
BrushHasLight,
|
||||||
BrushHasModelRef,
|
BrushHasModelRef,
|
||||||
InvalidBrushGeometry(String),
|
InvalidBrushGeometry(String),
|
||||||
|
InvalidTerrain(String),
|
||||||
StaticMeshMissingPrimitive,
|
StaticMeshMissingPrimitive,
|
||||||
StaticMeshHasLight,
|
StaticMeshHasLight,
|
||||||
StaticMeshHasModelRef,
|
StaticMeshHasModelRef,
|
||||||
@@ -166,6 +170,7 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
|||||||
}
|
}
|
||||||
let geometry_source_count = usize::from(entity.get::<Primitive>().is_some())
|
let geometry_source_count = usize::from(entity.get::<Primitive>().is_some())
|
||||||
+ usize::from(entity.get::<BrushDesc>().is_some())
|
+ usize::from(entity.get::<BrushDesc>().is_some())
|
||||||
|
+ usize::from(entity.get::<TerrainDesc>().is_some())
|
||||||
+ usize::from(entity.get::<StaticMeshRenderer>().is_some())
|
+ usize::from(entity.get::<StaticMeshRenderer>().is_some())
|
||||||
+ usize::from(entity.get::<SkinnedMeshRenderer>().is_some())
|
+ usize::from(entity.get::<SkinnedMeshRenderer>().is_some())
|
||||||
+ usize::from(entity.get::<ModelRef>().is_some());
|
+ usize::from(entity.get::<ModelRef>().is_some());
|
||||||
@@ -186,6 +191,11 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
|||||||
return Err(ActorValidationError::InvalidBrushGeometry(message));
|
return Err(ActorValidationError::InvalidBrushGeometry(message));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(terrain) = entity.get::<TerrainDesc>() {
|
||||||
|
terrain
|
||||||
|
.validate()
|
||||||
|
.map_err(ActorValidationError::InvalidTerrain)?;
|
||||||
|
}
|
||||||
if let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
|
if let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
|
||||||
if renderer.path.trim().is_empty() {
|
if renderer.path.trim().is_empty() {
|
||||||
return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
|
return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
|
||||||
@@ -218,6 +228,13 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
|
|||||||
}
|
}
|
||||||
let _ = brush;
|
let _ = brush;
|
||||||
}
|
}
|
||||||
|
ActorKind::Terrain => {
|
||||||
|
if entity.get::<TerrainDesc>().is_none() {
|
||||||
|
return Err(ActorValidationError::InvalidTerrain(
|
||||||
|
"terrain actor is missing TerrainDesc".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
ActorKind::StaticMesh => {
|
ActorKind::StaticMesh => {
|
||||||
let has_static_mesh_renderer = entity
|
let has_static_mesh_renderer = entity
|
||||||
.get::<StaticMeshRenderer>()
|
.get::<StaticMeshRenderer>()
|
||||||
|
|||||||
@@ -290,6 +290,7 @@ pub fn inspector_component_active(order: Option<&InspectorOrder>, type_name: &st
|
|||||||
// Rust type paths remain serialization details and may change during refactors.
|
// Rust type paths remain serialization details and may change during refactors.
|
||||||
pub const AUTHORING_COMPONENT_PRIMITIVE: &str = "render.primitive";
|
pub const AUTHORING_COMPONENT_PRIMITIVE: &str = "render.primitive";
|
||||||
pub const AUTHORING_COMPONENT_BRUSH: &str = "render.brush";
|
pub const AUTHORING_COMPONENT_BRUSH: &str = "render.brush";
|
||||||
|
pub const AUTHORING_COMPONENT_TERRAIN: &str = "render.terrain";
|
||||||
pub const AUTHORING_COMPONENT_STATIC_MESH_RENDERER: &str = "render.static_mesh_renderer";
|
pub const AUTHORING_COMPONENT_STATIC_MESH_RENDERER: &str = "render.static_mesh_renderer";
|
||||||
pub const AUTHORING_COMPONENT_SKINNED_MESH_RENDERER: &str = "render.skinned_mesh_renderer";
|
pub const AUTHORING_COMPONENT_SKINNED_MESH_RENDERER: &str = "render.skinned_mesh_renderer";
|
||||||
pub const AUTHORING_COMPONENT_MATERIAL: &str = "render.material";
|
pub const AUTHORING_COMPONENT_MATERIAL: &str = "render.material";
|
||||||
@@ -318,6 +319,7 @@ pub fn authoring_component_id(key: &str) -> Option<&'static str> {
|
|||||||
match key {
|
match key {
|
||||||
AUTHORING_COMPONENT_PRIMITIVE | COMPONENT_PRIMITIVE => Some(AUTHORING_COMPONENT_PRIMITIVE),
|
AUTHORING_COMPONENT_PRIMITIVE | COMPONENT_PRIMITIVE => Some(AUTHORING_COMPONENT_PRIMITIVE),
|
||||||
AUTHORING_COMPONENT_BRUSH | COMPONENT_BRUSH_DESC => Some(AUTHORING_COMPONENT_BRUSH),
|
AUTHORING_COMPONENT_BRUSH | COMPONENT_BRUSH_DESC => Some(AUTHORING_COMPONENT_BRUSH),
|
||||||
|
AUTHORING_COMPONENT_TERRAIN | COMPONENT_TERRAIN_DESC => Some(AUTHORING_COMPONENT_TERRAIN),
|
||||||
AUTHORING_COMPONENT_STATIC_MESH_RENDERER | COMPONENT_STATIC_MESH_RENDERER => {
|
AUTHORING_COMPONENT_STATIC_MESH_RENDERER | COMPONENT_STATIC_MESH_RENDERER => {
|
||||||
Some(AUTHORING_COMPONENT_STATIC_MESH_RENDERER)
|
Some(AUTHORING_COMPONENT_STATIC_MESH_RENDERER)
|
||||||
}
|
}
|
||||||
@@ -386,6 +388,7 @@ pub fn authoring_component_key(key: &str) -> &str {
|
|||||||
|
|
||||||
pub const COMPONENT_PRIMITIVE: &str = "shared::components::Primitive";
|
pub const COMPONENT_PRIMITIVE: &str = "shared::components::Primitive";
|
||||||
pub const COMPONENT_BRUSH_DESC: &str = "shared::components::BrushDesc";
|
pub const COMPONENT_BRUSH_DESC: &str = "shared::components::BrushDesc";
|
||||||
|
pub const COMPONENT_TERRAIN_DESC: &str = "shared::components::TerrainDesc";
|
||||||
pub const COMPONENT_STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer";
|
pub const COMPONENT_STATIC_MESH_RENDERER: &str = "shared::components::StaticMeshRenderer";
|
||||||
pub const COMPONENT_MATERIAL_DESC: &str = "shared::components::MaterialDesc";
|
pub const COMPONENT_MATERIAL_DESC: &str = "shared::components::MaterialDesc";
|
||||||
pub const COMPONENT_MATERIAL_OVERRIDE: &str = "shared::components::MaterialOverride";
|
pub const COMPONENT_MATERIAL_OVERRIDE: &str = "shared::components::MaterialOverride";
|
||||||
@@ -852,6 +855,124 @@ impl BrushDesc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub const TERRAIN_SCHEMA_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
/// Persistent height-grid terrain authoring data. Hydration partitions the grid into generated
|
||||||
|
/// render/collider chunks; saved scenes retain only this descriptor.
|
||||||
|
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TerrainDesc {
|
||||||
|
#[serde(default = "default_terrain_schema_version")]
|
||||||
|
pub schema_version: u32,
|
||||||
|
#[serde(default = "default_terrain_resolution")]
|
||||||
|
pub resolution: u32,
|
||||||
|
#[serde(default = "default_terrain_heights")]
|
||||||
|
pub heights: Vec<f32>,
|
||||||
|
#[serde(default = "default_terrain_sample_spacing")]
|
||||||
|
pub sample_spacing: f32,
|
||||||
|
#[serde(default = "default_terrain_height_scale")]
|
||||||
|
pub height_scale: f32,
|
||||||
|
#[serde(default = "default_terrain_chunk_quads")]
|
||||||
|
pub chunk_quads: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub base_material: Option<EditorAssetRef>,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub generate_colliders: bool,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub cast_shadows: bool,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub receive_shadows: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TerrainDesc {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
schema_version: TERRAIN_SCHEMA_VERSION,
|
||||||
|
resolution: default_terrain_resolution(),
|
||||||
|
heights: default_terrain_heights(),
|
||||||
|
sample_spacing: default_terrain_sample_spacing(),
|
||||||
|
height_scale: default_terrain_height_scale(),
|
||||||
|
chunk_quads: default_terrain_chunk_quads(),
|
||||||
|
base_material: None,
|
||||||
|
generate_colliders: true,
|
||||||
|
cast_shadows: true,
|
||||||
|
receive_shadows: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerrainDesc {
|
||||||
|
pub fn flat(resolution: u32) -> Self {
|
||||||
|
let resolution = resolution.max(2);
|
||||||
|
Self {
|
||||||
|
resolution,
|
||||||
|
heights: vec![0.0; resolution as usize * resolution as usize],
|
||||||
|
chunk_quads: (resolution - 1).min(default_terrain_chunk_quads()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self) -> Result<(), String> {
|
||||||
|
if self.schema_version != TERRAIN_SCHEMA_VERSION {
|
||||||
|
return Err(format!(
|
||||||
|
"terrain schema {} is unsupported; expected {}",
|
||||||
|
self.schema_version, TERRAIN_SCHEMA_VERSION
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !(2..=1025).contains(&self.resolution) {
|
||||||
|
return Err("terrain resolution must be between 2 and 1025 samples".into());
|
||||||
|
}
|
||||||
|
let expected = self.resolution as usize * self.resolution as usize;
|
||||||
|
if self.heights.len() != expected {
|
||||||
|
return Err(format!(
|
||||||
|
"terrain resolution {} requires {expected} height samples, found {}",
|
||||||
|
self.resolution,
|
||||||
|
self.heights.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.heights.iter().any(|height| !height.is_finite()) {
|
||||||
|
return Err("terrain height samples must all be finite".into());
|
||||||
|
}
|
||||||
|
if !self.sample_spacing.is_finite() || self.sample_spacing <= 0.0 {
|
||||||
|
return Err("terrain sample spacing must be finite and positive".into());
|
||||||
|
}
|
||||||
|
if !self.height_scale.is_finite() || self.height_scale <= 0.0 {
|
||||||
|
return Err("terrain height scale must be finite and positive".into());
|
||||||
|
}
|
||||||
|
if self.chunk_quads == 0 || self.chunk_quads > self.resolution - 1 {
|
||||||
|
return Err(format!(
|
||||||
|
"terrain chunk size must be between 1 and {} quads",
|
||||||
|
self.resolution - 1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_schema_version() -> u32 {
|
||||||
|
TERRAIN_SCHEMA_VERSION
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_resolution() -> u32 {
|
||||||
|
33
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_heights() -> Vec<f32> {
|
||||||
|
vec![0.0; default_terrain_resolution() as usize * default_terrain_resolution() as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_sample_spacing() -> f32 {
|
||||||
|
1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_height_scale() -> f32 {
|
||||||
|
10.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_terrain_chunk_quads() -> u32 {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for BrushDesc {
|
impl Default for BrushDesc {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::cuboid(Vec3::ONE)
|
Self::cuboid(Vec3::ONE)
|
||||||
@@ -1392,6 +1513,7 @@ impl Default for EditorVisibility {
|
|||||||
pub enum ActorKind {
|
pub enum ActorKind {
|
||||||
Empty,
|
Empty,
|
||||||
Brush,
|
Brush,
|
||||||
|
Terrain,
|
||||||
StaticMesh,
|
StaticMesh,
|
||||||
SkinnedMesh,
|
SkinnedMesh,
|
||||||
ImportedModel,
|
ImportedModel,
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ use bevy::prelude::*;
|
|||||||
use crate::{
|
use crate::{
|
||||||
asset_server_path, authoring_component_active, brush_math::validate_brush,
|
asset_server_path, authoring_component_active, brush_math::validate_brush,
|
||||||
AuthoringComponentStates, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject,
|
AuthoringComponentStates, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject,
|
||||||
MaterialAsset, MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
|
MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
|
||||||
COMPONENT_MATERIAL_DESC,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::materials::material_from_desc;
|
use super::materials::material_from_desc;
|
||||||
@@ -214,8 +213,8 @@ fn brush_group_material(
|
|||||||
texture_path: Option<&str>,
|
texture_path: Option<&str>,
|
||||||
) -> StandardMaterial {
|
) -> StandardMaterial {
|
||||||
let mut material = material_path
|
let mut material = material_path
|
||||||
.and_then(|path| MaterialAsset::load_from_path(path).ok())
|
.and_then(|path| crate::load_resolved_material_from_path(path).ok())
|
||||||
.map(|asset| material_from_desc(asset_server, &asset.material))
|
.map(|(desc, _)| material_from_desc(asset_server, &desc))
|
||||||
.or_else(|| parent_material.map(|material| material_from_desc(asset_server, material)))
|
.or_else(|| parent_material.map(|material| material_from_desc(asset_server, material)))
|
||||||
.unwrap_or_else(default_brush_material);
|
.unwrap_or_else(default_brush_material);
|
||||||
if let Some(texture_path) = texture_path {
|
if let Some(texture_path) = texture_path {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ mod primitives;
|
|||||||
mod skinned_meshes;
|
mod skinned_meshes;
|
||||||
mod static_meshes;
|
mod static_meshes;
|
||||||
pub mod strip;
|
pub mod strip;
|
||||||
|
mod terrain;
|
||||||
mod visibility;
|
mod visibility;
|
||||||
|
|
||||||
pub use lights::cascade_config_from_rendering;
|
pub use lights::cascade_config_from_rendering;
|
||||||
@@ -37,6 +38,8 @@ use static_meshes::{
|
|||||||
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
|
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
|
||||||
StaticMeshArtifactCache,
|
StaticMeshArtifactCache,
|
||||||
};
|
};
|
||||||
|
pub use terrain::HydratedTerrainChunk;
|
||||||
|
use terrain::{cleanup_removed_terrain, hydrate_terrain};
|
||||||
use visibility::{
|
use visibility::{
|
||||||
ensure_level_object_visibility_hierarchy, init_editor_visibility_on_spawn,
|
ensure_level_object_visibility_hierarchy, init_editor_visibility_on_spawn,
|
||||||
sync_editor_visibility, visibility_from_editor,
|
sync_editor_visibility, visibility_from_editor,
|
||||||
@@ -52,17 +55,28 @@ use crate::{
|
|||||||
/// Registers hydration systems in deterministic order.
|
/// Registers hydration systems in deterministic order.
|
||||||
pub struct HydrationPlugin;
|
pub struct HydrationPlugin;
|
||||||
|
|
||||||
|
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
enum HydrationSet {
|
||||||
|
Visibility,
|
||||||
|
Content,
|
||||||
|
}
|
||||||
|
|
||||||
impl Plugin for HydrationPlugin {
|
impl Plugin for HydrationPlugin {
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
app.init_resource::<StaticMeshArtifactCache>()
|
app.init_resource::<StaticMeshArtifactCache>()
|
||||||
.add_observer(tag_hydrated_prefab_members)
|
.add_observer(tag_hydrated_prefab_members)
|
||||||
.add_observer(mark_skinned_materials_ready)
|
.add_observer(mark_skinned_materials_ready)
|
||||||
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
|
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
|
||||||
|
.configure_sets(
|
||||||
|
Update,
|
||||||
|
(HydrationSet::Visibility, HydrationSet::Content).chain(),
|
||||||
|
)
|
||||||
.add_systems(
|
.add_systems(
|
||||||
Update,
|
Update,
|
||||||
(
|
(
|
||||||
hydrate_primitives,
|
hydrate_primitives,
|
||||||
hydrate_brushes,
|
hydrate_brushes,
|
||||||
|
hydrate_terrain,
|
||||||
hydrate_materials,
|
hydrate_materials,
|
||||||
hydrate_lights,
|
hydrate_lights,
|
||||||
reconcile_missing_runtime_lights,
|
reconcile_missing_runtime_lights,
|
||||||
@@ -73,8 +87,10 @@ impl Plugin for HydrationPlugin {
|
|||||||
hydrate_models,
|
hydrate_models,
|
||||||
hydrate_prefabs,
|
hydrate_prefabs,
|
||||||
hydrate_physics,
|
hydrate_physics,
|
||||||
|
cleanup_removed_terrain,
|
||||||
)
|
)
|
||||||
.chain(),
|
.chain()
|
||||||
|
.in_set(HydrationSet::Content),
|
||||||
)
|
)
|
||||||
.add_systems(
|
.add_systems(
|
||||||
Update,
|
Update,
|
||||||
@@ -83,7 +99,8 @@ impl Plugin for HydrationPlugin {
|
|||||||
sync_editor_visibility,
|
sync_editor_visibility,
|
||||||
init_editor_visibility_on_spawn,
|
init_editor_visibility_on_spawn,
|
||||||
)
|
)
|
||||||
.chain(),
|
.chain()
|
||||||
|
.in_set(HydrationSet::Visibility),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,9 @@ use std::collections::{HashMap, HashSet};
|
|||||||
use crate::{
|
use crate::{
|
||||||
asset_server_path, authoring_component_active, standard_material_asset_path,
|
asset_server_path, authoring_component_active, standard_material_asset_path,
|
||||||
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
|
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
|
||||||
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialAsset,
|
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialDesc,
|
||||||
MaterialDesc, MaterialInstanceAsset, MaterialOverride, MaterialRef, StaticMeshRenderer,
|
MaterialOverride, MaterialRef, StaticMeshRenderer, StaticMeshRendererEntry,
|
||||||
StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
|
COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_STATIC_MESH_RENDERER,
|
||||||
COMPONENT_STATIC_MESH_RENDERER,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::materials::material_from_desc;
|
use super::materials::material_from_desc;
|
||||||
@@ -457,22 +456,7 @@ fn resolve_shared_material(
|
|||||||
return Some(handle.clone());
|
return Some(handle.clone());
|
||||||
}
|
}
|
||||||
let path = reference.0.source_path.as_deref()?;
|
let path = reference.0.source_path.as_deref()?;
|
||||||
let desc_and_state = MaterialAsset::load_from_path(path)
|
let desc_and_state = crate::load_resolved_material_from_path(path).ok()?;
|
||||||
.map(|asset| (asset.material, asset.render_state))
|
|
||||||
.or_else(|_| {
|
|
||||||
let instance = MaterialInstanceAsset::load_from_path(path)?;
|
|
||||||
let base_path = instance.base.0.source_path.as_deref().ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"material instance {} has no loadable base path",
|
|
||||||
instance.label
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
let base = MaterialAsset::load_from_path(base_path)?;
|
|
||||||
let mut desc = base.material;
|
|
||||||
instance.apply_to(&mut desc);
|
|
||||||
Ok::<_, String>((desc, base.render_state))
|
|
||||||
})
|
|
||||||
.ok()?;
|
|
||||||
let mut material = material_from_desc(asset_server, &desc_and_state.0);
|
let mut material = material_from_desc(asset_server, &desc_and_state.0);
|
||||||
material.alpha_mode = match desc_and_state.1.alpha_mode {
|
material.alpha_mode = match desc_and_state.1.alpha_mode {
|
||||||
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
|
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
|
||||||
|
|||||||
@@ -0,0 +1,314 @@
|
|||||||
|
//! Chunked render and collider hydration for authored height-grid terrain.
|
||||||
|
|
||||||
|
use avian3d::prelude::ColliderConstructor;
|
||||||
|
use bevy::asset::RenderAssetUsages;
|
||||||
|
use bevy::light::{NotShadowCaster, NotShadowReceiver};
|
||||||
|
use bevy::mesh::{Indices, PrimitiveTopology};
|
||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
authoring_component_active, load_resolved_material_from_path, AuthoringComponentStates,
|
||||||
|
InspectorOrder, LevelObject, RaytracingExcluded, TerrainDesc, COMPONENT_TERRAIN_DESC,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::materials::material_from_desc;
|
||||||
|
|
||||||
|
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[reflect(Component, Default, Debug)]
|
||||||
|
pub struct HydratedTerrainChunk {
|
||||||
|
pub owner: Entity,
|
||||||
|
pub chunk_x: u32,
|
||||||
|
pub chunk_z: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HydratedTerrainChunk {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
owner: Entity::PLACEHOLDER,
|
||||||
|
chunk_x: 0,
|
||||||
|
chunk_z: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn hydrate_terrain(
|
||||||
|
mut commands: Commands,
|
||||||
|
asset_server: Res<AssetServer>,
|
||||||
|
mut meshes: ResMut<Assets<Mesh>>,
|
||||||
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||||
|
terrains: Query<
|
||||||
|
(
|
||||||
|
Entity,
|
||||||
|
&TerrainDesc,
|
||||||
|
Option<&AuthoringComponentStates>,
|
||||||
|
Option<&InspectorOrder>,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
With<LevelObject>,
|
||||||
|
Or<(
|
||||||
|
Added<TerrainDesc>,
|
||||||
|
Changed<TerrainDesc>,
|
||||||
|
Changed<AuthoringComponentStates>,
|
||||||
|
Changed<InspectorOrder>,
|
||||||
|
)>,
|
||||||
|
),
|
||||||
|
>,
|
||||||
|
children: Query<&Children>,
|
||||||
|
chunks: Query<(), With<HydratedTerrainChunk>>,
|
||||||
|
) {
|
||||||
|
for (entity, terrain, states, order) in &terrains {
|
||||||
|
despawn_terrain_chunks(&mut commands, entity, &children, &chunks);
|
||||||
|
if authoring_component_active(states, order, COMPONENT_TERRAIN_DESC) {
|
||||||
|
spawn_terrain_chunks(
|
||||||
|
&mut commands,
|
||||||
|
&asset_server,
|
||||||
|
&mut meshes,
|
||||||
|
&mut materials,
|
||||||
|
entity,
|
||||||
|
terrain,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cleanup_removed_terrain(
|
||||||
|
mut commands: Commands,
|
||||||
|
mut removed: RemovedComponents<TerrainDesc>,
|
||||||
|
children: Query<&Children>,
|
||||||
|
chunks: Query<(), With<HydratedTerrainChunk>>,
|
||||||
|
) {
|
||||||
|
for entity in removed.read() {
|
||||||
|
despawn_terrain_chunks(&mut commands, entity, &children, &chunks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_terrain_chunks(
|
||||||
|
commands: &mut Commands,
|
||||||
|
asset_server: &AssetServer,
|
||||||
|
meshes: &mut Assets<Mesh>,
|
||||||
|
materials: &mut Assets<StandardMaterial>,
|
||||||
|
owner: Entity,
|
||||||
|
terrain: &TerrainDesc,
|
||||||
|
) {
|
||||||
|
if let Err(error) = terrain.validate() {
|
||||||
|
warn!("Terrain hydration skipped invalid actor {owner:?}: {error}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let material = terrain
|
||||||
|
.base_material
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|reference| reference.source_path.as_deref())
|
||||||
|
.and_then(|path| match load_resolved_material_from_path(path) {
|
||||||
|
Ok((desc, _)) => Some(material_from_desc(asset_server, &desc)),
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Terrain {owner:?} material could not resolve: {error}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| StandardMaterial {
|
||||||
|
base_color: Color::srgb(0.24, 0.29, 0.25),
|
||||||
|
perceptual_roughness: 0.92,
|
||||||
|
..default()
|
||||||
|
});
|
||||||
|
let material = materials.add(material);
|
||||||
|
let quad_count = terrain.resolution - 1;
|
||||||
|
let chunks_per_axis = quad_count.div_ceil(terrain.chunk_quads);
|
||||||
|
|
||||||
|
for chunk_z in 0..chunks_per_axis {
|
||||||
|
for chunk_x in 0..chunks_per_axis {
|
||||||
|
let start_x = chunk_x * terrain.chunk_quads;
|
||||||
|
let start_z = chunk_z * terrain.chunk_quads;
|
||||||
|
let end_x = (start_x + terrain.chunk_quads).min(quad_count);
|
||||||
|
let end_z = (start_z + terrain.chunk_quads).min(quad_count);
|
||||||
|
let Some(mesh) = terrain_chunk_mesh(terrain, start_x, start_z, end_x, end_z) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mesh = meshes.add(mesh);
|
||||||
|
let mut chunk = commands.spawn((
|
||||||
|
HydratedTerrainChunk {
|
||||||
|
owner,
|
||||||
|
chunk_x,
|
||||||
|
chunk_z,
|
||||||
|
},
|
||||||
|
Name::new(format!("Terrain Chunk {chunk_x},{chunk_z}")),
|
||||||
|
Mesh3d(mesh),
|
||||||
|
MeshMaterial3d(material.clone()),
|
||||||
|
Transform::default(),
|
||||||
|
Visibility::Visible,
|
||||||
|
RaytracingExcluded,
|
||||||
|
ChildOf(owner),
|
||||||
|
));
|
||||||
|
if terrain.generate_colliders {
|
||||||
|
chunk.insert(ColliderConstructor::TrimeshFromMesh);
|
||||||
|
}
|
||||||
|
if !terrain.cast_shadows {
|
||||||
|
chunk.insert(NotShadowCaster);
|
||||||
|
}
|
||||||
|
if !terrain.receive_shadows {
|
||||||
|
chunk.insert(NotShadowReceiver);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn despawn_terrain_chunks(
|
||||||
|
commands: &mut Commands,
|
||||||
|
entity: Entity,
|
||||||
|
children: &Query<&Children>,
|
||||||
|
chunks: &Query<(), With<HydratedTerrainChunk>>,
|
||||||
|
) {
|
||||||
|
let Ok(children) = children.get(entity) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for child in children.iter() {
|
||||||
|
if chunks.get(child).is_ok() {
|
||||||
|
commands.entity(child).despawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terrain_chunk_mesh(
|
||||||
|
terrain: &TerrainDesc,
|
||||||
|
start_x: u32,
|
||||||
|
start_z: u32,
|
||||||
|
end_x: u32,
|
||||||
|
end_z: u32,
|
||||||
|
) -> Option<Mesh> {
|
||||||
|
if start_x >= end_x
|
||||||
|
|| start_z >= end_z
|
||||||
|
|| end_x >= terrain.resolution
|
||||||
|
|| end_z >= terrain.resolution
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let width = end_x - start_x + 1;
|
||||||
|
let depth = end_z - start_z + 1;
|
||||||
|
let mut positions = Vec::with_capacity((width * depth) as usize);
|
||||||
|
let mut normals = Vec::with_capacity((width * depth) as usize);
|
||||||
|
let mut uvs = Vec::with_capacity((width * depth) as usize);
|
||||||
|
let quad_count = (terrain.resolution - 1) as f32;
|
||||||
|
let half_extent = quad_count * terrain.sample_spacing * 0.5;
|
||||||
|
|
||||||
|
let sample = |x: u32, z: u32| {
|
||||||
|
terrain.heights[(z * terrain.resolution + x) as usize] * terrain.height_scale
|
||||||
|
};
|
||||||
|
for z in start_z..=end_z {
|
||||||
|
for x in start_x..=end_x {
|
||||||
|
let left = sample(x.saturating_sub(1), z);
|
||||||
|
let right = sample((x + 1).min(terrain.resolution - 1), z);
|
||||||
|
let down = sample(x, z.saturating_sub(1));
|
||||||
|
let up = sample(x, (z + 1).min(terrain.resolution - 1));
|
||||||
|
let normal = Vec3::new(left - right, 2.0 * terrain.sample_spacing, down - up)
|
||||||
|
.normalize_or_zero();
|
||||||
|
positions.push([
|
||||||
|
x as f32 * terrain.sample_spacing - half_extent,
|
||||||
|
sample(x, z),
|
||||||
|
z as f32 * terrain.sample_spacing - half_extent,
|
||||||
|
]);
|
||||||
|
normals.push(normal.to_array());
|
||||||
|
uvs.push([x as f32 / quad_count, z as f32 / quad_count]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut indices = Vec::with_capacity(((width - 1) * (depth - 1) * 6) as usize);
|
||||||
|
for z in 0..depth - 1 {
|
||||||
|
for x in 0..width - 1 {
|
||||||
|
let a = z * width + x;
|
||||||
|
let b = a + 1;
|
||||||
|
let c = a + width;
|
||||||
|
let d = c + 1;
|
||||||
|
indices.extend_from_slice(&[a, c, b, b, c, d]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut mesh = Mesh::new(
|
||||||
|
PrimitiveTopology::TriangleList,
|
||||||
|
RenderAssetUsages::default(),
|
||||||
|
);
|
||||||
|
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
|
||||||
|
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
|
||||||
|
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
|
||||||
|
mesh.insert_indices(Indices::U32(indices));
|
||||||
|
if let Err(error) = mesh.generate_tangents() {
|
||||||
|
warn!("Terrain chunk tangent generation failed: {error:?}");
|
||||||
|
}
|
||||||
|
Some(mesh)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::ActorKind;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chunk_mesh_has_expected_topology() {
|
||||||
|
let terrain = TerrainDesc::flat(5);
|
||||||
|
let mesh = terrain_chunk_mesh(&terrain, 0, 0, 4, 4).unwrap();
|
||||||
|
assert_eq!(mesh.count_vertices(), 25);
|
||||||
|
assert_eq!(mesh.indices().unwrap().len(), 96);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn descriptor_rejects_mismatched_and_non_finite_heights() {
|
||||||
|
let mut terrain = TerrainDesc::flat(3);
|
||||||
|
terrain.heights.pop();
|
||||||
|
assert!(terrain.validate().unwrap_err().contains("requires 9"));
|
||||||
|
terrain.heights.push(f32::NAN);
|
||||||
|
assert!(terrain.validate().unwrap_err().contains("finite"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn descriptor_round_trips_through_ron() {
|
||||||
|
let mut terrain = TerrainDesc::flat(5);
|
||||||
|
terrain.heights[12] = 0.75;
|
||||||
|
terrain.sample_spacing = 2.0;
|
||||||
|
let text = ron::to_string(&terrain).unwrap();
|
||||||
|
let restored: TerrainDesc = ron::from_str(&text).unwrap();
|
||||||
|
assert_eq!(restored, terrain);
|
||||||
|
assert!(restored.validate().is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hydration_generates_runtime_only_chunks_and_cleans_up() {
|
||||||
|
let mut app = App::new();
|
||||||
|
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
|
||||||
|
.init_asset::<Mesh>()
|
||||||
|
.init_asset::<StandardMaterial>()
|
||||||
|
.add_systems(Update, (hydrate_terrain, cleanup_removed_terrain).chain());
|
||||||
|
let owner = app
|
||||||
|
.world_mut()
|
||||||
|
.spawn((
|
||||||
|
LevelObject,
|
||||||
|
ActorKind::Terrain,
|
||||||
|
TerrainDesc {
|
||||||
|
resolution: 5,
|
||||||
|
heights: vec![0.0; 25],
|
||||||
|
chunk_quads: 2,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Transform::default(),
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
|
||||||
|
app.update();
|
||||||
|
app.update();
|
||||||
|
let children = app.world().get::<Children>(owner).unwrap();
|
||||||
|
assert_eq!(children.len(), 4);
|
||||||
|
for child in children.iter() {
|
||||||
|
assert!(app.world().get::<HydratedTerrainChunk>(child).is_some());
|
||||||
|
assert!(app.world().get::<LevelObject>(child).is_none());
|
||||||
|
assert!(app.world().get::<Mesh3d>(child).is_some());
|
||||||
|
assert!(app.world().get::<ColliderConstructor>(child).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
app.world_mut().entity_mut(owner).remove::<TerrainDesc>();
|
||||||
|
app.update();
|
||||||
|
app.update();
|
||||||
|
assert!(app
|
||||||
|
.world()
|
||||||
|
.get::<Children>(owner)
|
||||||
|
.is_none_or(Children::is_empty));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,12 +22,13 @@ pub use components::*;
|
|||||||
pub use hydration::{
|
pub use hydration::{
|
||||||
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
|
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
|
||||||
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
|
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
|
||||||
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydrationPlugin, PrefabHydrationBlocked,
|
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydratedTerrainChunk, HydrationPlugin,
|
||||||
|
PrefabHydrationBlocked,
|
||||||
};
|
};
|
||||||
pub use material_asset::{
|
pub use material_asset::{
|
||||||
MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset, MaterialRenderState,
|
load_resolved_material_from_path, MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset,
|
||||||
ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset, MATERIAL_ASSET_SCHEMA_VERSION,
|
MaterialRenderState, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
|
||||||
MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
|
MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
|
||||||
};
|
};
|
||||||
pub use navigation::*;
|
pub use navigation::*;
|
||||||
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
|
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
|
||||||
@@ -112,6 +113,7 @@ impl Plugin for SharedTypesPlugin {
|
|||||||
.register_type::<Primitive>()
|
.register_type::<Primitive>()
|
||||||
.register_type::<PrimitiveShape>()
|
.register_type::<PrimitiveShape>()
|
||||||
.register_type::<BrushDesc>()
|
.register_type::<BrushDesc>()
|
||||||
|
.register_type::<TerrainDesc>()
|
||||||
.register_type::<BrushKind>()
|
.register_type::<BrushKind>()
|
||||||
.register_type::<BrushPlaneDesc>()
|
.register_type::<BrushPlaneDesc>()
|
||||||
.register_type::<BrushFaceDesc>()
|
.register_type::<BrushFaceDesc>()
|
||||||
|
|||||||
@@ -79,6 +79,33 @@ impl MaterialAsset {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads a project Material or direct-base Material Instance into one effective descriptor.
|
||||||
|
///
|
||||||
|
/// The returned descriptor retains the selected asset path so primitive/brush authoring can locate
|
||||||
|
/// the shared source while renderer slots continue to preserve their stable [`MaterialRef`].
|
||||||
|
pub fn load_resolved_material_from_path(
|
||||||
|
catalog_path: &str,
|
||||||
|
) -> Result<(MaterialDesc, MaterialRenderState), String> {
|
||||||
|
if let Ok(asset) = MaterialAsset::load_from_path(catalog_path) {
|
||||||
|
let mut material = asset.material;
|
||||||
|
material.material_asset_path = Some(catalog_path.to_string());
|
||||||
|
return Ok((material, asset.render_state));
|
||||||
|
}
|
||||||
|
|
||||||
|
let instance = MaterialInstanceAsset::load_from_path(catalog_path)?;
|
||||||
|
let base_path = instance.base.0.source_path.as_deref().ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"material instance {} has no loadable base path",
|
||||||
|
instance.label
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let base = MaterialAsset::load_from_path(base_path)?;
|
||||||
|
let mut material = base.material;
|
||||||
|
instance.apply_to(&mut material);
|
||||||
|
material.material_asset_path = Some(catalog_path.to_string());
|
||||||
|
Ok((material, base.render_state))
|
||||||
|
}
|
||||||
|
|
||||||
/// Explicit reusable overrides over one project Material asset.
|
/// Explicit reusable overrides over one project Material asset.
|
||||||
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
pub struct MaterialInstanceAsset {
|
pub struct MaterialInstanceAsset {
|
||||||
@@ -270,4 +297,66 @@ mod tests {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|value| value.name == "edge_width"));
|
.any(|value| value.name == "edge_width"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolved_material_instance_applies_sparse_overrides_and_keeps_instance_path() {
|
||||||
|
let root = std::env::temp_dir().join(format!(
|
||||||
|
"blacksite-resolved-material-instance-{}",
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
));
|
||||||
|
let base_path = root.join("base.ron");
|
||||||
|
let instance_path = root.join("instance.ron");
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
let base = MaterialAsset {
|
||||||
|
schema_version: MATERIAL_ASSET_SCHEMA_VERSION,
|
||||||
|
label: "Base".into(),
|
||||||
|
shader: None,
|
||||||
|
shader_ref: None,
|
||||||
|
render_state: MaterialRenderState {
|
||||||
|
double_sided: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
material: MaterialDesc {
|
||||||
|
roughness: 0.8,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
};
|
||||||
|
std::fs::write(
|
||||||
|
&base_path,
|
||||||
|
ron::ser::to_string_pretty(&base, ron::ser::PrettyConfig::default()).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let instance = MaterialInstanceAsset {
|
||||||
|
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
|
||||||
|
label: "Instance".into(),
|
||||||
|
base: MaterialRef::new(
|
||||||
|
EditorAssetRef::new("base", "material:source", "Base")
|
||||||
|
.with_source_path(base_path.to_string_lossy().into_owned()),
|
||||||
|
),
|
||||||
|
parameters: vec![MaterialParameter {
|
||||||
|
name: "roughness".into(),
|
||||||
|
value: crate::MaterialParameterValue::Float(0.25),
|
||||||
|
}],
|
||||||
|
textures: Vec::new(),
|
||||||
|
};
|
||||||
|
std::fs::write(
|
||||||
|
&instance_path,
|
||||||
|
ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default()).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (resolved, state) =
|
||||||
|
load_resolved_material_from_path(instance_path.to_str().unwrap()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(resolved.roughness, 0.25);
|
||||||
|
assert_eq!(
|
||||||
|
resolved.material_asset_path.as_deref(),
|
||||||
|
instance_path.to_str()
|
||||||
|
);
|
||||||
|
assert!(state.double_sided);
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+12
-1
@@ -51,13 +51,16 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
|
|||||||
| [0034](adr/0034-registry-driven-authoring-components.md) | Stable component IDs, reflected lifecycle/history, composition, and independent active state |
|
| [0034](adr/0034-registry-driven-authoring-components.md) | Stable component IDs, reflected lifecycle/history, composition, and independent active state |
|
||||||
| [0035](adr/0035-shared-material-assets-and-renderer-slots.md) | Shared Material/Material Instance assets, stable renderer slots, and runtime-only property blocks |
|
| [0035](adr/0035-shared-material-assets-and-renderer-slots.md) | Shared Material/Material Instance assets, stable renderer slots, and runtime-only property blocks |
|
||||||
| [0036](adr/0036-surface-abi-and-solari-parity.md) | Constrained Surface ABI v1, raster/Solari evaluator parity, and deformed-geometry boundary |
|
| [0036](adr/0036-surface-abi-and-solari-parity.md) | Constrained Surface ABI v1, raster/Solari evaluator parity, and deformed-geometry boundary |
|
||||||
|
| [0037](adr/0037-collaborative-authored-file-safety.md) | Exact authored-file revisions, observational Git status, and optional ownership providers |
|
||||||
|
| [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 |
|
||||||
|
|
||||||
## Editor framework
|
## Editor framework
|
||||||
|
|
||||||
| Document | Purpose |
|
| Document | Purpose |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| [editor/release-notes.md](editor/release-notes.md) | Editor framework 1.0 baseline |
|
| [editor/release-notes.md](editor/release-notes.md) | Editor framework 1.0 baseline |
|
||||||
| [editor/evaluations/](editor/evaluations/) | Horizon gate sign-offs (R1–R6) |
|
| [editor/evaluations/](editor/evaluations/) | Acceptance records, screenshots, and Gitea evidence-publishing policy |
|
||||||
| [editor/architecture.md](editor/architecture.md) | Viewport / PIE / settings data flow |
|
| [editor/architecture.md](editor/architecture.md) | Viewport / PIE / settings data flow |
|
||||||
| [editor/visual-language.md](editor/visual-language.md) | Editor chrome, viewport, selection, gizmo, and visualizer language |
|
| [editor/visual-language.md](editor/visual-language.md) | Editor chrome, viewport, selection, gizmo, and visualizer language |
|
||||||
| [editor/roadmap.md](editor/roadmap.md) | Phased editor roadmap and status |
|
| [editor/roadmap.md](editor/roadmap.md) | Phased editor roadmap and status |
|
||||||
@@ -75,8 +78,13 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
|
|||||||
| [editor/navigation-authoring.md](editor/navigation-authoring.md) | Bounds/obstacles/areas/links, deterministic bake, overlay, path preview, and runtime queries |
|
| [editor/navigation-authoring.md](editor/navigation-authoring.md) | Bounds/obstacles/areas/links, deterministic bake, overlay, path preview, and runtime queries |
|
||||||
| [editor/extensibility.md](editor/extensibility.md) | Static authoring component registration, lifecycle, composition, and history contract |
|
| [editor/extensibility.md](editor/extensibility.md) | Static authoring component registration, lifecycle, composition, and history contract |
|
||||||
| [editor/material-system.md](editor/material-system.md) | Shared material assets and instances, renderer-slot assignment, Surface evaluators, migration, and diagnostics |
|
| [editor/material-system.md](editor/material-system.md) | Shared material assets and instances, renderer-slot assignment, Surface evaluators, migration, and diagnostics |
|
||||||
|
| [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/evaluations/material-renderer-foundation/](editor/evaluations/material-renderer-foundation/) | Live screenshots and acceptance results for the renderer/material/component foundation |
|
| [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/navigation-authoring/](editor/evaluations/navigation-authoring/) | Live screenshots and acceptance results for navigation authoring and runtime parity |
|
| [editor/evaluations/navigation-authoring/](editor/evaluations/navigation-authoring/) | Live screenshots and acceptance results for navigation authoring and runtime parity |
|
||||||
|
| [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)
|
## Working plans (not canonical long-term)
|
||||||
|
|
||||||
@@ -95,6 +103,9 @@ Detailed milestone and feature plans live in [`.cursor/plans/`](../.cursor/plans
|
|||||||
| `animation_authoring_*.plan.md` | M7 glTF skeletal animation import, preview, controller, and runtime acceptance |
|
| `animation_authoring_*.plan.md` | M7 glTF skeletal animation import, preview, controller, and runtime acceptance |
|
||||||
| `navigation_authoring_*.plan.md` | M7 navigation bounds, deterministic bake, diagnostics, preview, and runtime query API |
|
| `navigation_authoring_*.plan.md` | M7 navigation bounds, deterministic bake, diagnostics, preview, and runtime query API |
|
||||||
| `renderer_material_component_foundation_*.plan.md` | Renderer/material slots, skinned pose lifecycle, Surface ABI, and component foundation |
|
| `renderer_material_component_foundation_*.plan.md` | Renderer/material slots, skinned pose lifecycle, Surface ABI, and component foundation |
|
||||||
|
| `source_control_collaboration_safety_*.plan.md` | Exact authored-file guards, observational Git status, conflict recovery, and provider contract |
|
||||||
|
| `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 |
|
||||||
|
|
||||||
## Crate responsibilities (quick reference)
|
## Crate responsibilities (quick reference)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# ADR 0037: Collaborative Authored-File Safety
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Transactional replacement protects an authored file from partial writes, but it does not prevent
|
||||||
|
an editor session from replacing a newer revision written by another tool or collaborator. Git can
|
||||||
|
explain common workspace states, while Perforce-style ownership or lock services may be present in
|
||||||
|
some teams. Neither Git nor a provider may be assumed, and source-control integration must never
|
||||||
|
stage, reset, discard, commit, or otherwise mutate repository state.
|
||||||
|
|
||||||
|
Blacksite needs one save boundary for user-authored scenes and assets. The boundary must detect
|
||||||
|
changes using file content rather than timestamps alone, preserve atomic replacement, explain
|
||||||
|
read-only and collaboration conflicts, and remain useful in projects with no repository or lock
|
||||||
|
provider.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
- Every loaded authored document records a `FileSnapshot` containing a BLAKE3 content revision and
|
||||||
|
comparison metadata. Missing files have an explicit revision so create/save-as races are guarded.
|
||||||
|
- Authored writes compare the current revision with the caller's baseline before serialization is
|
||||||
|
published and again immediately before the same-directory atomic rename. A mismatch, read-only
|
||||||
|
target, or provider lock blocks publication and leaves the existing file untouched.
|
||||||
|
- The conflict workflow offers reload, metadata comparison, save-as, and cancel. There is no
|
||||||
|
force-overwrite action. Reload semantics are owned by the document type so scene and asset state
|
||||||
|
cannot be confused.
|
||||||
|
- Git status is collected asynchronously with read-only commands and parsed from NUL-delimited
|
||||||
|
porcelain output. The editor reports clean, modified, untracked, and conflicted state for the
|
||||||
|
active scene and selected asset without making Git a project requirement.
|
||||||
|
- Optional ownership integrations implement a thread-safe provider trait over the currently
|
||||||
|
tracked project-relative paths. Provider absence performs no work and produces no warning.
|
||||||
|
Provider errors are diagnostic status, not a reason to disable filesystem revision protection.
|
||||||
|
- Generated registries, import artifacts, caches, recovery snapshots, and package output do not
|
||||||
|
open authored-file conflict UI. Their existing subsystem-specific transactional or regenerative
|
||||||
|
rules remain authoritative.
|
||||||
|
- Source-control integration is observational. Blacksite never stages, commits, resets, checks out,
|
||||||
|
discards, or changes locks through the Git status path.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- External changes to loaded scenes, prefabs, materials, material instances, and project settings
|
||||||
|
cannot be silently replaced by normal editor save/apply/history paths.
|
||||||
|
- Timestamp-only changes do not create false content conflicts, while metadata remains available
|
||||||
|
for human comparison.
|
||||||
|
- A save conflict requires an explicit recovery choice and may interrupt a bulk save operation.
|
||||||
|
- Git is invoked periodically in a worker thread; the frame loop does not wait for repository I/O.
|
||||||
|
- Provider implementations must be deterministic, bounded, and safe to call off the main thread.
|
||||||
|
- Native filesystem replacement cannot coordinate with unrelated writers that ignore advisory
|
||||||
|
conventions after Blacksite's final revision check; the narrow check-to-rename interval is the
|
||||||
|
platform boundary, and deterministic race hooks cover the editor-controlled interval.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# ADR 0038: Non-Blocking Native Dialog Broker
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Blacksite opens native file, folder, Save As, and confirmation dialogs from editor workflows. Calling
|
||||||
|
the synchronous `rfd` API inside a Bevy/egui system stops window event processing until the dialog
|
||||||
|
returns. On Wayland compositors this can trigger an application-not-responding prompt even though
|
||||||
|
the native dialog is operating normally.
|
||||||
|
|
||||||
|
Path selection precedes stateful main-thread work such as scene serialization, imports, history
|
||||||
|
changes, prefab relinking, collaborative revision checks, and project activation. Moving those
|
||||||
|
operations to arbitrary worker threads would violate ECS ownership and weaken existing guards.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
The editor owns one `NativeDialogBroker` resource. A workflow submits native dialog construction and
|
||||||
|
a typed completion callback. The broker runs only the blocking native dialog wait on a worker thread,
|
||||||
|
then queues the result. An exclusive Bevy system drains the queue and invokes each completion exactly
|
||||||
|
once with `&mut World`.
|
||||||
|
|
||||||
|
Only one native dialog may be active. Additional requests fail immediately with explicit status.
|
||||||
|
Cancellation is delivered as the dialog API's empty or cancel result and remains non-mutating.
|
||||||
|
Initiating workflows capture stable entity IDs or paths and revalidate them before applying a result.
|
||||||
|
|
||||||
|
Native confirmation dialogs use the same broker. A requested close or project switch proceeds only
|
||||||
|
after the confirmation result and any required save have completed; an incomplete asynchronous save
|
||||||
|
pauses the transition rather than discarding content.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Blacksite continues rendering and answering compositor pings while native dialogs are open.
|
||||||
|
- Project and ECS mutations remain on the Bevy main thread with their existing history, validation,
|
||||||
|
and collaborative file-revision boundaries.
|
||||||
|
- Workflows split dialog acquisition from result application and handle stale initiating state.
|
||||||
|
- The one-dialog policy is intentionally global across the editor and Project Browser.
|
||||||
|
- A future platform-specific async backend can replace the worker without changing completions.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# ADR 0039: Inline Height-Grid Terrain Foundation
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Terrain sculpting, material painting, physics placement, recovery, and prefab workflows need one
|
||||||
|
stable owner for height data. Generated meshes and colliders cannot be authoritative because they
|
||||||
|
are runtime artifacts, while introducing an external binary heightmap before editing semantics exist
|
||||||
|
would add file-move, revision, import, and multi-document transaction complexity prematurely.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
`TerrainDesc` schema v1 stores a bounded square grid of normalized finite `f32` heights directly in
|
||||||
|
the authored scene component. It also stores sample spacing, height scale, chunk quad size, an
|
||||||
|
optional shared base Material/Material Instance reference, collider generation, and shadow flags.
|
||||||
|
|
||||||
|
Hydration deterministically partitions grid quads into generated children. Boundary samples are
|
||||||
|
duplicated between neighboring render chunks so each chunk has complete normals and independent
|
||||||
|
triangle geometry. Chunk meshes/colliders are never `LevelObject` entities and are therefore absent
|
||||||
|
from saved scenes, recovery documents, prefabs, and history snapshots.
|
||||||
|
|
||||||
|
Resolution changes are explicit destructive flat-grid replacements in the foundation inspector.
|
||||||
|
Sculpt tools mutate the existing grid through grouped history transactions. A future external
|
||||||
|
heightmap representation requires an explicit schema migration and authored-file ownership ADR; it
|
||||||
|
must not silently rewrite an inline terrain during normal load.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Scene, prefab, undo, recovery, collaboration, and validation use one exact terrain document.
|
||||||
|
- V1 grids are bounded to 1025×1025 samples to prevent accidental unbounded scene payloads.
|
||||||
|
- Large production terrains may eventually need tiled external storage and streaming.
|
||||||
|
- Foundation chunks remain raster-only in Solari until terrain layer materials have an exact Surface
|
||||||
|
evaluator in `#24`; explicit exclusion is preferred to a black or mismatched ray-traced proxy.
|
||||||
|
- Layer weights and sculpt strokes extend this descriptor contract in `#23`/`#24`; generated chunks
|
||||||
|
remain disposable regardless of the editing representation.
|
||||||
+16
-1
@@ -23,8 +23,18 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
|||||||
| [navigation-authoring.md](navigation-authoring.md) | Bounds, source geometry, deterministic bake, viewport path preview, and runtime query workflow |
|
| [navigation-authoring.md](navigation-authoring.md) | Bounds, source geometry, deterministic bake, viewport path preview, and runtime query workflow |
|
||||||
| [extensibility.md](extensibility.md) | Static authoring component lifecycle registration, stable IDs, composition, and generic history |
|
| [extensibility.md](extensibility.md) | Static authoring component lifecycle registration, stable IDs, composition, and generic history |
|
||||||
| [material-system.md](material-system.md) | Shared Material/Material Instance assets, static/skinned renderer slots, Surface ABI, Solari scope, and migration |
|
| [material-system.md](material-system.md) | Shared Material/Material Instance assets, static/skinned renderer slots, Surface ABI, Solari scope, and migration |
|
||||||
|
| [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 |
|
||||||
|
| [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-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 |
|
||||||
|
| [evaluations/collaborative-file-safety/](evaluations/collaborative-file-safety/) | Live screenshot and verification record for source-control status and guarded external-change recovery |
|
||||||
|
| [evaluations/native-dialog-responsiveness/](evaluations/native-dialog-responsiveness/) | Live native-Wayland screenshot and verification record for non-blocking picker responsiveness |
|
||||||
|
| [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/navigation-authoring/](evaluations/navigation-authoring/) | Live screenshots and verification record for navigation authoring and runtime parity |
|
| [evaluations/navigation-authoring/](evaluations/navigation-authoring/) | Live screenshots and verification record for navigation authoring and runtime parity |
|
||||||
|
| [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)
|
## Subsystems (code → doc)
|
||||||
|
|
||||||
@@ -32,17 +42,20 @@ 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 |
|
| `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::BrushDesc` / `shared::hydration::brushes` | Persisted brush authoring data and generated runtime mesh hydration | brushes.md, ADR 0021 |
|
||||||
|
| `shared::components::TerrainDesc` / `shared::hydration::terrain` | Persisted height grid and generated render/collider chunks | terrain.md, ADR 0039 |
|
||||||
| `scene/` | Level I/O, tabs, composition materialization, schema, viewport render-target setup | architecture.md, multi-scene-composition.md, ADR 0026 |
|
| `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 |
|
| `viewport/` | Camera, selection, gizmos, render views | architecture.md |
|
||||||
| `play/` | PIE session, editor mode state | architecture.md |
|
| `play/` | PIE session, editor mode state | architecture.md |
|
||||||
| `play/audio_preview.rs` / `game::audio` | Non-dirty editor audition and authored runtime playback/bus adapter | audio-authoring.md, ADR 0030 |
|
| `play/audio_preview.rs` / `game::audio` | Non-dirty editor audition and authored runtime playback/bus adapter | audio-authoring.md, ADR 0030 |
|
||||||
| `assets/animation.rs` / `ui/animation_inspector.rs` / `game::animation` | Generated animation manifests, controller authoring/preview, and runtime state adapter | animation-authoring.md, ADR 0031 |
|
| `assets/animation.rs` / `ui/animation_inspector.rs` / `game::animation` | Generated animation manifests, controller authoring/preview, and runtime state adapter | animation-authoring.md, ADR 0031 |
|
||||||
| `ui/navigation_inspector.rs` / `scene::navigation` / `game::navigation` | Navigation authoring, deterministic bake artifacts, viewport preview, and runtime path queries | navigation-authoring.md, ADR 0032 |
|
| `ui/navigation_inspector.rs` / `scene::navigation` / `game::navigation` | Navigation authoring, deterministic bake artifacts, viewport preview, and runtime path queries | navigation-authoring.md, ADR 0032 |
|
||||||
| `assets/materials.rs` / `shared::renderer_material` / `shared::hydration::{static_meshes,skinned_meshes}` | Shared material discovery, stable renderer slots, and draw binding | material-system.md, ADR 0035 |
|
| `assets/materials.rs` / `ui/material_library.rs` / `viewport/material_drop.rs` / `shared::renderer_material` | Shared material discovery, docked catalog/usage UI, exact reversible surface drops, stable renderer slots, and draw binding | material-system.md, ADR 0035 |
|
||||||
| `blacksite_surface` / `game_hot::rendering::solari` / `third_party/bevy_solari` | Surface ABI packing, raster composition, Solari evaluator dispatch, and deformation eligibility | material-system.md, rendering.md, ADR 0036 |
|
| `blacksite_surface` / `game_hot::rendering::solari` / `third_party/bevy_solari` | Surface ABI packing, raster composition, Solari evaluator dispatch, and deformation eligibility | material-system.md, rendering.md, ADR 0036 |
|
||||||
| `assets/` | Catalog, asset DB, static mesh artifacts, `thumbnails/`, `materials.rs`, prefab overrides v2 | this file (below), prefab-authoring.md, ADR 0017, ADR 0027 |
|
| `assets/` | Catalog, asset DB, static mesh artifacts, `thumbnails/`, `materials.rs`, prefab overrides v2 | this file (below), prefab-authoring.md, ADR 0017, ADR 0027 |
|
||||||
| `shared::prefab_overrides` | Versioned stable override schema and editor-independent runtime application | prefab-authoring.md, ADR 0027 |
|
| `shared::prefab_overrides` | Versioned stable override schema and editor-independent runtime application | prefab-authoring.md, ADR 0027 |
|
||||||
| `project/` | Workspace, settings UI, user prefs, support diagnostics | roadmap Phase 1 |
|
| `project/` | Workspace, settings UI, user prefs, support diagnostics | roadmap Phase 1 |
|
||||||
|
| `project/collaboration.rs` | Guarded authored writes, asynchronous Git status, and optional ownership providers | collaborative-file-safety.md, ADR 0037 |
|
||||||
|
| `project/native_dialog.rs` | One-at-a-time native dialog worker and one-shot main-thread completions | native-dialogs.md, ADR 0038 |
|
||||||
| `project/session.rs` | Versioned XDG session document, clean marker, and safe resume | session-recovery.md, ADR 0024 |
|
| `project/session.rs` | Versioned XDG session document, clean marker, and safe resume | session-recovery.md, ADR 0024 |
|
||||||
| `project/diagnostics_bundle.rs` | Privacy-bounded transactional support report export | session-recovery.md, ADR 0024 |
|
| `project/diagnostics_bundle.rs` | Privacy-bounded transactional support report export | session-recovery.md, ADR 0024 |
|
||||||
| `project/launcher.rs` | Strict project inspection, CLI activation, recent filtering, and sandbox scaffolding | project-launcher.md, ADR 0025 |
|
| `project/launcher.rs` | Strict project inspection, CLI activation, recent filtering, and sandbox scaffolding | project-launcher.md, ADR 0025 |
|
||||||
@@ -65,6 +78,7 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
|||||||
- **Unified viewport** uses one render-to-texture target for both the editor fly camera and the possessed player camera so HDR/atmosphere is not broken by sub-viewport cropping.
|
- **Unified viewport** uses one render-to-texture target for both the editor fly camera and the possessed player camera so HDR/atmosphere is not broken by sub-viewport cropping.
|
||||||
- **PIE:** F8 possess/eject while sim runs; **F6** pauses/resumes simulation in Play; project settings drive shared rendering for the active viewport camera.
|
- **PIE:** F8 possess/eject while sim runs; **F6** pauses/resumes simulation in Play; project settings drive shared rendering for the active viewport camera.
|
||||||
- **Asset browser** mirrors the on-disk `assets/` directory with project tree, breadcrumb, search/filter/sort, grid/list views, texture/model/material thumbnails, a details pane, and context-aware row/menu actions; narrow docks prioritize content, keep the root panel fixed, switch list view to a compact single-column layout, and hide tree/details panes when they would crowd the content area. The footer stays pinned while only the project tree, asset content, and details panels scroll. **Built-ins** holds spawnable primitives and lights. **Materials** folder scans `assets/materials/*.ron`, renders material thumbnails on a sphere using `MaterialDesc`, and exposes shader-schema-driven parameters/textures in the details editor; **Shaders** holds shader schema RON files. **Audio** accepts Bevy-supported Ogg/Vorbis and Speex (`.ogg`, `.oga`, `.spx`), WAV, MP3, and FLAC clips under `assets/audio/`, with a dedicated filter, waveform icon, format/file details, and stable registry-backed references that retain a runtime source path. glTF/GLB/FBX rows can expand into a shelf of normalized embedded mesh, material, and texture subassets with independent generated thumbnails. Mesh subassets can be selected, dragged into the viewport, or placed from details/context menus; material subassets render source-material spheres; texture subassets can be applied to the selected actor. Model import settings are staged with **Apply** / **Revert**, asset context menus can regenerate thumbnails, material asset details edit shared `MaterialAsset` fields, and file asset deletion moves sources/generated artifacts into `assets/.trash/`. Before thumbnail loading, glTF sources preflight local external buffers/images and show a stable non-retryable failure state when a dependency is missing instead of repeatedly invoking the asset loader.
|
- **Asset browser** mirrors the on-disk `assets/` directory with project tree, breadcrumb, search/filter/sort, grid/list views, texture/model/material thumbnails, a details pane, and context-aware row/menu actions; narrow docks prioritize content, keep the root panel fixed, switch list view to a compact single-column layout, and hide tree/details panes when they would crowd the content area. The footer stays pinned while only the project tree, asset content, and details panels scroll. **Built-ins** holds spawnable primitives and lights. **Materials** folder scans `assets/materials/*.ron`, renders material thumbnails on a sphere using `MaterialDesc`, and exposes shader-schema-driven parameters/textures in the details editor; **Shaders** holds shader schema RON files. **Audio** accepts Bevy-supported Ogg/Vorbis and Speex (`.ogg`, `.oga`, `.spx`), WAV, MP3, and FLAC clips under `assets/audio/`, with a dedicated filter, waveform icon, format/file details, and stable registry-backed references that retain a runtime source path. glTF/GLB/FBX rows can expand into a shelf of normalized embedded mesh, material, and texture subassets with independent generated thumbnails. Mesh subassets can be selected, dragged into the viewport, or placed from details/context menus; material subassets render source-material spheres; texture subassets can be applied to the selected actor. Model import settings are staged with **Apply** / **Revert**, asset context menus can regenerate thumbnails, material asset details edit shared `MaterialAsset` fields, and file asset deletion moves sources/generated artifacts into `assets/.trash/`. Before thumbnail loading, glTF sources preflight local external buffers/images and show a stable non-retryable failure state when a dependency is missing instead of repeatedly invoking the asset loader.
|
||||||
|
- **Material Library** is a dockable bottom-panel catalog for cross-folder Material and direct-base Material Instance authoring. It provides search, type and scene-usage filters, grid/list thumbnails, dependency health, usage counts, creation, guarded details editing, and first-class drag sources. Viewport drops resolve an exact renderer slot, primitive, or brush face under the pointer, preview transiently, reject incompatible/read-only targets explicitly, restore on target change/cancel, and commit one typed undo step on release.
|
||||||
- **Static/skinned renderer split** — model drag/drop uses normalized artifacts under `assets/meshes/generated/`. Unrigged, non-animated sources create `ActorKind::StaticMesh + StaticMeshRenderer`; skin-bound or animated sources create `ActorKind::SkinnedMesh + SkinnedMeshRenderer` and preserve the imported hierarchy. Static slots never contain marked skinned primitives or geometry from animated sources. `SceneInstance` placement keeps `ImportedModel + ModelRef` for generic full-source scenes. See [ADR 0033](../adr/0033-dedicated-skinned-mesh-renderer.md).
|
- **Static/skinned renderer split** — model drag/drop uses normalized artifacts under `assets/meshes/generated/`. Unrigged, non-animated sources create `ActorKind::StaticMesh + StaticMeshRenderer`; skin-bound or animated sources create `ActorKind::SkinnedMesh + SkinnedMeshRenderer` and preserve the imported hierarchy. Static slots never contain marked skinned primitives or geometry from animated sources. `SceneInstance` placement keeps `ImportedModel + ModelRef` for generic full-source scenes. See [ADR 0033](../adr/0033-dedicated-skinned-mesh-renderer.md).
|
||||||
- **Animation authoring** — glTF/GLB imports generate UUID-keyed rig/clip manifests and expandable skeleton/clip shelves. Clip drag creates a skinned actor or adds one exact-signature-compatible state to a selected skinned actor through typed history. `AnimationControllerDesc` exposes named states, ranges, loop/speed, default/crossfade, and non-dirty runtime-backed preview; project validation resolves the same stable refs and blocks animated/skinned FBX with conversion guidance. Production acceptance completed in Gitea #46. See [animation-authoring.md](animation-authoring.md) and [ADR 0031](../adr/0031-animation-authoring-runtime-contract.md).
|
- **Animation authoring** — glTF/GLB imports generate UUID-keyed rig/clip manifests and expandable skeleton/clip shelves. Clip drag creates a skinned actor or adds one exact-signature-compatible state to a selected skinned actor through typed history. `AnimationControllerDesc` exposes named states, ranges, loop/speed, default/crossfade, and non-dirty runtime-backed preview; project validation resolves the same stable refs and blocks animated/skinned FBX with conversion guidance. Production acceptance completed in Gitea #46. See [animation-authoring.md](animation-authoring.md) and [ADR 0031](../adr/0031-animation-authoring-runtime-contract.md).
|
||||||
- **Navigation authoring** — bounds, obstacles, areas, and links use typed history and viewport visualizers. Rerecast produces a versioned fingerprinted artifact; Polyanya powers both editor path preview and the game-owned runtime API. The existing horizontal toolbar path button creates or bakes bounds, while Scene > Navigation exposes the complete workflow. See [navigation-authoring.md](navigation-authoring.md) and [ADR 0032](../adr/0032-versioned-navigation-bake-and-runtime-query.md).
|
- **Navigation authoring** — bounds, obstacles, areas, and links use typed history and viewport visualizers. Rerecast produces a versioned fingerprinted artifact; Polyanya powers both editor path preview and the game-owned runtime API. The existing horizontal toolbar path button creates or bakes bounds, while Scene > Navigation exposes the complete workflow. See [navigation-authoring.md](navigation-authoring.md) and [ADR 0032](../adr/0032-versioned-navigation-bake-and-runtime-query.md).
|
||||||
@@ -86,6 +100,7 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
|
|||||||
components on load and component transactions, and does not prohibit compatible composition such
|
components on load and component transactions, and does not prohibit compatible composition such
|
||||||
as renderer plus light. Component validation owns requirements and geometry-source conflicts.
|
as renderer plus light. Component validation owns requirements and geometry-source conflicts.
|
||||||
- **Scene persistence and recovery** use transactional same-directory writes for authored scenes and bounded user-local recovery snapshots for dirty saved scenes. Recovery runs every 120 seconds by default, keeps five generations, never marks the scene clean, and appears as a status/File-menu restore or discard action when newer than the authored file. Restore leaves the original scene dirty until manually saved. See [ADR 0023](../adr/0023-transactional-scene-persistence-and-recovery.md).
|
- **Scene persistence and recovery** use transactional same-directory writes for authored scenes and bounded user-local recovery snapshots for dirty saved scenes. Recovery runs every 120 seconds by default, keeps five generations, never marks the scene clean, and appears as a status/File-menu restore or discard action when newer than the authored file. Restore leaves the original scene dirty until manually saved. See [ADR 0023](../adr/0023-transactional-scene-persistence-and-recovery.md).
|
||||||
|
- **Collaborative file safety** records exact content revisions for loaded scenes, prefab source operations, editable materials, and Project Settings, then rechecks them immediately before atomic publication. External changes, create races, read-only files, and optional ownership locks keep the existing bytes intact and open Reload/Compare Metadata/Save As/Cancel recovery. Git status is asynchronous, observational, and absent without noise outside a repository. See [collaborative-file-safety.md](collaborative-file-safety.md) and [ADR 0037](../adr/0037-collaborative-authored-file-safety.md).
|
||||||
- **Scene visualizers** expose actor root icons, colliders, lights, player spawns, gameplay markers, volumes, prefab/model anchors, Project Sun, and runtime player/camera markers without changing saved scene data. Spot lights show inner/outer cones and cameras show near/far frusta. Viewport options independently gate visualizer categories and include actor icon and transform-gizmo size sliders.
|
- **Scene visualizers** expose actor root icons, colliders, lights, player spawns, gameplay markers, volumes, prefab/model anchors, Project Sun, and runtime player/camera markers without changing saved scene data. Spot lights show inner/outer cones and cameras show near/far frusta. Viewport options independently gate visualizer categories and include actor icon and transform-gizmo size sliders.
|
||||||
- **Clean game-view overlay** (`G`) hides editor chrome, grid, selection outlines, transform gizmos, actor root icons, visualizers, and selectable proxies without changing camera ownership; `Ctrl+G` toggles grid.
|
- **Clean game-view overlay** (`G`) hides editor chrome, grid, selection outlines, transform gizmos, actor root icons, visualizers, and selectable proxies without changing camera ownership; `Ctrl+G` toggles grid.
|
||||||
- **Viewport shading** (toolbar): **Lit** (default WYSIWYG), **Unlit** (base-color debug), **Colliders** (hide meshes, emphasize collider gizmos). The viewport combines active shading/render path in one bottom-right chip, draws a camera-relative X/Y/Z orientation widget, identifies the primary selection in a responsive top-right HUD, and previews asset placement with a pointer card, placement reticle, corner brackets, and highlighted drop boundary.
|
- **Viewport shading** (toolbar): **Lit** (default WYSIWYG), **Unlit** (base-color debug), **Colliders** (hide meshes, emphasize collider gizmos). The viewport combines active shading/render path in one bottom-right chip, draws a camera-relative X/Y/Z orientation widget, identifies the primary selection in a responsive top-right HUD, and previews asset placement with a pointer card, placement reticle, corner brackets, and highlighted drop boundary.
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ Native-only dependencies (`rfd`, BRP HTTP) stay in `editor`. `settings`, `shared
|
|||||||
| `ActorIconsPlugin` | Selectable actor root billboard icons |
|
| `ActorIconsPlugin` | Selectable actor root billboard icons |
|
||||||
| `EditorVisualizersPlugin` | Collider/light/spawn/prefab/runtime visualizers and selectable proxies |
|
| `EditorVisualizersPlugin` | Collider/light/spawn/prefab/runtime visualizers and selectable proxies |
|
||||||
| `SceneIoPlugin` | Level New/Open/Save, recent paths |
|
| `SceneIoPlugin` | Level New/Open/Save, recent paths |
|
||||||
|
| `CollaborationPlugin` | Exact authored-file guards, asynchronous Git status, optional ownership providers |
|
||||||
| `OperatorPlugin` | Active operator lifecycle/status for commands and modal tools |
|
| `OperatorPlugin` | Active operator lifecycle/status for commands and modal tools |
|
||||||
| `SettingsUiPlugin` | egui Project Settings panel |
|
| `SettingsUiPlugin` | egui Project Settings panel |
|
||||||
| `EditorUiPlugin` | Dock, themed egui shell, viewport overlays, menus, status bar |
|
| `EditorUiPlugin` | Dock, themed egui shell, viewport overlays, menus, status bar |
|
||||||
@@ -76,6 +77,15 @@ The bounded in-session scene I/O event log feeds the Diagnostics window so a lat
|
|||||||
does not erase a save or recovery failure.
|
does not erase a save or recovery failure.
|
||||||
See [ADR 0023](../adr/0023-transactional-scene-persistence-and-recovery.md).
|
See [ADR 0023](../adr/0023-transactional-scene-persistence-and-recovery.md).
|
||||||
|
|
||||||
|
`project/collaboration.rs` wraps user-authored publication with BLAKE3 baselines and a second
|
||||||
|
revision/read-only check immediately before the same-directory rename. Scene tabs, prefab source
|
||||||
|
Apply/history, staged Material documents, and Project Settings use this shared boundary. Its worker
|
||||||
|
observes path-scoped Git porcelain and optional ownership providers without blocking the frame loop
|
||||||
|
or changing repository state; conflict recovery is explicit Reload, metadata comparison, Save As,
|
||||||
|
or Cancel. Generated artifacts remain under their subsystem-owned regeneration policy. See
|
||||||
|
[collaborative-file-safety.md](collaborative-file-safety.md) and
|
||||||
|
[ADR 0037](../adr/0037-collaborative-authored-file-safety.md).
|
||||||
|
|
||||||
`project/session.rs` owns the independent versioned restart document under the user state
|
`project/session.rs` owns the independent versioned restart document under the user state
|
||||||
directory. It snapshots allowlisted paths, panel visibility, dock/hierarchy metadata, and camera
|
directory. It snapshots allowlisted paths, panel visibility, dock/hierarchy metadata, and camera
|
||||||
bookmarks, writes a running marker at startup, and records clean `AppExit`. Abnormal sessions do
|
bookmarks, writes a running marker at startup, and records clean `AppExit`. Abnormal sessions do
|
||||||
@@ -151,7 +161,7 @@ The egui layer lives under `crates/editor/src/ui/`:
|
|||||||
| `diagnostics.rs` | Detailed stats (Window → Diagnostics, Asset Browser footer) |
|
| `diagnostics.rs` | Detailed stats (Window → Diagnostics, Asset Browser footer) |
|
||||||
| `layout.rs` | Dock layout RON persistence in `editor_prefs.ron` |
|
| `layout.rs` | Dock layout RON persistence in `editor_prefs.ron` |
|
||||||
|
|
||||||
The Viewport fills the tab (no inline help text). Gizmo/grid/play controls sit on a near-black semi-transparent overlay, and `G` hides editor-only overlays for a clean game view. The fixed dark status strip prioritizes `SceneIo.status` feedback and also shows scene path/dirty state, mode, selection count, history, and the active operator. Long feedback is truncated responsively and available in a hover tooltip. Dock layout restores from `~/.config/bevy-fps/editor_prefs.ron` on startup; **View → Reset Layout** restores defaults.
|
The Viewport fills the tab (no inline help text). Gizmo/grid/play controls sit on a near-black semi-transparent overlay, and `G` hides editor-only overlays for a clean game view. The fixed dark status strip prioritizes `SceneIo.status` feedback and also shows scene path/dirty state, compact active-file collaboration status, mode, selection count, history, and the active operator. Long feedback is truncated responsively and available in a hover tooltip. Dock layout restores from `~/.config/bevy-fps/editor_prefs.ron` on startup; **View → Reset Layout** restores defaults.
|
||||||
|
|
||||||
**Follow-up (Phase 4b):** inspector search and richer per-asset previews.
|
**Follow-up (Phase 4b):** inspector search and richer per-asset previews.
|
||||||
|
|
||||||
@@ -247,7 +257,7 @@ PIE stop restores player simulation state only; authored `LevelObject` edits mad
|
|||||||
| `viewport/` | Camera, selection, gizmos, render views, panel settings |
|
| `viewport/` | Camera, selection, gizmos, render views, panel settings |
|
||||||
| `play/` | PIE session, editor mode, net editor profiles |
|
| `play/` | PIE session, editor mode, net editor profiles |
|
||||||
| `assets/` | Catalog, asset DB, static mesh artifacts, prefab overrides |
|
| `assets/` | Catalog, asset DB, static mesh artifacts, prefab overrides |
|
||||||
| `project/` | Project I/O and settings UI |
|
| `project/` | Project I/O, settings UI, authored-file safety, and observational collaboration status |
|
||||||
| `ext/` | Command palette, BRP, game panel adapters |
|
| `ext/` | Command palette, BRP, game panel adapters |
|
||||||
| `history/` | Undo commands + plugin |
|
| `history/` | Undo commands + plugin |
|
||||||
| `ui/` | egui dock shell |
|
| `ui/` | egui dock shell |
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Collaborative File Safety
|
||||||
|
|
||||||
|
Blacksite protects loaded user-authored documents with exact content revisions. This layer covers
|
||||||
|
scene and prefab documents, editable Material and Material Instance assets, and `assets/project.ron`.
|
||||||
|
Generated import artifacts, registries, thumbnails, navigation bakes, recovery snapshots, and package output keep
|
||||||
|
their subsystem-owned regeneration rules and never interrupt editing with authored-file conflicts.
|
||||||
|
|
||||||
|
## Status Surfaces
|
||||||
|
|
||||||
|
The bottom status strip shows a compact state for the active saved scene. The selected asset's
|
||||||
|
Details header shows the same state when the asset has an on-disk source. Hover either indicator for
|
||||||
|
the path, Git state, read-only state, ownership detail, and scanner diagnostics.
|
||||||
|
|
||||||
|
When Git is available, Blacksite distinguishes clean, modified, untracked, and conflicted files.
|
||||||
|
The path-scoped scanner uses only `rev-parse` and NUL-delimited `status --porcelain`; it never
|
||||||
|
stages, commits, resets, checks out, restores, or discards files. A missing Git executable or
|
||||||
|
project outside a repository is a normal quiet state.
|
||||||
|
|
||||||
|
## Save Conflicts
|
||||||
|
|
||||||
|
On load, the editor records a BLAKE3 revision and file metadata. Save verifies that revision before
|
||||||
|
preparing the atomic replacement and again immediately before rename. A changed, newly created, or
|
||||||
|
read-only target remains untouched and opens the collaborative-file dialog.
|
||||||
|
|
||||||
|
The dialog provides:
|
||||||
|
|
||||||
|
- **Reload**: discard the editor draft for that document and load the current disk revision.
|
||||||
|
- **Compare Metadata**: show expected/current revision, byte size, modified time, and permissions.
|
||||||
|
- **Save As**: preserve the editor draft at a separately chosen path, guarded against a create race.
|
||||||
|
- **Cancel**: keep the editor draft and make no filesystem change.
|
||||||
|
|
||||||
|
There is intentionally no force-overwrite action. Resolve or preserve the other revision first.
|
||||||
|
|
||||||
|
## Ownership Providers
|
||||||
|
|
||||||
|
Teams can register an implementation of `FileOwnershipProvider` with
|
||||||
|
`register_file_ownership_provider`. Providers receive the active project root and a bounded list of
|
||||||
|
currently tracked project-relative paths on the background scan worker. They return owner/lock
|
||||||
|
details per path.
|
||||||
|
|
||||||
|
A lock held by another user blocks authored publication and uses the same recovery dialog. Provider
|
||||||
|
errors appear only in indicator details; the exact filesystem revision guard continues to work. An
|
||||||
|
empty provider registry performs no calls and adds no UI.
|
||||||
|
|
||||||
|
## Recovery Notes
|
||||||
|
|
||||||
|
- Scene Reload explicitly replaces the active dirty document with disk content and clears its local
|
||||||
|
history. Use Save As first when both versions matter.
|
||||||
|
- Material Reload discards only the staged Details draft and reloads the asset on the next draw.
|
||||||
|
- Project Settings Reload strictly parses the current manifest, reapplies it live, and refreshes the
|
||||||
|
panel draft; invalid external RON stays blocked and visible.
|
||||||
|
- Prefab Apply conflicts keep instance overrides intact. Reload tears down stale hydration and
|
||||||
|
queues the current source for rehydration; retry Apply after reviewing Changed Base/conflict
|
||||||
|
state, or Save As to preserve the proposed source copy.
|
||||||
|
- Prefab source undo/redo stays blocked when the exact expected source revision is absent.
|
||||||
|
|
||||||
|
The architectural policy is recorded in
|
||||||
|
[ADR 0037](../adr/0037-collaborative-authored-file-safety.md).
|
||||||
|
|
||||||
|
Live editor acceptance, including external-change detection, metadata comparison, cancel/reload
|
||||||
|
invariants, and source-control status, is recorded in the
|
||||||
|
[collaborative file-safety evaluation](evaluations/collaborative-file-safety/).
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Editor Evaluation Evidence
|
||||||
|
|
||||||
|
Each subdirectory keeps the canonical, versioned acceptance record for an editor feature. Screenshots
|
||||||
|
remain in the repository beside that record and are intentionally stored through Git LFS.
|
||||||
|
|
||||||
|
## Publishing To Gitea
|
||||||
|
|
||||||
|
Do not embed a repository `/raw/branch/...` or `/raw/commit/...` PNG URL in an issue or pull-request
|
||||||
|
comment. Gitea can serve the LFS pointer document at that URL, which renders as text instead of an
|
||||||
|
image. Upload the PNG to the relevant issue as a native attachment and use the returned
|
||||||
|
`/attachments/<uuid>` URL for the Markdown image. Keep the repository evaluation link next to the
|
||||||
|
attachment so the evidence remains traceable to its committed source.
|
||||||
|
|
||||||
|
Native attachments are presentation copies. The committed evaluation directory remains the source of
|
||||||
|
truth and should retain the original image and verification notes.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Collaborative File Safety Evaluation
|
||||||
|
|
||||||
|
Date: 2026-07-12
|
||||||
|
Branch: `codex/collaboration-live-acceptance`
|
||||||
|
Implementation commits: `5a82a9e`, `f2ad88f`
|
||||||
|
|
||||||
|
This record captures live acceptance for source-control status and guarded authored-file writes.
|
||||||
|
The permanent workflow and recovery contract live in the
|
||||||
|
[collaborative file-safety guide](../../collaborative-file-safety.md).
|
||||||
|
|
||||||
|
## Live Editor Evidence
|
||||||
|
|
||||||
|
The image below is a native Wayland capture from the debug editor. A disposable untracked scene
|
||||||
|
was loaded, changed locally, and then changed independently on disk before Save.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The bottom status strip reports the active scene as `UNTRACKED`. The guarded save left the disk
|
||||||
|
revision unchanged and opened recovery choices with the exact loaded/current revision, byte count,
|
||||||
|
modified time, and permissions.
|
||||||
|
|
||||||
|
## Acceptance Results
|
||||||
|
|
||||||
|
| Area | Result | Evidence |
|
||||||
|
|------|--------|----------|
|
||||||
|
| Source-control status | Pass | Active disposable scene reported `UNTRACKED` without disrupting the editor workflow |
|
||||||
|
| External-change guard | Pass | Save detected the changed disk revision and did not overwrite it |
|
||||||
|
| Metadata comparison | Pass | Loaded/current revision, byte count, modified time, and permissions were displayed |
|
||||||
|
| Cancel invariants | Pass | Cancel preserved the dirty local scene and made no filesystem change |
|
||||||
|
| Invalid reload | Pass | Malformed external RON failed safely, kept the recovery dialog open, and reported the error |
|
||||||
|
| Valid reload | Pass | Reload replaced the local draft, removed its duplicate actor, cleared dirty/history state, and adopted the disk revision |
|
||||||
|
| Repository hygiene | Pass | Disposable scene and importer registry churn were removed after acceptance |
|
||||||
|
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
|
||||||
|
|
||||||
|
## Automated Verification
|
||||||
|
|
||||||
|
The implementation commits were already covered on integrated `main` by the workspace formatting,
|
||||||
|
check, strict Clippy, test, level-validation, and navigation-artifact suites. This evidence-only
|
||||||
|
change was additionally checked with `git diff --check`.
|
||||||
Binary file not shown.
@@ -1,5 +1,7 @@
|
|||||||
# H1 Gate Sign-Off — Game Development Ready
|
# H1 Gate Sign-Off — Game Development Ready
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Evaluator:** implementation pass
|
**Evaluator:** implementation pass
|
||||||
**Result:** Pass (implementation complete; manual dogfood recommended)
|
**Result:** Pass (implementation complete; manual dogfood recommended)
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# H2 Gate Sign-Off — Content Pipeline Maturity
|
# H2 Gate Sign-Off — Content Pipeline Maturity
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Result:** Pass with waivers
|
**Result:** Pass with waivers
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# H3 Gate Sign-Off — Gameplay Authoring
|
# H3 Gate Sign-Off — Gameplay Authoring
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Result:** Pass
|
**Result:** Pass
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# H4 Gate Sign-Off — Multiplayer Tooling
|
# H4 Gate Sign-Off — Multiplayer Tooling
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Result:** Pass with waivers
|
**Result:** Pass with waivers
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# H5 Gate Sign-Off — Extensibility
|
# H5 Gate Sign-Off — Extensibility
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Result:** Pass
|
**Result:** Pass
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# H6 Gate Sign-Off — Production / Framework 1.0
|
# H6 Gate Sign-Off — Production / Framework 1.0
|
||||||
|
|
||||||
|
> Historical baseline only. Current production authority: [production-readiness matrix](production-readiness/).
|
||||||
|
|
||||||
**Date:** 2026-05-30
|
**Date:** 2026-05-30
|
||||||
**Result:** Pass with waivers
|
**Result:** Pass with waivers
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Material Library And Targeted Drop Evaluation
|
||||||
|
|
||||||
|
Date: 2026-07-12
|
||||||
|
Branch: `codex/material-library-targeted-drop`
|
||||||
|
Implementation commit: `02247f0`
|
||||||
|
|
||||||
|
This record captures live acceptance for the docked Material Library and exact viewport
|
||||||
|
Material/Texture assignment workflow. The permanent user workflow lives in the
|
||||||
|
[material-system guide](../../material-system.md), and the implementation plan is
|
||||||
|
[material_library_and_targeted_drop_2026-07-12.plan.md](../../../../.cursor/plans/material_library_and_targeted_drop_2026-07-12.plan.md).
|
||||||
|
|
||||||
|
## Live Editor Evidence
|
||||||
|
|
||||||
|
The image below is a native Wayland capture from the debug editor. The assignment was previewed,
|
||||||
|
committed once, undone, previewed again, and canceled with Escape; the authored scene was not saved.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The Material Library resolves `surface_tint_instance` through its base Material and sparse
|
||||||
|
overrides. While the pointer is over the viewport, the green card names `Ground / Surface`, the
|
||||||
|
inspector reflects the transient material, and the scene-usage section identifies the exact actor
|
||||||
|
and surface. The preview does not push history or dirty the scene.
|
||||||
|
|
||||||
|
## Acceptance Results
|
||||||
|
|
||||||
|
| Area | Result | Evidence |
|
||||||
|
|------|--------|----------|
|
||||||
|
| Catalog workflow | Pass | Window menu entry, persisted bottom dock, search, Material/Instance/Used/Unused filters, grid/list views, resolved instance thumbnail, and details selection |
|
||||||
|
| Exact targeting | Pass | Primitive preview resolves one actor surface; automated coverage resolves one stable renderer slot and one stable brush face |
|
||||||
|
| Feedback | Pass | Neutral acquisition changes to green valid actor/surface feedback; invalid payload and read-only paths are covered by focused tests |
|
||||||
|
| Preview lifecycle | Pass | Live material and usage update without a history entry; Escape restores the exact prior material |
|
||||||
|
| Commit lifecycle | Pass | Release creates one typed history/operator entry; undo restores the prior surface |
|
||||||
|
| Startup hygiene | Pass | Relaunching the authored showcase after visibility-order correction produced no Bevy hierarchy warnings |
|
||||||
|
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
|
||||||
|
|
||||||
|
## Automated Verification
|
||||||
|
|
||||||
|
| Command/suite | Result |
|
||||||
|
|---------------|--------|
|
||||||
|
| `cargo fmt --all -- --check` | Pass |
|
||||||
|
| `cargo check --workspace --all-targets` | Pass |
|
||||||
|
| `cargo clippy --workspace --all-targets -- -D warnings` | Pass |
|
||||||
|
| `cargo test --workspace` | Pass |
|
||||||
|
| Editor strict Clippy with `dev` and `hot-reload` features | Pass |
|
||||||
|
| `cargo validate-levels --project .` | 59 dependencies, 5 non-blocking findings, 0 blocking errors |
|
||||||
|
| `cargo bake-navigation --project . --check` | 1 deterministic artifact current |
|
||||||
|
| `git diff --check` | Pass |
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,42 @@
|
|||||||
|
# Native Dialog Responsiveness Evaluation
|
||||||
|
|
||||||
|
Date: 2026-07-12
|
||||||
|
Branch: `codex/non-blocking-native-dialogs`
|
||||||
|
Implementation commits: `d038cf3` and the closing commit for Gitea #52
|
||||||
|
|
||||||
|
This record captures live acceptance for the non-blocking native-dialog broker. The permanent
|
||||||
|
workflow contract lives in the [native-dialog guide](../../native-dialogs.md).
|
||||||
|
|
||||||
|
## Live Editor Evidence
|
||||||
|
|
||||||
|
The native KDE portal Open dialog below was launched through the production `SceneIoRequest::Open`
|
||||||
|
path in a native Wayland debug editor and held open for 12 seconds.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
During the hold, Hyprland continued to report Blacksite as mapped, visible, input-capable, and native
|
||||||
|
Wayland. No application-not-responding client appeared. Cancel closed the picker without changing the
|
||||||
|
active scene, and the editor then stopped cleanly.
|
||||||
|
|
||||||
|
## Acceptance Results
|
||||||
|
|
||||||
|
| Area | Result | Evidence |
|
||||||
|
|------|--------|----------|
|
||||||
|
| Frame responsiveness | Pass | A blocked-dialog regression test advances eight Bevy frames before releasing the worker; live editor remained compositor-responsive during the 12-second picker hold |
|
||||||
|
| Shared coverage | Pass | Every `rfd::FileDialog` and `rfd::MessageDialog` construction is inside a `NativeDialogBroker::request` worker closure |
|
||||||
|
| Request exclusivity | Pass | Focused test rejects a second request while one is pending and permits work after one-shot completion |
|
||||||
|
| Cancellation | Pass | Live Open cancellation preserved the active scene; workflow callbacks retain explicit non-mutating cancel branches |
|
||||||
|
| Main-thread application | Pass | Paths/results cross the broker, while scene, asset, history, registry, project, and collaboration work remains in `&mut World` completions |
|
||||||
|
| Stale initiating state | Pass | Prefab/export completions reject missing initiating entities; composition validates against current state after selection |
|
||||||
|
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
|
||||||
|
|
||||||
|
## Automated Verification
|
||||||
|
|
||||||
|
| Command/suite | Result |
|
||||||
|
|---------------|--------|
|
||||||
|
| `cargo fmt --all -- --check` | Pass |
|
||||||
|
| `cargo check --workspace --all-targets` | Pass |
|
||||||
|
| `cargo clippy --workspace --all-targets -- -D warnings` | Pass |
|
||||||
|
| `cargo test --workspace` | Pass |
|
||||||
|
| Focused native-dialog lifecycle and frame-progress tests | 2 passed |
|
||||||
|
| `git diff --check` | Pass |
|
||||||
Binary file not shown.
@@ -0,0 +1,105 @@
|
|||||||
|
# Production-Readiness Acceptance Matrix
|
||||||
|
|
||||||
|
**Matrix version:** 0.2
|
||||||
|
|
||||||
|
**Last audit:** 2026-07-12
|
||||||
|
|
||||||
|
**Release-candidate commit:** Not nominated
|
||||||
|
|
||||||
|
**Overall result:** **Not ready**
|
||||||
|
|
||||||
|
This is the current authority for Gitea
|
||||||
|
[`#50`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/50).
|
||||||
|
The older H1-H6 files are historical implementation snapshots and do not satisfy this gate.
|
||||||
|
|
||||||
|
## Evidence Rules
|
||||||
|
|
||||||
|
| State | Meaning |
|
||||||
|
|-------|---------|
|
||||||
|
| Pass | Candidate-specific evidence proves the full row. |
|
||||||
|
| Partial | Some implementation/evidence exists, but the full row is not proven. |
|
||||||
|
| Deferred | The project owner has explicitly postponed this check; it is not a pass. |
|
||||||
|
| Missing | Required implementation or candidate evidence does not exist. |
|
||||||
|
| Fail | Current authoritative evidence contradicts the gate. |
|
||||||
|
| External | Requires a person other than the implementer. |
|
||||||
|
|
||||||
|
Acceptance evidence must name the exact candidate commit and commands or protocol used. Results from
|
||||||
|
another commit, a dirty worktree, or an older package do not transfer to the candidate.
|
||||||
|
|
||||||
|
## Exit Gate
|
||||||
|
|
||||||
|
| 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. |
|
||||||
|
| 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. |
|
||||||
|
|
||||||
|
## Deliverables
|
||||||
|
|
||||||
|
| ID | Deliverable | State | Evidence or next action |
|
||||||
|
|----|-------------|-------|-------------------------|
|
||||||
|
| D1 | Versioned acceptance matrix under `docs/editor/evaluations/` | Pass | This file, version 0.2. |
|
||||||
|
| D2 | Release-candidate representative project and reproducible validation commands | Missing | Expand the committed project/regression pack through `#32`, including terrain and physics-placement samples, then nominate an exact commit. |
|
||||||
|
| D3 | Signed milestone comment linking evidence, limitations, and exact commit | Missing | Post only after G1-G8 pass; no candidate exists yet. |
|
||||||
|
|
||||||
|
## Workflow Coverage
|
||||||
|
|
||||||
|
| Workflow | Implementation status | Candidate acceptance |
|
||||||
|
|----------|-----------------------|----------------------|
|
||||||
|
| Project create/open/resume | Implemented | Not rerun |
|
||||||
|
| Scene save, autosave, recovery | Implemented | Not rerun |
|
||||||
|
| 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 |
|
||||||
|
| Animation | Implemented | Not rerun |
|
||||||
|
| Audio | Implemented | Not rerun |
|
||||||
|
| Navigation | Implemented | Not rerun |
|
||||||
|
| PIE | Implemented | Not rerun |
|
||||||
|
| Build/package/runtime | Implemented foundation | Deferred by owner |
|
||||||
|
| Collaborative file safety | Implemented; `#49` closed with live external-change acceptance | Not rerun as one candidate |
|
||||||
|
| Native file/folder dialogs | Implemented; `#52` closed with live 12-second compositor-responsiveness hold | Not rerun as one candidate |
|
||||||
|
|
||||||
|
## Candidate Validation Commands
|
||||||
|
|
||||||
|
Run these from a fresh clone of the nominated commit with Git LFS content present. Record wall time,
|
||||||
|
machine profile, exit code, and artifact hashes. Packaged commands stay disabled until the project
|
||||||
|
owner re-enables them.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo check --workspace --all-targets
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
cargo clippy -p editor -p game --bins --features dev,hot-reload -- -D warnings
|
||||||
|
cargo test --workspace
|
||||||
|
cargo validate-levels --project .
|
||||||
|
cargo bake-navigation --project . --check
|
||||||
|
```
|
||||||
|
|
||||||
|
When packaged acceptance is re-enabled, append the exact `package-project` profile/target commands,
|
||||||
|
package hash verification, and packaged-runtime smoke protocol used for the candidate.
|
||||||
|
|
||||||
|
## Soak Protocol
|
||||||
|
|
||||||
|
The final candidate must run for eight continuous hours against the representative project. The
|
||||||
|
record must sample process RSS, GPU memory, target-directory size, recovery generations, background
|
||||||
|
job counts, and error/warning totals at least every five minutes. Exercise scene switching, save and
|
||||||
|
recovery, asset refresh, material editing, brush/terrain/physics tools, animation/audio/navigation,
|
||||||
|
PIE transitions, and build UI cancellation without replacing the candidate during the run.
|
||||||
|
|
||||||
|
A pass requires no unrecoverable editor failure, no lost authored work, no unbounded upward trend in
|
||||||
|
steady-state resource use, bounded recovery/cache behavior, and a triaged explanation for every
|
||||||
|
error. Numeric thresholds remain blocked on the performance-budget work in `#34`.
|
||||||
|
|
||||||
|
## Independent Sign-Off
|
||||||
|
|
||||||
|
The evaluator must not be the implementation agent. They record the candidate commit, machine,
|
||||||
|
elapsed first-hour workflow, recovery scenario, defects, severity, and go/no-go decision. Waivers
|
||||||
|
must include a workaround and owner ticket; an open P0 cannot be waived.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Terrain Foundation Evaluation
|
||||||
|
|
||||||
|
Date: 2026-07-12
|
||||||
|
Branch: `codex/terrain-foundation`
|
||||||
|
Gitea issue: `#22`
|
||||||
|
|
||||||
|
This record captures acceptance for the persistent height-grid terrain schema and deterministic
|
||||||
|
runtime chunk hydration. The permanent workflow lives in the [terrain guide](../../terrain.md).
|
||||||
|
|
||||||
|
## Live Editor Evidence
|
||||||
|
|
||||||
|
The native Wayland debug editor loaded the committed
|
||||||
|
`assets/levels/terrain_authoring_showcase.scn.ron` fixture. The screenshot uses Forward rendering to
|
||||||
|
isolate mesh/material/light correctness while foundation terrain remains explicitly excluded from
|
||||||
|
Solari until exact terrain layer/Surface parity lands in `#24`.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The 5×5 authored grid renders as the expected asymmetric hill, resolves the committed shared
|
||||||
|
Material Instance, and is split into four 2×2-quad chunks with generated trimesh colliders. The
|
||||||
|
authored scene contains no `HydratedTerrainChunk`, `Mesh3d`, or collider-constructor components.
|
||||||
|
|
||||||
|
## Acceptance Results
|
||||||
|
|
||||||
|
| Area | Result | Evidence |
|
||||||
|
|------|--------|----------|
|
||||||
|
| Schema and serialization | Pass | Versioned bounded descriptor, exact height count, finite-value and scale/chunk validation, RON round-trip test |
|
||||||
|
| Chunk hydration | Pass | Deterministic four-chunk runtime fixture; topology test verifies 25 vertices and 96 indices for a 4×4-quad mesh |
|
||||||
|
| Runtime-only ownership | Pass | Hydration test verifies children have mesh/collider/owner markers but no `LevelObject`, then verifies removal cleanup |
|
||||||
|
| Actor/editor integration | Pass | First-class Terrain kind, registry descriptor, hierarchy/viewport icon, reflected Add Component and inspector transaction path |
|
||||||
|
| Material behavior | Pass with boundary | Shared Material/Instance source resolves for raster; missing source uses visible fallback; Solari submission is explicitly excluded pending `#24` |
|
||||||
|
| Project validation | Pass | 60 level dependencies, existing 5 non-blocking findings, 0 blocking errors |
|
||||||
|
| Packaged acceptance | Deferred | Explicitly deferred by project-owner direction; no packaged result is claimed here |
|
||||||
|
|
||||||
|
## Automated Verification
|
||||||
|
|
||||||
|
| Command/suite | Result |
|
||||||
|
|---------------|--------|
|
||||||
|
| Focused terrain descriptor/topology/hydration tests | 4 passed |
|
||||||
|
| Editor component registry reflection contract | Pass |
|
||||||
|
| `cargo check --workspace --all-targets` | Pass |
|
||||||
|
| `cargo validate-levels --project .` | 60 dependencies, 5 findings, 0 blockers |
|
||||||
Binary file not shown.
@@ -0,0 +1,31 @@
|
|||||||
|
# Terrain Sculpt Tools Acceptance
|
||||||
|
|
||||||
|
Issue: Gitea `#23`
|
||||||
|
|
||||||
|
Scope: native Wayland debug editor; packaged acceptance remains deferred by project-owner direction.
|
||||||
|
|
||||||
|
## Live Evidence
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The committed terrain showcase was selected in Forward rendering. Enabling the mountains tool kept
|
||||||
|
the actor selected, removed the transform gizmo, expanded Raise/Lower/Flatten/Smooth/Noise plus
|
||||||
|
radius/strength controls inside the existing horizontal viewport toolbar, and displayed the modal
|
||||||
|
cancel/undo hints. A dragged Raise stroke visibly changed the generated terrain while the footprint
|
||||||
|
tracked the sampled surface. Release produced exactly `Undo: Raise Terrain`; no transform `Move`
|
||||||
|
history entry was created.
|
||||||
|
|
||||||
|
Escape/right-click restoration, deterministic brush math, exact vertical-ray sampling, multi-dab
|
||||||
|
stroke grouping, and sculpt-time gizmo exclusion are covered by focused tests. The live pass also
|
||||||
|
exposed and corrected toolbar click-through into raw mesh picking before this evidence was captured.
|
||||||
|
|
||||||
|
## Source Verification
|
||||||
|
|
||||||
|
- `cargo fmt --all -- --check`
|
||||||
|
- `cargo check -p editor --all-targets`
|
||||||
|
- `cargo clippy -p editor --all-targets -- -D warnings`
|
||||||
|
- six focused terrain-sculpt/input-ownership tests
|
||||||
|
- `git diff --check`
|
||||||
|
|
||||||
|
The canonical fixture remains `assets/levels/terrain_authoring_showcase.scn.ron`; no QA-only scene or
|
||||||
|
project setting is retained.
|
||||||
Binary file not shown.
@@ -21,17 +21,34 @@ material, but may not reference another instance.
|
|||||||
|
|
||||||
## Assign materials
|
## Assign materials
|
||||||
|
|
||||||
1. Select a static- or skinned-mesh actor.
|
Open **Window > Material Library** for the cross-folder Material/Material Instance catalog. It
|
||||||
2. In **Static Mesh Renderer** or **Skinned Mesh Renderer**, find the material slot by its imported
|
supports search, Material/Instance/scene-usage filters, grid/list thumbnails, dependency health,
|
||||||
name and stable ID.
|
scene-reference counts, creation, drag sources, and the guarded shared-asset editor. It lives in the
|
||||||
3. Use **Browse** or **Select** to assign a Material or Material Instance. **Locate** reveals the
|
existing bottom dock and does not add permanent viewport chrome. Scene-usage rows select the exact
|
||||||
current asset in the Asset Browser.
|
actor, focus the viewport, and identify its renderer slot, primitive surface, or brush face.
|
||||||
4. Use **Clear** to remove only the explicit assignment. The slot returns to its read-only imported
|
|
||||||
source material.
|
Assign through either exact workflow:
|
||||||
|
|
||||||
|
1. Drag a Material or Material Instance from the Material Library or Asset Browser onto the desired
|
||||||
|
viewport surface. A hydrated static/skinned draw targets its exact stable renderer slot, a
|
||||||
|
primitive targets its actor material, and a brush targets the exact face under the pointer.
|
||||||
|
2. Check the pointer card and target visual. Green names a valid actor/slot/face; red gives the
|
||||||
|
blocking reason. Release commits one undoable assignment. Move away, leave the viewport, press
|
||||||
|
Escape, or right-click to restore the pre-drag state without history or dirtying the scene.
|
||||||
|
3. Alternatively, select a static- or skinned-mesh actor and use **Browse** or **Select** on the
|
||||||
|
named slot in its renderer inspector. **Locate** reveals the current asset in the Asset Browser;
|
||||||
|
**Clear** removes only the explicit assignment and restores the read-only imported source.
|
||||||
|
|
||||||
From the Asset Browser, **Apply Material** assigns the selected material to every material slot on
|
From the Asset Browser, **Apply Material** assigns the selected material to every material slot on
|
||||||
each selected static or skinned renderer. Use the per-slot inspector when different draws need
|
each selected static or skinned renderer. This is the explicit bulk path. A viewport hit never
|
||||||
different assignments.
|
silently broadens to all slots.
|
||||||
|
|
||||||
|
Texture drops target a primitive's base-color texture or one brush face. Direct Texture drops on a
|
||||||
|
renderer slot are rejected because a renderer slot stores a Material reference; create or edit a
|
||||||
|
Material Instance and assign the texture there.
|
||||||
|
|
||||||
|
See the [Material Library and targeted-drop evaluation](evaluations/material-library-targeted-drop/)
|
||||||
|
for the live preview, commit/undo, cancel, and source-verification record.
|
||||||
|
|
||||||
Static draw slots and material slots are separate. Removing a static draw retains its explicit
|
Static draw slots and material slots are separate. Removing a static draw retains its explicit
|
||||||
material assignment as an orphan rather than guessing a replacement. Reimport also reconciles
|
material assignment as an orphan rather than guessing a replacement. Reimport also reconciles
|
||||||
@@ -39,10 +56,11 @@ slots by stable ID, never by display name. Resolve an orphan explicitly in the r
|
|||||||
|
|
||||||
## Author shared assets
|
## Author shared assets
|
||||||
|
|
||||||
Material files and material-instance files are RON documents under `assets/materials/`. The Asset
|
Material files and material-instance files are RON documents under `assets/materials/`. The
|
||||||
Browser identifies the document kind, exposes its schema-driven properties and texture bindings,
|
Material Library and Asset Browser identify the document kind, expose the same guarded
|
||||||
and uses stable subasset IDs (`material:source` or `material:instance`). Built-in shader schemas
|
schema-driven editor and texture bindings, and use stable subasset IDs (`material:source` or
|
||||||
live under `assets/shaders/`.
|
`material:instance`). Material Instance thumbnails resolve the direct base plus sparse overrides.
|
||||||
|
Built-in shader schemas live under `assets/shaders/`.
|
||||||
|
|
||||||
Select a Material and use **Create Instance** to create a direct-base variant beside it. The
|
Select a Material and use **Create Instance** to create a direct-base variant beside it. The
|
||||||
instance inspector exposes its base Material plus sparse property and texture override checkboxes;
|
instance inspector exposes its base Material plus sparse property and texture override checkboxes;
|
||||||
@@ -147,3 +165,5 @@ bases, and unsupported project content through the same editor/headless finding
|
|||||||
| Custom normal has no visible effect | Verify the mesh has tangents. |
|
| Custom normal has no visible effect | Verify the mesh has tangents. |
|
||||||
| Animated actor is missing from Solari GI | Expected for current skinned/morph geometry; inspect the deformed-exclusion diagnostic. |
|
| Animated actor is missing from Solari GI | Expected for current skinned/morph geometry; inspect the deformed-exclusion diagnostic. |
|
||||||
| Material reference is unresolved | Run project validation and repair/reselect the stable asset reference; do not hand-edit a display-name match. |
|
| Material reference is unresolved | Run project validation and repair/reselect the stable asset reference; do not hand-edit a display-name match. |
|
||||||
|
| Texture drop is red on an imported renderer | Renderer slots accept Materials, not loose textures. Create/edit a Material Instance, set its texture, then assign it. |
|
||||||
|
| Drag preview remains after leaving a target | This is a regression: target changes, viewport exit, Escape, right-click, and invalid release must restore the exact snapshot. |
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Native Dialog Workflows
|
||||||
|
|
||||||
|
Blacksite routes native file, folder, Save As, and unsaved-change confirmation dialogs through the
|
||||||
|
shared `NativeDialogBroker`. A native dialog may remain open without blocking Bevy's window event
|
||||||
|
loop or editor rendering.
|
||||||
|
|
||||||
|
## Workflow Contract
|
||||||
|
|
||||||
|
- One native dialog can be active at a time. Direct controls are disabled while pending; other
|
||||||
|
concurrent requests report that a dialog is already open.
|
||||||
|
- Native work returns only selected paths or a confirmation result. Scene, asset, project, history,
|
||||||
|
registry, and collaborative-file mutations run later on the Bevy main thread.
|
||||||
|
- Cancel is non-mutating and produces workflow-specific status.
|
||||||
|
- Entity-based operations capture the initiating entity and reject stale results. Composition
|
||||||
|
additions validate against the current composition so intervening edits are not overwritten.
|
||||||
|
- Collaborative Save As performs the same revision and destination checks after selection.
|
||||||
|
- Close or project switch never treats an opened Save As picker as a completed save. When a save
|
||||||
|
remains pending, the transition pauses and can be retried after saving.
|
||||||
|
|
||||||
|
## Covered Surfaces
|
||||||
|
|
||||||
|
The broker owns scene Open/Save As, import/export, prefab creation and relinking, recovery copies,
|
||||||
|
subscene selection, collaborative conflict copies, Project Browser folder selection, and dirty-scene
|
||||||
|
confirmations. New workflows must use the broker instead of calling `rfd` from an egui/Bevy system.
|
||||||
|
|
||||||
|
See [ADR 0038](../adr/0038-non-blocking-native-dialog-broker.md).
|
||||||
|
|
||||||
|
Live native-Wayland acceptance is recorded in the
|
||||||
|
[native-dialog responsiveness evaluation](evaluations/native-dialog-responsiveness/).
|
||||||
@@ -147,7 +147,7 @@ with implementation sequencing in
|
|||||||
| Milestone | Exit condition | Status |
|
| Milestone | Exit condition | Status |
|
||||||
|-----------|----------------|--------|
|
|-----------|----------------|--------|
|
||||||
| M6 Reliability, recovery, and project workflow | Transactional save/recovery, stable sessions, project launcher, hardened hierarchy/prefabs, multi-scene composition | Implementation complete; all six scoped issues are closed after prefab #43 passed workspace, headless, packaged-runtime, and live editor acceptance |
|
| M6 Reliability, recovery, and project workflow | Transactional save/recovery, stable sessions, project launcher, hardened hierarchy/prefabs, multi-scene composition | Implementation complete; all six scoped issues are closed after prefab #43 passed workspace, headless, packaged-runtime, and live editor acceptance |
|
||||||
| M7 Content production and shipping | Build/package profiles, content release gate, animation, audio, navigation, collaborative safety | Active; #44-#48 are complete. Source-control safety #49 and final readiness gate #50 remain; packaged acceptance is deferred until requested by the project owner. |
|
| M7 Content production and shipping | Build/package profiles, content release gate, animation, audio, navigation, collaborative safety | Active; #44-#48 are complete. #49 implementation and source/headless acceptance are complete, with live visual acceptance pending; final readiness gate #50 remains. Packaged acceptance is deferred until requested by the project owner. |
|
||||||
|
|
||||||
Production readiness is not inferred from feature count. Gitea
|
Production readiness is not inferred from feature count. Gitea
|
||||||
[`#50`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/50)
|
[`#50`](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/50)
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Terrain Authoring
|
||||||
|
|
||||||
|
Terrain is a first-class authored actor backed by `TerrainDesc`. Add it from the Inspector's
|
||||||
|
**Add Component** shelf by searching for Terrain. It conflicts with other geometry sources on the
|
||||||
|
same actor: Primitive, Brush, Static Mesh Renderer, and Skinned Mesh Renderer.
|
||||||
|
|
||||||
|
## Foundation Workflow
|
||||||
|
|
||||||
|
The Terrain card exposes grid resolution, sample spacing, height scale, chunk size, generated
|
||||||
|
collision, shadows, base material status, and validation. **Resize Flat** deliberately replaces the
|
||||||
|
height array with a flat grid; normal numeric edits retain all height samples. Every accepted edit is
|
||||||
|
one reflected history transaction and rebuilds only that terrain's generated chunks.
|
||||||
|
|
||||||
|
## Sculpt Workflow
|
||||||
|
|
||||||
|
Select a terrain actor and enable the mountains button in the existing horizontal viewport toolbar.
|
||||||
|
Choose **Raise**, **Lower**, **Flatten**, **Smooth**, or **Noise**, then LMB-drag across the terrain.
|
||||||
|
The radius and strength controls use world meters; the colored footprint follows the sampled terrain
|
||||||
|
surface and identifies the active mode.
|
||||||
|
|
||||||
|
Each drag is one stroke and one undo entry, regardless of how many interpolated dabs it contains.
|
||||||
|
Escape or right-click restores the exact pre-stroke height grid; when no stroke is active, either input
|
||||||
|
closes the sculpt tool. Flatten captures the height under the initial press. Smooth samples a stable
|
||||||
|
copy of the current neighborhood per dab, and Noise uses a deterministic per-stroke seed so authored
|
||||||
|
results remain reproducible.
|
||||||
|
|
||||||
|
`assets/levels/terrain_authoring_showcase.scn.ron` is the deterministic foundation fixture. Its 5×5
|
||||||
|
grid forms an asymmetric hill split into four 2×2-quad chunks. It validates chunk boundaries,
|
||||||
|
normals, selection through generated children, collider generation, inspector state, and save
|
||||||
|
stripping without requiring external assets.
|
||||||
|
|
||||||
|
## Data And Hydration
|
||||||
|
|
||||||
|
- Heights are finite normalized values multiplied by Height Scale at hydration time.
|
||||||
|
- Sample Spacing controls X/Z distance and the grid remains centered on the actor origin.
|
||||||
|
- Chunk Size is measured in quads. Neighboring chunks share boundary samples but not runtime mesh
|
||||||
|
assets, allowing later stroke updates to rebuild only affected chunks.
|
||||||
|
- A resolvable shared Material/Material Instance source supplies the chunk material. Missing or
|
||||||
|
invalid references produce a warning and visible terrain fallback rather than missing geometry.
|
||||||
|
- Generated `HydratedTerrainChunk` children own mesh, optional trimesh collider, and shadow state.
|
||||||
|
They are runtime-only and never serialized as authored actors.
|
||||||
|
- Foundation chunks are explicitly excluded from Solari submission and remain raster-visible while
|
||||||
|
Auto/Solari is active. Terrain Surface/layer parity enters with the material-layer work in `#24`;
|
||||||
|
the editor never substitutes a black or semantically different ray-traced terrain proxy.
|
||||||
|
|
||||||
|
Material layers and weight painting are tracked by Gitea `#24`. The persistence decision is recorded in
|
||||||
|
[ADR 0039](../adr/0039-inline-height-grid-terrain-foundation.md).
|
||||||
|
|
||||||
|
Live native-Wayland evidence and focused verification are recorded in the
|
||||||
|
[terrain foundation evaluation](evaluations/terrain-foundation/).
|
||||||
Reference in new issue
Block a user