Compare commits

..
Author SHA1 Message Date
Rbanh ed21bcc52d Add chunked terrain authoring foundation
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:43:42 -04:00
Rbanh 577d8dcb27 Refresh production readiness matrix
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:10:03 -04:00
Rbanh ba59f57a5a Finish non-blocking native dialog workflows
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 18:06:57 -04:00
Rbanh d038cf3670 Add non-blocking native dialog broker 2026-07-12 17:48:51 -04:00
Rbanh 61be2440bd Document collaborative file safety acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 17:43:07 -04:00
Rbanh 3794faa4aa Document material workflow acceptance
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 13:18:40 -04:00
Rbanh 02247f029a Add material library and targeted surface drops 2026-07-12 13:14:47 -04:00
Rbanh 3931de1f0a Fix hot reload feature matrix
CI / Format, lint, test, build (push) Waiting to run
2026-07-12 11:35:57 -04:00
61 changed files with 4435 additions and 288 deletions

No files matched your search

@@ -8,21 +8,26 @@ present; this slice completes the production-facing catalog and drag/drop workfl
## Status
Source audit complete. Implementation starts on a clean branch after collaborative-safety `#49` is
published, because both slices touch the Asset Browser and should remain independently reviewable.
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.
## Current Gaps
## Resolved Gaps
- Material assets are edited inside generic Asset Browser Details; no dedicated Material Library or
scene-usage view exists.
- Viewport material/texture drops act on the existing selection instead of the surface under the
pointer.
- Multi-slot renderers silently assign all slots; the hydrated draw hit already carries
`HydratedRendererMaterialBinding`, but the drop path does not use it.
- Primitive and brush-face targeting is not explicit, and unsupported authored actors can receive a
generic `MaterialDesc` instead of an actionable rejection.
- Drag UI describes an eventual action but does not preview the actual affected surface or restore a
preview on cancel/target change.
- 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
@@ -73,12 +78,17 @@ menu; a viewport hit never silently broadens from one slot to all slots.
## Verification
- Unit-test ray-hit to authored target/slot mapping, primitive/face targeting, and invalid reasons.
- Use `OperatorInvariantHarness` for preview target changes, release commit, Escape/outside cancel,
dirty-state preservation, helper cleanup, and one-step undo/redo.
- Cover static one/multi-slot, skinned multi-slot, primitive, brush face, Texture rejection on a
renderer slot, missing material, and linked/locked prefab boundaries.
- Verify Material Library filtering, scene-usage counts, dependency diagnostics, and drag sources in
headless egui tests.
- Run full source/headless checks. Packaged testing remains deferred until the project owner requests
it again; live visual acceptance is still required before closing `#16`/`#18`.
- 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.
@@ -15,9 +15,10 @@ owner requests it again.
1. Keep one evidence matrix under `docs/editor/evaluations/production-readiness/`; historical H1-H6
notes remain context only.
2. Close implementation blockers before nominating a candidate: collaborative safety `#49`, the
remaining Material/drag-drop contract in `#16`, `#18`, and `#51`, terrain `#22`-`#24`, physics
placement/diagnostics `#25`-`#26`, and their regression fixtures.
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.
@@ -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.
+9 -2
View File
@@ -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 |
| 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/` |
| 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 |
| `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 |
@@ -160,13 +163,14 @@ deep-stale variants.
| 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 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 |
| 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 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 |
| 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 |
@@ -395,6 +399,8 @@ crates/
- [x] Filtered hierarchy, inspector, viewport, toolbar, asset browser, and status panels
- [x] Delete, duplicate, rename, and structural/material undo-redo
- [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] Non-blocking native file/folder/confirmation broker across scene, asset, prefab, composition, collaboration, and Project Browser workflows ([ADR 0038](docs/adr/0038-non-blocking-native-dialog-broker.md), [workflow guide](docs/editor/native-dialogs.md), [Gitea #52](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/52))
- [x] Asset import, static mesh/prefab placement, texture assignment, and selection export
- [x] PIE player-only snapshot/restore (authored `LevelObject` edits persist on stop)
- [x] Unified viewport render-to-texture target + Play session bootstrap
@@ -434,6 +440,7 @@ crates/
- [x] FBX/glTF model import + normalized static/skinned renderer routing; explicit generic scene-instance load via `bevy_ufbx` / `ModelRef`
- [x] Asset browser model thumbnails (unified `assets/thumbnails/` pipeline; `ThumbnailState` cache; FBX via `FbxThumbnailSource`)
- [x] Shared Material/Material Instance assets, stable static/skinned renderer material slots, imported-source fallback, orphan preservation, and runtime-only property blocks ([ADR 0035](docs/adr/0035-shared-material-assets-and-renderer-slots.md), [material-system guide](docs/editor/material-system.md))
- [x] Docked Material Library with cross-folder type/usage filters, resolved Material Instance thumbnails, shared guarded editors, and exact reversible viewport Material/Texture drops for renderer slots, primitives, and brush faces ([material-system guide](docs/editor/material-system.md); [Gitea #16](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/16), [Gitea #18](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/18))
- [x] Prefab v2 core: shared stable nested override paths, property/component/structural scopes, recursive graph validation, linked-root variants, conflict recovery, transactional source Apply, and undoable unpack/convert ([ADR 0027](docs/adr/0027-stable-prefab-ownership-and-variants.md))
- [x] Prefab v2 production acceptance: committed base/nested/variant fixtures pass workspace tests, recursive headless validation, packaged release startup, and live editor placement/inspection regression coverage ([Gitea #43](https://git.spacetrainclubhouse.com/Falling-Metal-Interactive/Blacksite/issues/43))
- [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))
@@ -476,7 +483,7 @@ crates/
**Unpack Layer** preserves nested links; **Convert to Local** recursively removes them. Current
authoring UI coverage and production-acceptance gaps are tracked in
[prefab-authoring.md](docs/editor/prefab-authoring.md).
- Material and direct-base Material Instance assets live under `assets/materials/`; shader schemas live under `assets/shaders/`. 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.
- 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.
+18
View File
@@ -269,6 +269,24 @@
),
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"),
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,
),
}),
})
+2 -5
View File
@@ -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> {
let asset = load_material_asset(catalog_path)?;
let mut desc = asset.material;
desc.material_asset_path = Some(catalog_path.to_string());
Ok(desc)
shared::load_resolved_material_from_path(catalog_path).map(|(desc, _)| desc)
}
pub fn apply_material_asset_to_selection(
@@ -110,7 +107,7 @@ pub fn apply_material_asset_to_selection(
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 {
if part.material_slot_id.0.trim().is_empty() {
part.material_slot_id = if part.id.0.trim().is_empty() {
+2 -2
View File
@@ -13,8 +13,8 @@ pub mod thumbnails;
pub use catalog::*;
pub use thumbnails::{
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_folder_thumbnails, AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState,
ThumbnailStudio, ThumbnailsPlugin,
prefetch_asset_thumbnails, prefetch_folder_thumbnails, AssetThumbnailCache,
ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
};
/// Refreshes both generated contracts derived from one imported model source.
+35 -3
View File
@@ -22,6 +22,7 @@ use crate::asset_db::{ensure_asset_record, AssetRegistry};
use crate::history::{
capture_prefab_edit_state, record_prefab_edit_state, record_prefab_source_apply,
};
use crate::native_dialog::NativeDialogBroker;
use crate::ui::inspector::{
apply_component_card_response, component_card, component_card_context, property_row,
ComponentCardOptions,
@@ -751,13 +752,44 @@ fn relink_prefab_source(world: &mut World, entity: Entity) {
else {
return;
};
let Some(path) = rfd::FileDialog::new()
.set_directory(project_root.join("assets/prefabs"))
let 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"])
.pick_file()
else {
},
move |world, path| {
let Some(path) = path else {
world
.resource_mut::<crate::scene_io::SceneIo>()
.set_status("Prefab relink cancelled");
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 {
return;
};
+41 -4
View File
@@ -188,18 +188,24 @@ impl AssetThumbnailCache {
{
return;
}
let material = match shared::MaterialAsset::load_from_path(&path) {
Ok(asset) => asset,
let material = match shared::load_resolved_material_from_path(&path) {
Ok((material, _)) => material,
Err(error) => {
self.mark_studio_failed(&key, &error, true);
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(
key.clone(),
ThumbnailJobSource::MaterialAsset {
label: material.label.clone(),
material: Box::new(material.material),
label,
material: Box::new(material),
},
) {
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());
}
/// 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) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if !world.contains_resource::<ThumbnailStudio>() {
+3 -2
View File
@@ -8,8 +8,9 @@ mod sources;
mod studio;
pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_asset_thumbnails,
prefetch_folder_thumbnails, AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot,
ThumbnailState,
};
pub use job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{
+6
View File
@@ -25,6 +25,7 @@ pub use play::state;
pub use project::collaboration;
pub use project::diagnostics_bundle;
pub use project::launcher;
pub use project::native_dialog;
pub use project::project_io;
pub use project::session;
pub use project::settings_ui;
@@ -37,6 +38,7 @@ pub use viewport::brush_edit;
pub use viewport::brush_tool;
pub use viewport::camera;
pub use viewport::gizmos;
pub use viewport::material_drop;
pub use viewport::render_view;
pub use viewport::rendering_diagnostics;
pub use viewport::selection;
@@ -62,10 +64,12 @@ use extensibility::ExtensibilityPlugin;
use gizmos::EditorGizmoPlugin;
use history::EditorHistoryPlugin;
use infra::EditorInfraPlugin;
use material_drop::MaterialDropPlugin;
use operators::OperatorPlugin;
use play::audio_preview::AudioPreviewPlugin;
use play::PlaySessionPlugin;
use project::collaboration::CollaborationPlugin;
use project::native_dialog::NativeDialogPlugin;
use project_io::ProjectIoPlugin;
use render_view::RenderViewPlugin;
use scene_io::SceneIoPlugin;
@@ -88,6 +92,7 @@ impl PluginGroup for EditorPluginGroup {
let group = PluginGroupBuilder::start::<Self>()
.add(EditorInfraPlugin)
.add(ProjectIoPlugin)
.add(NativeDialogPlugin)
.add(scene_schema::SceneSchemaPlugin)
.add(net_editor::NetEditorPlugin)
.add(AssetDbPlugin)
@@ -107,6 +112,7 @@ impl PluginGroup for EditorPluginGroup {
.add(EditorCameraPlugin)
.add(AudioPreviewPlugin)
.add(ActorIconsPlugin)
.add(MaterialDropPlugin)
.add(EditorSelectionPlugin)
.add(SelectionOutlinePlugin)
.add(EditorGizmoPlugin)
+25 -3
View File
@@ -15,6 +15,7 @@ use egui_phosphor_icons::icons;
use shared::PrefabInstance;
use crate::assets::EditorAssets;
use crate::native_dialog::NativeDialogBroker;
use crate::project_io::ProjectWorkspace;
use crate::scene::recovery::atomic_write_with_pre_rename;
use crate::scene_io::SceneIo;
@@ -880,13 +881,34 @@ fn resolve_conflict_reload(world: &mut World, conflict: &PendingFileConflict) {
}
fn resolve_conflict_save_as(world: &mut World, conflict: &PendingFileConflict) {
let directory = conflict.path.parent().unwrap_or_else(|| Path::new("."));
let conflict = conflict.clone();
let directory = conflict
.path
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
let file_name = conflict_copy_file_name(&conflict.path);
let Some(destination) = rfd::FileDialog::new()
let request = world.resource::<NativeDialogBroker>().request(
move || {
rfd::FileDialog::new()
.set_directory(directory)
.set_file_name(file_name)
.save_file()
else {
},
move |world, destination| finish_conflict_save_as(world, conflict, destination),
);
world.resource_mut::<SceneIo>().set_status(match request {
Ok(()) => "Choose a destination for the conflict copy".into(),
Err(error) => format!("Save As unavailable: {error}"),
});
}
fn finish_conflict_save_as(
world: &mut World,
conflict: PendingFileConflict,
destination: Option<PathBuf>,
) {
let Some(destination) = destination else {
world
.resource_mut::<SceneIo>()
.set_status("Save conflict copy cancelled");
+37 -5
View File
@@ -13,6 +13,7 @@ use settings::{
PROJECT_TEMPLATE_VERSION,
};
use crate::native_dialog::{NativeDialogBroker, NativeDialogPlugin};
use crate::project_io::UserPreferences;
use crate::scene::recovery::atomic_write;
use crate::ui::theme::{
@@ -91,6 +92,7 @@ pub fn run_project_launcher() {
..default()
}))
.add_plugins(EguiPlugin::default())
.add_plugins(NativeDialogPlugin)
.init_resource::<ProjectLauncherUi>()
.add_systems(Startup, spawn_project_launcher_camera)
.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),
);
ui.add_space(8.0);
if ui.button("Browse Existing...").clicked() {
if let Some(root) = rfd::FileDialog::new().pick_folder() {
open_project_from_launcher(world, state, root);
let dialog_pending = world.resource::<NativeDialogBroker>().is_pending();
if ui
.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(),
);
if ui.button("Choose Empty Folder...").clicked() {
state.sandbox_destination = rfd::FileDialog::new().pick_folder();
if ui
.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 =
state.sandbox_destination.is_some() && !state.sandbox_name.trim().is_empty();
+1
View File
@@ -3,6 +3,7 @@
pub mod collaboration;
pub mod diagnostics_bundle;
pub mod launcher;
pub mod native_dialog;
pub mod project_io;
pub mod session;
pub mod settings_ui;
+171
View File
@@ -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());
}
}
+185 -90
View File
@@ -23,6 +23,7 @@ use shared::{
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
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::{
default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
@@ -82,8 +83,6 @@ pub struct SceneIo {
pub request: Option<SceneIoRequest>,
pub status: String,
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.
pub recovery_snapshot: Option<PathBuf>,
/// Bounded in-session audit trail for scene persistence and recovery operations.
@@ -119,7 +118,6 @@ impl Default for SceneIo {
request: None,
status: "Ready".to_string(),
dirty: false,
pending_request: None,
recovery_snapshot: None,
events: VecDeque::new(),
tabs: vec![SceneTab {
@@ -291,40 +289,16 @@ fn load_startup_scene(world: &mut World) {
}
fn process_scene_io_requests(world: &mut World) {
let request = {
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);
let Some(request) = world.resource_mut::<SceneIo>().request.take() else {
return;
}
Some(req) => req,
None => return,
}
}
};
if world.resource::<SceneIo>().has_unsaved_tabs() && needs_dirty_confirm(&request) {
match confirm_discard_or_save() {
DirtyConfirm::Save => {
let save_status = save_all_tabs(world);
if save_status.starts_with("Save failed") || save_status.ends_with("cancelled") {
world.resource_mut::<SceneIo>().set_status(save_status);
if matches!(request, SceneIoRequest::SwitchProject)
&& world.resource::<SceneIo>().has_unsaved_tabs()
{
request_switch_project_confirmation(world);
return;
}
}
DirtyConfirm::Discard => {}
DirtyConfirm::Cancel => {
world
.resource_mut::<SceneIo>()
.set_status("Operation cancelled");
return;
}
}
}
let status = match request {
SceneIoRequest::New => new_scene_tab(world),
@@ -348,16 +322,6 @@ fn process_scene_io_requests(world: &mut World) {
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 {
match crate::launcher::spawn_project_launcher_process() {
Ok(()) => {
@@ -368,19 +332,41 @@ fn switch_project(world: &mut World) -> String {
}
}
fn confirm_discard_or_save() -> DirtyConfirm {
use rfd::{MessageButtons, MessageDialog, MessageLevel};
match MessageDialog::new()
fn request_switch_project_confirmation(world: &mut World) {
let result = world.resource::<NativeDialogBroker>().request(
|| {
rfd::MessageDialog::new()
.set_title("Unsaved Changes")
.set_description("The scene has unsaved changes. Save before continuing?")
.set_level(MessageLevel::Warning)
.set_buttons(MessageButtons::YesNoCancel)
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancel)
.show()
{
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
_ => DirtyConfirm::Cancel,
},
|world, decision| match decision {
rfd::MessageDialogResult::Yes => {
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 {
@@ -533,18 +519,14 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
}
if world.resource::<SceneIo>().dirty {
match confirm_close_scene() {
DirtyConfirm::Save => {
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(),
}
request_close_scene_confirmation(world);
return "Waiting for close-scene confirmation".to_string();
}
finish_close_scene_tab(world)
}
fn finish_close_scene_tab(world: &mut World) -> String {
if world.resource::<SceneIo>().tabs.len() == 1 {
clear_scene_world(world);
world.insert_resource(SceneComposition {
@@ -618,18 +600,36 @@ fn reload_active_composition(world: &mut World) -> String {
"Reloaded active scene composition".to_string()
}
fn confirm_close_scene() -> DirtyConfirm {
use rfd::{MessageButtons, MessageDialog, MessageLevel};
match MessageDialog::new()
fn request_close_scene_confirmation(world: &mut World) {
let result = world.resource::<NativeDialogBroker>().request(
|| {
rfd::MessageDialog::new()
.set_title("Close Scene")
.set_description("This scene tab has unsaved changes. Save before closing it?")
.set_level(MessageLevel::Warning)
.set_buttons(MessageButtons::YesNoCancel)
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancel)
.show()
{
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
_ => DirtyConfirm::Cancel,
},
|world, decision| {
let status = match decision {
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}"));
}
}
@@ -694,12 +694,31 @@ fn save_selection_as_prefab(world: &mut World) -> 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")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("prefab.scn.ron")
.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();
};
let expected = match FileSnapshot::capture(&path) {
@@ -859,12 +878,27 @@ fn save_active_or_prompt(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")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name("editor_scene.scn.ron")
.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();
};
let expected = match FileSnapshot::capture(&path) {
@@ -885,31 +919,51 @@ fn save_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")
.add_filter("Bevy scene", &["scn.ron", "ron"])
.pick_file()
else {
return "Open cancelled".to_string();
};
open_path(world, path)
},
|world, path| {
let status = path.map_or_else(
|| "Open cancelled".to_string(),
|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 {
let Some(paths) = rfd::FileDialog::new()
let request = world.resource::<NativeDialogBroker>().request(
|| {
rfd::FileDialog::new()
.add_filter("Editor assets", IMPORTABLE_ASSET_EXTENSIONS)
.pick_files()
else {
return "Import cancelled".to_string();
};
match import_external_assets(&paths) {
},
|world, paths| {
let status = match paths {
None => "Import cancelled".to_string(),
Some(paths) => match import_external_assets(&paths) {
Ok(count) => {
world.resource_mut::<EditorAssets>().refresh();
format!("Imported {count} asset(s)")
}
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}"),
}
}
@@ -921,14 +975,32 @@ fn export_selection_with_dialog(world: &mut World) -> 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")
.add_filter("Bevy prefab", &["scn.ron", "ron"])
.set_file_name("selection.scn.ron")
.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();
};
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}"),
@@ -1041,6 +1113,9 @@ fn format_actor_validation(err: ActorValidationError) -> String {
ActorValidationError::InvalidBrushGeometry(message) => {
format!("Save failed: invalid brush geometry: {message}")
}
ActorValidationError::InvalidTerrain(message) => {
format!("Save failed: invalid terrain: {message}")
}
ActorValidationError::StaticMeshMissingPrimitive => {
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
.into()
@@ -1607,12 +1682,32 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
|| "recovered_scene.scn.ron".to_string(),
|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)
.add_filter("Bevy scene", &["scn.ron", "ron"])
.set_file_name(file_name)
.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();
};
let expected = match FileSnapshot::capture(&destination) {
@@ -112,6 +112,7 @@ pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel
| ActorKind::Light
| ActorKind::Empty
@@ -143,6 +144,7 @@ fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::Brush
| ActorKind::Terrain
| ActorKind::ImportedModel => icons::CUBE,
ActorKind::Light => icons::LIGHTBULB,
ActorKind::PrefabAnchor => icons::PACKAGE,
+6 -2
View File
@@ -1855,7 +1855,7 @@ 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,
ui: &mut egui::Ui,
selected_entities: &SelectedEntities,
@@ -2524,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
.get_resource_mut::<crate::asset_db::AssetRegistry>()
.ok_or_else(|| "Asset registry is unavailable".to_string())
@@ -373,6 +373,27 @@ impl Default for EditorComponentRegistry {
],
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 {
id: shared::AUTHORING_COMPONENT_MATERIAL,
type_name: "shared::components::MaterialDesc",
+11 -5
View File
@@ -36,7 +36,10 @@ impl PanelNodes {
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
EditorTab::Hierarchy => self.hierarchy(),
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::Hierarchy => nodes.hierarchy = path.node.0,
EditorTab::Inspector => nodes.inspector = path.node.0,
EditorTab::AssetBrowser | EditorTab::Build | EditorTab::Toolbar => {
nodes.bottom = path.node.0
}
EditorTab::AssetBrowser
| EditorTab::MaterialLibrary
| EditorTab::Build
| EditorTab::Toolbar => nodes.bottom = path.node.0,
}
}
nodes
}
}
pub const PANEL_TABS: [EditorTab; 5] = [
pub const PANEL_TABS: [EditorTab; 6] = [
EditorTab::Viewport,
EditorTab::Hierarchy,
EditorTab::Inspector,
EditorTab::AssetBrowser,
EditorTab::MaterialLibrary,
EditorTab::Build,
];
@@ -74,6 +79,7 @@ pub fn tab_label(tab: &EditorTab) -> &'static str {
EditorTab::Hierarchy => "Hierarchy",
EditorTab::Inspector => "Inspector",
EditorTab::AssetBrowser => "Asset Browser",
EditorTab::MaterialLibrary => "Material Library",
EditorTab::Build => "Build",
EditorTab::Toolbar => "Toolbar (legacy)",
}
+2
View File
@@ -205,6 +205,7 @@ fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
.map(|kind| match kind {
ActorKind::Empty => 0,
ActorKind::Brush
| ActorKind::Terrain
| ActorKind::StaticMesh
| ActorKind::SkinnedMesh
| ActorKind::ImportedModel => 1,
@@ -468,6 +469,7 @@ pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
match kind {
ActorKind::Empty => icons::FOLDER.as_str(),
ActorKind::Brush => icons::CUBE.as_str(),
ActorKind::Terrain => icons::MOUNTAINS.as_str(),
ActorKind::StaticMesh => icons::CUBE.as_str(),
ActorKind::SkinnedMesh => icons::PERSON_SIMPLE_RUN.as_str(),
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
+127 -4
View File
@@ -16,8 +16,8 @@ use shared::{
MaterialParameterValue, MaterialRef, MaterialShaderKind, NavigationArea, NavigationBounds,
NavigationLink, NavigationObstacle, ObjectiveMarker, PhysicsBody, PlayerSpawn,
PostProcessVolumeDesc, PrefabInstance, Primitive, PrimitiveShape, ProjectSun, RigidBodyDesc,
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TriggerVolume,
WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
SkinnedMeshRenderer, StaticMeshRenderer, StaticMeshRendererEntry, TeamSpawn, TerrainDesc,
TriggerVolume, WeaponSpawn, AUTHORING_DIRECTIONAL_LUX_MAX, AUTHORING_POINT_SPOT_LUMENS_MAX,
COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_AUDIO_LISTENER_DESC,
COMPONENT_AUDIO_SOURCE_DESC, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
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_POST_PROCESS_VOLUME, COMPONENT_PREFAB_INSTANCE, COMPONENT_PRIMITIVE,
COMPONENT_PROJECT_SUN, COMPONENT_RIGID_BODY_DESC, COMPONENT_SKINNED_MESH_RENDERER,
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TRIGGER_VOLUME,
COMPONENT_WEAPON_SPAWN,
COMPONENT_STATIC_MESH_RENDERER, COMPONENT_TEAM_SPAWN, COMPONENT_TERRAIN_DESC,
COMPONENT_TRIGGER_VOLUME, COMPONENT_WEAPON_SPAWN,
};
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_SKINNED_MESH_RENDERER => skinned_mesh_renderer_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_MATERIAL_DESC => material_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) {
let report = validate_brush(brush);
if report.diagnostics.is_empty() {
+5 -2
View File
@@ -32,8 +32,11 @@ pub fn default_dock_layout() -> DockLayoutSnapshot {
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
let [main_view_node, hierarchy_node] =
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
let [main_view_node, bottom_node] =
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]);
let [main_view_node, bottom_node] = tree.split_below(
main_view_node,
0.88,
vec![EditorTab::AssetBrowser, EditorTab::MaterialLibrary],
);
let panel_nodes = PanelNodes {
main_view: main_view_node.0,
File diff suppressed because it is too large. Load diff
+20
View File
@@ -13,6 +13,7 @@ pub mod hierarchy_ops;
pub mod hierarchy_state;
pub(crate) mod inspector;
mod layout;
mod material_library;
mod menu;
pub(crate) mod navigation_inspector;
mod play_controls;
@@ -75,6 +76,9 @@ pub struct UiState {
last_mode_tab: Option<EditorMode>,
}
#[derive(Resource, Default)]
struct DockTabRequest(Option<EditorTab>);
pub fn egui_captures_keyboard(ctx: &egui::Context) -> bool {
ctx.egui_wants_keyboard_input()
}
@@ -187,6 +191,10 @@ impl UiState {
.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);
mark_layout_dirty_if_changed(
@@ -283,6 +291,7 @@ pub enum EditorTab {
Inspector,
Toolbar,
AssetBrowser,
MaterialLibrary,
Build,
}
@@ -298,6 +307,9 @@ impl Plugin for EditorUiPlugin {
.init_resource::<component_registry::EditorComponentRegistry>()
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
.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::InspectorPanelState>()
.init_resource::<animation_inspector::AnimationInspectorState>()
@@ -315,6 +327,10 @@ impl Plugin for EditorUiPlugin {
apply_ui_state_from_prefs
.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(
Update,
@@ -421,6 +437,9 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::AssetBrowser => {
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),
}
}
@@ -432,6 +451,7 @@ impl egui_dock::TabViewer for TabViewer<'_> {
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
EditorTab::MaterialLibrary => (icons::PALETTE, "Material Library"),
EditorTab::Build => (icons::HAMMER, "Build"),
};
tab_title(icon, label)
+42 -19
View File
@@ -8,6 +8,7 @@ use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
use egui_phosphor_icons::icons;
use shared::{SceneComposition, SubsceneReference};
use crate::native_dialog::NativeDialogBroker;
use crate::scene_io::{ComposedSceneMember, SceneIo, SceneIoRequest};
use crate::selection::SelectedEntity;
@@ -195,19 +196,47 @@ fn composition_menu(
ui.separator();
if ui
.add_enabled(editing, egui::Button::new("Add Subscene..."))
.add_enabled(
editing && !world.resource::<NativeDialogBroker>().is_pending(),
egui::Button::new("Add Subscene..."),
)
.clicked()
{
match choose_subscene(world, &composition) {
Ok(Some(reference)) => {
composition.subscenes.push(reference);
changed = true;
let project_root =
PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
let directory = project_root.join("assets/levels");
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, &current, 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
.resource_mut::<SceneIo>()
.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 {
@@ -218,20 +247,14 @@ fn composition_menu(
}
}
fn choose_subscene(
world: &World,
fn validate_subscene_choice(
project_root: &Path,
composition: &SceneComposition,
) -> Result<Option<SubsceneReference>, String> {
let project_root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root)
path: PathBuf,
) -> Result<SubsceneReference, String> {
let project_root = project_root
.canonicalize()
.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
.canonicalize()
.map_err(|error| format!("could not resolve {}: {error}", path.display()))?;
@@ -251,12 +274,12 @@ fn choose_subscene(
{
return Err(format!("{relative} is already composed"));
}
Ok(Some(SubsceneReference {
Ok(SubsceneReference {
id: uuid::Uuid::new_v4().to_string(),
path: relative,
visible: true,
locked: true,
}))
})
}
fn focus_subscene(world: &mut World, selected: &mut SelectedEntities, reference_id: &str) {
+98 -62
View File
@@ -7,8 +7,8 @@ use egui_phosphor_icons::icons;
use transform_gizmo_bevy::prelude::GizmoOptions;
use crate::assets::operators::{
apply_material_operator, apply_texture_operator, assign_animation_clip_operator,
assign_audio_clip_operator, place_asset_operator, place_subasset_operator,
assign_animation_clip_operator, assign_audio_clip_operator, place_asset_operator,
place_subasset_operator,
};
use crate::assets::thumbnails::kind_icon;
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
@@ -21,8 +21,8 @@ use crate::viewport::actor_icons::ActorIconSettings;
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
use crate::viewport::{
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
ViewportSettings,
material_drop::is_surface_asset_selection, snap_translation, viewport_ground_position,
EditorViewportMode, MaterialDropState, ViewportDisplayMode, ViewportSettings,
};
use super::helpers::{
@@ -30,7 +30,8 @@ use super::helpers::{
};
use super::theme::{
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::{
icon_button_small, panel_toolbar_row, phosphor_icon, tool_button, tool_button_accent,
@@ -69,9 +70,17 @@ pub fn viewport_tab_ui(
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
*viewport_pointer_pos = response
.interact_pointer_pos()
.or_else(|| response.hover_pos())
// A drag source owns egui's interaction response, so `Response::hover_pos()`
// is intentionally empty while an asset is dragged over the viewport. The
// 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));
*pointer_in_viewport = viewport_pointer_pos.is_some();
@@ -820,11 +829,44 @@ fn viewport_asset_drop_ui(
.resource::<EditorAssets>()
.dragging_selection()
.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()
.and_then(|selection| asset_drag_descriptor(world, selection, selected));
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()) {
draw_asset_drag_preview(
ui,
@@ -833,7 +875,7 @@ fn viewport_asset_drop_ui(
*icon,
label,
action,
over_viewport,
drag_visual_state,
);
}
@@ -841,7 +883,7 @@ fn viewport_asset_drop_ui(
ui.painter().rect_stroke(
viewport_rect.shrink(2.0),
0.0,
egui::Stroke::new(2.0, ACCENT_HOVER),
egui::Stroke::new(2.0, highlight_color),
egui::StrokeKind::Inside,
);
}
@@ -851,6 +893,11 @@ fn viewport_asset_drop_ui(
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)) {
world.resource_mut::<EditorAssets>().clear_drag();
return;
@@ -903,26 +950,6 @@ fn viewport_asset_drop_ui(
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 assets = world.resource::<EditorAssets>();
assets.asset_for_selection(&selection).cloned()
@@ -943,18 +970,6 @@ fn viewport_asset_drop_ui(
}
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);
}
@@ -996,11 +1011,11 @@ fn asset_drag_descriptor(
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Texture,
..
} if !selected.is_empty() => "Apply texture to selection",
} => "Drop onto a primitive or brush face",
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Material,
..
} if !selected.is_empty() => "Apply material to selection",
} => "Drop onto an exact renderer slot",
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Skeleton,
..
@@ -1020,12 +1035,8 @@ fn asset_drag_descriptor(
..
} => "Create animated actor",
_ => match asset.kind {
crate::assets::EditorAssetKind::Texture if !selected.is_empty() => {
"Apply texture to selection"
}
crate::assets::EditorAssetKind::Material if !selected.is_empty() => {
"Apply material to selection"
}
crate::assets::EditorAssetKind::Texture => "Drop onto a primitive or brush face",
crate::assets::EditorAssetKind::Material => "Drop onto a renderable surface",
crate::assets::EditorAssetKind::AudioClip
if selected
.as_slice()
@@ -1041,6 +1052,29 @@ fn asset_drag_descriptor(
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(
ui: &egui::Ui,
viewport_rect: egui::Rect,
@@ -1048,39 +1082,41 @@ fn draw_asset_drag_preview(
icon: egui_phosphor_icons::Icon,
label: &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 {
let painter = ui.painter();
painter.circle_filled(pointer, 3.0, ACCENT_HOVER);
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, ACCENT_HOVER));
painter.circle_filled(pointer, 3.0, highlight_color);
painter.circle_stroke(pointer, 11.0, egui::Stroke::new(1.5, highlight_color));
painter.line_segment(
[
pointer - egui::vec2(17.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(
[
pointer + egui::vec2(7.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(
[
pointer - egui::vec2(0.0, 17.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(
[
pointer + egui::vec2(0.0, 7.0),
pointer + egui::vec2(0.0, 17.0),
],
egui::Stroke::new(1.5, ACCENT_HOVER),
egui::Stroke::new(1.5, highlight_color),
);
}
@@ -1101,7 +1137,7 @@ fn draw_asset_drag_preview(
ui.set_width(228.0);
ui.horizontal(|ui| {
ui.label(phosphor_icon(icon, 20.0).color(if over_viewport {
ACCENT_HOVER
highlight_color
} else {
TEXT_DIM
}));
@@ -1116,7 +1152,7 @@ fn draw_asset_drag_preview(
})
.size(11.0)
.color(if over_viewport {
ACCENT_HOVER
highlight_color
} else {
TEXT_MUTED
}),
@@ -1152,9 +1188,9 @@ fn draw_asset_drag_preview(
),
] {
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()
.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,
category: ActorIconCategory::Mesh,
},
ActorKind::Terrain => ActorIconSpec {
image: ActorIconImage::Mesh,
category: ActorIconCategory::Mesh,
},
ActorKind::StaticMesh => {
if components.has_primitive || components.has_static_mesh_renderer {
ActorIconSpec {
+11
View File
@@ -1047,6 +1047,17 @@ fn pick_face(
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> {
face.vertices
.iter()
File diff suppressed because it is too large. Load diff
+2
View File
@@ -6,6 +6,7 @@ pub mod brush_edit;
pub mod brush_tool;
pub mod camera;
pub mod gizmos;
pub mod material_drop;
mod panel;
pub mod render_view;
pub mod rendering_diagnostics;
@@ -21,5 +22,6 @@ pub use brush_csg::{
};
pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
pub use brush_tool::{BrushToolPlugin, BrushToolState};
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
pub use panel::*;
pub use viewport_mode::EditorViewportMode;
+18
View File
@@ -21,6 +21,7 @@ use crate::viewport::ViewportDisplayMode;
use crate::visualizers::EditorVisualizerProxy;
use bevy_egui::egui;
use crate::viewport::material_drop::{MaterialDropSet, MaterialDropState};
use crate::viewport::scene_view_ray;
#[derive(Resource, Default, Debug, Clone, Copy)]
@@ -47,6 +48,7 @@ struct PickTargetQueries<'w, 's> {
icon_proxies: Query<'w, 's, &'static ActorIconProxy>,
parents: Query<'w, 's, &'static ChildOf>,
editor_only: Query<'w, 's, (), With<EditorOnly>>,
material_drop: Option<Res<'w, MaterialDropState>>,
}
impl Plugin for EditorSelectionPlugin {
@@ -68,6 +70,7 @@ impl Plugin for EditorSelectionPlugin {
Last,
(handle_pick_events, cycle_overlapping_viewport_pick)
.chain()
.after(MaterialDropSet)
.run_if(scene_tools_active),
);
}
@@ -110,6 +113,14 @@ fn handle_pick_events(
gizmo_targets: Query<&GizmoTarget>,
hierarchy: Option<Res<HierarchyPanelState>>,
) -> Result {
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
&& !buttons.any_pressed([MouseButton::Right, MouseButton::Middle])
&& keys.just_pressed(KeyCode::Escape)
@@ -216,7 +227,14 @@ fn cycle_overlapping_viewport_pick(
keys: Res<ButtonInput<KeyCode>>,
buttons: Res<ButtonInput<MouseButton>>,
display: Res<ViewportDisplayMode>,
material_drop: Option<Res<MaterialDropState>>,
) -> Result {
if material_drop
.as_deref()
.is_some_and(MaterialDropState::captures_viewport_input)
{
return Ok(());
}
if display.clean_game_view {
return Ok(());
}
+1 -1
View File
@@ -94,7 +94,7 @@ mod hot {
ActiveCameraRenderProfile, ProjectRenderCamera, ProjectSettings, RenderingCapabilities,
SimTuning,
};
use shared::{InspectorOrder, LevelObject, LightDesc, ProjectSun};
use shared::{AuthoringComponentStates, InspectorOrder, LevelObject, LightDesc, ProjectSun};
use sim::{
CameraSensitivity, Crouching, GameInputEnabled, GameInputFocused, Grounded, JumpState,
Player, PlayerCamera, PlayerVelocity, PlayerYawSensitivity,
+1
View File
@@ -175,6 +175,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
match kind {
ActorKind::Empty => "Empty",
ActorKind::Brush => "Brush",
ActorKind::Terrain => "Terrain",
ActorKind::StaticMesh => "StaticMesh",
ActorKind::SkinnedMesh => "SkinnedMesh",
ActorKind::ImportedModel => "ImportedModel",
+18 -1
View File
@@ -11,7 +11,7 @@ use crate::{
ActorKind, AnimationControllerDesc, AudioListenerDesc, AudioSourceDesc, BrushDesc, LevelObject,
LightDesc, ModelRef, NavigationArea, NavigationBounds, NavigationLink, NavigationObstacle,
ObjectiveMarker, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
SkinnedMeshRenderer, StaticMeshRenderer, TeamSpawn, TerrainDesc, TriggerVolume, WeaponSpawn,
AUDIO_CLIP_SUB_ASSET_ID,
};
@@ -31,6 +31,9 @@ pub fn infer_actor_kind(entity: EntityRef<'_>) -> Option<ActorKind> {
if entity.get::<BrushDesc>().is_some() {
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() {
return Some(ActorKind::StaticMesh);
}
@@ -84,6 +87,7 @@ pub enum ActorValidationError {
BrushHasLight,
BrushHasModelRef,
InvalidBrushGeometry(String),
InvalidTerrain(String),
StaticMeshMissingPrimitive,
StaticMeshHasLight,
StaticMeshHasModelRef,
@@ -166,6 +170,7 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
}
let geometry_source_count = usize::from(entity.get::<Primitive>().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::<SkinnedMeshRenderer>().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));
}
}
if let Some(terrain) = entity.get::<TerrainDesc>() {
terrain
.validate()
.map_err(ActorValidationError::InvalidTerrain)?;
}
if let Some(renderer) = entity.get::<SkinnedMeshRenderer>() {
if renderer.path.trim().is_empty() {
return Err(ActorValidationError::SkinnedMeshInvalidRenderer);
@@ -218,6 +228,13 @@ pub fn validate_actor(entity: EntityRef<'_>) -> Result<(), ActorValidationError>
}
let _ = brush;
}
ActorKind::Terrain => {
if entity.get::<TerrainDesc>().is_none() {
return Err(ActorValidationError::InvalidTerrain(
"terrain actor is missing TerrainDesc".into(),
));
}
}
ActorKind::StaticMesh => {
let has_static_mesh_renderer = entity
.get::<StaticMeshRenderer>()
+122
View File
@@ -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.
pub const AUTHORING_COMPONENT_PRIMITIVE: &str = "render.primitive";
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_SKINNED_MESH_RENDERER: &str = "render.skinned_mesh_renderer";
pub const AUTHORING_COMPONENT_MATERIAL: &str = "render.material";
@@ -318,6 +319,7 @@ pub fn authoring_component_id(key: &str) -> Option<&'static str> {
match key {
AUTHORING_COMPONENT_PRIMITIVE | COMPONENT_PRIMITIVE => Some(AUTHORING_COMPONENT_PRIMITIVE),
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 => {
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_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_MATERIAL_DESC: &str = "shared::components::MaterialDesc";
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 {
fn default() -> Self {
Self::cuboid(Vec3::ONE)
@@ -1392,6 +1513,7 @@ impl Default for EditorVisibility {
pub enum ActorKind {
Empty,
Brush,
Terrain,
StaticMesh,
SkinnedMesh,
ImportedModel,
+3 -4
View File
@@ -11,8 +11,7 @@ use bevy::prelude::*;
use crate::{
asset_server_path, authoring_component_active, brush_math::validate_brush,
AuthoringComponentStates, BrushDesc, BrushFaceDesc, ColliderDesc, InspectorOrder, LevelObject,
MaterialAsset, MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC,
COMPONENT_MATERIAL_DESC,
MaterialDesc, COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
};
use super::materials::material_from_desc;
@@ -214,8 +213,8 @@ fn brush_group_material(
texture_path: Option<&str>,
) -> StandardMaterial {
let mut material = material_path
.and_then(|path| MaterialAsset::load_from_path(path).ok())
.map(|asset| material_from_desc(asset_server, &asset.material))
.and_then(|path| crate::load_resolved_material_from_path(path).ok())
.map(|(desc, _)| material_from_desc(asset_server, &desc))
.or_else(|| parent_material.map(|material| material_from_desc(asset_server, material)))
.unwrap_or_else(default_brush_material);
if let Some(texture_path) = texture_path {
+19 -2
View File
@@ -10,6 +10,7 @@ mod primitives;
mod skinned_meshes;
mod static_meshes;
pub mod strip;
mod terrain;
mod visibility;
pub use lights::cascade_config_from_rendering;
@@ -37,6 +38,8 @@ use static_meshes::{
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
StaticMeshArtifactCache,
};
pub use terrain::HydratedTerrainChunk;
use terrain::{cleanup_removed_terrain, hydrate_terrain};
use visibility::{
ensure_level_object_visibility_hierarchy, init_editor_visibility_on_spawn,
sync_editor_visibility, visibility_from_editor,
@@ -52,17 +55,28 @@ use crate::{
/// Registers hydration systems in deterministic order.
pub struct HydrationPlugin;
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum HydrationSet {
Visibility,
Content,
}
impl Plugin for HydrationPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<StaticMeshArtifactCache>()
.add_observer(tag_hydrated_prefab_members)
.add_observer(mark_skinned_materials_ready)
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
.configure_sets(
Update,
(HydrationSet::Visibility, HydrationSet::Content).chain(),
)
.add_systems(
Update,
(
hydrate_primitives,
hydrate_brushes,
hydrate_terrain,
hydrate_materials,
hydrate_lights,
reconcile_missing_runtime_lights,
@@ -73,8 +87,10 @@ impl Plugin for HydrationPlugin {
hydrate_models,
hydrate_prefabs,
hydrate_physics,
cleanup_removed_terrain,
)
.chain(),
.chain()
.in_set(HydrationSet::Content),
)
.add_systems(
Update,
@@ -83,7 +99,8 @@ impl Plugin for HydrationPlugin {
sync_editor_visibility,
init_editor_visibility_on_spawn,
)
.chain(),
.chain()
.in_set(HydrationSet::Visibility),
);
}
}
+4 -20
View File
@@ -10,10 +10,9 @@ use std::collections::{HashMap, HashSet};
use crate::{
asset_server_path, authoring_component_active, standard_material_asset_path,
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialAsset,
MaterialDesc, MaterialInstanceAsset, MaterialOverride, MaterialRef, StaticMeshRenderer,
StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC,
COMPONENT_STATIC_MESH_RENDERER,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialDesc,
MaterialOverride, MaterialRef, StaticMeshRenderer, StaticMeshRendererEntry,
COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_STATIC_MESH_RENDERER,
};
use super::materials::material_from_desc;
@@ -457,22 +456,7 @@ fn resolve_shared_material(
return Some(handle.clone());
}
let path = reference.0.source_path.as_deref()?;
let desc_and_state = MaterialAsset::load_from_path(path)
.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 desc_and_state = crate::load_resolved_material_from_path(path).ok()?;
let mut material = material_from_desc(asset_server, &desc_and_state.0);
material.alpha_mode = match desc_and_state.1.alpha_mode {
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
+314
View File
@@ -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));
}
}
+6 -4
View File
@@ -22,12 +22,13 @@ pub use components::*;
pub use hydration::{
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
strip_hydrated, strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember,
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydrationPlugin, PrefabHydrationBlocked,
HydratedPrefabReady, HydratedSkinnedMeshRoot, HydratedTerrainChunk, HydrationPlugin,
PrefabHydrationBlocked,
};
pub use material_asset::{
MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset, MaterialRenderState,
ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset, MATERIAL_ASSET_SCHEMA_VERSION,
MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
load_resolved_material_from_path, MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset,
MaterialRenderState, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
};
pub use navigation::*;
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
@@ -112,6 +113,7 @@ impl Plugin for SharedTypesPlugin {
.register_type::<Primitive>()
.register_type::<PrimitiveShape>()
.register_type::<BrushDesc>()
.register_type::<TerrainDesc>()
.register_type::<BrushKind>()
.register_type::<BrushPlaneDesc>()
.register_type::<BrushFaceDesc>()
+89
View File
@@ -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.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MaterialInstanceAsset {
@@ -270,4 +297,66 @@ mod tests {
.iter()
.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();
}
}
+4
View File
@@ -52,6 +52,8 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
| [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 |
| [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
@@ -77,6 +79,8 @@ Immutable-style log of significant decisions. Add a new numbered ADR when changi
| [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/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/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 |
@@ -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.
+10 -1
View File
@@ -24,7 +24,13 @@ Docs for the in-process egui editor (`crates/editor/`). Update this index when a
| [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 |
| [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/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/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 |
@@ -34,18 +40,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 |
| `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 |
| `viewport/` | Camera, selection, gizmos, render views | 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 |
| `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 |
| `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 |
| `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 |
| `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/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 |
@@ -68,6 +76,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.
- **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.
- **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).
- **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).
+4
View File
@@ -56,3 +56,7 @@ empty provider registry performs no calls and adds no UI.
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,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.
![External-change guard showing loaded and current revision metadata while the dirty untracked scene remains open](external-change-metadata.png)
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`.
@@ -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.
![Material Instance preview on the exact Ground surface with the docked Material Library and green target feedback](material-instance-surface-preview.png)
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 |
@@ -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.
![Native KDE Open dialog over the still-rendered Blacksite editor](native-open-dialog.png)
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 |
@@ -1,6 +1,6 @@
# Production-Readiness Acceptance Matrix
**Matrix version:** 0.1
**Matrix version:** 0.2
**Last audit:** 2026-07-12
@@ -30,20 +30,20 @@ another commit, a dirty worktree, or an older package do not transfer to the can
| ID | Requirement | State | Current evidence and gap |
|----|-------------|-------|--------------------------|
| G1 | Project create/open/resume, scene authoring, autosave/recovery, hierarchy, prefab, and asset integrity pass | Partial | Project/recovery/session/multi-scene/prefab implementations are documented in [project launcher](../../project-launcher.md), [session recovery](../../session-recovery.md), [multi-scene composition](../../multi-scene-composition.md), and [prefab authoring](../../prefab-authoring.md). Candidate-specific end-to-end reruns and the open asset-integrity work remain. |
| G2 | Brush, material, terrain, physics placement, animation, audio, navigation, PIE, and build/package samples pass | Fail | Animation, audio, navigation, and build foundations are implemented. Material/drag-drop tickets `#16`, `#18`, and `#51` remain open; terrain `#22`-`#24` and physics placement `#25` are not complete; brush acceptance `#37` remains open. Packaged testing is owner-deferred. |
| 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 `#16`, `#18`, `#32`, `#33`, `#35`, and `#51`; `#50` cannot close while a gate-relevant P0 remains. |
| 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.1. |
| 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. |
@@ -56,7 +56,7 @@ another commit, a dirty worktree, or an older package do not transfer to the can
| Hierarchy parenting and prefab structure | Implemented | Not rerun |
| Multi-scene composition | Implemented | Not rerun |
| Brush blockout/edit/CSG | Implemented foundation; `#37` open | Not signed off |
| Material catalog and assignment | Partial; `#16`, `#18`, `#51` open | Blocked |
| 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 |
@@ -64,7 +64,8 @@ another commit, a dirty worktree, or an older package do not transfer to the can
| Navigation | Implemented | Not rerun |
| PIE | Implemented | Not rerun |
| Build/package/runtime | Implemented foundation | Deferred by owner |
| Collaborative file safety | Local source/headless acceptance; `#49` open | Awaiting publication and live visual QA |
| 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
@@ -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`.
![Asymmetric shared-material terrain hill generated from four runtime chunks](terrain-showcase-forward.png)
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 |
+33 -13
View File
@@ -21,17 +21,34 @@ material, but may not reference another instance.
## Assign materials
1. Select a static- or skinned-mesh actor.
2. In **Static Mesh Renderer** or **Skinned Mesh Renderer**, find the material slot by its imported
name and stable ID.
3. Use **Browse** or **Select** to assign a Material or Material Instance. **Locate** reveals the
current asset in the Asset Browser.
4. Use **Clear** to remove only the explicit assignment. The slot returns to its read-only imported
source material.
Open **Window > Material Library** for the cross-folder Material/Material Instance catalog. It
supports search, Material/Instance/scene-usage filters, grid/list thumbnails, dependency health,
scene-reference counts, creation, drag sources, and the guarded shared-asset editor. It lives in the
existing bottom dock and does not add permanent viewport chrome. Scene-usage rows select the exact
actor, focus the viewport, and identify its renderer slot, primitive surface, or brush face.
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
each selected static or skinned renderer. Use the per-slot inspector when different draws need
different assignments.
each selected static or skinned renderer. This is the explicit bulk path. A viewport hit never
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
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
Material files and material-instance files are RON documents under `assets/materials/`. The Asset
Browser identifies the document kind, exposes its schema-driven properties and texture bindings,
and uses stable subasset IDs (`material:source` or `material:instance`). Built-in shader schemas
live under `assets/shaders/`.
Material files and material-instance files are RON documents under `assets/materials/`. The
Material Library and Asset Browser identify the document kind, expose the same guarded
schema-driven editor and texture bindings, and use stable subasset IDs (`material:source` or
`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
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. |
| 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. |
| 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. |
+29
View File
@@ -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/).
+38
View File
@@ -0,0 +1,38 @@
# 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.
`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.
Sculpt brushes and grouped stroke undo are tracked by Gitea `#23`; material layers and weight
painting are tracked by `#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/).