From 733c99304d67b4e769cdf91d39ae5e099b0d3132 Mon Sep 17 00:00:00 2001 From: Xein Date: Sun, 15 Nov 2026 19:26:09 +0100 Subject: [PATCH 1/2] voxelline --- .github/workflows/ci-linux-main.yml | 22 -- editor/VoxelEditor/VoxelEditorActions.cs | 6 +- editor/VoxelEditor/VoxelEditorView.axaml | 19 +- editor/VoxelEditor/VoxelEditorView.axaml.cs | 1 + editor/VoxelEditor/VoxelEditorViewModel.cs | 31 ++- editor/VoxelEditor/VoxelOrthoView.cs | 43 +++- engine/assets/lua/voxel.d.lua | 21 +- .../toast/voxel/nodes/procedural_voxel.cpp | 2 + engine/src/toast/voxel/nodes/voxel_line.cpp | 243 ++++++++++++++++++ engine/src/toast/voxel/nodes/voxel_line.hpp | 106 ++++++++ .../toast/voxel/nodes/voxel_node_utils.hpp | 1 + engine/src/toast/voxel/nodes/voxel_piece.hpp | 2 + engine/src/toast/voxel/voxel_edit.cpp | 18 ++ engine/src/toast/voxel/voxel_edit.hpp | 5 + engine/src/toast/world/workspace.hpp | 2 + engine/src/toast/world/workspace_events.cpp | 10 + engine/src/toast/world/workspace_events.hpp | 3 + engine/src/toast/world/workspace_voxel.cpp | 110 +++++++- protos/workspace_events.proto | 3 + 19 files changed, 605 insertions(+), 43 deletions(-) create mode 100644 engine/src/toast/voxel/nodes/voxel_line.cpp create mode 100644 engine/src/toast/voxel/nodes/voxel_line.hpp diff --git a/.github/workflows/ci-linux-main.yml b/.github/workflows/ci-linux-main.yml index 879a9fd60..bf2a0a0ad 100644 --- a/.github/workflows/ci-linux-main.yml +++ b/.github/workflows/ci-linux-main.yml @@ -98,28 +98,6 @@ jobs: bash ./tools/ci/clang_tidy.sh build " - dotnet-reflection-generator: - name: Dotnet reflection_generator (${{ matrix.build_type }}) - runs-on: [self-hosted, Linux, X64] - strategy: - matrix: - build_type: [Debug, Release] - fail-fast: false - steps: - - name: Checkout PR branch - uses: actions/checkout@v4 - with: - repository: ${{ github.event.pull_request.head.repo.full_name }} - ref: ${{ github.head_ref }} - fetch-depth: 1 - submodules: true - - - name: Install Nix - uses: cachix/install-nix-action@v31.10.6 - - - name: Dotnet build and test - run: nix develop --command bash -c 'dotnet build tools/reflection_generator/reflection_generator.csproj --configuration ${{ matrix.build_type }} && dotnet test tools/reflection_generator/tests/ReflectionGenerator.Tests --configuration ${{ matrix.build_type }}' - dotnet-editor: name: Dotnet editor (${{ matrix.build_type }}) runs-on: [self-hosted, Linux, X64] diff --git a/editor/VoxelEditor/VoxelEditorActions.cs b/editor/VoxelEditor/VoxelEditorActions.cs index fc6b1d0b0..93fa56f3f 100644 --- a/editor/VoxelEditor/VoxelEditorActions.cs +++ b/editor/VoxelEditor/VoxelEditorActions.cs @@ -76,13 +76,13 @@ private static async Task BakeAsync(HierarchyElement node) { // Every volume gets a model void Walk(HierarchyElement parent) { foreach (var child in parent.Children) { - if (child.Type is "toast::FillVolume" or "toast::VoxelMesh") { + if (child.Type is "toast::FillVolume" or "toast::VoxelMesh" or "toast::VoxelLine") { var path = $"{folder}/{UniqueFileName(child.Name, taken)}.tvox"; CreateVoxelFile(path); bake.Pieces.Add(new VoxelBakePiece { Uid = child.Uid, Path = path }); } - if (child.Type is "toast::VoxelGroup" or "toast::FillVolume" or "toast::VoxelMesh" or "toast::CarveVolume" - or "toast::PaintVolume") { + if (child.Type is "toast::VoxelGroup" or "toast::FillVolume" or "toast::VoxelMesh" or "toast::VoxelLine" + or "toast::CarveVolume" or "toast::PaintVolume") { Walk(child); } } diff --git a/editor/VoxelEditor/VoxelEditorView.axaml b/editor/VoxelEditor/VoxelEditorView.axaml index 0567fa933..c997490d6 100644 --- a/editor/VoxelEditor/VoxelEditorView.axaml +++ b/editor/VoxelEditor/VoxelEditorView.axaml @@ -86,13 +86,21 @@ + + + + + + ToolTip.Tip="Fill mode new fills and lines get"> diff --git a/editor/VoxelEditor/VoxelEditorView.axaml.cs b/editor/VoxelEditor/VoxelEditorView.axaml.cs index 09b1c97ad..53d3f91bb 100644 --- a/editor/VoxelEditor/VoxelEditorView.axaml.cs +++ b/editor/VoxelEditor/VoxelEditorView.axaml.cs @@ -67,6 +67,7 @@ private void OnShortcut(object? sender, KeyEventArgs e) { case Key.T when mods == KeyModifiers.Shift: vm.SetToolCommand.Execute("Bucket"); break; case Key.Y when mods == KeyModifiers.None: vm.SetToolCommand.Execute("Split"); break; case Key.Y when mods == KeyModifiers.Shift: vm.SetToolCommand.Execute("Slice"); break; + case Key.U when mods == KeyModifiers.None: vm.SetToolCommand.Execute("Line"); break; case Key.G when mods == KeyModifiers.None: vm.ShowUnitGrid = !vm.ShowUnitGrid; break; case Key.G when mods == KeyModifiers.Shift: vm.ShowVoxelGrid = !vm.ShowVoxelGrid; break; case Key.G when mods == KeyModifiers.Alt: vm.ShowVoxelEdges = !vm.ShowVoxelEdges; break; diff --git a/editor/VoxelEditor/VoxelEditorViewModel.cs b/editor/VoxelEditor/VoxelEditorViewModel.cs index fef6675b3..74b388f47 100644 --- a/editor/VoxelEditor/VoxelEditorViewModel.cs +++ b/editor/VoxelEditor/VoxelEditorViewModel.cs @@ -14,7 +14,7 @@ namespace editor.VoxelEditor; -public enum VoxelTool { Select, Move, Extrude, Buildup, Carve, Paint, Bucket, Split, Slice } +public enum VoxelTool { Select, Move, Extrude, Buildup, Carve, Paint, Bucket, Split, Slice, Line } public enum VoxelViewMode { Lit, Albedo, MetallicRoughness, PaletteId, PhysicsMaterial, DdaSteps, Volumes } @@ -72,6 +72,7 @@ public partial class VoxelEditorViewModel : ObservableObject, IDisposable { [ObservableProperty] private bool m_snapToUnit; [ObservableProperty] private int m_paletteId = 1; [ObservableProperty] private string? m_defaultScript; + [ObservableProperty] private string? m_defaultModel; [ObservableProperty] private string m_defaultFillModeName = "Replace"; public static IReadOnlyList FillModes { get; } = ["Replace", "Empty Only", "Solid Only", "Match"]; private uint DefaultFillMode => (uint)Math.Max(0, FillModes.ToList().IndexOf(DefaultFillModeName)); @@ -138,6 +139,10 @@ public VoxelEditorViewModel( new InspectorSection("Volume", green, "BoxOccluder", ["position", "size"]), new InspectorSection("Script", "Magenta", "Circle", ["m_shape_script"]) ], + "VoxelLine" => [ + new InspectorSection("Line", green, "BoxMesh", ["position", "size", "axis", "tile_space", "tile_offset", "flip", "mode", "match_id"]), + new InspectorSection("Model", green, "MeshItem", ["m_model", "m_palette"]) + ], "VoxelMesh" => [ new InspectorSection("Position", green, "Move3d", ["position"]), new InspectorSection("Model", green, "MeshItem", ["m_model"]), @@ -378,6 +383,17 @@ public void CreateVolume(VoxelTool tool, (int X, int Y, int Z) min, (int X, int }); } + public void CreateLine((int X, int Y, int Z) min, (int X, int Y, int Z) max, int axis) { + if (string.IsNullOrEmpty(DefaultModel)) { + _ = App.Modals.ShowWarning("Line", "Pick a voxel model for the Line tool in the toolbar first"); + return; + } + Events.Send(new VoxelCreatePiece { + Parent = CreationParent(), Type = "toast::VoxelLine", Min = Int3(min), Max = Int3(max), Model = DefaultModel, + Axis = (uint)axis, Mode = DefaultFillMode + }); + } + [RelayCommand] private void AddMesh() { EnsureEngine(); @@ -482,7 +498,8 @@ private static bool IsVolume(HierarchyElement node) { } private static bool IsPiece(HierarchyElement node) { - return IsVolume(node) || node.Type.EndsWith("VoxelMesh", StringComparison.Ordinal); + return IsVolume(node) || node.Type.EndsWith("VoxelMesh", StringComparison.Ordinal) || + node.Type.EndsWith("VoxelLine", StringComparison.Ordinal); } // Split and Slice only cut the selected shape @@ -491,7 +508,9 @@ private List CutTargets() { } private string CreationParent() { - if (Hierarchy.SelectedNode is { Type: "toast::VoxelGroup" } group) return group.Uid; + var selected = Hierarchy.SelectedNode; + if (selected is { Type: "toast::VoxelGroup" } group) return group.Uid; + if (selected?.Parent is { Type: "toast::VoxelGroup" } owner) return owner.Uid; return Workspace.RootUid ?? ""; } @@ -527,6 +546,10 @@ partial void OnDefaultScriptChanged(string? value) { SendTool(); } + partial void OnDefaultModelChanged(string? value) { + SendTool(); + } + partial void OnDefaultFillModeNameChanged(string value) { SendTool(); } @@ -603,7 +626,7 @@ private void SendTool() { if (!OwnsEngine) return; Events.Send(new SetVoxelTool { Tool = (uint)ActiveTool, PaintId = (uint)Math.Clamp(PaletteId, 1, 255), DefaultScript = DefaultScript ?? "", - DefaultMode = DefaultFillMode + DefaultMode = DefaultFillMode, DefaultModel = DefaultModel ?? "" }); var gizmo = ActiveTool == VoxelTool.Move ? GizmoTool.VolumeFaces : GizmoTool.Select; Events.Send(new SetGizmoTool { Tool = (uint)gizmo }); diff --git a/editor/VoxelEditor/VoxelOrthoView.cs b/editor/VoxelEditor/VoxelOrthoView.cs index 9ac52b0fe..8c8317d30 100644 --- a/editor/VoxelEditor/VoxelOrthoView.cs +++ b/editor/VoxelEditor/VoxelOrthoView.cs @@ -39,7 +39,9 @@ public sealed class VoxelOrthoView : Control { private bool m_awaitingSliceSide; private bool m_boxClickMode; // a plain click started the box, it follows the mouse until the next click - private enum Drag { None, Pan, Move, EdgeMinH, EdgeMaxH, EdgeMinV, EdgeMaxV, Extrude, Box, Cut } + private enum Drag { None, Pan, Move, EdgeMinH, EdgeMaxH, EdgeMinV, EdgeMaxV, Extrude, Box, Cut, Line } + + private bool m_lineAlongH = true; static VoxelOrthoView() { AffectsRender(ProjectionProperty); @@ -226,7 +228,7 @@ public override void Render(DrawingContext context) { DrawPiece(context, piece, box, selected); } - if (m_drag is Drag.Box or Drag.Extrude) DrawPreviewBox(context); + if (m_drag is Drag.Box or Drag.Extrude or Drag.Line) DrawPreviewBox(context); if (m_cutLine is { } line) DrawCut(context, bounds, line.A, line.B); DrawLabel(context, Projection.ToString(), new Point(8, 6), Brush("TextMuted", Brushes.Gray)); } @@ -469,6 +471,11 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) { m_drag = Drag.Box; m_dragBox = SnapBox(cell.Item1, cell.Item2, cell.Item1, cell.Item2); break; + case VoxelTool.Line: + m_drag = Drag.Line; + m_lineAlongH = true; + m_dragBox = LineBox(cell.Item1, cell.Item2, cell.Item1, cell.Item2, true); + break; case VoxelTool.Split or VoxelTool.Slice: m_drag = Drag.Cut; var cutStart = SnapPoint(point.Position); @@ -569,6 +576,17 @@ protected override void OnPointerMoved(PointerEventArgs e) { m_dragBox = SnapBox((int)Math.Floor(h0), (int)Math.Floor(v0), (int)Math.Floor(h), (int)Math.Floor(v)); break; } + case Drag.Line: { + var (h, v) = ToVoxel(at); + var (h0, v0) = ToVoxel(m_pressed); + var (ch, cv) = ((int)Math.Floor(h0), (int)Math.Floor(v0)); + var (dh, dv) = ((int)Math.Floor(h) - ch, (int)Math.Floor(v) - cv); + m_lineAlongH = VAxis > 1 || Math.Abs(dv) <= Math.Abs(dh); + m_dragBox = m_lineAlongH + ? LineBox(Math.Min(ch, ch + dh), cv, Math.Max(ch, ch + dh), cv, true) + : LineBox(ch, Math.Min(cv, cv + dv), ch, Math.Max(cv, cv + dv), false); + break; + } case Drag.Cut when m_cutLine is { } line: var cutEnd = SnapPoint(at); m_cutLine = (line.A, cutEnd); @@ -633,6 +651,9 @@ protected override void OnPointerReleased(PointerReleasedEventArgs e) { case Drag.Box: CreateFromBox(editor); break; + case Drag.Line: + CreateLine(editor); + break; case Drag.Extrude when m_dragPiece is { } piece: editor.Extrude(piece.Uid, ToShape(piece, m_dragBox, false), ToShape(piece, m_dragBox, true), false); break; @@ -688,6 +709,24 @@ private void CreateFromBox(VoxelEditorViewModel editor) { editor.CreateVolume(editor.ActiveTool, (min[0], min[1], min[2]), (max[0], max[1], max[2])); } + private (int H0, int V0, int H1, int V1) LineBox(int h0, int v0, int h1, int v1, bool alongH) { + var box = SnapBox(h0, v0, h1, v1); + return alongH ? (box.H0, box.V0, box.H1, box.V0) : (box.H0, box.V0, box.H0, box.V1); + } + + private void CreateLine(VoxelEditorViewModel editor) { + var depth = editor.SelectedPiece is { } around ? around.Axis(DepthAxis, false) : 0; + int[] min = new int[3]; + int[] max = new int[3]; + min[HAxis] = m_dragBox.H0; + max[HAxis] = m_dragBox.H1; + min[VAxis] = m_dragBox.V0; + max[VAxis] = m_dragBox.V1; + min[DepthAxis] = depth; + max[DepthAxis] = depth; + editor.CreateLine((min[0], min[1], min[2]), (max[0], max[1], max[2]), m_lineAlongH ? HAxis : VAxis); + } + private void BucketAt(VoxelEditorViewModel editor, (int H, int V) cell) { int[] voxel = new int[3]; voxel[HAxis] = cell.H; diff --git a/engine/assets/lua/voxel.d.lua b/engine/assets/lua/voxel.d.lua index 33c3cf420..754d85e28 100644 --- a/engine/assets/lua/voxel.d.lua +++ b/engine/assets/lua/voxel.d.lua @@ -221,7 +221,7 @@ function VoxelNodeProxy:localBoundingSphere() end -- Procedural voxel pieces -- --- FillVolume, CarveVolume, PaintVolume and VoxelMesh are pieces of a ProceduralVoxel +-- FillVolume, CarveVolume, PaintVolume, VoxelMesh and VoxelLine are pieces of a ProceduralVoxel -- Each one draws into its own grid with editShape and the ProceduralVoxel applies them top to bottom -- Positions are in voxels from the piece corner and nothing can be drawn past getSize() -- @@ -428,6 +428,25 @@ function VoxelMeshProxy:getPalette() end ---@param palette Asset function VoxelMeshProxy:setPalette(palette) end +---@class VoxelLine: VoxelVolume +---@field flip boolean The model is mirrored across the line so the other side faces out +local VoxelLineProxy = {} + +--- The voxel model the line repeats +---@return Asset +function VoxelLineProxy:getModel() end + +--- Swaps the model and redraws the line +---@param model Asset +function VoxelLineProxy:setModel(model) end + +--- The palette that replaces the model colors +---@return Asset +function VoxelLineProxy:getPalette() end + +---@param palette Asset +function VoxelLineProxy:setPalette(palette) end + ---@class VoxelBucket local VoxelBucketProxy = {} diff --git a/engine/src/toast/voxel/nodes/procedural_voxel.cpp b/engine/src/toast/voxel/nodes/procedural_voxel.cpp index df83eb94d..8ff102cd6 100644 --- a/engine/src/toast/voxel/nodes/procedural_voxel.cpp +++ b/engine/src/toast/voxel/nodes/procedural_voxel.cpp @@ -673,6 +673,7 @@ auto ProceduralVoxel::land(const std::vector& pieces, bool wait) -> s for (const Collected& entry : pieces) { const auto [placement, exact] = snappedPlacement(entry.to_root); entry.piece->setMisaligned(!exact); + entry.piece->landedAt(placement); VoxelPiece::GridRef grid = wait ? entry.piece->gridRef() : entry.piece->readyGrid(); if (grid == nullptr) { continue; @@ -771,6 +772,7 @@ void ProceduralVoxel::tickAsyncBuild() { std::vector pieces; collect(*this, glm::mat4(1.0f), pieces); for (const Collected& entry : pieces) { + entry.piece->landedAt(snappedPlacement(entry.to_root).first); entry.piece->collectGrid(); entry.piece->requestGrid(); } diff --git a/engine/src/toast/voxel/nodes/voxel_line.cpp b/engine/src/toast/voxel/nodes/voxel_line.cpp new file mode 100644 index 000000000..ab669e08a --- /dev/null +++ b/engine/src/toast/voxel/nodes/voxel_line.cpp @@ -0,0 +1,243 @@ +#include "voxel_line.hpp" + +#include "voxel_node_utils.hpp" + +#include +#include + +namespace toast { + +namespace { + +using _detail::instantiateModel; +using _detail::voxelModelOf; + +[[nodiscard]] +auto floorMod(int32_t value, int32_t divisor) noexcept -> int32_t { + const int32_t out = value % divisor; + return out < 0 ? out + divisor : out; +} + +[[nodiscard]] +auto bricksFor(int32_t voxels) noexcept -> uint32_t { + const auto dim = static_cast(voxel::k_brick_dim); + return static_cast((voxels + dim - 1) / dim); +} + +[[nodiscard]] +auto mirroredAcross(const voxel::Volume& pattern, const voxel::EditBounds& solid, int axis) -> std::unique_ptr { + const glm::ivec3 size = solid.max - solid.min + 1; + auto mirrored = std::make_unique( + voxel::proceduralBrickPool(), glm::uvec3(bricksFor(size.x), bricksFor(size.y), bricksFor(size.z)) + ); + for (int32_t z = 0; z < size.z; ++z) { + for (int32_t y = 0; y < size.y; ++y) { + for (int32_t x = 0; x < size.x; ++x) { + const glm::ivec3 cell {x, y, z}; + const uint8_t id = pattern.materialAt(solid.min + cell); + if (id != voxel::k_empty_palette_index) { + glm::ivec3 to = cell; + to[axis] = size[axis] - 1 - cell[axis]; + mirrored->setVoxel(to, id); + } + } + } + } + return mirrored; +} + +[[nodiscard]] +auto turnedAboutZ(const voxel::Volume& pattern, const voxel::EditBounds& solid) -> std::unique_ptr { + const glm::ivec3 size = solid.max - solid.min + 1; + auto turned = std::make_unique( + voxel::proceduralBrickPool(), glm::uvec3(bricksFor(size.y), bricksFor(size.x), bricksFor(size.z)) + ); + for (int32_t z = 0; z < size.z; ++z) { + for (int32_t y = 0; y < size.y; ++y) { + for (int32_t x = 0; x < size.x; ++x) { + const uint8_t id = pattern.materialAt(solid.min + glm::ivec3(x, y, z)); + if (id != voxel::k_empty_palette_index) { + turned->setVoxel({size.y - 1 - y, x, z}, id); + } + } + } + } + return turned; +} + +} + +auto VoxelLine::getModel() const -> const assets::Handle& { + return m_model; +} + +void VoxelLine::setModel(assets::Handle model) { + m_model = std::move(model); + markGridDirty(); + refit(false); +} + +void VoxelLine::refit(bool axis_changed) { + const glm::ivec3 tile = tileSizeOf(m_model, axis); + if (glm::any(glm::lessThan(tile, glm::ivec3(1)))) { + return; + } + glm::ivec3 size = sizeVoxels(); + const int along = axis == LineAxis::y ? 1 : 0; + if (axis_changed) { + size[along] = std::max(size.x, size.y); + } + for (int a = 0; a < 3; ++a) { + if (a != along) { + size[a] = tile[a]; + } + } + setSizeVoxels(size); +} + +void VoxelLine::onReflectedFieldChanged(std::string_view field_name) { + VoxelVolume::onReflectedFieldChanged(field_name); + if (field_name == "axis") { + refit(true); + } else if (field_name == "m_model") { + refit(false); + } +} + +auto VoxelLine::getPalette() const -> const assets::Handle& { + return m_palette; +} + +void VoxelLine::setPalette(assets::Handle palette) { + m_palette = std::move(palette); + markLandingDirty(); +} + +void VoxelLine::setAxis(LineAxis value) { + if (axis != value) { + axis = value; + markGridDirty(); + refit(true); + } +} + +void VoxelLine::setFlip(bool value) { + if (flip != value) { + flip = value; + markGridDirty(); + } +} + +void VoxelLine::setTileSpace(LineSpace value) { + if (tile_space != value) { + tile_space = value; + markGridDirty(); + } +} + +auto VoxelLine::tileSizeOf(const assets::Handle& model, LineAxis along) -> glm::ivec3 { + const auto* source = voxelModelOf(model); + const std::unique_ptr pattern = source != nullptr ? instantiateModel(*source) : nullptr; + const std::optional solid = pattern != nullptr ? voxel::occupiedBounds(*pattern) : std::nullopt; + if (!solid.has_value()) { + return glm::ivec3(0); + } + const glm::ivec3 size = solid->max - solid->min + 1; + return along == LineAxis::y ? glm::ivec3(size.y, size.x, size.z) : size; +} + +auto VoxelLine::sourcePaletteUid() const -> uint64_t { + return m_palette.uid().data(); +} + +void VoxelLine::init() { + if (!scripts().empty()) { + setShapeScript({}); + } +} + +void VoxelLine::landedAt(const voxel::LatticePlacement& placement) { + if (tile_space != LineSpace::world) { + return; + } + const auto local_axis = static_cast(axis == LineAxis::y ? 1 : 0); + size_t shape_axis = 0; + for (size_t i = 0; i < 3; ++i) { + if (placement.orientation.source[i] == local_axis) { + shape_axis = i; + } + } + const int32_t anchor = placement.offset[static_cast(shape_axis)]; + const bool flipped = placement.orientation.flip[shape_axis]; + if (anchor != m_anchor.load() || flipped != m_flipped.load()) { + m_anchor.store(anchor); + m_flipped.store(flipped); + markGridDirty(); + } +} + +void VoxelLine::finishGrid(voxel::Volume& grid) { + const voxel::WriteBrush empty {.id = voxel::k_empty_palette_index}; + voxel::fillBox(grid, glm::ivec3(0), glm::ivec3(grid.voxelDims()) - 1, empty); + + tileInto(grid); + + VoxelVolume::finishGrid(grid); +} + +void VoxelLine::tileInto(voxel::Volume& grid) { + const auto* model = voxelModelOf(m_model); + if (model == nullptr) { + return; + } + const std::unique_ptr pattern = instantiateModel(*model); + std::optional solid = pattern != nullptr ? voxel::occupiedBounds(*pattern) : std::nullopt; + if (!solid.has_value()) { + return; + } + + const voxel::Volume* repeated = pattern.get(); + std::unique_ptr turned; + if (axis == LineAxis::y) { + turned = turnedAboutZ(*pattern, *solid); + solid = voxel::occupiedBounds(*turned); + repeated = turned.get(); + if (!solid.has_value()) { + return; + } + } + + std::unique_ptr mirrored; + if (flip) { + mirrored = mirroredAcross(*repeated, *solid, axis == LineAxis::y ? 0 : 1); + solid = voxel::occupiedBounds(*mirrored); + repeated = mirrored.get(); + if (!solid.has_value()) { + return; + } + } + + const int line_axis = axis == LineAxis::y ? 1 : 0; + int32_t phase = 0; + if (tile_space == LineSpace::world) { + const int32_t tile = solid->max[line_axis] - solid->min[line_axis] + 1; + phase = m_flipped.load() ? floorMod(-m_anchor.load(), tile) : m_anchor.load(); + } + voxel::tileLine( + grid, *repeated, line_axis, glm::ivec3(0), sizeVoxels()[line_axis], phase + tile_offset, voxel::identityRemap() + ); +} + +void VoxelLine::updateInspectorMessages() { + VoxelPiece::updateInspectorMessages(); + const NodeMessage no_model { + .severity = NodeMessage::warning, .id = _detail::k_message_no_model, .text = "Pick a voxel model to repeat" + }; + if (voxelModelOf(m_model) == nullptr) { + addInspectorMessage(no_model); + } else { + removeInspectorMessage(no_model); + } +} + +} diff --git a/engine/src/toast/voxel/nodes/voxel_line.hpp b/engine/src/toast/voxel/nodes/voxel_line.hpp new file mode 100644 index 000000000..19e4c6cdc --- /dev/null +++ b/engine/src/toast/voxel/nodes/voxel_line.hpp @@ -0,0 +1,106 @@ + +#pragma once +#include "voxel_volume.hpp" + +#include + +namespace assets { +class VoxelPalette; +} + +namespace toast { + +enum class LineAxis : uint8_t { + x, + y, +}; + +enum class LineSpace : uint8_t { + local, + world, +}; + +[[nodiscard]] +inline auto lineAxisFor(glm::ivec3 anchor, glm::ivec3 current) noexcept -> LineAxis { + const glm::ivec3 moved = glm::abs(current - anchor); + return moved.y > moved.x ? LineAxis::y : LineAxis::x; +} + +class [[ToastNode, Icon("MeshItem")]] TOAST_API VoxelLine : public VoxelVolume { +public: + [[nodiscard, Reflect]] + auto getModel() const -> const assets::Handle&; + + [[Reflect]] + void setModel(assets::Handle model); + + [[nodiscard, Reflect]] + auto getPalette() const -> const assets::Handle&; + + [[Reflect]] + void setPalette(assets::Handle palette); + + [[nodiscard]] + auto getAxis() const noexcept -> LineAxis { + return axis; + } + + void setAxis(LineAxis value); + + [[nodiscard]] + auto getTileSpace() const noexcept -> LineSpace { + return tile_space; + } + + void setTileSpace(LineSpace value); + + [[nodiscard]] + auto getFlip() const noexcept -> bool { + return flip; + } + + void setFlip(bool value); + + [[nodiscard]] + static auto tileSizeOf(const assets::Handle& model, LineAxis along = LineAxis::x) -> glm::ivec3; + + [[nodiscard]] + auto sourcePaletteUid() const -> uint64_t override; + + void landedAt(const voxel::LatticePlacement& placement) override; + +protected: + void init(); + + void finishGrid(voxel::Volume& grid) override; + void updateInspectorMessages() override; + void onReflectedFieldChanged(std::string_view field_name) override; + + [[Reflect, Name("Model")]] + assets::Handle m_model; + + [[Reflect, Name("Palette Override")]] + assets::Handle m_palette; + + [[Reflect, Name("Axis"), Enum("X", "Y")]] + LineAxis axis = LineAxis::x; + + [[Reflect, Name("Tile Space"), Enum("Local", "World")]] + LineSpace tile_space = LineSpace::local; + + [[Reflect, Name("Flip")]] + bool flip = false; + + [[Reflect, Name("Tile Offset"), Unit("voxels")]] + int tile_offset = 0; + +private: + void tileInto(voxel::Volume& grid); + + void refit(bool axis_changed); + + std::atomic m_anchor {0}; + std::atomic m_flipped {false}; +}; + +} diff --git a/engine/src/toast/voxel/nodes/voxel_node_utils.hpp b/engine/src/toast/voxel/nodes/voxel_node_utils.hpp index ff707f34f..cf4705294 100644 --- a/engine/src/toast/voxel/nodes/voxel_node_utils.hpp +++ b/engine/src/toast/voxel/nodes/voxel_node_utils.hpp @@ -24,6 +24,7 @@ namespace toast::_detail { enum : uint8_t { k_message_outside = 40, k_message_misaligned = 41, + k_message_no_model = 42, }; /** The loaded asset when it is really of type, null otherwise */ diff --git a/engine/src/toast/voxel/nodes/voxel_piece.hpp b/engine/src/toast/voxel/nodes/voxel_piece.hpp index ef41ca0ff..861176801 100644 --- a/engine/src/toast/voxel/nodes/voxel_piece.hpp +++ b/engine/src/toast/voxel/nodes/voxel_piece.hpp @@ -271,6 +271,8 @@ class [[ToastNode, Hidden, Interface, Icon("Shape"), Color("Magenta")]] TOAST_AP /** Set by the ProceduralVoxel when the transform had to be snapped to the voxel lattice */ void setMisaligned(bool misaligned); + virtual void landedAt(const voxel::LatticePlacement&) { } + protected: /** The size scripts draw into, the grid itself is rounded up to whole bricks */ [[nodiscard]] diff --git a/engine/src/toast/voxel/voxel_edit.cpp b/engine/src/toast/voxel/voxel_edit.cpp index b331e2bd4..5e08051bd 100644 --- a/engine/src/toast/voxel/voxel_edit.cpp +++ b/engine/src/toast/voxel/voxel_edit.cpp @@ -1008,6 +1008,24 @@ auto tileVolume( return result; } +auto tileLine( + Volume& target, const Volume& pattern, int axis, glm::ivec3 origin, int32_t length, int32_t phase, + const PaletteRemapTable& remap, WriteMode mode, uint8_t match_id +) -> EditResult { + const std::optional solid = occupiedBounds(pattern); + if (!solid.has_value() || length < 1 || (axis != 0 && axis != 1)) { + return {}; + } + + glm::ivec3 last = origin + (solid->max - solid->min); + last[axis] = origin[axis] + length - 1; + + TileOptions options; + options.fit = TileFit::crop; + options.offset[axis] = phase; + return tileVolume(target, pattern, origin, last, options, remap, mode, match_id); +} + auto floodFill(Volume& volume, glm::ivec3 seed, uint8_t id) -> EditResult { ZoneScoped; EditResult result; diff --git a/engine/src/toast/voxel/voxel_edit.hpp b/engine/src/toast/voxel/voxel_edit.hpp index 3b5aa6ac6..58ffa4245 100644 --- a/engine/src/toast/voxel/voxel_edit.hpp +++ b/engine/src/toast/voxel/voxel_edit.hpp @@ -202,6 +202,11 @@ TOAST_API auto tileVolume( WriteMode mode = WriteMode::replace, uint8_t match_id = k_empty_palette_index ) -> EditResult; +TOAST_API auto tileLine( + Volume& target, const Volume& pattern, int axis, glm::ivec3 origin, int32_t length, int32_t phase, + const PaletteRemapTable& remap, WriteMode mode = WriteMode::replace, uint8_t match_id = k_empty_palette_index +) -> EditResult; + /** Repaints the solid voxels connected to seed that share its id */ TOAST_API auto floodFill(Volume& volume, glm::ivec3 seed, uint8_t id) -> EditResult; diff --git a/engine/src/toast/world/workspace.hpp b/engine/src/toast/world/workspace.hpp index 4a0eec13b..8aa9a53ca 100644 --- a/engine/src/toast/world/workspace.hpp +++ b/engine/src/toast/world/workspace.hpp @@ -213,6 +213,8 @@ class TOAST_API Workspace : public INodeOwner { uint8_t paint_id = 1; UID default_script; ///< What new volumes draw with uint8_t default_mode = 0; ///< voxel::WriteMode new fill volumes land with + UID default_model; + glm::ivec3 line_tile {1}; Phase phase = Phase::idle; bool dragging = false; ///< if its drawing the mouse make it 2 clicks rather than 3 UID extrude_source; ///< The piece Extrude grows from diff --git a/engine/src/toast/world/workspace_events.cpp b/engine/src/toast/world/workspace_events.cpp index 022d4239b..069d217b6 100644 --- a/engine/src/toast/world/workspace_events.cpp +++ b/engine/src/toast/world/workspace_events.cpp @@ -1212,6 +1212,10 @@ struct ProtoTraits { p.set_script(e.script); } p.set_mode(e.mode); + if (e.model.data() != 0) { + p.set_model(e.model); + } + p.set_axis(e.axis); return p; } @@ -1224,6 +1228,8 @@ struct ProtoTraits { e.max = readInt3(p.max()); e.script = toast::UID::fromString(p.script()); e.mode = p.mode(); + e.model = toast::UID::fromString(p.model()); + e.axis = p.axis(); return e; } }; @@ -1513,6 +1519,9 @@ struct ProtoTraits { p.set_default_script(e.default_script); } p.set_default_mode(e.default_mode); + if (e.default_model.data() != 0) { + p.set_default_model(e.default_model); + } return p; } @@ -1522,6 +1531,7 @@ struct ProtoTraits { e.paint_id = p.paint_id(); e.default_script = toast::UID::fromString(p.default_script()); e.default_mode = p.default_mode(); + e.default_model = toast::UID::fromString(p.default_model()); return e; } }; diff --git a/engine/src/toast/world/workspace_events.hpp b/engine/src/toast/world/workspace_events.hpp index 516269b63..3ced28e9a 100644 --- a/engine/src/toast/world/workspace_events.hpp +++ b/engine/src/toast/world/workspace_events.hpp @@ -228,6 +228,8 @@ struct VoxelCreatePiece : Event { glm::ivec3 max {0}; toast::UID script; uint32_t mode = 0; + toast::UID model; + uint32_t axis = 0; }; struct VoxelExtrude : Event { @@ -327,6 +329,7 @@ struct SetVoxelTool : Event { uint32_t paint_id = 1; toast::UID default_script; uint32_t default_mode = 0; + toast::UID default_model; }; struct SetShowOthers : Event { diff --git a/engine/src/toast/world/workspace_voxel.cpp b/engine/src/toast/world/workspace_voxel.cpp index dc5536570..42830d72c 100644 --- a/engine/src/toast/world/workspace_voxel.cpp +++ b/engine/src/toast/world/workspace_voxel.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -63,7 +64,9 @@ auto voxelQuarterTurn(uint32_t axis, int32_t turns) -> glm::mat3 { return out; } -constexpr std::array k_volume_types {"toast::FillVolume", "toast::CarveVolume", "toast::PaintVolume"}; +constexpr std::array k_volume_types { + "toast::FillVolume", "toast::CarveVolume", "toast::PaintVolume", "toast::VoxelLine" +}; } @@ -104,6 +107,7 @@ enum : uint8_t { k_tool_bucket = 6, k_tool_split = 7, k_tool_slice = 8, + k_tool_line = 9, }; constexpr uint32_t k_left_button = 1; @@ -132,6 +136,9 @@ auto boxToolNodeType(uint32_t tool) noexcept -> const char* { if (tool == k_tool_paint) { return "toast::PaintVolume"; } + if (tool == k_tool_line) { + return "toast::VoxelLine"; + } return "toast::FillVolume"; } @@ -210,6 +217,22 @@ auto Workspace::voxelToolShape() -> ProceduralVoxel* { } auto Workspace::VoxelToolState::box() const -> std::pair { + if (tool == k_tool_line) { + const int along = lineAxisFor(anchor, current) == LineAxis::y ? 1 : 0; + const int across = 1 - along; + const glm::ivec3 tile = along == 1 ? glm::ivec3(line_tile.y, line_tile.x, line_tile.z) : line_tile; + const auto floor_to = [this](int32_t v) { + return snap_plane > 1 ? static_cast(std::floor(static_cast(v) / snap_plane)) * snap_plane : v; + }; + const auto ceil_to = [this, &floor_to](int32_t v) { return snap_plane > 1 ? floor_to(v) + snap_plane - 1 : v; }; + glm::ivec3 first = anchor; + first[across] = floor_to(anchor[across]); + glm::ivec3 last = first + tile - 1; + const int32_t low = floor_to(std::min(anchor[along], current[along])); + first[along] = low; + last[along] = anchor[along] == current[along] ? low + tile[along] - 1 : ceil_to(std::max(anchor[along], current[along])); + return {first, last}; + } glm::ivec3 min = glm::min(anchor, current); glm::ivec3 max = glm::max(anchor, current); if (snap_plane > 1) { @@ -551,13 +574,25 @@ auto Workspace::voxelToolMouseButton(uint32_t button, bool pressed, int mods) -> event::send(extrude); } else { event::VoxelCreatePiece create; - const bool in_group = m_focused_node.exists() && reflect_cast(&*m_focused_node) != nullptr; - create.parent = in_group ? m_focused_node->uid() : shape->uid(); + Box home; + if (m_focused_node.exists()) { + Box above = m_focused_node->parentInternal(); + if (reflect_cast(&*m_focused_node) != nullptr) { + home = m_focused_node; + } else if (above.exists() && reflect_cast(&*above) != nullptr) { + home = above; + } + } + create.parent = home.exists() ? home->uid() : shape->uid(); create.type = boxToolNodeType(tool); create.min = min; create.max = max; create.script = m_voxel_tool.default_script; create.mode = m_voxel_tool.default_mode; + if (tool == k_tool_line) { + create.model = m_voxel_tool.default_model; + create.axis = lineAxisFor(m_voxel_tool.anchor, m_voxel_tool.current) == LineAxis::y ? 1u : 0u; + } event::send(create); } voxelToolCancel(); @@ -606,6 +641,12 @@ auto Workspace::voxelToolMouseButton(uint32_t button, bool pressed, int mods) -> return true; case VoxelToolState::Phase::box: + if (tool == k_tool_line) { + if (!pressed && m_voxel_tool.dragging) { + place(); + } + return true; + } if (!pressed && m_voxel_tool.dragging) { // trackpad support, dragging is akward if (m_voxel_tool.current == m_voxel_tool.anchor) { @@ -638,7 +679,7 @@ auto Workspace::voxelToolMouseButton(uint32_t button, bool pressed, int mods) -> case VoxelToolState::Phase::idle: break; } - if (!box_tool && !cut_tool && tool != k_tool_bucket) { + if (!box_tool && !cut_tool && tool != k_tool_bucket && tool != k_tool_line) { return tool == k_tool_extrude; } if (!pressed) { @@ -670,6 +711,46 @@ auto Workspace::voxelToolMouseButton(uint32_t button, bool pressed, int mods) -> m_voxel_tool.face_min = glm::ivec3(std::numeric_limits::min()); m_voxel_tool.face_max = glm::ivec3(std::numeric_limits::max()); + + if (tool == k_tool_line) { + m_voxel_tool.line_tile = VoxelLine::tileSizeOf(assets::load(m_voxel_tool.default_model)); + if (glm::any(glm::lessThan(m_voxel_tool.line_tile, glm::ivec3(1)))) { + TOAST_WARN("Voxel", "The Line tool needs a voxel model to repeat, pick one in the toolbar"); + return true; + } + glm::ivec3 cell; + int32_t layer = 0; + if (hit.has_value()) { + layer = hit->voxel.z + hit->normal.z; + cell = glm::ivec3(hit->voxel.x + hit->normal.x, hit->voxel.y + hit->normal.y, layer); + } else { + const std::optional ground = voxelCellOnPlane(local, 2, 0.0f); + if (!ground.has_value()) { + return true; + } + cell = *ground; + layer = 0; + } + cell.z = layer; + m_voxel_tool.axis = 2; + m_voxel_tool.sign = 1; + m_voxel_tool.surface = layer - 1; + m_voxel_tool.plane = static_cast(layer); + m_voxel_tool.anchor = cell; + m_voxel_tool.current = cell; + m_voxel_tool.snap_plane = voxelSnapStep(m_translate_snap); + m_voxel_tool.snap_depth = 1; + m_voxel_tool.depth = 1; + m_voxel_tool.dragging = true; + m_voxel_tool.phase = VoxelToolState::Phase::box; + + renderer::EditorOverlays& line_overlays = renderer::editorOverlays(); + line_overlays.tool_root = shape->uid(); + line_overlays.tool_box_color = boxToolColor(tool); + voxelUpdatePreview(boxToolKind(tool)); + return true; + } + if (hit.has_value()) { int axis = 2; if (hit->normal.x != 0) { @@ -733,12 +814,13 @@ void Workspace::subscribeVoxelEditing() { } // Selecting a piece picks its color we shouldn't resend everything const auto mode = static_cast(std::min(e.default_mode, 3u)); - const bool only_colour = - e.tool == m_voxel_tool.tool && e.default_script == m_voxel_tool.default_script && mode == m_voxel_tool.default_mode; + const bool only_colour = e.tool == m_voxel_tool.tool && e.default_script == m_voxel_tool.default_script && + mode == m_voxel_tool.default_mode && e.default_model == m_voxel_tool.default_model; m_voxel_tool.tool = e.tool; m_voxel_tool.paint_id = static_cast(std::clamp(e.paint_id, 1u, 255u)); m_voxel_tool.default_script = e.default_script; m_voxel_tool.default_mode = mode; + m_voxel_tool.default_model = e.default_model; if (auto* shape = m_root_node.exists() ? reflect_cast(&*m_root_node) : nullptr; shape && !only_colour) { shape->sendLayout(); } @@ -831,13 +913,23 @@ void Workspace::subscribeVoxelEditing() { } if (VoxelPiece* piece = voxelPieceOf(made)) { piece->setClipPlanes({}); + auto* line = voxelPieceOf(source) == nullptr ? reflect_cast(piece) : nullptr; + if (line != nullptr) { + line->setAxis(e.axis == 1 ? LineAxis::y : LineAxis::x); + } placePiece(*piece, orientation, e.min, e.max); if (e.script.data() != 0) { piece->setShapeScript(assets::load(e.script)); } - // Only fills take a mode - if (auto* fill = reflect_cast(piece); fill != nullptr && voxelPieceOf(source) == nullptr) { - fill->setMode(static_cast(std::min(e.mode, 3u))); + if (line != nullptr && e.model.data() != 0) { + line->setModel(assets::load(e.model)); + } + if (voxelPieceOf(source) == nullptr) { + if (auto* fill = reflect_cast(piece)) { + fill->setMode(static_cast(std::min(e.mode, 3u))); + } else if (line != nullptr) { + line->setMode(static_cast(std::min(e.mode, 3u))); + } } } }); diff --git a/protos/workspace_events.proto b/protos/workspace_events.proto index 60a607e5b..a1d720920 100644 --- a/protos/workspace_events.proto +++ b/protos/workspace_events.proto @@ -202,6 +202,8 @@ message VoxelCreatePiece { VoxelInt3 max = 5; string script = 6; uint32 mode = 7; + string model = 8; + uint32 axis = 9; } message VoxelExtrude { @@ -310,6 +312,7 @@ message SetVoxelTool { uint32 paint_id = 2; string default_script = 3; uint32 default_mode = 4; + string default_model = 5; } message SetShowOthers { From 48ccefbab3740da8e04a5ab5aa3d84db52e79bbd Mon Sep 17 00:00:00 2001 From: Xein Date: Sun, 15 Nov 2026 20:06:46 +0100 Subject: [PATCH 2/2] mecagoenlaputa --- engine/src/toast/voxel/nodes/voxel_line.hpp | 1 - engine/src/toast/world/workspace.hpp | 12 ++++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/engine/src/toast/voxel/nodes/voxel_line.hpp b/engine/src/toast/voxel/nodes/voxel_line.hpp index 19e4c6cdc..e7c5b8108 100644 --- a/engine/src/toast/voxel/nodes/voxel_line.hpp +++ b/engine/src/toast/voxel/nodes/voxel_line.hpp @@ -1,4 +1,3 @@ - #pragma once #include "voxel_volume.hpp" diff --git a/engine/src/toast/world/workspace.hpp b/engine/src/toast/world/workspace.hpp index 8aa9a53ca..71a7b7115 100644 --- a/engine/src/toast/world/workspace.hpp +++ b/engine/src/toast/world/workspace.hpp @@ -216,12 +216,12 @@ class TOAST_API Workspace : public INodeOwner { UID default_model; glm::ivec3 line_tile {1}; Phase phase = Phase::idle; - bool dragging = false; ///< if its drawing the mouse make it 2 clicks rather than 3 - UID extrude_source; ///< The piece Extrude grows from - int axis = 2; ///< The face the box lies on - int32_t surface = 0; ///< The voxel layer of the face that was clicked - float plane = 0.0f; ///< Where along axis the mouse ray is cut to find the rectangle - int32_t sign = 1; ///< Which way is out of the face + bool dragging = false; ///< if its drawing the mouse make it 2 clicks rather than 3 + UID extrude_source; ///< The piece Extrude grows from + int axis = 2; ///< The face the box lies on + int32_t surface = 0; ///< The voxel layer of the face that was clicked + float plane = 0.0f; ///< Where along axis the mouse ray is cut to find the rectangle + int32_t sign = 1; ///< Which way is out of the face int32_t depth = 1; int32_t snap_plane = 1; int32_t snap_depth = 1;