mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
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
This commit is contained in:
1 parent
a8aaa3c3cf
commit
8136fa857f
24 files changed
+719
-48
No files matched your search
+1
-1
@@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes.
|
||||
| Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` |
|
||||
| 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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<BlockPosition, Integer> 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);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,20 @@ public non-sealed interface SceneView extends StudioView {
|
||||
*/
|
||||
Optional<GeneratedObject> 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<BlockParts> 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;
|
||||
|
||||
@@ -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<BlockPosition, Integer> 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<SceneEntry> entries(PackWorld world) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<GeneratedObject> scene(PackWorld world, String key, int variant) {
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
|
||||
assertFalse(plain.hasParts());
|
||||
assertTrue(plain.parts(null, "any", 0).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -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<ObjectBlock> 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());
|
||||
}
|
||||
|
||||
@@ -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<PatternEntryWire> 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. */
|
||||
|
||||
@@ -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<BlockParts> 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);
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+20
@@ -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<BlockPosition, Integer> 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);
|
||||
|
||||
@@ -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<BlockParts> 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;
|
||||
|
||||
@@ -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<Int32Array> {
|
||||
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<ModuleViewInfo[]> {
|
||||
return this.json('patterns')
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<number, number>()
|
||||
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))
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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<Direction, number> = { 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<SceneMesh> {
|
||||
export async function buildSceneMesh(
|
||||
scene: BlockScene,
|
||||
models: BlockModels,
|
||||
images: ImageSource,
|
||||
farLeavesOnly = false,
|
||||
faint: Uint8Array | null = null
|
||||
): Promise<SceneMesh> {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 && (
|
||||
<NodePane editor={editor} entryKey={entry.key} selected={selected} onSelect={(node) => setSelectedPath(node?.path ?? null)} />
|
||||
<NodePane
|
||||
editor={editor}
|
||||
entryKey={entry.key}
|
||||
selected={selected}
|
||||
onSelect={(node) => {
|
||||
setSelectedPath(node?.path ?? null)
|
||||
setPickedPart(NO_PART)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
|
||||
@@ -98,12 +139,14 @@ interface SceneAreaProps {
|
||||
/** What is being built, or null when nothing is. */
|
||||
status: string | null
|
||||
onVariant(variant: number): void
|
||||
/** Called when a block is clicked; absent when the scene has no parts to pick. */
|
||||
onPick?(picked: PickedSurface): void
|
||||
}
|
||||
|
||||
function SceneArea({ entry, variant, shown, status, onVariant }: SceneAreaProps): React.JSX.Element {
|
||||
function SceneArea({ entry, variant, shown, status, onVariant, onPick }: SceneAreaProps): React.JSX.Element {
|
||||
return (
|
||||
<div className="relative min-h-0 flex-[11]">
|
||||
<SceneViewport content={shown?.mesh.content ?? null} framing={shown?.scene} />
|
||||
<SceneViewport content={shown?.mesh.content ?? null} framing={shown?.scene} onPick={onPick} />
|
||||
{entry !== null && entry.variants > 1 && (
|
||||
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
|
||||
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => onVariant(variant - 1)}>
|
||||
@@ -126,10 +169,19 @@ function SceneArea({ entry, variant, shown, status, onVariant }: SceneAreaProps)
|
||||
)
|
||||
}
|
||||
|
||||
function summaryOf(entry: SceneEntry, scene: BlockScene): string {
|
||||
function summaryOf(entry: SceneEntry, scene: BlockScene, partNote: string): string {
|
||||
const [width, height, depth] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis])
|
||||
const blocks = scene.blocks.length / INTS_PER_BLOCK
|
||||
return `${entry.key} · ${NUMBER.format(blocks)} blocks · ${width} × ${height} × ${depth}`
|
||||
return `${entry.key} · ${NUMBER.format(blocks)} blocks${partNote} · ${width} × ${height} × ${depth}`
|
||||
}
|
||||
|
||||
// A part that only carves has no blocks of its own, which is why nothing lights up.
|
||||
function partNote(parts: Int32Array, part: number): string {
|
||||
if (part === NO_PART) {
|
||||
return ''
|
||||
}
|
||||
const blocks = blocksInPart(parts, part)
|
||||
return blocks === 0 ? ' · part has no blocks here' : ` · part has ${NUMBER.format(blocks)}`
|
||||
}
|
||||
|
||||
function useSceneEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): SceneEntry[] {
|
||||
@@ -152,25 +204,42 @@ interface ShownScene {
|
||||
mesh: SceneMesh
|
||||
}
|
||||
|
||||
/** The part of each block of {@code scene}, when the parts were read for that scene. */
|
||||
interface SceneParts {
|
||||
scene: BlockScene
|
||||
parts: Int32Array
|
||||
}
|
||||
|
||||
function partsOf(sceneParts: SceneParts | null, scene: BlockScene | null): Int32Array | null {
|
||||
return sceneParts !== null && sceneParts.scene === scene ? sceneParts.parts : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The chosen entry's scene, and its mesh, with only the far leaves drawn when asked; a newer choice abandons an older
|
||||
* one, and a replaced mesh is freed. Asking for the far leaves builds the mesh again from the scene already read.
|
||||
* The chosen entry's scene, and its mesh, with only the far leaves drawn when asked and every block outside the
|
||||
* highlighted part drawn faintly; a newer choice abandons an older one, and a replaced mesh is freed. Asking for the
|
||||
* far leaves or another part builds the mesh again from the scene already read. A view with parts also reads which
|
||||
* part placed each block, once the scene is in.
|
||||
*/
|
||||
function useSceneMesh(
|
||||
client: BridgeClient,
|
||||
viewId: string,
|
||||
view: SceneViewInfo,
|
||||
entry: SceneEntry | null,
|
||||
variant: number,
|
||||
packRevision: number,
|
||||
models: BlockModels,
|
||||
images: BridgeAssets,
|
||||
farLeavesOnly: boolean,
|
||||
highlightedPart: number,
|
||||
tell: (message: string) => void
|
||||
): { scene: BlockScene | null; shown: ShownScene | null; building: boolean } {
|
||||
): { scene: BlockScene | null; shown: ShownScene | null; sceneParts: SceneParts | null; building: boolean } {
|
||||
const [scene, setScene] = useState<BlockScene | null>(null)
|
||||
const [sceneParts, setSceneParts] = useState<SceneParts | null>(null)
|
||||
const [shown, setShown] = useState<ShownScene | null>(null)
|
||||
const [building, setBuilding] = useState(false)
|
||||
const unknownStatesTold = useRef<BlockScene | null>(null)
|
||||
const key = entry?.key ?? null
|
||||
const viewId = view.id
|
||||
const hasParts = view.parts
|
||||
|
||||
useEffect(() => {
|
||||
if (key === null) {
|
||||
@@ -180,7 +249,18 @@ function useSceneMesh(
|
||||
setBuilding(true)
|
||||
client
|
||||
.scene(viewId, key, variant, stop.signal)
|
||||
.then((found) => !stop.signal.aborted && setScene(found))
|
||||
.then((found) => {
|
||||
if (stop.signal.aborted) {
|
||||
return
|
||||
}
|
||||
setScene(found)
|
||||
if (hasParts) {
|
||||
client
|
||||
.sceneParts(viewId, key, variant, stop.signal)
|
||||
.then((parts) => !stop.signal.aborted && setSceneParts({ scene: found, parts }))
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
}
|
||||
})
|
||||
.catch((failure: Error) => {
|
||||
if (stop.signal.aborted) {
|
||||
return
|
||||
@@ -189,7 +269,12 @@ function useSceneMesh(
|
||||
setBuilding(false)
|
||||
})
|
||||
return () => stop.abort()
|
||||
}, [client, viewId, key, variant, packRevision, tell])
|
||||
}, [client, viewId, hasParts, key, variant, packRevision, tell])
|
||||
|
||||
const faint = useMemo(() => {
|
||||
const parts = partsOf(sceneParts, scene)
|
||||
return parts === null ? null : blocksOutsidePart(parts, highlightedPart)
|
||||
}, [sceneParts, scene, highlightedPart])
|
||||
|
||||
useEffect(() => {
|
||||
if (scene === null) {
|
||||
@@ -197,25 +282,26 @@ function useSceneMesh(
|
||||
}
|
||||
const stop = new AbortController()
|
||||
setBuilding(true)
|
||||
buildSceneMesh(scene, models, images, farLeavesOnly)
|
||||
buildSceneMesh(scene, models, images, farLeavesOnly, faint)
|
||||
.then((built) => {
|
||||
if (stop.signal.aborted) {
|
||||
disposeMesh(built)
|
||||
return
|
||||
}
|
||||
setShown({ scene, mesh: built })
|
||||
if (!farLeavesOnly && built.unknownStates.length > 0) {
|
||||
if (!farLeavesOnly && built.unknownStates.length > 0 && unknownStatesTold.current !== scene) {
|
||||
unknownStatesTold.current = scene
|
||||
tell(`No model for ${built.unknownStates.length === 1 ? built.unknownStates[0] : `${built.unknownStates.length} block states`}`)
|
||||
}
|
||||
})
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
.finally(() => !stop.signal.aborted && setBuilding(false))
|
||||
return () => stop.abort()
|
||||
}, [scene, farLeavesOnly, models, images, tell])
|
||||
}, [scene, farLeavesOnly, faint, models, images, tell])
|
||||
|
||||
useEffect(() => () => disposeMesh(shown?.mesh ?? null), [shown])
|
||||
|
||||
return { scene, shown, building }
|
||||
return { scene, shown, sceneParts, building }
|
||||
}
|
||||
|
||||
function disposeMesh(mesh: SceneMesh | null): void {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Box3, MOUSE, PerspectiveCamera, Ray, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three'
|
||||
import { Box3, MOUSE, PerspectiveCamera, Ray, Raycaster, Scene, Sphere, Vector2, Vector3, WebGLRenderer, type Object3D } from 'three'
|
||||
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
|
||||
import type { SightView } from '../scene/cameraSight'
|
||||
import { surfaceAlong } from '../scene/surfacePick'
|
||||
@@ -14,6 +14,13 @@ const NEAR_CLIP_PER_ORBIT_DISTANCE = 0.01
|
||||
// The far plane keeps up with zooming out, so ground reaching to the horizon stays in view.
|
||||
const FAR_CLIP_PER_ORBIT_DISTANCE = 20
|
||||
|
||||
// A press that moves further than this between pressing and releasing is a drag, not a click.
|
||||
const CLICK_SLOP_PIXELS = 4
|
||||
|
||||
function turnsView(event: PointerEvent): boolean {
|
||||
return event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey
|
||||
}
|
||||
|
||||
/** The camera of a viewport, for content that draws only what the camera looks at. */
|
||||
export interface CameraLink {
|
||||
/** Where the camera is and how it looks now. */
|
||||
@@ -34,14 +41,19 @@ export interface ViewportContent {
|
||||
follow?(camera: CameraLink): () => void
|
||||
}
|
||||
|
||||
/** Where a click met the content, and the way it was looking; null when the click met nothing. */
|
||||
export type PickedSurface = { point: Vector3; direction: Vector3 } | null
|
||||
|
||||
interface SceneViewportProps {
|
||||
content: ViewportContent | null
|
||||
/** Changes when the camera should frame the content again; the same content keeps the camera where it is. */
|
||||
framing?: unknown
|
||||
/** Called when the content is clicked, not dragged. */
|
||||
onPick?(picked: PickedSurface): void
|
||||
}
|
||||
|
||||
/** Something in 3D: drag to turn around what is in the middle, right drag to move, scroll to come closer to the cursor. Drawn only when it changes. */
|
||||
export function SceneViewport({ content, framing }: SceneViewportProps): React.JSX.Element {
|
||||
export function SceneViewport({ content, framing, onPick }: SceneViewportProps): React.JSX.Element {
|
||||
const host = useRef<HTMLDivElement>(null)
|
||||
const stage = useRef<Stage | null>(null)
|
||||
|
||||
@@ -56,6 +68,7 @@ export function SceneViewport({ content, framing }: SceneViewportProps): React.J
|
||||
|
||||
useEffect(() => stage.current?.show(content), [content])
|
||||
useEffect(() => stage.current?.frameShown(), [framing])
|
||||
useEffect(() => stage.current?.onPick(onPick ?? null), [onPick])
|
||||
|
||||
return <div ref={host} className="absolute inset-0 bg-map-background" />
|
||||
}
|
||||
@@ -73,6 +86,8 @@ class Stage {
|
||||
private framed = false
|
||||
private framedFar = this.camera.far
|
||||
private frameRequested = false
|
||||
private pickListener: ((picked: PickedSurface) => void) | null = null
|
||||
private pressedAt: { x: number; y: number } | null = null
|
||||
|
||||
constructor(private readonly host: HTMLDivElement) {
|
||||
this.renderer.setPixelRatio(window.devicePixelRatio)
|
||||
@@ -82,7 +97,11 @@ class Stage {
|
||||
this.controls.enableDamping = true
|
||||
this.controls.zoomToCursor = true
|
||||
this.controls.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN }
|
||||
this.renderer.domElement.addEventListener('pointerdown', (event) => this.pivotOnSurfaceInMiddle(event))
|
||||
this.renderer.domElement.addEventListener('pointerdown', (event) => {
|
||||
this.pressedAt = turnsView(event) ? { x: event.clientX, y: event.clientY } : null
|
||||
this.pivotOnSurfaceInMiddle(event)
|
||||
})
|
||||
this.renderer.domElement.addEventListener('pointerup', (event) => this.pickIfClicked(event))
|
||||
this.controls.addEventListener('change', () => {
|
||||
this.fitClipToOrbit()
|
||||
this.notifyMoved()
|
||||
@@ -154,10 +173,32 @@ class Stage {
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
onPick(listener: ((picked: PickedSurface) => void) | null): void {
|
||||
this.pickListener = listener
|
||||
}
|
||||
|
||||
// A press that stays where it was is a click; one that moved turned the view.
|
||||
private pickIfClicked(event: PointerEvent): void {
|
||||
const pressed = this.pressedAt
|
||||
this.pressedAt = null
|
||||
if (pressed === null || this.shown === null || this.pickListener === null) {
|
||||
return
|
||||
}
|
||||
if (Math.hypot(event.clientX - pressed.x, event.clientY - pressed.y) > CLICK_SLOP_PIXELS) {
|
||||
return
|
||||
}
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect()
|
||||
const pointer = new Vector2(((event.clientX - bounds.left) / bounds.width) * 2 - 1, -((event.clientY - bounds.top) / bounds.height) * 2 + 1)
|
||||
const caster = new Raycaster()
|
||||
this.camera.updateMatrixWorld()
|
||||
caster.setFromCamera(pointer, this.camera)
|
||||
const point = surfaceAlong(this.shown, caster.ray, this.camera.far)
|
||||
this.pickListener(point === null ? null : { point, direction: caster.ray.direction.clone() })
|
||||
}
|
||||
|
||||
// The pivot slides along the line of sight, so the picture stays put while turning now goes around what is there.
|
||||
private pivotOnSurfaceInMiddle(event: PointerEvent): void {
|
||||
const turns = event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey
|
||||
if (!turns || this.shown === null) {
|
||||
if (!turnsView(event) || this.shown === null) {
|
||||
return
|
||||
}
|
||||
const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3()))
|
||||
|
||||
Reference in new issue
Block a user