From 8136fa857ff6e846e3ddbe32bbeb219d85764a93 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 12:44:27 +0100 Subject: [PATCH] Pick procedural parts by clicking blocks in the studio scene view Authors could not tell which part of a procedural object placed a block. A click on a block in the Procedural view now finds its part and chooses the node that draws it; choosing a node lights up its blocks and draws everything else faintly. SceneView gains hasParts and parts (BlockParts), served as scene-parts, aligned with the scene's blocks. No pins moved: the trace bakes with its own builder and generation is untouched, ProceduralObjectsGoldenTest digests are unchanged. v3: ff0190384 --- api/CONTRACTS.md | 2 +- api/README.md | 4 + .../java/com/volmit/tooling/BlockParts.java | 32 +++++ .../java/com/volmit/tooling/SceneView.java | 14 ++ .../com/volmit/tooling/BlockPartsTest.java | 78 +++++++++++ .../core/studio/bridge/SceneEncoding.java | 14 ++ .../iris/core/studio/bridge/StudioBridge.java | 23 +++- .../iris/core/studio/scene/StudioScenes.java | 16 +++ .../core/studio/bridge/SceneEncodingTest.java | 17 +++ .../procedural/ProceduralPartTraceTest.java | 113 +++++++++++++++ .../engine/procedural/part/PartTrace.java | 5 + .../part/ResolvedProceduralObject.java | 20 +++ .../objects/ProceduralObjectScenes.java | 15 ++ .../src/renderer/src/bridge/BridgeClient.ts | 6 + studio/src/renderer/src/bridge/types.ts | 3 +- .../renderer/src/editor/nodeLayout.test.ts | 23 +++- studio/src/renderer/src/editor/nodeLayout.ts | 17 +++ .../src/renderer/src/scene/blockPick.test.ts | 43 ++++++ studio/src/renderer/src/scene/blockPick.ts | 38 +++++ .../src/renderer/src/scene/partFocus.test.ts | 20 +++ studio/src/renderer/src/scene/partFocus.ts | 14 ++ studio/src/renderer/src/scene/sceneMesh.ts | 69 ++++++++-- .../src/renderer/src/studio/SceneStudio.tsx | 130 +++++++++++++++--- .../src/renderer/src/studio/SceneViewport.tsx | 51 ++++++- 24 files changed, 719 insertions(+), 48 deletions(-) create mode 100644 api/api/src/main/java/com/volmit/tooling/BlockParts.java create mode 100644 api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/procedural/ProceduralPartTraceTest.java create mode 100644 studio/src/renderer/src/scene/blockPick.test.ts create mode 100644 studio/src/renderer/src/scene/blockPick.ts create mode 100644 studio/src/renderer/src/scene/partFocus.test.ts create mode 100644 studio/src/renderer/src/scene/partFocus.ts diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 4c78a7916..7b83ad413 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes. | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | -| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | +| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | | Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | diff --git a/api/README.md b/api/README.md index 55dcc472d..0f0c95df4 100644 --- a/api/README.md +++ b/api/README.md @@ -521,6 +521,10 @@ final class RuinScenes implements SceneView { - A `SceneView` whose entries are baked from settings says so (`isBaked`) and times a bake on request (`timeBake`, a `BakeRun` with a time per stage). One call is one run; the studio asks five times off the server's threads and keeps the median. +- A `SceneView` whose entries are built from parts says so (`hasParts`) and tells which part placed each block of a + scene (`parts`, a `BlockParts` keyed by the block's position in the scene). Parts are numbered as `GraphNode.part()` + numbers the nodes that draw them, so the studio lights up a node's blocks when it is chosen and chooses a node when + its block is clicked. - A view's id is the module's id or starts with it and `/`. A second view with an id already registered fails the pack load, naming both modules. - The studio asks from its own threads, several at once, for a world of the pack it shows. A view keeps what it diff --git a/api/api/src/main/java/com/volmit/tooling/BlockParts.java b/api/api/src/main/java/com/volmit/tooling/BlockParts.java new file mode 100644 index 000000000..fe2ff1ec5 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/BlockParts.java @@ -0,0 +1,32 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; + +import java.util.Map; +import java.util.Objects; + +/** + * Which part of an entry placed each block of one scene, as {@link SceneView#parts} reports it. A part is numbered the + * way {@link GraphNode#part()} numbers the node that draws it, so the studio can light up the blocks of a node and find + * the node of a block. + * + * @param partsByBlock the part of each block that has one, by the block's position in the scene + */ +public record BlockParts(Map partsByBlock) { + /** What {@link #partAt} answers for a block no part placed, such as a decoration. */ + public static final int NO_PART = -1; + + public BlockParts { + Objects.requireNonNull(partsByBlock, "partsByBlock"); + partsByBlock = Map.copyOf(partsByBlock); + partsByBlock.forEach((position, part) -> { + if (part < 0) { + throw new IllegalArgumentException("Block " + position + " is in part " + part + "; parts are numbered from 0"); + } + }); + } + + public int partAt(BlockPosition position) { + return partsByBlock.getOrDefault(position, NO_PART); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/SceneView.java b/api/api/src/main/java/com/volmit/tooling/SceneView.java index dfbbaa7ea..b02022b3e 100644 --- a/api/api/src/main/java/com/volmit/tooling/SceneView.java +++ b/api/api/src/main/java/com/volmit/tooling/SceneView.java @@ -22,6 +22,20 @@ public non-sealed interface SceneView extends StudioView { */ Optional scene(PackWorld world, String key, int variant); + /** Whether the entries are built from parts the studio can pick out of the scene, which {@link #parts} tells apart. */ + default boolean hasParts() { + return false; + } + + /** + * Which part placed each block of the scene {@link #scene} gives for the same arguments, found the way that scene + * was built. Asked off the server's threads; empty when the view has no parts, the pack has no such entry, or the + * entry has fewer variants. + */ + default Optional parts(PackWorld world, String key, int variant) { + return Optional.empty(); + } + /** Whether the entries are baked from settings, which costs generation time {@link #timeBake} can measure. */ default boolean isBaked() { return false; diff --git a/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java b/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java new file mode 100644 index 000000000..1181ca5b2 --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java @@ -0,0 +1,78 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BlockPartsTest { + private static final BlockPosition TRUNK = new BlockPosition(0, 1, 0); + private static final BlockPosition DECORATION = new BlockPosition(2, 1, 0); + + @Test + void answersNoPartForABlockNoPartPlaced() { + BlockParts parts = new BlockParts(Map.of(TRUNK, 3)); + + assertEquals(3, parts.partAt(TRUNK)); + assertEquals(BlockParts.NO_PART, parts.partAt(DECORATION)); + } + + @Test + void keepsItsBlocksApartFromTheMapItWasGiven() { + Map given = new HashMap<>(Map.of(TRUNK, 3)); + BlockParts parts = new BlockParts(given); + given.clear(); + + assertEquals(3, parts.partAt(TRUNK)); + assertThrows(UnsupportedOperationException.class, () -> parts.partsByBlock().clear()); + } + + @Test + void refusesAPartBelowZero() { + assertThrows(IllegalArgumentException.class, () -> new BlockParts(Map.of(TRUNK, BlockParts.NO_PART))); + } + + @Test + void aViewWithoutPartsSaysSoAndFindsNone() { + SceneView plain = new SceneView() { + @Override + public ResourceId id() { + return ResourceId.parse("test:plain"); + } + + @Override + public String label() { + return "Plain"; + } + + @Override + public String description() { + return "Plain"; + } + + @Override + public List entries(PackWorld world) { + return List.of(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + return Optional.empty(); + } + }; + + assertFalse(plain.hasParts()); + assertTrue(plain.parts(null, "any", 0).isEmpty()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/SceneEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/SceneEncoding.java index 31baeee73..e12354b4a 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/SceneEncoding.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/SceneEncoding.java @@ -24,6 +24,7 @@ import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockPosition; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; +import com.volmit.tooling.BlockParts; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -80,6 +81,19 @@ final class SceneEncoding { return buffer.array(); } + /** + * The part of each block {@link #encode} writes, in the same order, as little endian i32 numbers; a block no part + * placed is {@link BlockParts#NO_PART}. + */ + static byte[] encodeParts(GeneratedObject scene, BlockParts parts) { + List drawn = scene.blocks().stream().filter(block -> !isAir(block.state())).toList(); + ByteBuffer buffer = ByteBuffer.allocate(drawn.size() * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN); + for (ObjectBlock block : drawn) { + buffer.putInt(parts.partAt(block.position())); + } + return buffer.array(); + } + private static boolean isAir(BlockState state) { return AIR.contains(state.material().toString()); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index a03fde2c6..89b1c6afa 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -54,6 +54,7 @@ import com.volmit.tooling.BlockPattern; import com.volmit.tooling.PatternArea; import com.volmit.tooling.PatternEntry; import com.volmit.tooling.BakeRun; +import com.volmit.tooling.BlockParts; import com.volmit.tooling.SceneEntry; import java.io.IOException; @@ -238,6 +239,7 @@ public final class StudioBridge implements AutoCloseable { case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query)); case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query)); case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query)); + case "scene-parts" -> sendBytes(exchange, "application/octet-stream", sceneParts(get(exchange).engine(), query)); case "saved-worlds" -> sendJson(exchange, STATUS_OK, savedWorlds(exchange)); case "saved-start" -> sendJson(exchange, STATUS_OK, savedStart(exchange, query)); case "saved-tile" -> sendBytes(exchange, "application/octet-stream", savedTile(get(exchange).engine(), query)); @@ -339,7 +341,7 @@ public final class StudioBridge implements AutoCloseable { StudioEditors editors = StudioEditors.of(engine); StudioScenes scenes = StudioScenes.of(engine); return scenes.views().stream() - .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), scenes.isBaked(view.id()))) + .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id()))) .toList(); } @@ -422,6 +424,21 @@ public final class StudioBridge implements AutoCloseable { return SceneEncoding.encode(scene.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)), gson); } + private static byte[] sceneParts(Engine engine, Query query) { + String key = query.text("key"); + int variant = query.whole("variant", 0); + try { + StudioScenes scenes = StudioScenes.of(engine); + GeneratedObject scene = scenes.scene(query.text("view"), key, variant) + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)); + BlockParts parts = scenes.parts(query.text("view"), key, variant) + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No parts for " + key)); + return SceneEncoding.encodeParts(scene, parts); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } + } + private static List patternEntries(Engine engine, Query query) { try { return StudioPatterns.of(engine).entries(query.text("view")).stream().map(PatternEntryWire::of).toList(); @@ -751,8 +768,8 @@ public final class StudioBridge implements AutoCloseable { private record ErrorBody(String error) { } - /** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code baked} when their bake can be timed. */ - private record SceneViewInfo(String id, String label, String description, boolean editable, boolean baked) { + /** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */ + private record SceneViewInfo(String id, String label, String description, boolean editable, boolean baked, boolean parts) { } /** A {@link SceneEntry} as the studio reads it, with a blank group for none. */ diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java index 55bfe9448..487cf7fae 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java @@ -21,6 +21,7 @@ package art.arcane.iris.core.studio.scene; import art.arcane.iris.engine.framework.Engine; import com.volmit.object.GeneratedObject; import com.volmit.tooling.BakeRun; +import com.volmit.tooling.BlockParts; import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneView; @@ -58,6 +59,21 @@ public final class StudioScenes { return views.ask(viewId, "build " + key, view -> view.scene(views.world(), key, variant)); } + /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ + public boolean hasParts(String viewId) { + return views.ask(viewId, "say whether it has parts", SceneView::hasParts); + } + + /** + * Which part placed each block of the scene {@link #scene} gives for the same arguments; empty when the view has no + * such entry or variant, or no parts. + * + * @throws NoSuchElementException when no module registered a scene view {@code viewId} + */ + public Optional parts(String viewId, String key, int variant) { + return views.ask(viewId, "find the parts of " + key, view -> view.parts(views.world(), key, variant)); + } + /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ public boolean isBaked(String viewId) { return views.ask(viewId, "say whether it bakes", SceneView::isBaked); diff --git a/core/src/test/java/art/arcane/iris/core/studio/bridge/SceneEncodingTest.java b/core/src/test/java/art/arcane/iris/core/studio/bridge/SceneEncodingTest.java index 187c93ca3..b30dd6f5d 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/bridge/SceneEncodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/bridge/SceneEncodingTest.java @@ -8,12 +8,14 @@ import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockPosition; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; +import com.volmit.tooling.BlockParts; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -40,4 +42,19 @@ public class SceneEncodingTest { body.position(blocksAt + 2 * 16); assertEquals(List.of(0, 2, 0, 1), List.of(body.getInt(), body.getInt(), body.getInt(), body.getInt())); } + + @Test + public void partsFollowTheBlocksTheSceneDrawsAndLeaveAirOut() { + GeneratedObject tree = new GeneratedObject(new BlockBox(0, 0, 0, 3, 3, 3), new BlockPosition(1, 0, 1), List.of( + new ObjectBlock(new BlockPosition(1, 0, 1), BlockState.parse("minecraft:oak_log[axis=y]")), + new ObjectBlock(new BlockPosition(0, 1, 1), BlockState.parse("minecraft:air")), + new ObjectBlock(new BlockPosition(1, 1, 1), BlockState.parse("minecraft:oak_log[axis=y]")), + new ObjectBlock(new BlockPosition(1, 2, 1), BlockState.parse("minecraft:oak_leaves"))), List.of()); + BlockParts parts = new BlockParts(Map.of(new BlockPosition(1, 0, 1), 4, new BlockPosition(0, 1, 1), 9, new BlockPosition(1, 1, 1), 7)); + + ByteBuffer encoded = ByteBuffer.wrap(SceneEncoding.encodeParts(tree, parts)).order(ByteOrder.LITTLE_ENDIAN); + + assertEquals(3 * Integer.BYTES, encoded.remaining()); + assertEquals(List.of(4, 7, BlockParts.NO_PART), List.of(encoded.getInt(), encoded.getInt(), encoded.getInt())); + } } diff --git a/core/src/test/java/art/arcane/iris/engine/procedural/ProceduralPartTraceTest.java b/core/src/test/java/art/arcane/iris/engine/procedural/ProceduralPartTraceTest.java new file mode 100644 index 000000000..d4ffd361b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/procedural/ProceduralPartTraceTest.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.procedural; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.JsonFormsCodecs; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.procedural.part.PartTrace; +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ResolvedProceduralObject; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.volmit.object.PlaceableObject; +import com.volmit.tooling.BlockParts; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + +/** The parts the studio picks out of a baked variant are the ones that placed the blocks it shows. */ +public class ProceduralPartTraceTest { + private static final String FIXTURE = "/procedural-parts"; + private static final String DEFINITIONS = "procedural"; + private static final String[] OBJECTS = {"trees/estranged/baobab-giant", "trees/estranged/stiltroot", "formations/frozen/glacial-arch"}; + + private Path pack; + private IrisPackResources resources; + private Gson gson; + + @Before + public void bindGameLikePlatform() throws URISyntaxException { + UsableBlockPlatform.bind(new GameLikeBlocks().registries()); + pack = Path.of(ProceduralPartTraceTest.class.getResource(FIXTURE).toURI()); + IrisData data = mock(IrisData.class, withSettings().stubOnly().defaultAnswer(CALLS_REAL_METHODS)); + doReturn(pack.toFile()).when(data).getDataFolder(); + doReturn(mock(ResourceLoader.class)).when(data).getBlockLoader(); + doReturn(null).when(data).getEngine(); + resources = new IrisPackResources(data); + doReturn(resources).when(data).getPackResources(); + gson = new GsonBuilder().registerTypeAdapterFactory(data).registerTypeAdapterFactory(new JsonFormsCodecs()).create(); + } + + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void everyTracedBlockIsABlockOfTheVariantAndItsPartIsInTheOutline() throws IOException { + for (String path : OBJECTS) { + ResolvedProceduralObject object = resolved(path); + for (PlaceableObject variant : object.variants()) { + PartTrace trace = object.trace(variant); + BlockParts parts = object.parts(variant); + + assertFalse(path + " " + variant.name() + " has no part blocks", parts.partsByBlock().isEmpty()); + assertEquals(path + " " + variant.name() + " traced blocks that are not shown", trace.blockCount(), parts.partsByBlock().size()); + assertTrue(parts.partsByBlock().values().stream().allMatch(part -> part < object.outline().nodeCount())); + } + } + } + + @Test + public void aVariantBakedFromAnotherObjectHasNoParts() throws IOException { + ResolvedProceduralObject object = resolved(OBJECTS[0]); + PlaceableObject foreign = resolved(OBJECTS[1]).variants().get(0); + + assertTrue(object.parts(foreign).partsByBlock().isEmpty()); + } + + @Test + public void tracingTwiceFindsTheSameParts() throws IOException { + ResolvedProceduralObject object = resolved(OBJECTS[0]); + PlaceableObject variant = object.variants().get(0); + + assertEquals(object.parts(variant), object.parts(variant)); + } + + private ResolvedProceduralObject resolved(String path) throws IOException { + String json = Files.readString(pack.resolve(DEFINITIONS).resolve(path + ".json")); + return new ResolvedProceduralObject(path, gson.fromJson(json, ProceduralObject.class), resources); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java index c64ff5a2b..0fe9b13b0 100644 --- a/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java @@ -32,6 +32,11 @@ public final class PartTrace { this.partsByBlock = partsByBlock; } + /** How many blocks a part placed. */ + public int blockCount() { + return partsByBlock.size(); + } + /** The {@link PartOutline} id of the part that placed the block, or {@link PartOutline#NO_PART}. */ public int partAt(int x, int y, int z) { return partsByBlock.getOrDefault(PartCanvas.key(x, y, z), PartOutline.NO_PART); diff --git a/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java b/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java index 6e5f5e0a4..45b2b2742 100644 --- a/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java +++ b/module/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java @@ -22,8 +22,14 @@ import art.arcane.iris.engine.procedural.ProceduralShape; import art.arcane.iris.engine.procedural.ProceduralVariants; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.ObjectBlock; import com.volmit.object.PlaceableObject; import com.volmit.resource.PackResources; +import com.volmit.tooling.BlockParts; + +import java.util.HashMap; +import java.util.Map; /** The variants of a procedural object, baked by {@link ObjectBaker}. */ public final class ResolvedProceduralObject extends ProceduralVariants { @@ -45,6 +51,20 @@ public final class ResolvedProceduralObject extends ProceduralVariants { return outline; } + /** The part of each block of {@code variant} that has one, in the positions of its geometry; empty when it is not one of these. */ + public BlockParts parts(PlaceableObject variant) { + PartTrace trace = trace(variant); + Map partsByBlock = new HashMap<>(); + for (ObjectBlock block : variant.geometry().blocks()) { + BlockPosition position = block.position(); + int part = trace.partAt(position.x(), position.y(), position.z()); + if (part != PartOutline.NO_PART) { + partsByBlock.put(position, part); + } + } + return new BlockParts(partsByBlock); + } + /** Which part placed each block of {@code variant}, baked again to find out; empty when it is not one of these. */ public PartTrace trace(PlaceableObject variant) { int index = bakeIndexOf(variant); diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index 8bb14c674..e43f6bb49 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -22,10 +22,12 @@ import art.arcane.iris.engine.procedural.BakeProfile; import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.engine.procedural.ProceduralVariants; import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ResolvedProceduralObject; import com.volmit.object.GeneratedObject; import com.volmit.object.PlaceableObject; import com.volmit.resource.ResourceId; import com.volmit.tooling.BakeRun; +import com.volmit.tooling.BlockParts; import com.volmit.tooling.EditableSceneView; import com.volmit.tooling.JsonText; import com.volmit.tooling.NodeGraph; @@ -76,6 +78,19 @@ public final class ProceduralObjectScenes implements EditableSceneView { .map(PlaceableObject::geometry); } + @Override + public boolean hasParts() { + return true; + } + + @Override + public Optional parts(PackWorld world, String key, int variant) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) + .filter(ResolvedProceduralObject.class::isInstance) + .map(ResolvedProceduralObject.class::cast) + .flatMap(resolved -> resolved.variant(variant).map(resolved::parts)); + } + @Override public boolean isBaked() { return true; diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index 229cbd344..a80177bc2 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -174,6 +174,12 @@ export class BridgeClient { return decodeScene(await response.arrayBuffer()) } + /** The part that placed each block of {@link scene}, in the same order, or NO_PART; baked again on the server to find out. */ + async sceneParts(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene-parts?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal }) + return new Int32Array(await response.arrayBuffer()) + } + /** The pattern views the pack's modules show, such as its palettes. */ patternViews(): Promise { return this.json('patterns') diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index e42774221..17f1bd7f6 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -33,10 +33,11 @@ export interface SceneEntry { variants: number } -/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed. */ +/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */ export interface SceneViewInfo extends ModuleViewInfo { editable: boolean baked: boolean + parts: boolean } /** One timed bake of a scene entry (IrisApi BakeRun): a time per step, added up over every variant. */ diff --git a/studio/src/renderer/src/editor/nodeLayout.test.ts b/studio/src/renderer/src/editor/nodeLayout.test.ts index 7eb18f73f..78e4d8f97 100644 --- a/studio/src/renderer/src/editor/nodeLayout.test.ts +++ b/studio/src/renderer/src/editor/nodeLayout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { GraphNode, JsonPath } from '../bridge/types' import { NO_PART } from '../bridge/types' -import { isWithin, layoutNodes, NODE_WIDTH } from './nodeLayout' +import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout' function node(path: JsonPath, children: GraphNode[] = []): GraphNode { return { @@ -38,6 +38,27 @@ describe('layoutNodes', () => { }) }) +describe('nodeDrawingPart', () => { + const drawing = (path: JsonPath, partId: number, children: GraphNode[] = []): GraphNode => ({ ...node(path, children), partId }) + + it('finds the node that draws the part, whichever tree and depth it is in', () => { + const roots = [drawing([], 0, [drawing(['parts', 0], 1)]), drawing(['materials', 0], NO_PART, [drawing(['materials', 0, 'parts', 0], 2)])] + + expect(nodeDrawingPart(roots, 1)?.path).toEqual(['parts', 0]) + expect(nodeDrawingPart(roots, 2)?.path).toEqual(['materials', 0, 'parts', 0]) + }) + + it('takes the outer node when a node and the one it copies draw the same part', () => { + const roots = [drawing([], 3, [drawing(['branches', 'part'], 3)])] + + expect(nodeDrawingPart(roots, 3)?.path).toEqual([]) + }) + + it('finds none for a part no node draws', () => { + expect(nodeDrawingPart([drawing([], 0)], 5)).toBeNull() + }) +}) + describe('isWithin', () => { it('holds for the path itself and what sits inside it, not for a sibling', () => { expect(isWithin(['parts', 0, 'children', 1], ['parts', 0])).toBe(true) diff --git a/studio/src/renderer/src/editor/nodeLayout.ts b/studio/src/renderer/src/editor/nodeLayout.ts index df108ce23..4f300a441 100644 --- a/studio/src/renderer/src/editor/nodeLayout.ts +++ b/studio/src/renderer/src/editor/nodeLayout.ts @@ -49,6 +49,23 @@ export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | nu return null } +/** The first node, going down each tree in turn, that draws {@code part}, or null when none does. */ +export function nodeDrawingPart(roots: GraphNode[], part: number): GraphNode | null { + for (const root of roots) { + if (root.partId === part) { + return root + } + const found = nodeDrawingPart( + root.children.map((link) => link.node), + part + ) + if (found !== null) { + return found + } + } + return null +} + /** Whether {@code path} is {@code ancestor} or sits inside it. */ export function isWithin(path: JsonPath, ancestor: JsonPath): boolean { return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step) diff --git a/studio/src/renderer/src/scene/blockPick.test.ts b/studio/src/renderer/src/scene/blockPick.test.ts new file mode 100644 index 000000000..d994b1ca4 --- /dev/null +++ b/studio/src/renderer/src/scene/blockPick.test.ts @@ -0,0 +1,43 @@ +import { Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { BlockIndex, blockAtHit, NO_BLOCK } from './blockPick' +import type { BlockScene } from './sceneDecoding' + +// Three blocks in a row along x, from -1 to 1, and one above the middle one. +const SCENE: BlockScene = { + palette: ['minecraft:stone'], + blocks: new Int32Array([-1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]), + min: [-1, 0, 0], + max: [2, 2, 1] +} + +describe('BlockIndex', () => { + it('finds each block by position, in the scene order', () => { + const index = new BlockIndex(SCENE) + + expect([index.at(-1, 0, 0), index.at(0, 0, 0), index.at(1, 0, 0), index.at(0, 1, 0)]).toEqual([0, 1, 2, 3]) + }) + + it('finds nothing where the scene has no block, inside its bounds or beyond', () => { + const index = new BlockIndex(SCENE) + + expect(index.at(1, 1, 0)).toBe(NO_BLOCK) + expect(index.at(5, 0, 0)).toBe(NO_BLOCK) + expect(index.at(0, -1, 0)).toBe(NO_BLOCK) + }) +}) + +describe('blockAtHit', () => { + const index = new BlockIndex(SCENE) + + it('takes the block a ray goes into, whichever way it faces', () => { + expect(blockAtHit(index, new Vector3(2, 0.5, 0.5), new Vector3(-1, 0, 0))).toBe(2) + expect(blockAtHit(index, new Vector3(-1, 0.5, 0.5), new Vector3(1, 0, 0))).toBe(0) + expect(blockAtHit(index, new Vector3(0.5, 2, 0.5), new Vector3(0, -1, 0))).toBe(3) + expect(blockAtHit(index, new Vector3(0.5, 0, 0.5), new Vector3(0, 1, 0))).toBe(1) + }) + + it('finds no block in the open', () => { + expect(blockAtHit(index, new Vector3(5.5, 0.5, 0.5), new Vector3(-1, 0, 0))).toBe(NO_BLOCK) + }) +}) diff --git a/studio/src/renderer/src/scene/blockPick.ts b/studio/src/renderer/src/scene/blockPick.ts new file mode 100644 index 000000000..8e86c2878 --- /dev/null +++ b/studio/src/renderer/src/scene/blockPick.ts @@ -0,0 +1,38 @@ +import type { Vector3 } from 'three' +import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding' + +/** How far past a hit surface along the ray a point is taken to tell which block the surface belongs to, in blocks. */ +const SURFACE_NUDGE = 1e-3 +export const NO_BLOCK = -1 + +/** The blocks of a scene by position. */ +export class BlockIndex { + private readonly indexes = new Map() + private readonly sizeY: number + private readonly sizeZ: number + + constructor(private readonly scene: BlockScene) { + ;[this.sizeY, this.sizeZ] = [scene.max[1] - scene.min[1], scene.max[2] - scene.min[2]] + const blocks = scene.blocks + for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) { + this.indexes.set(this.keyOf(blocks[offset], blocks[offset + 1], blocks[offset + 2]), offset / INTS_PER_BLOCK) + } + } + + /** The place of the block at x, y and z among the scene's blocks, or NO_BLOCK. */ + at(x: number, y: number, z: number): number { + const inside = [x, y, z].every((value, axis) => value >= this.scene.min[axis] && value < this.scene.max[axis]) + return inside ? (this.indexes.get(this.keyOf(x, y, z)) ?? NO_BLOCK) : NO_BLOCK + } + + private keyOf(x: number, y: number, z: number): number { + const [localX, localY, localZ] = [x - this.scene.min[0], y - this.scene.min[1], z - this.scene.min[2]] + return (localX * this.sizeY + localY) * this.sizeZ + localZ + } +} + +/** The block whose surface a ray met at {@code point}: the one the ray goes into. NO_BLOCK when that spot holds none. */ +export function blockAtHit(index: BlockIndex, point: Vector3, direction: Vector3): number { + const inside = point.clone().addScaledVector(direction, SURFACE_NUDGE) + return index.at(Math.floor(inside.x), Math.floor(inside.y), Math.floor(inside.z)) +} diff --git a/studio/src/renderer/src/scene/partFocus.test.ts b/studio/src/renderer/src/scene/partFocus.test.ts new file mode 100644 index 000000000..c66824091 --- /dev/null +++ b/studio/src/renderer/src/scene/partFocus.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { NO_PART } from '../bridge/types' +import { blocksInPart, blocksOutsidePart } from './partFocus' + +const PARTS = Int32Array.of(2, NO_PART, 0, 2, 2) + +describe('part focus', () => { + it('marks every block outside the chosen part, the ones no part placed too', () => { + expect(blocksOutsidePart(PARTS, 2)).toEqual(Uint8Array.of(0, 1, 1, 0, 0)) + }) + + it('marks nothing when no part is chosen', () => { + expect(blocksOutsidePart(PARTS, NO_PART)).toBeNull() + }) + + it('counts the blocks of a part, none for a part that placed nothing', () => { + expect(blocksInPart(PARTS, 2)).toBe(3) + expect(blocksInPart(PARTS, 7)).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/partFocus.ts b/studio/src/renderer/src/scene/partFocus.ts new file mode 100644 index 000000000..20c905b48 --- /dev/null +++ b/studio/src/renderer/src/scene/partFocus.ts @@ -0,0 +1,14 @@ +import { NO_PART } from '../bridge/types' + +/** Which blocks are not of {@code part}, one 1 per block in the scene's order; null when no part is chosen. */ +export function blocksOutsidePart(parts: Int32Array, part: number): Uint8Array | null { + if (part === NO_PART) { + return null + } + return Uint8Array.from(parts, (blockPart) => (blockPart === part ? 0 : 1)) +} + +/** How many blocks {@code part} placed. */ +export function blocksInPart(parts: Int32Array, part: number): number { + return parts.reduce((count, blockPart) => count + (blockPart === part ? 1 : 0), 0) +} diff --git a/studio/src/renderer/src/scene/sceneMesh.ts b/studio/src/renderer/src/scene/sceneMesh.ts index b26b16bdf..8a77c3575 100644 --- a/studio/src/renderer/src/scene/sceneMesh.ts +++ b/studio/src/renderer/src/scene/sceneMesh.ts @@ -1,4 +1,4 @@ -import { Box3, BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial } from 'three' +import { Box3, BufferAttribute, BufferGeometry, Group, Mesh, MeshBasicMaterial } from 'three' import type { ViewportContent } from '../studio/SceneViewport' import { cubeModel, parseState, type BlockModels, type BlockModel, type Direction, type Quad } from './blockModels' import { blockTint } from './blockTints' @@ -15,6 +15,8 @@ export interface SceneMesh { } const CUTOUT_ALPHA = 0.1 +/** How much of a faint block shows, from 0 for none to 1 for all. */ +const FAINT_OPACITY = 0.12 /** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */ const FACE_LIGHT: Record = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 } @@ -40,11 +42,26 @@ interface PaletteEntry { shown: boolean } +interface PlacedQuad { + quad: Quad + entry: PaletteEntry + x: number + y: number + z: number +} + /** * One geometry for the whole scene, its faces against solid neighbours left out, textured from one atlas. With - * `farLeavesOnly` and far leaves in the scene, nothing but them is drawn. + * `farLeavesOnly` and far leaves in the scene, nothing but them is drawn. Blocks `faint` flags, one per block in the + * scene's order, are drawn through a faint geometry of their own that hides nothing behind it. */ -export async function buildSceneMesh(scene: BlockScene, models: BlockModels, images: ImageSource, farLeavesOnly = false): Promise { +export async function buildSceneMesh( + scene: BlockScene, + models: BlockModels, + images: ImageSource, + farLeavesOnly = false, + faint: Uint8Array | null = null +): Promise { const singlingOutFarLeaves = farLeavesOnly && countFarLeaves(scene) > 0 const resolved = await Promise.all(scene.palette.map((state) => models.model(state))) const unknownStates = scene.palette.filter((_, index) => resolved[index] === null) @@ -59,15 +76,30 @@ export async function buildSceneMesh(scene: BlockScene, models: BlockModels, ima const solid = shown && model.fullCube && model.quads.every((quad) => atlas.cell(quad.texture).solid) return { model, name: state.name, properties: state.properties, solid, shown } }) - const geometry = geometryOf(scene, palette, atlas) - const material = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA }) - const bounds = new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute) + const { solid: solidQuads, faint: faintQuads } = visibleQuads(scene, palette, faint) + const solidGeometry = geometryOf(solidQuads, atlas) + const faintGeometry = geometryOf(faintQuads, atlas) + const solidMaterial = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA }) + const faintMaterial = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA * FAINT_OPACITY, transparent: true, opacity: FAINT_OPACITY, depthWrite: false }) + const object = new Group() + const bounds = new Box3() + for (const [quads, geometry, material] of [ + [solidQuads, solidGeometry, solidMaterial], + [faintQuads, faintGeometry, faintMaterial] + ] as const) { + if (quads.length > 0) { + object.add(new Mesh(geometry, material)) + bounds.union(new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute)) + } + } return { - content: { object: new Mesh(geometry, material), bounds }, + content: { object, bounds }, unknownStates, dispose: () => { - geometry.dispose() - material.dispose() + solidGeometry.dispose() + faintGeometry.dispose() + solidMaterial.dispose() + faintMaterial.dispose() atlas.dispose() } } @@ -84,9 +116,10 @@ function drawnModel(model: BlockModel | null): BlockModel { return model } -function geometryOf(scene: BlockScene, palette: PaletteEntry[], atlas: TextureAtlas): BufferGeometry { - const solids = new SolidBlocks(scene, palette) - const visible: { quad: Quad; entry: PaletteEntry; x: number; y: number; z: number }[] = [] +// A faint block hides no face of a neighbour, so what stands behind it is drawn whole. +function visibleQuads(scene: BlockScene, palette: PaletteEntry[], faint: Uint8Array | null): { solid: PlacedQuad[]; faint: PlacedQuad[] } { + const solids = new SolidBlocks(scene, palette, faint) + const quads = { solid: [] as PlacedQuad[], faint: [] as PlacedQuad[] } const blocks = scene.blocks for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) { const [x, y, z, paletteIndex] = [blocks[offset], blocks[offset + 1], blocks[offset + 2], blocks[offset + 3]] @@ -94,13 +127,18 @@ function geometryOf(scene: BlockScene, palette: PaletteEntry[], atlas: TextureAt if (!entry.shown) { continue } + const drawnIn = faint !== null && faint[offset / INTS_PER_BLOCK] === 1 ? quads.faint : quads.solid for (const quad of entry.model.quads) { if (quad.cullFace !== null && solids.besides(x, y, z, quad.cullFace)) { continue } - visible.push({ quad, entry, x, y, z }) + drawnIn.push({ quad, entry, x, y, z }) } } + return quads +} + +function geometryOf(visible: PlacedQuad[], atlas: TextureAtlas): BufferGeometry { const positions = new Float32Array(visible.length * CORNERS_PER_QUAD * 3) const uvs = new Float32Array(visible.length * CORNERS_PER_QUAD * 2) const colors = new Float32Array(visible.length * CORNERS_PER_QUAD * 3) @@ -136,12 +174,13 @@ class SolidBlocks { private readonly sizeY: number private readonly sizeZ: number - constructor(private readonly scene: BlockScene, palette: PaletteEntry[]) { + constructor(private readonly scene: BlockScene, palette: PaletteEntry[], faint: Uint8Array | null) { ;[this.sizeX, this.sizeY, this.sizeZ] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis]) this.solid = new Uint8Array(this.sizeX * this.sizeY * this.sizeZ) const blocks = scene.blocks for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) { - if (palette[blocks[offset + 3]].solid) { + const isFaint = faint !== null && faint[offset / INTS_PER_BLOCK] === 1 + if (palette[blocks[offset + 3]].solid && !isFaint) { this.solid[this.indexOf(blocks[offset], blocks[offset + 1], blocks[offset + 2])] = 1 } } diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 63b364721..2aa3d4b31 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -1,23 +1,25 @@ import { ChevronLeft, ChevronRight } from 'lucide-react' -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { ScrollArea } from '@/components/ui/scroll-area' import { cn } from '@/lib/utils' import type { BridgeClient } from '../bridge/BridgeClient' -import type { JsonPath, SceneEntry, SceneViewInfo } from '../bridge/types' +import { NO_PART, type JsonPath, type SceneEntry, type SceneViewInfo } from '../bridge/types' import { parsedText } from '../editor/jsonValues' -import { nodeWithPath } from '../editor/nodeLayout' +import { nodeDrawingPart, nodeWithPath } from '../editor/nodeLayout' import { useNodeEditor } from '../editor/useNodeEditor' +import { BlockIndex, blockAtHit, NO_BLOCK } from '../scene/blockPick' import { BlockModels } from '../scene/blockModels' import { BridgeAssets } from '../scene/BridgeAssets' import { countFarLeaves } from '../scene/farLeaves' +import { blocksInPart, blocksOutsidePart } from '../scene/partFocus' import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' import { BakeMeter, useBakeTiming } from './BakeMeter' import { EntryBrowser } from './EntryBrowser' import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' -import { SceneViewport } from './SceneViewport' +import { SceneViewport, type PickedSurface } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' @@ -46,7 +48,6 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null const variant = entry !== null && chosen?.key === entry.key ? Math.min(chosen.variant, entry.variants - 1) : 0 const [farLeavesOnly, setFarLeavesOnly] = useState(false) - const { scene, shown, building } = useSceneMesh(client, view.id, entry, variant, packRevision, models, images, farLeavesOnly, tell) const chooseVariant = (next: number): void => { if (entry !== null) { setChosen({ key: entry.key, variant: (next + entry.variants) % entry.variants }) @@ -60,9 +61,40 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state]) - useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary]) + const [pickedPart, setPickedPart] = useState(NO_PART) + const highlightedPart = view.parts ? (selected?.partId ?? pickedPart) : NO_PART + const { scene, shown, sceneParts, building } = useSceneMesh(client, view, entry, variant, packRevision, models, images, farLeavesOnly, highlightedPart, tell) + const shownScene = shown?.scene ?? null + const blockIndex = useMemo(() => (shownScene === null ? null : new BlockIndex(shownScene)), [shownScene]) + const shownParts = partsOf(sceneParts, shownScene) + const pickPart = (picked: PickedSurface): void => { + const choose = (part: number): void => { + setPickedPart(part) + setSelectedPath(part === NO_PART || editor.state?.roots == null ? null : (nodeDrawingPart(editor.state.roots, part)?.path ?? null)) + } + const block = picked === null || blockIndex === null ? NO_BLOCK : blockAtHit(blockIndex, picked.point, picked.direction) + if (block === NO_BLOCK) { + choose(NO_PART) + } else if (shownParts === null) { + tell('Still finding which part placed each block') + } else if (shownParts[block] === NO_PART) { + choose(NO_PART) + tell('That block belongs to no part') + } else { + choose(shownParts[block]) + } + } + + const summaryParts = partsOf(sceneParts, scene) + useEffect( + () => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene, summaryParts === null ? '' : partNote(summaryParts, highlightedPart))), + [entry, scene, summaryParts, highlightedPart, onSummary] + ) useEffect(() => () => onSummary(null), [onSummary]) - useEffect(() => setSelectedPath(null), [entry?.key]) + useEffect(() => { + setSelectedPath(null) + setPickedPart(NO_PART) + }, [entry?.key]) return ( <> @@ -73,9 +105,18 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce shown={shown} status={building && entry !== null ? (waiting ?? `Building ${entry.name}`) : null} onVariant={chooseVariant} + onPick={view.parts ? pickPart : undefined} /> {view.editable && entry !== null && ( - setSelectedPath(node?.path ?? null)} /> + { + setSelectedPath(node?.path ?? null) + setPickedPart(NO_PART) + }} + /> )}