From 564dcdcc72e255dfabaadb9634c3f3619df76571 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 14 Nov 2026 14:53:07 +0100 Subject: [PATCH] Add Iris Studio app - Add the Electron studio (electron-vite, React, three) - Ignore node_modules and build output under studio/ --- studio/.gitignore | 4 + studio/LICENSE | 518 ++ studio/components.json | 21 + studio/electron.vite.config.ts | 21 + studio/package-lock.json | 4574 +++++++++++++++++ studio/package.json | 40 + studio/src/main/dedicatedGpu.ts | 80 + studio/src/main/index.ts | 198 + studio/src/preload/index.ts | 20 + studio/src/renderer/index.html | 15 + studio/src/renderer/src/App.tsx | 68 + .../src/renderer/src/bridge/BridgeClient.ts | 391 ++ .../src/bridge/patternDecoding.test.ts | 32 + .../renderer/src/bridge/patternDecoding.ts | 27 + .../renderer/src/bridge/savedTileDecoding.ts | 41 + .../src/renderer/src/bridge/tileDecoding.ts | 145 + studio/src/renderer/src/bridge/types.ts | 436 ++ .../src/renderer/src/components/IdeIcon.tsx | 64 + .../src/renderer/src/components/ui/button.tsx | 63 + .../src/components/ui/context-menu.tsx | 254 + .../src/renderer/src/components/ui/dialog.tsx | 158 + .../src/renderer/src/components/ui/input.tsx | 20 + studio/src/renderer/src/components/ui/kbd.tsx | 28 + .../src/components/ui/scroll-area.tsx | 57 + .../renderer/src/components/ui/separator.tsx | 25 + .../src/components/ui/toggle-group.tsx | 69 + .../src/renderer/src/components/ui/toggle.tsx | 44 + .../renderer/src/components/ui/tooltip.tsx | 55 + studio/src/renderer/src/css.d.ts | 1 + .../renderer/src/editor/EditHistory.test.ts | 35 + studio/src/renderer/src/editor/EditHistory.ts | 45 + studio/src/renderer/src/editor/curves.test.ts | 84 + studio/src/renderer/src/editor/curves.ts | 217 + .../src/renderer/src/editor/entryKeys.test.ts | 32 + studio/src/renderer/src/editor/entryKeys.ts | 18 + studio/src/renderer/src/editor/jsonValues.ts | 22 + .../renderer/src/editor/nodeLayout.test.ts | 68 + studio/src/renderer/src/editor/nodeLayout.ts | 108 + .../renderer/src/editor/settingFolds.test.ts | 79 + .../src/renderer/src/editor/settingFolds.ts | 128 + .../renderer/src/editor/settingText.test.ts | 27 + studio/src/renderer/src/editor/settingText.ts | 48 + .../src/editor/suggestionStore.test.ts | 25 + .../renderer/src/editor/suggestionStore.ts | 23 + .../renderer/src/editor/suggestions.test.ts | 82 + studio/src/renderer/src/editor/suggestions.ts | 79 + .../src/renderer/src/editor/useNodeEditor.ts | 122 + studio/src/renderer/src/env.d.ts | 10 + .../renderer/src/icons/LICENSE-APACHE-2.0.txt | 202 + studio/src/renderer/src/icons/NOTICE.txt | 6 + studio/src/renderer/src/icons/actualZoom.svg | 5 + .../renderer/src/icons/actualZoom_dark.svg | 5 + studio/src/renderer/src/icons/add.svg | 4 + studio/src/renderer/src/icons/add_dark.svg | 4 + studio/src/renderer/src/icons/blocks.svg | 4 + studio/src/renderer/src/icons/blocks_dark.svg | 4 + studio/src/renderer/src/icons/borders.svg | 3 + .../src/renderer/src/icons/borders_dark.svg | 3 + studio/src/renderer/src/icons/checked.svg | 4 + .../src/renderer/src/icons/checked_dark.svg | 4 + studio/src/renderer/src/icons/chevronLeft.svg | 4 + .../renderer/src/icons/chevronLeft_dark.svg | 4 + .../src/renderer/src/icons/chevronRight.svg | 4 + .../renderer/src/icons/chevronRight_dark.svg | 4 + studio/src/renderer/src/icons/closeSmall.svg | 4 + .../renderer/src/icons/closeSmall_dark.svg | 4 + studio/src/renderer/src/icons/decoration.svg | 5 + .../renderer/src/icons/decoration_dark.svg | 5 + studio/src/renderer/src/icons/delete.svg | 4 + studio/src/renderer/src/icons/delete_dark.svg | 4 + studio/src/renderer/src/icons/exit.svg | 5 + studio/src/renderer/src/icons/exit_dark.svg | 12 + studio/src/renderer/src/icons/grid.svg | 7 + studio/src/renderer/src/icons/grid_dark.svg | 7 + studio/src/renderer/src/icons/groups.svg | 7 + studio/src/renderer/src/icons/groups_dark.svg | 7 + studio/src/renderer/src/icons/help.svg | 5 + studio/src/renderer/src/icons/help_dark.svg | 5 + studio/src/renderer/src/icons/lightning.svg | 4 + .../src/renderer/src/icons/lightning_dark.svg | 4 + studio/src/renderer/src/icons/locate.svg | 4 + studio/src/renderer/src/icons/locate_dark.svg | 4 + studio/src/renderer/src/icons/locked.svg | 4 + studio/src/renderer/src/icons/locked_dark.svg | 4 + studio/src/renderer/src/icons/memory.svg | 7 + studio/src/renderer/src/icons/memory_dark.svg | 7 + studio/src/renderer/src/icons/mob.svg | 6 + studio/src/renderer/src/icons/mob_dark.svg | 6 + studio/src/renderer/src/icons/redo.svg | 4 + studio/src/renderer/src/icons/redo_dark.svg | 4 + studio/src/renderer/src/icons/refresh.svg | 7 + .../src/renderer/src/icons/refresh_dark.svg | 7 + studio/src/renderer/src/icons/reset.svg | 4 + studio/src/renderer/src/icons/reset_dark.svg | 4 + studio/src/renderer/src/icons/search.svg | 5 + studio/src/renderer/src/icons/search_dark.svg | 5 + studio/src/renderer/src/icons/settings.svg | 4 + .../src/renderer/src/icons/settings_dark.svg | 4 + studio/src/renderer/src/icons/shading.svg | 4 + .../src/renderer/src/icons/shading_dark.svg | 4 + studio/src/renderer/src/icons/stopWatch.svg | 6 + .../src/renderer/src/icons/stopWatch_dark.svg | 6 + studio/src/renderer/src/icons/symlink.svg | 4 + .../src/renderer/src/icons/symlink_dark.svg | 4 + studio/src/renderer/src/icons/theme.svg | 4 + studio/src/renderer/src/icons/theme_dark.svg | 4 + studio/src/renderer/src/icons/undo.svg | 4 + studio/src/renderer/src/icons/undo_dark.svg | 4 + .../src/renderer/src/icons/views/biomes.svg | 8 + .../renderer/src/icons/views/biomes_dark.svg | 8 + studio/src/renderer/src/icons/views/noise.svg | 3 + .../renderer/src/icons/views/noise_dark.svg | 3 + .../src/renderer/src/icons/views/objects.svg | 4 + .../renderer/src/icons/views/objects_dark.svg | 4 + .../src/renderer/src/icons/views/palettes.svg | 6 + .../src/icons/views/palettes_dark.svg | 6 + .../renderer/src/icons/views/procedural.svg | 7 + .../src/icons/views/procedural_dark.svg | 7 + .../src/renderer/src/icons/views/regions.svg | 4 + .../renderer/src/icons/views/regions_dark.svg | 4 + .../renderer/src/icons/views/saved-world.svg | 4 + .../src/icons/views/saved-world_dark.svg | 4 + .../src/renderer/src/icons/views/world-3d.svg | 4 + .../src/icons/views/world-3d_dark.svg | 4 + studio/src/renderer/src/icons/web.svg | 4 + studio/src/renderer/src/icons/web_dark.svg | 4 + studio/src/renderer/src/lib/utils.ts | 6 + studio/src/renderer/src/main.tsx | 13 + studio/src/renderer/src/map/MapController.ts | 386 ++ studio/src/renderer/src/map/TileStore.ts | 200 + studio/src/renderer/src/map/TiledView.ts | 188 + studio/src/renderer/src/map/census.ts | 85 + studio/src/renderer/src/map/heightColors.ts | 76 + studio/src/renderer/src/map/map.test.ts | 323 ++ studio/src/renderer/src/map/mapTileSource.ts | 61 + studio/src/renderer/src/map/playerArrow.ts | 85 + studio/src/renderer/src/map/tileDrawing.ts | 82 + studio/src/renderer/src/map/tileStyle.ts | 193 + studio/src/renderer/src/map/viewport.ts | 97 + studio/src/renderer/src/noise/noise.test.ts | 60 + studio/src/renderer/src/noise/noiseScale.ts | 81 + studio/src/renderer/src/noise/noiseTerrain.ts | 62 + studio/src/renderer/src/noise/noiseTiles.ts | 77 + .../src/renderer/src/pattern/patternTiles.ts | 152 + studio/src/renderer/src/scene/BridgeAssets.ts | 44 + .../src/renderer/src/scene/bakeTiming.test.ts | 81 + studio/src/renderer/src/scene/bakeTiming.ts | 87 + studio/src/renderer/src/scene/blockArt.ts | 57 + studio/src/renderer/src/scene/blockColors.ts | 100 + .../src/renderer/src/scene/blockLooks.test.ts | 153 + studio/src/renderer/src/scene/blockLooks.ts | 151 + .../renderer/src/scene/blockModels.test.ts | 68 + studio/src/renderer/src/scene/blockModels.ts | 389 ++ .../src/renderer/src/scene/blockPick.test.ts | 43 + studio/src/renderer/src/scene/blockPick.ts | 38 + studio/src/renderer/src/scene/blockTints.ts | 51 + studio/src/renderer/src/scene/cameraSight.ts | 130 + studio/src/renderer/src/scene/columnFaces.ts | 214 + studio/src/renderer/src/scene/columnField.ts | 185 + .../src/scene/compactGeometry.test.ts | 37 + .../src/renderer/src/scene/compactGeometry.ts | 68 + studio/src/renderer/src/scene/coverFaces.ts | 45 + studio/src/renderer/src/scene/coverLooks.ts | 46 + .../src/renderer/src/scene/farLeaves.test.ts | 32 + studio/src/renderer/src/scene/farLeaves.ts | 26 + .../renderer/src/scene/groundInView.test.ts | 62 + studio/src/renderer/src/scene/groundInView.ts | 66 + .../src/renderer/src/scene/mapTerrain.test.ts | 66 + studio/src/renderer/src/scene/mapTerrain.ts | 150 + .../src/renderer/src/scene/partFocus.test.ts | 20 + studio/src/renderer/src/scene/partFocus.ts | 14 + .../renderer/src/scene/pendingWork.test.ts | 19 + studio/src/renderer/src/scene/pendingWork.ts | 17 + studio/src/renderer/src/scene/quadBatch.ts | 118 + studio/src/renderer/src/scene/raisedFaces.ts | 71 + .../src/renderer/src/scene/runFaces.test.ts | 121 + studio/src/renderer/src/scene/runFaces.ts | 258 + .../renderer/src/scene/savedTerrain.test.ts | 64 + studio/src/renderer/src/scene/savedTerrain.ts | 81 + .../src/renderer/src/scene/savedTileSource.ts | 31 + .../src/renderer/src/scene/sceneDecoding.ts | 32 + studio/src/renderer/src/scene/sceneMesh.ts | 201 + studio/src/renderer/src/scene/skyLight.ts | 39 + .../renderer/src/scene/surfaceMarch.test.ts | 72 + studio/src/renderer/src/scene/surfaceMarch.ts | 47 + .../renderer/src/scene/surfacePick.test.ts | 34 + studio/src/renderer/src/scene/surfacePick.ts | 12 + .../renderer/src/scene/terrainAtlas.test.ts | 23 + studio/src/renderer/src/scene/terrainAtlas.ts | 207 + .../renderer/src/scene/terrainCover.test.ts | 151 + studio/src/renderer/src/scene/terrainCover.ts | 164 + .../renderer/src/scene/terrainMesh.test.ts | 216 + studio/src/renderer/src/scene/terrainMesh.ts | 173 + .../renderer/src/scene/terrainMeshWorker.ts | 56 + .../renderer/src/scene/terrainMeshWorkers.ts | 74 + .../renderer/src/scene/terrainStream.test.ts | 285 + .../src/renderer/src/scene/terrainStream.ts | 465 ++ .../renderer/src/scene/terrainTiles.test.ts | 46 + studio/src/renderer/src/scene/terrainTiles.ts | 98 + studio/src/renderer/src/scene/textureAtlas.ts | 104 + .../src/scene/texturedTerrain.test.ts | 209 + .../src/renderer/src/scene/voxelMesh.test.ts | 110 + studio/src/renderer/src/scene/voxelMesh.ts | 271 + studio/src/renderer/src/scene/waterTint.ts | 34 + studio/src/renderer/src/studio/BakeMeter.tsx | 87 + studio/src/renderer/src/studio/BlockIcon.tsx | 34 + .../src/renderer/src/studio/ConnectScreen.tsx | 93 + studio/src/renderer/src/studio/CurveField.tsx | 190 + .../src/renderer/src/studio/EntryBrowser.tsx | 255 + .../renderer/src/studio/EntryFileDialogs.tsx | 150 + studio/src/renderer/src/studio/FieldRow.tsx | 41 + studio/src/renderer/src/studio/HelpDialog.tsx | 50 + studio/src/renderer/src/studio/HoverCard.tsx | 145 + studio/src/renderer/src/studio/Legend.tsx | 92 + studio/src/renderer/src/studio/MapCanvas.tsx | 204 + studio/src/renderer/src/studio/MapStudio.tsx | 525 ++ studio/src/renderer/src/studio/NodeCanvas.tsx | 314 ++ .../src/renderer/src/studio/NodeInspector.tsx | 295 ++ studio/src/renderer/src/studio/NodePane.tsx | 110 + studio/src/renderer/src/studio/NoiseChart.tsx | 131 + .../src/renderer/src/studio/NoiseStudio.tsx | 338 ++ .../src/renderer/src/studio/PatternStudio.tsx | 206 + .../src/renderer/src/studio/PickInspector.tsx | 120 + studio/src/renderer/src/studio/PickRows.tsx | 86 + .../renderer/src/studio/RegionPreviewList.tsx | 72 + .../renderer/src/studio/SavedWorldStudio.tsx | 209 + .../src/renderer/src/studio/SceneStudio.tsx | 406 ++ .../src/renderer/src/studio/SceneViewport.tsx | 379 ++ .../renderer/src/studio/ShortcutSettings.tsx | 167 + studio/src/renderer/src/studio/Sidebar.tsx | 98 + studio/src/renderer/src/studio/StatusBar.tsx | 104 + .../src/renderer/src/studio/StudioToolbar.tsx | 147 + .../renderer/src/studio/SuggestionInput.tsx | 91 + .../src/renderer/src/studio/TiledCanvas.tsx | 78 + studio/src/renderer/src/studio/ViewList.tsx | 145 + .../src/renderer/src/studio/WorldStudio3D.tsx | 189 + studio/src/renderer/src/studio/colors.ts | 4 + .../renderer/src/studio/serverUsage.test.ts | 31 + studio/src/renderer/src/studio/serverUsage.ts | 27 + .../renderer/src/studio/shortcutStore.test.ts | 67 + .../src/renderer/src/studio/shortcutStore.ts | 69 + .../src/renderer/src/studio/shortcuts.test.ts | 129 + studio/src/renderer/src/studio/shortcuts.ts | 261 + studio/src/renderer/src/studio/theme.ts | 33 + studio/src/renderer/src/studio/useBindings.ts | 19 + .../renderer/src/studio/usePickInspection.ts | 38 + .../renderer/src/studio/useSpotActions.tsx | 46 + .../renderer/src/studio/useTerrainStream.ts | 91 + .../src/renderer/src/studio/useWorldCaves.ts | 92 + studio/src/renderer/src/styles.css | 118 + studio/src/shared/bridge.ts | 52 + studio/tsconfig.json | 19 + 252 files changed, 24496 insertions(+) create mode 100644 studio/.gitignore create mode 100644 studio/LICENSE create mode 100644 studio/components.json create mode 100644 studio/electron.vite.config.ts create mode 100644 studio/package-lock.json create mode 100644 studio/package.json create mode 100644 studio/src/main/dedicatedGpu.ts create mode 100644 studio/src/main/index.ts create mode 100644 studio/src/preload/index.ts create mode 100644 studio/src/renderer/index.html create mode 100644 studio/src/renderer/src/App.tsx create mode 100644 studio/src/renderer/src/bridge/BridgeClient.ts create mode 100644 studio/src/renderer/src/bridge/patternDecoding.test.ts create mode 100644 studio/src/renderer/src/bridge/patternDecoding.ts create mode 100644 studio/src/renderer/src/bridge/savedTileDecoding.ts create mode 100644 studio/src/renderer/src/bridge/tileDecoding.ts create mode 100644 studio/src/renderer/src/bridge/types.ts create mode 100644 studio/src/renderer/src/components/IdeIcon.tsx create mode 100644 studio/src/renderer/src/components/ui/button.tsx create mode 100644 studio/src/renderer/src/components/ui/context-menu.tsx create mode 100644 studio/src/renderer/src/components/ui/dialog.tsx create mode 100644 studio/src/renderer/src/components/ui/input.tsx create mode 100644 studio/src/renderer/src/components/ui/kbd.tsx create mode 100644 studio/src/renderer/src/components/ui/scroll-area.tsx create mode 100644 studio/src/renderer/src/components/ui/separator.tsx create mode 100644 studio/src/renderer/src/components/ui/toggle-group.tsx create mode 100644 studio/src/renderer/src/components/ui/toggle.tsx create mode 100644 studio/src/renderer/src/components/ui/tooltip.tsx create mode 100644 studio/src/renderer/src/css.d.ts create mode 100644 studio/src/renderer/src/editor/EditHistory.test.ts create mode 100644 studio/src/renderer/src/editor/EditHistory.ts create mode 100644 studio/src/renderer/src/editor/curves.test.ts create mode 100644 studio/src/renderer/src/editor/curves.ts create mode 100644 studio/src/renderer/src/editor/entryKeys.test.ts create mode 100644 studio/src/renderer/src/editor/entryKeys.ts create mode 100644 studio/src/renderer/src/editor/jsonValues.ts create mode 100644 studio/src/renderer/src/editor/nodeLayout.test.ts create mode 100644 studio/src/renderer/src/editor/nodeLayout.ts create mode 100644 studio/src/renderer/src/editor/settingFolds.test.ts create mode 100644 studio/src/renderer/src/editor/settingFolds.ts create mode 100644 studio/src/renderer/src/editor/settingText.test.ts create mode 100644 studio/src/renderer/src/editor/settingText.ts create mode 100644 studio/src/renderer/src/editor/suggestionStore.test.ts create mode 100644 studio/src/renderer/src/editor/suggestionStore.ts create mode 100644 studio/src/renderer/src/editor/suggestions.test.ts create mode 100644 studio/src/renderer/src/editor/suggestions.ts create mode 100644 studio/src/renderer/src/editor/useNodeEditor.ts create mode 100644 studio/src/renderer/src/env.d.ts create mode 100644 studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt create mode 100644 studio/src/renderer/src/icons/NOTICE.txt create mode 100644 studio/src/renderer/src/icons/actualZoom.svg create mode 100644 studio/src/renderer/src/icons/actualZoom_dark.svg create mode 100644 studio/src/renderer/src/icons/add.svg create mode 100644 studio/src/renderer/src/icons/add_dark.svg create mode 100644 studio/src/renderer/src/icons/blocks.svg create mode 100644 studio/src/renderer/src/icons/blocks_dark.svg create mode 100644 studio/src/renderer/src/icons/borders.svg create mode 100644 studio/src/renderer/src/icons/borders_dark.svg create mode 100644 studio/src/renderer/src/icons/checked.svg create mode 100644 studio/src/renderer/src/icons/checked_dark.svg create mode 100644 studio/src/renderer/src/icons/chevronLeft.svg create mode 100644 studio/src/renderer/src/icons/chevronLeft_dark.svg create mode 100644 studio/src/renderer/src/icons/chevronRight.svg create mode 100644 studio/src/renderer/src/icons/chevronRight_dark.svg create mode 100644 studio/src/renderer/src/icons/closeSmall.svg create mode 100644 studio/src/renderer/src/icons/closeSmall_dark.svg create mode 100644 studio/src/renderer/src/icons/decoration.svg create mode 100644 studio/src/renderer/src/icons/decoration_dark.svg create mode 100644 studio/src/renderer/src/icons/delete.svg create mode 100644 studio/src/renderer/src/icons/delete_dark.svg create mode 100644 studio/src/renderer/src/icons/exit.svg create mode 100644 studio/src/renderer/src/icons/exit_dark.svg create mode 100644 studio/src/renderer/src/icons/grid.svg create mode 100644 studio/src/renderer/src/icons/grid_dark.svg create mode 100644 studio/src/renderer/src/icons/groups.svg create mode 100644 studio/src/renderer/src/icons/groups_dark.svg create mode 100644 studio/src/renderer/src/icons/help.svg create mode 100644 studio/src/renderer/src/icons/help_dark.svg create mode 100644 studio/src/renderer/src/icons/lightning.svg create mode 100644 studio/src/renderer/src/icons/lightning_dark.svg create mode 100644 studio/src/renderer/src/icons/locate.svg create mode 100644 studio/src/renderer/src/icons/locate_dark.svg create mode 100644 studio/src/renderer/src/icons/locked.svg create mode 100644 studio/src/renderer/src/icons/locked_dark.svg create mode 100644 studio/src/renderer/src/icons/memory.svg create mode 100644 studio/src/renderer/src/icons/memory_dark.svg create mode 100644 studio/src/renderer/src/icons/mob.svg create mode 100644 studio/src/renderer/src/icons/mob_dark.svg create mode 100644 studio/src/renderer/src/icons/redo.svg create mode 100644 studio/src/renderer/src/icons/redo_dark.svg create mode 100644 studio/src/renderer/src/icons/refresh.svg create mode 100644 studio/src/renderer/src/icons/refresh_dark.svg create mode 100644 studio/src/renderer/src/icons/reset.svg create mode 100644 studio/src/renderer/src/icons/reset_dark.svg create mode 100644 studio/src/renderer/src/icons/search.svg create mode 100644 studio/src/renderer/src/icons/search_dark.svg create mode 100644 studio/src/renderer/src/icons/settings.svg create mode 100644 studio/src/renderer/src/icons/settings_dark.svg create mode 100644 studio/src/renderer/src/icons/shading.svg create mode 100644 studio/src/renderer/src/icons/shading_dark.svg create mode 100644 studio/src/renderer/src/icons/stopWatch.svg create mode 100644 studio/src/renderer/src/icons/stopWatch_dark.svg create mode 100644 studio/src/renderer/src/icons/symlink.svg create mode 100644 studio/src/renderer/src/icons/symlink_dark.svg create mode 100644 studio/src/renderer/src/icons/theme.svg create mode 100644 studio/src/renderer/src/icons/theme_dark.svg create mode 100644 studio/src/renderer/src/icons/undo.svg create mode 100644 studio/src/renderer/src/icons/undo_dark.svg create mode 100644 studio/src/renderer/src/icons/views/biomes.svg create mode 100644 studio/src/renderer/src/icons/views/biomes_dark.svg create mode 100644 studio/src/renderer/src/icons/views/noise.svg create mode 100644 studio/src/renderer/src/icons/views/noise_dark.svg create mode 100644 studio/src/renderer/src/icons/views/objects.svg create mode 100644 studio/src/renderer/src/icons/views/objects_dark.svg create mode 100644 studio/src/renderer/src/icons/views/palettes.svg create mode 100644 studio/src/renderer/src/icons/views/palettes_dark.svg create mode 100644 studio/src/renderer/src/icons/views/procedural.svg create mode 100644 studio/src/renderer/src/icons/views/procedural_dark.svg create mode 100644 studio/src/renderer/src/icons/views/regions.svg create mode 100644 studio/src/renderer/src/icons/views/regions_dark.svg create mode 100644 studio/src/renderer/src/icons/views/saved-world.svg create mode 100644 studio/src/renderer/src/icons/views/saved-world_dark.svg create mode 100644 studio/src/renderer/src/icons/views/world-3d.svg create mode 100644 studio/src/renderer/src/icons/views/world-3d_dark.svg create mode 100644 studio/src/renderer/src/icons/web.svg create mode 100644 studio/src/renderer/src/icons/web_dark.svg create mode 100644 studio/src/renderer/src/lib/utils.ts create mode 100644 studio/src/renderer/src/main.tsx create mode 100644 studio/src/renderer/src/map/MapController.ts create mode 100644 studio/src/renderer/src/map/TileStore.ts create mode 100644 studio/src/renderer/src/map/TiledView.ts create mode 100644 studio/src/renderer/src/map/census.ts create mode 100644 studio/src/renderer/src/map/heightColors.ts create mode 100644 studio/src/renderer/src/map/map.test.ts create mode 100644 studio/src/renderer/src/map/mapTileSource.ts create mode 100644 studio/src/renderer/src/map/playerArrow.ts create mode 100644 studio/src/renderer/src/map/tileDrawing.ts create mode 100644 studio/src/renderer/src/map/tileStyle.ts create mode 100644 studio/src/renderer/src/map/viewport.ts create mode 100644 studio/src/renderer/src/noise/noise.test.ts create mode 100644 studio/src/renderer/src/noise/noiseScale.ts create mode 100644 studio/src/renderer/src/noise/noiseTerrain.ts create mode 100644 studio/src/renderer/src/noise/noiseTiles.ts create mode 100644 studio/src/renderer/src/pattern/patternTiles.ts create mode 100644 studio/src/renderer/src/scene/BridgeAssets.ts create mode 100644 studio/src/renderer/src/scene/bakeTiming.test.ts create mode 100644 studio/src/renderer/src/scene/bakeTiming.ts create mode 100644 studio/src/renderer/src/scene/blockArt.ts create mode 100644 studio/src/renderer/src/scene/blockColors.ts create mode 100644 studio/src/renderer/src/scene/blockLooks.test.ts create mode 100644 studio/src/renderer/src/scene/blockLooks.ts create mode 100644 studio/src/renderer/src/scene/blockModels.test.ts create mode 100644 studio/src/renderer/src/scene/blockModels.ts 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/blockTints.ts create mode 100644 studio/src/renderer/src/scene/cameraSight.ts create mode 100644 studio/src/renderer/src/scene/columnFaces.ts create mode 100644 studio/src/renderer/src/scene/columnField.ts create mode 100644 studio/src/renderer/src/scene/compactGeometry.test.ts create mode 100644 studio/src/renderer/src/scene/compactGeometry.ts create mode 100644 studio/src/renderer/src/scene/coverFaces.ts create mode 100644 studio/src/renderer/src/scene/coverLooks.ts create mode 100644 studio/src/renderer/src/scene/farLeaves.test.ts create mode 100644 studio/src/renderer/src/scene/farLeaves.ts create mode 100644 studio/src/renderer/src/scene/groundInView.test.ts create mode 100644 studio/src/renderer/src/scene/groundInView.ts create mode 100644 studio/src/renderer/src/scene/mapTerrain.test.ts create mode 100644 studio/src/renderer/src/scene/mapTerrain.ts create mode 100644 studio/src/renderer/src/scene/partFocus.test.ts create mode 100644 studio/src/renderer/src/scene/partFocus.ts create mode 100644 studio/src/renderer/src/scene/pendingWork.test.ts create mode 100644 studio/src/renderer/src/scene/pendingWork.ts create mode 100644 studio/src/renderer/src/scene/quadBatch.ts create mode 100644 studio/src/renderer/src/scene/raisedFaces.ts create mode 100644 studio/src/renderer/src/scene/runFaces.test.ts create mode 100644 studio/src/renderer/src/scene/runFaces.ts create mode 100644 studio/src/renderer/src/scene/savedTerrain.test.ts create mode 100644 studio/src/renderer/src/scene/savedTerrain.ts create mode 100644 studio/src/renderer/src/scene/savedTileSource.ts create mode 100644 studio/src/renderer/src/scene/sceneDecoding.ts create mode 100644 studio/src/renderer/src/scene/sceneMesh.ts create mode 100644 studio/src/renderer/src/scene/skyLight.ts create mode 100644 studio/src/renderer/src/scene/surfaceMarch.test.ts create mode 100644 studio/src/renderer/src/scene/surfaceMarch.ts create mode 100644 studio/src/renderer/src/scene/surfacePick.test.ts create mode 100644 studio/src/renderer/src/scene/surfacePick.ts create mode 100644 studio/src/renderer/src/scene/terrainAtlas.test.ts create mode 100644 studio/src/renderer/src/scene/terrainAtlas.ts create mode 100644 studio/src/renderer/src/scene/terrainCover.test.ts create mode 100644 studio/src/renderer/src/scene/terrainCover.ts create mode 100644 studio/src/renderer/src/scene/terrainMesh.test.ts create mode 100644 studio/src/renderer/src/scene/terrainMesh.ts create mode 100644 studio/src/renderer/src/scene/terrainMeshWorker.ts create mode 100644 studio/src/renderer/src/scene/terrainMeshWorkers.ts create mode 100644 studio/src/renderer/src/scene/terrainStream.test.ts create mode 100644 studio/src/renderer/src/scene/terrainStream.ts create mode 100644 studio/src/renderer/src/scene/terrainTiles.test.ts create mode 100644 studio/src/renderer/src/scene/terrainTiles.ts create mode 100644 studio/src/renderer/src/scene/textureAtlas.ts create mode 100644 studio/src/renderer/src/scene/texturedTerrain.test.ts create mode 100644 studio/src/renderer/src/scene/voxelMesh.test.ts create mode 100644 studio/src/renderer/src/scene/voxelMesh.ts create mode 100644 studio/src/renderer/src/scene/waterTint.ts create mode 100644 studio/src/renderer/src/studio/BakeMeter.tsx create mode 100644 studio/src/renderer/src/studio/BlockIcon.tsx create mode 100644 studio/src/renderer/src/studio/ConnectScreen.tsx create mode 100644 studio/src/renderer/src/studio/CurveField.tsx create mode 100644 studio/src/renderer/src/studio/EntryBrowser.tsx create mode 100644 studio/src/renderer/src/studio/EntryFileDialogs.tsx create mode 100644 studio/src/renderer/src/studio/FieldRow.tsx create mode 100644 studio/src/renderer/src/studio/HelpDialog.tsx create mode 100644 studio/src/renderer/src/studio/HoverCard.tsx create mode 100644 studio/src/renderer/src/studio/Legend.tsx create mode 100644 studio/src/renderer/src/studio/MapCanvas.tsx create mode 100644 studio/src/renderer/src/studio/MapStudio.tsx create mode 100644 studio/src/renderer/src/studio/NodeCanvas.tsx create mode 100644 studio/src/renderer/src/studio/NodeInspector.tsx create mode 100644 studio/src/renderer/src/studio/NodePane.tsx create mode 100644 studio/src/renderer/src/studio/NoiseChart.tsx create mode 100644 studio/src/renderer/src/studio/NoiseStudio.tsx create mode 100644 studio/src/renderer/src/studio/PatternStudio.tsx create mode 100644 studio/src/renderer/src/studio/PickInspector.tsx create mode 100644 studio/src/renderer/src/studio/PickRows.tsx create mode 100644 studio/src/renderer/src/studio/RegionPreviewList.tsx create mode 100644 studio/src/renderer/src/studio/SavedWorldStudio.tsx create mode 100644 studio/src/renderer/src/studio/SceneStudio.tsx create mode 100644 studio/src/renderer/src/studio/SceneViewport.tsx create mode 100644 studio/src/renderer/src/studio/ShortcutSettings.tsx create mode 100644 studio/src/renderer/src/studio/Sidebar.tsx create mode 100644 studio/src/renderer/src/studio/StatusBar.tsx create mode 100644 studio/src/renderer/src/studio/StudioToolbar.tsx create mode 100644 studio/src/renderer/src/studio/SuggestionInput.tsx create mode 100644 studio/src/renderer/src/studio/TiledCanvas.tsx create mode 100644 studio/src/renderer/src/studio/ViewList.tsx create mode 100644 studio/src/renderer/src/studio/WorldStudio3D.tsx create mode 100644 studio/src/renderer/src/studio/colors.ts create mode 100644 studio/src/renderer/src/studio/serverUsage.test.ts create mode 100644 studio/src/renderer/src/studio/serverUsage.ts create mode 100644 studio/src/renderer/src/studio/shortcutStore.test.ts create mode 100644 studio/src/renderer/src/studio/shortcutStore.ts create mode 100644 studio/src/renderer/src/studio/shortcuts.test.ts create mode 100644 studio/src/renderer/src/studio/shortcuts.ts create mode 100644 studio/src/renderer/src/studio/theme.ts create mode 100644 studio/src/renderer/src/studio/useBindings.ts create mode 100644 studio/src/renderer/src/studio/usePickInspection.ts create mode 100644 studio/src/renderer/src/studio/useSpotActions.tsx create mode 100644 studio/src/renderer/src/studio/useTerrainStream.ts create mode 100644 studio/src/renderer/src/studio/useWorldCaves.ts create mode 100644 studio/src/renderer/src/styles.css create mode 100644 studio/src/shared/bridge.ts create mode 100644 studio/tsconfig.json diff --git a/studio/.gitignore b/studio/.gitignore new file mode 100644 index 000000000..3794c4269 --- /dev/null +++ b/studio/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +out/ +dist/ +*.log diff --git a/studio/LICENSE b/studio/LICENSE new file mode 100644 index 000000000..0a74fe454 --- /dev/null +++ b/studio/LICENSE @@ -0,0 +1,518 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the +works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all +versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies also to any other work released this way by its +authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make +sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive +source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and +that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. +Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: +responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients +the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must +show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute +and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. +For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems +will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although +the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the +software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely +where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict +development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger +that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". " +Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, +other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a +work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily +liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), making available to the public, and in some +countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction +with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright +notice, and (2) +tells the user that there is no warranty for the work (except to the extent that warranties are provided), that +licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a +list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means +any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, +or, in the case of interfaces specified for a particular programming language, one that is widely used among developers +working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in +the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to +enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is +available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used +to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and ( +for an executable work) run the object code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs +which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding +Source includes interface definition files associated with source files for the work, and the source code for shared +libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data +communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the +Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided +the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. +The output from running a covered work is covered by this License only if the output, given its content, constitutes a +covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license +otherwise remains in force. You may convey covered works to others for the sole purpose of having them make +modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do not control copyright. Those thus making or running +the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that +prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not +allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling +obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the +extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you +disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, +your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices +of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for +a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source +code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of +the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or +distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the +compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause +this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, +need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used +for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In +determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a +particular product received by a particular user, "normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way in which the particular user actually uses, or +expects or is expected to use, the product. A product is a consumer product regardless of whether the product has +substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of +the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information +required to install and execute modified versions of a covered work in that User Product from a modified version of its +Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code +is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the +conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to +the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding +Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not +apply if neither you nor any third party retains the ability to install modified object code on the User Product (for +example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support +service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product +in which it has been modified or installed. Access to a network may be denied when the modification itself materially +and adversely affects the operation of the network or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format +that is publicly documented (and with an implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of +its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were +included in this License, to the extent that they are valid under applicable law. If additional permissions apply only +to part of the Program, that part may be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or +from any part of it. (Additional permissions may be written to require their own removal in certain cases when you +modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have +or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by +the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the +Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with +a term that is a further restriction, you may remove that term. If a license document contains a further restriction but +permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of +that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a +statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as +exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to +propagate or modify it is void, and will automatically terminate your rights under this License (including any patent +licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is +reinstated (a) +provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) +permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days +after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you +of the violation by some reasonable means, this is the first time you have received notice of violation of this +License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the +notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or +rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a +covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not +require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered +work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, +modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third +parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or +subdividing an organization, or merging organizations. If propagation of a covered work results from an entity +transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work +the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with +reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For +example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, +and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, +selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the +Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already +acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or +selling its contributor version, but do not include claims that would be infringed only as a consequence of further +modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent +sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential +patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its +contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not +to enforce a patent +(such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a +patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not +available for anyone to copy, free of charge and under the terms of this License, through a publicly available network +server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, +or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a +manner consistent with the requirements of this License, to extend the patent license to downstream recipients. " +Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in +a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in +that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring +conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is +automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, +or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You +may not convey a covered work if you are a party to an arrangement with a third party that is in the business of +distributing software, under which you make payment to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a +discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from +those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered +work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to +infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this +License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to +satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence +you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further +conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License +would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work +licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special +requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply +to the combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to +time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new +problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the +GNU General Public License "or any later version" applies to it, you have the option of following the terms and +conditions either of that numbered version or of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, +that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the +Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed +on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING +THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU +ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO +MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO +LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to +their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program +in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve +this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to +most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer +to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of +course, your program's commands might be different; for a GUI interface, you would use an "about box". + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for +the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see +. + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is +a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If +this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read +. diff --git a/studio/components.json b/studio/components.json new file mode 100644 index 000000000..7ce205491 --- /dev/null +++ b/studio/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/renderer/src/styles.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} diff --git a/studio/electron.vite.config.ts b/studio/electron.vite.config.ts new file mode 100644 index 000000000..0508e88c4 --- /dev/null +++ b/studio/electron.vite.config.ts @@ -0,0 +1,21 @@ +import { resolve } from 'node:path' +import { defineConfig } from 'electron-vite' +import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + main: {}, + preload: { + build: { + rollupOptions: { + output: { format: 'cjs', entryFileNames: '[name].cjs' } + } + } + }, + renderer: { + resolve: { + alias: { '@': resolve(import.meta.dirname, 'src/renderer/src') } + }, + plugins: [react(), tailwindcss()] + } +}) diff --git a/studio/package-lock.json b/studio/package-lock.json new file mode 100644 index 000000000..fec043457 --- /dev/null +++ b/studio/package-lock.json @@ -0,0 +1,4574 @@ +{ + "name": "iris-studio", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "iris-studio", + "version": "0.1.0", + "dependencies": { + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cn": "^0.5.2", + "radix-ui": "^1.8.1", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "tailwind-merge": "^3.7.0", + "three": "^0.187.0" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.4", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/three": "^0.187.0", + "@vitejs/plugin-react": "^6.2.1", + "electron": "^45.2.3", + "electron-vite": "^6.0.0", + "tailwindcss": "^4.3.4", + "typescript": "^7.0.2", + "vite": "^8.3.6", + "vitest": "^5.1.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.13.tgz", + "integrity": "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.13.tgz", + "integrity": "sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.13" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", + "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.13.tgz", + "integrity": "sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.13.tgz", + "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.29.7.tgz", + "integrity": "sha512-N7zArUXWzAMzm+/N0uPBeVB3Fam5lMxtUwMmDK5f/IBBS7a7p1qeUoxd/6CckXoxUdgsntq1Dh8xNW06maZbDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.13.tgz", + "integrity": "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.11", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@electron-internal/extract-zip": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz", + "integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@electron/get": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz", + "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^3.0.0", + "graceful-fs": "^4.2.11", + "progress": "^2.0.3", + "semver": "^7.6.3", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=22.12.0" + }, + "optionalDependencies": { + "undici": "^7.24.4" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@radix-ui/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", + "license": "MIT" + }, + "node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-accessible-icon": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.2.0.tgz", + "integrity": "sha512-BB4+HHkFl3HipEAhm/mLhrpXV+2kRX7MvY4AaImUcQVeWQt5KhV1JEByNs8NGfJOcr95RcQGijt9+OrCo68xGA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-accordion": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.3.1.tgz", + "integrity": "sha512-lCZ6sbGS/7WO0j84yx4srIgOf0MRJ/sZ13RonADXxvKBym8xrxNCq5f6DibGcr38sIlwPk8/52uYdXeOPsbEDw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collapsible": "1.2.1", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-alert-dialog": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.2.1.tgz", + "integrity": "sha512-MWC4N7RY+qsbNrFNo7yQ9ZbdoZEW+B5DtpWxJfUnVCqcQxxqqg3qis3RMPTDbCNaTIdHJSn5XDkl9ZdVWXknLg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dialog": "1.3.1", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-arrow": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.17.tgz", + "integrity": "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-aspect-ratio": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.2.0.tgz", + "integrity": "sha512-gHEU+Lx8DlT/FYIjZQvvBJrFSwUngXTjh7FeL9QvJaNALDLez6pgDj2axCUihBjtPBy82LN0gNb25+sTcSXNmA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-avatar": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.3.1.tgz", + "integrity": "sha512-ssZOkfQNkFpYVmCPQlr978xSaU7moSrGXdwg4j2Xs2WlGl/1KsSZtfpK+WnLnx0Rwll1BAh6oUrAy/uR31SBvQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-checkbox": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.4.1.tgz", + "integrity": "sha512-KWtwhh+98ML3seZ9vO9yRY2OwaQG90dCiDAxjpSNY2AaZ3Hik3B0dsk6m0ILywo/no3A9/SozadyPMNweVT8yw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collapsible": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.2.1.tgz", + "integrity": "sha512-fSzLb/qy1wuZSxQBcxpW0hNXYHDMWiIXDGyJGdA4+FSLknOWZsNRrTCUavxb4PI8b8lvHo/CysO6NVi5zLpo5g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-context-menu": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.4.1.tgz", + "integrity": "sha512-Pddn3Z8lio3/ChxyXaEP3jHTTo1LTHCWwF8+mG1chQlWijP+ttVHBKwezrQTiV6Mj670ojvumqvuGh+mdv33iQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dialog": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.3.1.tgz", + "integrity": "sha512-+0E4qvVTwjAWra9sEhJ+9BTsvHE00zkUuNw1VGh7S+Gc13dfYk+S1PVQdchWDj+XYHhAai7Z7IpzXVDCGsDplg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.2.1.tgz", + "integrity": "sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-dropdown-menu": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.2.1.tgz", + "integrity": "sha512-XsHcmYG2AcqnvTqrOXXWcMrhquEIlqucizuDH1MV/qMRW+DndpBCMvNeTRXOxqmG1H5j89M/+I0/34Zdd+zDcQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-guards": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.2.0.tgz", + "integrity": "sha512-MPm5R0iRGUDrDnPNxmLBkv+X7pN4XKzt+MbWJEuJQsH3NFH4omrbpXpucyYCCKTSt+na/ZxGhEWQrWTZ0285cA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-focus-scope": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.3.1.tgz", + "integrity": "sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-form": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-form/-/react-form-0.3.0.tgz", + "integrity": "sha512-KnmrCM27m7Jo1R8S6cFDPrEeq20Jfn5dqde0SZrJr2lVXlj6/QZSUCyFoYh1d8ti0uUrMNK5Lx6dUDuINT+f4Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-hover-card": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.2.1.tgz", + "integrity": "sha512-4QooHxgmpCKRjj1Pft+hETKidYcrbPKcVwMGtk2Oa5DcWY2IH1fHuQt9LG6q5hUQBBV2MhQxSvtx6B/C1xfiTw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-label": { + "version": "2.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.17.tgz", + "integrity": "sha512-xmj7MN/drx1oUAXkfiFIvyDmGNUIN/omGobvA5oAoNqu9zO2MkISYGZOkBcqSzs/UZXXwV+/3ACRE7q7mGcmkA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menu": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.2.1.tgz", + "integrity": "sha512-G34BsU90SBj5foYpz8pQqq/Q0Dlfyyl6KitWEfRwXC0QvfwhWNAwS49DWP2+rRJ0iwv20Z2Qx7Sk+T03bGo5JA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-menubar": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.2.1.tgz", + "integrity": "sha512-bRTYtS9JITV2dUYqYZb7+N5SooQBkZrNRejfmyrSKe3Y57aXhKgx//kBUP0kY7pEpsWR/U1AHsAJRzjwCrK3PA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-navigation-menu": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.4.1.tgz", + "integrity": "sha512-XPPZjkeyCSMNNvt0FyDv/PUauG7Ow4GwHQ/XZSwW36F/TS7rR4HFTsXH8ewLnXTOLn3x96/pmTPNQIVoTX/86g==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-previous": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-one-time-password-field": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.2.1.tgz", + "integrity": "sha512-KtHdcgnaAK6rohQ/MMJoGYcbgSRJsIuGBdHrFeTB1/9SaKlDs14oSOniW6BL6M43HqvgCO3u4WuVdFLkuc6sqw==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-password-toggle-field": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.2.1.tgz", + "integrity": "sha512-vu4+ZoJAaFjdI7l1lDSZRs+4dEv83Jmu7lyzajPrAeQzX74y84n0rUNWbWSgN9XB5NE8IY86Z02kGH6oRrzR+w==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-is-hydrated": "0.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popover": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.3.1.tgz", + "integrity": "sha512-ZNxvXRx5W2Wos4fXCXb5lpdqN0Z5chf+mStOUOTr4ik7d+62MRvoe9rzCA/eGNg36lxXqSrKEKmwuZEcUrIstw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-popper": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.4.0.tgz", + "integrity": "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-portal": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.2.0.tgz", + "integrity": "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-progress": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.2.1.tgz", + "integrity": "sha512-yQBiM6J3YM8Ums1orkEFpbznK47geKxa0igikzcaS1xHgdba3DdAQBsGbCTt5BVfR8zhEvgxQ0poGcINaD3lvw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.5.1.tgz", + "integrity": "sha512-QbyVT1ddnjqB9H+CUYKkNWdU9fIK3QHCYtjf7mS6ekSqiuXkWtWn5UZW9mhA8qtl3vrVyIsmR9gePstAtKrqkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-roving-focus": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.2.1.tgz", + "integrity": "sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-scroll-area": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.4.0.tgz", + "integrity": "sha512-CFrLqHNejWq5FhKAcj9V/WPGRsol76HBQto81NdOBVFEOqIEkJkKIJt0Z824A/9hHLCtoiR/Kw3euRgzXP2pxg==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-select": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.4.1.tgz", + "integrity": "sha512-888ZwW0Md6GyptuqYABRX9nLKgoYfcooCyBBvVaX5Jp3e+8Jp2i4Zo/Uy50Hm+Ysn2JfloQXstW4U36w8teVtg==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13", + "aria-hidden": "^1.2.4", + "react-remove-scroll": "^2.7.2" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-separator": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.2.0.tgz", + "integrity": "sha512-1jUAap0wZEqVP05Ou7kJgRxe/W+Qftng+rUNWGa0qkKbv9r5pWTG3E7a3ELKo2eJoHKMECnzuYrZpSyO1YgcYQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.6.1.tgz", + "integrity": "sha512-IRNRR90moPqxfwCJ0XbMJIxo70W0/1ZExT/sNCxEHMaPx0SF9HoQrcPEC75+H28cFKa0b+KH63anfLYJmwKacw==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-switch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.4.1.tgz", + "integrity": "sha512-NpBGwc40rY02ZmSvuyeKk0Bvc8ZsNeTMi4qHvJ+ZH4EiYCv0zIXEgdCW4bVdzgIUeP9xxbLJSxKOUfqITYNmkA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tabs": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.2.1.tgz", + "integrity": "sha512-hRoJlode+hg5ZNlR+3tkfkUliIybdTpD5lkAvHQ9yaXseGf7XVO9Ib2GPEIOuaJJbo7YWYbNpDDRfo8Dhf6/xA==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toast": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.3.1.tgz", + "integrity": "sha512-iQvL0J7XK4HtJNGkkWMyYrboNseI7vtotFeUkIno8YNxVA9oM7B6//fh0Mc6TSKI96+zioLWi98lQLso88yJmQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.2.1.tgz", + "integrity": "sha512-+3MUq+WyiBplXYqQ0EIYlq8R4sLQ0T5NbOK7DMdDLCKO93pe2uE0DUJTWWfTBprpJJXxfoF3eMW0xpakVZrYsg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toggle-group": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.2.1.tgz", + "integrity": "sha512-O8Ldx5ao4p4KoW+DO8/PmkOe5mdKNi3F2SseqjVj88wvDGDHe60cUmO0Zm/uHsKrvNgQGV8Efpuh95Tht/h4vw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-toggle": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-toolbar": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-toolbar/-/react-toolbar-1.2.1.tgz", + "integrity": "sha512-Cm8m7JTEeUdbfA6T9xgyu8HfOpyvSx8pB/wj0DlEuWaJe9FilIs4Az9wci/lU9RbthV/UkltszMw5WnnD+m/Ug==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-toggle-group": "1.2.1" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.4.1.tgz", + "integrity": "sha512-NxLFGSFtZ78zVfcoOhTwR1xwqo5qx1Jh8Pw6FMZ9McCaqfRzz7/gIRahs2Oy5XlPgQ+8QkUcKbN5B0U44J/kCg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-escape-keydown": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.6.tgz", + "integrity": "sha512-9cRullnQRv+kqnRmFlmh0WC3kAPuGmHiQ9VwsXdrYk//sBhgCKEttcpPEPgIQbyx6TGUmooVEHYTyohwz/lSJg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-previous": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.4.tgz", + "integrity": "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-visually-hidden": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.13.tgz", + "integrity": "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", + "license": "MIT" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", + "integrity": "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.16.tgz", + "integrity": "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.16.tgz", + "integrity": "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.16.tgz", + "integrity": "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.16.tgz", + "integrity": "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.16.tgz", + "integrity": "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.16.tgz", + "integrity": "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.16.tgz", + "integrity": "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.16.tgz", + "integrity": "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.16.tgz", + "integrity": "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.16.tgz", + "integrity": "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.16.tgz", + "integrity": "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.16.tgz", + "integrity": "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.16.tgz", + "integrity": "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.16.tgz", + "integrity": "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.4.tgz", + "integrity": "sha512-b7QK/QG04v3j04NbpG82XLCedRyulnkuwUDwRa9oK/ypnJIzMapz2Wg+0TltVczjUzDaJJHIa1+jj9aMUOFMTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.4" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.4.tgz", + "integrity": "sha512-riqsRw2sLF7B1sNCCkTl3KYXEqvhTiABzZ/4oxxHfZ3c3Td60bCBfOrUuUGOiHagd3E7V+zG46c+XBDWZGFBcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.4", + "@tailwindcss/oxide-darwin-arm64": "4.3.4", + "@tailwindcss/oxide-darwin-x64": "4.3.4", + "@tailwindcss/oxide-freebsd-x64": "4.3.4", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.4", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.4", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.4", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.4", + "@tailwindcss/oxide-linux-x64-musl": "4.3.4", + "@tailwindcss/oxide-wasm32-wasi": "4.3.4", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.4", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.4" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.4.tgz", + "integrity": "sha512-qkjxt+EFocOi3mtsUS3ndlj6yj4SHubwBdvBynLnS8T4mvSzX0Enn0CpypJKmBEtczUAXOHVZKA2zTGzSNU2Sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.4.tgz", + "integrity": "sha512-i/awUA/7mJQAbA3AzCW8aQtUh5goMieUdF1zOoclLaJUCxDvsXQ8VJqpQZY3dfcHS6PJjd3tw25nNneD/mEviQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.4.tgz", + "integrity": "sha512-q56V9U6AnoYz/yj/alkDLhSQ9AZoXQSEl93f7WETa0+32CudbqM57BXdYXfMYPKudueXKaA+MG6L/0KRseF7Jg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.4.tgz", + "integrity": "sha512-r0W7A+Z9HTHh7bwihJl45E/zZKLjxD50/jToVF/E/RZHSl8+EWO+4yKKJpPMcUooT9hdoip3Zx1uWnbMg4N79g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.4.tgz", + "integrity": "sha512-3aih/sRxzeYfi2Bkh+bGYNf2YU9Llamb2mpA7BNF1obYzdgEeWDAMQzK6BSwzLhs/eTdOaSur92qrGfchagUtQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.4.tgz", + "integrity": "sha512-ktJSrPGQou4OqL88rDEx5CkeM9BjzrwZvYo8u7B7VL1zkBa2XBm351o4MQrek95qikb2M++26Y7w7vbH6Mgl8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.4.tgz", + "integrity": "sha512-rt3hjUxT7utAtcB+df6wHyaXDyxhE7Zd1x7L/nvB5Jb2qBb8dZwFUoWqeRja1BaF5OlSqkKSjBmVXj9OsevmCQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.4.tgz", + "integrity": "sha512-XE3jO2yOOWjttpeGvpwf3/b274NMi3QapQSAI/EzsgrmYNan1Tw8dXT9JQkN7K0OgvuqiC8mcCyNvGzEkpVJPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.4.tgz", + "integrity": "sha512-PaAZ2FjJaZk9SQLYtKIfQWiFm/xtl7pX2MKPgCzn0mS/VU54yu+vP457AJdB2XFLxU3gO2abLCt8N7Lg4EbKNg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.4.tgz", + "integrity": "sha512-bjO9WmoM687p8AoCIyw1DUqzpAs4JICLvNmIPxIWDmhw8IOsdubtWQLShyJmISnDKtRy1BBApHVOUl6sNFQQJA==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.4.tgz", + "integrity": "sha512-jCrwCvWVtt7ruMXp6dFPd5KBNU8o1tWtEdZbTL/w/hvD3lUYZA0E2mmfvTzW4QLHIx5wGQU9HeY7997R1QTrEg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.4.tgz", + "integrity": "sha512-cge1wcedn1FrRSXL22lF5sNDYr8c9+VImk7zFYLPs12jkDmchSrZNfzWqOKub+5Hb/aYRdDEqERGGDKONBlOzQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.4.tgz", + "integrity": "sha512-wGukGWb8SVuN7+FJvSS7M5eSJWDIWwVSvUvj1q41eTIhGPsS2DAgFWjA7YURJNwjHSgty59Hz8iMUiyO+YMHBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.4", + "@tailwindcss/oxide": "4.3.4", + "tailwindcss": "4.3.4" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "devOptional": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz", + "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.2.1.tgz", + "integrity": "sha512-9KyWCij3r0+qLG3Q62vBmv0VyevmYibAtxaCIVK9o0k6CXgaajZRIe8tpfchQcdZArJ5b/7OrIz4W3b2uxVRDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.35", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.35.tgz", + "integrity": "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/cac": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cac/-/cac-7.1.0.tgz", + "integrity": "sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001822", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001822.tgz", + "integrity": "sha512-Y3fvWQWzc69dlCyr07tuNrEhotv+db5FpMSPD3slZnkPKwRNOKwFBz2dP966XUmWMXLTOt+YShkFoQoom3U7hg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cn": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.5.2.tgz", + "integrity": "sha512-wm10E6iuJ37rALOw3D+3cfaXXZSLNMh2uxpQn3dNICqfJM59yXqgbA9/9Iiz155j5kYNLdK6WreNdW3NQtx3OQ==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node-es": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", + "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", + "license": "MIT" + }, + "node_modules/electron": { + "version": "45.2.3", + "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.3.tgz", + "integrity": "sha512-Vurzu5UOA5nTGT4LqIwXD16QFGrOZdiXxF+1UP4KNsAOo/YtDcT3/u0jhP4WSwNJ0iLrLDi85hzBJ0arnGDhyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@electron-internal/extract-zip": "^1.0.1", + "@electron/get": "^5.0.0", + "@types/node": "^24.9.0" + }, + "bin": { + "electron": "cli.js", + "install-electron": "install.js" + }, + "engines": { + "node": ">= 22.12.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.477", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.477.tgz", + "integrity": "sha512-PN++F4zWZoVDGWinxMnSCpVqKhqFOJfLXxdU8bYJKudAEsHL/XKVITOKWVbfMt1r276Mi9RDLU9VHx9uKJ4RMQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/electron-vite": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/electron-vite/-/electron-vite-6.0.0.tgz", + "integrity": "sha512-zafg2uizgll7jdx0BNDkkzO/SowsUBsiHqYN3v9Ieq7XPDHreRGZ4G9IRY/+RslgBktpLOjLM4jlP+IVpV0BGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.29.7", + "@babel/plugin-transform-arrow-functions": "^7.29.7", + "cac": "^7.0.0", + "magic-string": "^1.4.2", + "picocolors": "^1.1.1", + "rolldown": "~1.2.10" + }, + "bin": { + "electron-vite": "bin/electron-vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@swc/core": "^1.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + } + } + }, + "node_modules/electron/node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/electron/node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/enhanced-resolve": { + "version": "5.26.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.1.tgz", + "integrity": "sha512-PPnnSJq3azKOIewXR/uppBV/6h98dprBJ/WaQ9Qgj10xX1lJLNfg+XShpbsrSqcDSy2yYYyhfXM1wWhftqgyzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-nonce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", + "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.63", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", + "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/radix-ui": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.8.1.tgz", + "integrity": "sha512-HPfpVGizO9xANlsFSauruLhRe/3+iOt3vPX0MXYle/UQi3gorQrSYtBcdiv0BZYewcl2rvL59qrIuLFMGAmUrw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-accessible-icon": "1.2.0", + "@radix-ui/react-accordion": "1.3.1", + "@radix-ui/react-alert-dialog": "1.2.1", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-aspect-ratio": "1.2.0", + "@radix-ui/react-avatar": "1.3.1", + "@radix-ui/react-checkbox": "1.4.1", + "@radix-ui/react-collapsible": "1.2.1", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-context-menu": "2.4.1", + "@radix-ui/react-dialog": "1.3.1", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-dropdown-menu": "2.2.1", + "@radix-ui/react-focus-guards": "1.2.0", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-form": "0.3.0", + "@radix-ui/react-hover-card": "1.2.1", + "@radix-ui/react-label": "2.1.17", + "@radix-ui/react-menu": "2.2.1", + "@radix-ui/react-menubar": "1.2.1", + "@radix-ui/react-navigation-menu": "1.4.1", + "@radix-ui/react-one-time-password-field": "0.2.1", + "@radix-ui/react-password-toggle-field": "0.2.1", + "@radix-ui/react-popover": "1.3.1", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-progress": "1.2.1", + "@radix-ui/react-radio-group": "1.5.1", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-scroll-area": "1.4.0", + "@radix-ui/react-select": "2.4.1", + "@radix-ui/react-separator": "1.2.0", + "@radix-ui/react-slider": "1.6.1", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-switch": "1.4.1", + "@radix-ui/react-tabs": "1.2.1", + "@radix-ui/react-toast": "1.3.1", + "@radix-ui/react-toggle": "1.2.1", + "@radix-ui/react-toggle-group": "1.2.1", + "@radix-ui/react-toolbar": "1.2.1", + "@radix-ui/react-tooltip": "1.4.1", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-escape-keydown": "1.1.6", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-remove-scroll": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz", + "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==", + "license": "MIT", + "dependencies": { + "react-remove-scroll-bar": "^2.3.7", + "react-style-singleton": "^2.2.3", + "tslib": "^2.1.0", + "use-callback-ref": "^1.3.3", + "use-sidecar": "^1.1.3" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-remove-scroll-bar": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz", + "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==", + "license": "MIT", + "dependencies": { + "react-style-singleton": "^2.2.2", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/react-style-singleton": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", + "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==", + "license": "MIT", + "dependencies": { + "get-nonce": "^1.0.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/rolldown": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.16.tgz", + "integrity": "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.16", + "@rolldown/binding-android-arm64": "1.2.16", + "@rolldown/binding-darwin-arm64": "1.2.16", + "@rolldown/binding-darwin-x64": "1.2.16", + "@rolldown/binding-freebsd-x64": "1.2.16", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", + "@rolldown/binding-linux-arm64-gnu": "1.2.16", + "@rolldown/binding-linux-arm64-musl": "1.2.16", + "@rolldown/binding-linux-ppc64-gnu": "1.2.16", + "@rolldown/binding-linux-s390x-gnu": "1.2.16", + "@rolldown/binding-linux-x64-gnu": "1.2.16", + "@rolldown/binding-linux-x64-musl": "1.2.16", + "@rolldown/binding-openharmony-arm64": "1.2.16", + "@rolldown/binding-win32-arm64-msvc": "1.2.16", + "@rolldown/binding-win32-x64-msvc": "1.2.16" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/sumchecker": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", + "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.1.0" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/tailwind-merge": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz", + "integrity": "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.4.tgz", + "integrity": "sha512-PCJZTFFdG+sL3gvnP1Do9o6GbkvH2q0p04xSs3f7cSvmAeK+sttG+/7ncK1fdRwKFfC7n+wDDJaOMBSefkI9ow==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", + "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/use-callback-ref": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", + "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-sidecar": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz", + "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==", + "license": "MIT", + "dependencies": { + "detect-node-es": "^1.1.0", + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/vite": { + "version": "8.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.6.tgz", + "integrity": "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.16", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/studio/package.json b/studio/package.json new file mode 100644 index 000000000..4e8bae009 --- /dev/null +++ b/studio/package.json @@ -0,0 +1,40 @@ +{ + "name": "iris-studio", + "productName": "Iris Studio", + "version": "0.1.0", + "description": "The studio app for Iris worlds: maps, objects and editors, connected to a running server", + "private": true, + "type": "module", + "main": "out/main/index.js", + "scripts": { + "dev": "electron-vite dev", + "build": "electron-vite build", + "start": "electron-vite preview", + "typecheck": "tsc --noEmit -p tsconfig.json", + "test": "vitest run" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.4", + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/three": "^0.187.0", + "@vitejs/plugin-react": "^6.2.1", + "electron": "^45.2.3", + "electron-vite": "^6.0.0", + "tailwindcss": "^4.3.4", + "typescript": "^7.0.2", + "vite": "^8.3.6", + "vitest": "^5.1.0" + }, + "dependencies": { + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cn": "^0.5.2", + "radix-ui": "^1.8.1", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "tailwind-merge": "^3.7.0", + "three": "^0.187.0" + } +} diff --git a/studio/src/main/dedicatedGpu.ts b/studio/src/main/dedicatedGpu.ts new file mode 100644 index 000000000..4c9ebf1d8 --- /dev/null +++ b/studio/src/main/dedicatedGpu.ts @@ -0,0 +1,80 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' + +const NVIDIA_VENDOR_ID = '0x10de' +const DRM_FOLDER = '/sys/class/drm' +const RENDER_NODE_PREFIX = 'renderD' +// Where the Vulkan loader looks for drivers, NixOS's first. +const VULKAN_DRIVER_FOLDERS = ['/run/opengl-driver/share/vulkan/icd.d', '/usr/share/vulkan/icd.d', '/etc/vulkan/icd.d'] +const NVIDIA_VULKAN_DRIVER_PREFIX = 'nvidia_icd' +const VULKAN_DRIVER_VARIABLES = ['VK_DRIVER_FILES', 'VK_ICD_FILENAMES'] + +/** + * Chromium on Wayland hands the desktop buffers made on the GPU it draws with, and a desktop that composites on the + * integrated GPU cannot show buffers of an NVIDIA GPU: the window stays empty. Through XWayland with Chromium drawing + * on Vulkan, NVIDIA's Vulkan driver copies each frame to the integrated GPU itself, as it does for games. + */ +export const DEDICATED_GPU_SWITCHES = ['--ozone-platform=x11', '--use-angle=vulkan', '--enable-features=Vulkan,VulkanFromANGLE,DefaultANGLEVulkan'] + +/** NVIDIA's Vulkan driver file on a Linux machine with an NVIDIA GPU; null where there is no such GPU or driver. */ +export function dedicatedGpuDriver(): string | null { + if (process.platform !== 'linux' || !hasNvidiaGpu()) { + return null + } + for (const folder of VULKAN_DRIVER_FOLDERS) { + const driver = driverIn(folder) + if (driver !== null) { + return driver + } + } + return null +} + +/** Shows Chromium only the given Vulkan driver, so it draws on that driver's GPU. */ +export function showOnlyVulkanDriver(env: NodeJS.ProcessEnv, driver: string): void { + for (const variable of VULKAN_DRIVER_VARIABLES) { + env[variable] = driver + } +} + +export function showEveryVulkanDriver(env: NodeJS.ProcessEnv): void { + for (const variable of VULKAN_DRIVER_VARIABLES) { + delete env[variable] + } +} + +export function runsOnDedicatedGpu(argv: string[]): boolean { + return DEDICATED_GPU_SWITCHES.every((option) => argv.includes(option)) +} + +/** The arguments with the dedicated GPU's switches in place of any the studio was started with under the same names. */ +export function withDedicatedGpuSwitches(argv: string[]): string[] { + const names = DEDICATED_GPU_SWITCHES.map(switchName) + return [...argv.filter((option) => !names.includes(switchName(option))), ...DEDICATED_GPU_SWITCHES] +} + +export function withoutDedicatedGpuSwitches(argv: string[]): string[] { + return argv.filter((option) => !DEDICATED_GPU_SWITCHES.includes(option)) +} + +function switchName(option: string): string { + return option.split('=')[0] +} + +function hasNvidiaGpu(): boolean { + try { + return readdirSync(DRM_FOLDER) + .filter((name) => name.startsWith(RENDER_NODE_PREFIX)) + .some((name) => readFileSync(join(DRM_FOLDER, name, 'device', 'vendor'), 'utf8').trim() === NVIDIA_VENDOR_ID) + } catch { + return false + } +} + +function driverIn(folder: string): string | null { + if (!existsSync(folder)) { + return null + } + const file = readdirSync(folder).find((name) => name.startsWith(NVIDIA_VULKAN_DRIVER_PREFIX)) + return file === undefined ? null : join(folder, file) +} diff --git a/studio/src/main/index.ts b/studio/src/main/index.ts new file mode 100644 index 000000000..749351ccb --- /dev/null +++ b/studio/src/main/index.ts @@ -0,0 +1,198 @@ +import { app, BrowserWindow, clipboard, ipcMain, nativeTheme, shell } from 'electron' +import { readFileSync } from 'node:fs' +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import type { BridgeConnection, GraphicsInfo, StoredShortcuts, ThemeChoice } from '../shared/bridge' +import { + dedicatedGpuDriver, + runsOnDedicatedGpu, + showEveryVulkanDriver, + showOnlyVulkanDriver, + withDedicatedGpuSwitches, + withoutDedicatedGpuSwitches +} from './dedicatedGpu' + +const CONNECTION_FOLDER = join(homedir(), '.iris', 'studio', 'bridges') +const SETTINGS_FILE = 'studio.json' +const SHORTCUTS_KEY = 'shortcuts' +const DEDICATED_GPU_KEY = 'dedicatedGpu' +const SETTINGS_INDENT = 2 +const LINK_PREFIX = 'iris-studio://' +const DARK_BACKGROUND = '#1e1f22' +const WINDOW_SIZE = { width: 1440, height: 880, minWidth: 820, minHeight: 520 } + +let window: BrowserWindow | null = null +let pendingLink: string | null = findLink(process.argv) +const dedicatedGpu = dedicatedGpuDriver() + +function findLink(argv: string[]): string | null { + return argv.find((argument) => argument.startsWith(LINK_PREFIX)) ?? null +} + +function isRunning(pid: unknown): boolean { + if (typeof pid !== 'number') { + return true + } + try { + process.kill(pid, 0) + return true + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM' + } +} + +/** The bridges announced on this machine whose server still runs, newest first. */ +async function listBridges(): Promise { + let files: string[] + try { + files = (await readdir(CONNECTION_FOLDER)).filter((name) => name.endsWith('.json')) + } catch { + return [] + } + const bridges = await Promise.all(files.map(readConnection)) + return bridges + .filter((bridge): bridge is BridgeConnection => bridge !== null) + .sort((first, second) => (second.startedMillis ?? 0) - (first.startedMillis ?? 0)) +} + +async function readConnection(name: string): Promise { + try { + const file = JSON.parse(await readFile(join(CONNECTION_FOLDER, name), 'utf8')) + if (!isRunning(file.pid) || typeof file.port !== 'number' || typeof file.token !== 'string') { + return null + } + return { world: String(file.world ?? ''), port: file.port, token: file.token, startedMillis: file.startedMillis } + } catch { + return null + } +} + +function settingsPath(): string { + return join(app.getPath('userData'), SETTINGS_FILE) +} + +async function readSettings(): Promise> { + try { + const settings: unknown = JSON.parse(await readFile(settingsPath(), 'utf8')) + return typeof settings === 'object' && settings !== null && !Array.isArray(settings) ? (settings as Record) : {} + } catch { + return {} + } +} + +async function saveSetting(key: string, value: unknown): Promise { + try { + const settings = { ...(await readSettings()), [key]: value } + await mkdir(dirname(settingsPath()), { recursive: true }) + await writeFile(settingsPath(), JSON.stringify(settings, null, SETTINGS_INDENT)) + } catch (failure) { + console.error(`Could not save the studio setting ${key} to ${settingsPath()}`, failure) + } +} + +/** Read before the app is ready, as the GPU the studio draws on is chosen by how it was started. */ +function choosesDedicatedGpu(): boolean { + try { + const settings: unknown = JSON.parse(readFileSync(settingsPath(), 'utf8')) + return typeof settings === 'object' && settings !== null && (settings as Record)[DEDICATED_GPU_KEY] === true + } catch { + return false + } +} + +function restartOnGpu(dedicated: boolean): void { + const args = process.argv.slice(1) + if (dedicated && dedicatedGpu !== null) { + showOnlyVulkanDriver(process.env, dedicatedGpu) + app.relaunch({ args: withDedicatedGpuSwitches(args) }) + } else { + showEveryVulkanDriver(process.env) + app.relaunch({ args: withoutDedicatedGpuSwitches(args) }) + } + app.exit(0) +} + +async function useDedicatedGpu(dedicated: boolean): Promise { + await saveSetting(DEDICATED_GPU_KEY, dedicated) + restartOnGpu(dedicated) +} + +function graphicsInfo(): GraphicsInfo { + return { canUseDedicatedGpu: dedicatedGpu !== null, usesDedicatedGpu: runsOnDedicatedGpu(process.argv) } +} + +function createWindow(): void { + window = new BrowserWindow({ + ...WINDOW_SIZE, + title: 'Iris Studio', + backgroundColor: DARK_BACKGROUND, + autoHideMenuBar: true, + show: false, + webPreferences: { + preload: join(import.meta.dirname, '../preload/index.cjs'), + sandbox: true, + contextIsolation: true + } + }) + window.once('ready-to-show', () => window?.show()) + window.webContents.setWindowOpenHandler(({ url }) => { + void shell.openExternal(url) + return { action: 'deny' } + }) + if (process.env.ELECTRON_RENDERER_URL) { + void window.loadURL(process.env.ELECTRON_RENDERER_URL) + } else { + void window.loadFile(join(import.meta.dirname, '../renderer/index.html')) + } +} + +function deliverLink(link: string): void { + if (window === null) { + pendingLink = link + return + } + window.webContents.send('studio:link', link) + if (window.isMinimized()) { + window.restore() + } + window.focus() +} + +if (dedicatedGpu !== null && choosesDedicatedGpu() && !runsOnDedicatedGpu(process.argv)) { + restartOnGpu(true) +} else if (!app.requestSingleInstanceLock()) { + app.quit() +} else { + app.setAsDefaultProtocolClient('iris-studio') + app.on('second-instance', (_event, argv) => { + const link = findLink(argv) + if (link !== null) { + deliverLink(link) + } else { + window?.focus() + } + }) + app.on('open-url', (event, url) => { + event.preventDefault() + deliverLink(url) + }) + + ipcMain.handle('studio:list-bridges', listBridges) + ipcMain.handle('studio:initial-link', () => { + const link = pendingLink + pendingLink = null + return link + }) + ipcMain.on('studio:set-theme', (_event, theme: ThemeChoice) => { + nativeTheme.themeSource = theme + }) + ipcMain.handle('studio:load-shortcuts', async () => (await readSettings())[SHORTCUTS_KEY] ?? {}) + ipcMain.on('studio:save-shortcuts', (_event, shortcuts: StoredShortcuts) => void saveSetting(SHORTCUTS_KEY, shortcuts)) + ipcMain.handle('studio:graphics', graphicsInfo) + ipcMain.on('studio:use-dedicated-gpu', (_event, dedicated: boolean) => void useDedicatedGpu(dedicated)) + ipcMain.on('studio:copy-text', (_event, text: string) => clipboard.writeText(text)) + + void app.whenReady().then(createWindow) + app.on('window-all-closed', () => app.quit()) +} diff --git a/studio/src/preload/index.ts b/studio/src/preload/index.ts new file mode 100644 index 000000000..684dc4516 --- /dev/null +++ b/studio/src/preload/index.ts @@ -0,0 +1,20 @@ +import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron' +import type { StoredShortcuts, StudioHost, ThemeChoice } from '../shared/bridge' + +const host: StudioHost = { + listBridges: () => ipcRenderer.invoke('studio:list-bridges'), + initialLink: () => ipcRenderer.invoke('studio:initial-link'), + onLink: (listener) => { + const forward = (_event: IpcRendererEvent, link: string): void => listener(link) + ipcRenderer.on('studio:link', forward) + return () => ipcRenderer.removeListener('studio:link', forward) + }, + setTheme: (theme: ThemeChoice) => ipcRenderer.send('studio:set-theme', theme), + copyText: (text: string) => ipcRenderer.send('studio:copy-text', text), + loadShortcuts: () => ipcRenderer.invoke('studio:load-shortcuts'), + saveShortcuts: (shortcuts: StoredShortcuts) => ipcRenderer.send('studio:save-shortcuts', shortcuts), + graphics: () => ipcRenderer.invoke('studio:graphics'), + useDedicatedGpu: (dedicated: boolean) => ipcRenderer.send('studio:use-dedicated-gpu', dedicated) +} + +contextBridge.exposeInMainWorld('studio', host) diff --git a/studio/src/renderer/index.html b/studio/src/renderer/index.html new file mode 100644 index 000000000..34d3713d1 --- /dev/null +++ b/studio/src/renderer/index.html @@ -0,0 +1,15 @@ + + + + + + Iris Studio + + +
+ + + diff --git a/studio/src/renderer/src/App.tsx b/studio/src/renderer/src/App.tsx new file mode 100644 index 000000000..97fd80594 --- /dev/null +++ b/studio/src/renderer/src/App.tsx @@ -0,0 +1,68 @@ +import { useCallback, useEffect, useState } from 'react' +import { parseStudioLink, type BridgeConnection } from '../../shared/bridge' +import { BridgeClient } from './bridge/BridgeClient' +import type { WorldInfo } from './bridge/types' +import { ConnectScreen } from './studio/ConnectScreen' +import { MapStudio } from './studio/MapStudio' +import { useTheme } from './studio/theme' +import { shortcutStore } from './studio/useBindings' + +interface Session { + client: BridgeClient + world: WorldInfo +} + +/** The studio: a connect screen until a bridge answers, then the map of its world. */ +export function App(): React.JSX.Element { + const theme = useTheme() + const [session, setSession] = useState(null) + const [error, setError] = useState(null) + const [connecting, setConnecting] = useState(false) + + const connect = useCallback(async (connection: BridgeConnection) => { + setConnecting(true) + setError(null) + const client = new BridgeClient(connection) + try { + setSession({ client, world: await client.world() }) + } catch (failure) { + setError(failure instanceof Error ? failure.message : String(failure)) + } finally { + setConnecting(false) + } + }, []) + + const connectLink = useCallback( + (link: string) => { + const connection = parseStudioLink(link) + if (connection === null) { + setError('That is not a studio link') + return + } + void connect(connection) + }, + [connect] + ) + + useEffect(() => { + void shortcutStore.load() + }, []) + + useEffect(() => { + void window.studio.initialLink().then((link) => link !== null && connectLink(link)) + return window.studio.onLink(connectLink) + }, [connectLink]) + + if (session === null) { + return + } + return ( + setSession(null)} + /> + ) +} diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts new file mode 100644 index 000000000..9e7739274 --- /dev/null +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -0,0 +1,391 @@ +import type { BridgeConnection } from '../../../shared/bridge' +import { decodeScene, type BlockScene } from '../scene/sceneDecoding' +import { decodePattern } from './patternDecoding' +import { decodeSavedTile } from './savedTileDecoding' +import { decodeTile } from './tileDecoding' +import type { + BakeRun, + BlockSource, + EditorState, + GraphEdit, + MapHover, + MapLabel, + MapTile, + Marker, + ModuleViewInfo, + NoiseSource, + NoiseTile, + PatternEntry, + PatternTile, + PickInspection, + SavedStart, + SavedTile, + SavedWorldInfo, + SceneEntry, + SceneViewInfo, + ServerUsage, + WorldInfo +} from './types' + +export const STATUS_NOT_FOUND = 404 +export const STATUS_CONFLICT = 409 +export const STATUS_UNAVAILABLE = 503 + +export class BridgeError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message) + } +} + +/** Which scene of a scene view: an entry's variant, at one of the view's sizes or null when it has none. */ +export interface ScenePlace { + key: string + variant: number + size: number | null +} + +export interface TileRequest { + view: string + /** The region the region view previews everywhere, or null for the world as it is. */ + preview: string | null + tileX: number + tileZ: number + blocksPerPixel: number + size: number + heights: boolean + pickNoise: boolean + /** Where the tile's blocks come from, or null for a tile without them. */ + blocks: BlockSource | null + /** + * Whether a tile with blocks also carries the ground's shape in 3D: every block seen from the open air at a block a + * pixel, the runs of solid blocks of each cell's area when coarser. + */ + shape?: boolean +} + +/** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */ +export interface PatternRequest { + viewId: string + key: string + depth: number + tileX: number + tileZ: number + blocksPerColumn: number + columns: number +} + +/** What a map spot or area is asked about: a view, and the region it previews. */ +export interface MapLayerQuery { + view: string + preview: string | null +} + +export interface WorldRect { + minX: number + minZ: number + maxX: number + maxZ: number +} + +export interface BridgeEvents { + onWorld(running: boolean): void + onPlayers(players: Marker[]): void + onUsage(usage: ServerUsage): void + onClosed(): void +} + +const EVENT_SEPARATOR = '\n\n' + +/** One connection to a world's bridge, over HTTP on the loopback interface. */ +export class BridgeClient { + private readonly base: string + private readonly authorization: string + + constructor(readonly connection: BridgeConnection) { + this.base = `http://127.0.0.1:${connection.port}/v1/` + this.authorization = `Bearer ${connection.token}` + } + + world(): Promise { + return this.json('world') + } + + hover(layer: MapLayerQuery, worldX: number, worldZ: number, signal?: AbortSignal): Promise { + return this.json(`hover?${layerQuery(layer, { x: String(worldX), z: String(worldZ) })}`, { signal }) + } + + /** How the noise picks what the layer shows across {@code area}. */ + picks(layer: MapLayerQuery, area: WorldRect, signal?: AbortSignal): Promise { + const corners = { minX: String(area.minX), minZ: String(area.minZ), maxX: String(area.maxX), maxZ: String(area.maxZ) } + return this.json(`picks?${layerQuery(layer, corners)}`, { signal }) + } + + /** The regions the world picks biomes for, which the region view can preview. */ + regions(): Promise { + return this.json('regions') + } + + entities(): Promise { + return this.json('entities') + } + + async teleport(worldX: number, worldZ: number): Promise { + await this.json(`teleport?x=${worldX}&z=${worldZ}`, { method: 'POST' }) + } + + /** Opens the file of the biome or region at a spot on the server's machine; the server's answer, if any. */ + async openInEditor(worldX: number, worldZ: number, view: string): Promise { + const answer = await this.json<{ message: string | null }>(`open?x=${worldX}&z=${worldZ}&view=${view}`, { method: 'POST' }) + return answer.message + } + + async tile(request: TileRequest, signal: AbortSignal): Promise { + const query = layerQuery(request, { + x: String(request.tileX), + z: String(request.tileZ), + scale: String(request.blocksPerPixel), + size: String(request.size), + heights: request.heights ? '1' : '0', + noise: request.pickNoise ? '1' : '0' + }) + if (request.blocks !== null) { + query.set('blocks', request.blocks) + if (request.shape === true) { + query.set('shape', '1') + } + this.cancelOnAbort(query, signal) + } + const response = await this.fetch(`tile?${query}`, { signal }) + return decodeTile(await response.arrayBuffer()) + } + + // A tile with blocks can keep the server generating chunks for a minute; dropping the request alone would not stop it. + private cancelOnAbort(query: URLSearchParams, signal: AbortSignal): void { + const request = crypto.randomUUID() + query.set('request', request) + signal.addEventListener('abort', () => void this.fetch(`tile-cancel?${new URLSearchParams({ request })}`, { method: 'POST' }).catch(() => {}), { once: true }) + } + + /** The scene views the pack's modules show, such as its objects. */ + sceneViews(): Promise { + return this.json('scenes') + } + + /** An editable entry's file, as nodes. */ + sceneFile(viewId: string, key: string, signal?: AbortSignal): Promise { + return this.json(`scene-file?${new URLSearchParams({ view: viewId, key })}`, { signal }) + } + + /** Makes {@code edit} on the file as it was at {@code revision} and saves it; refused with STATUS_CONFLICT when it changed since. */ + sceneEdit(viewId: string, key: string, revision: string, edit: GraphEdit): Promise { + return this.json(`scene-edit?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, edit }) }) + } + + /** Replaces the whole file, as undoing does; refused with STATUS_CONFLICT when it changed since {@code revision}. */ + sceneWrite(viewId: string, key: string, revision: string, text: string): Promise { + return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) }) + } + + /** Writes a new entry from its view's starter; it is listed once the pack has reloaded. Refused when the key can't name a new one. */ + async sceneCreate(viewId: string, key: string): Promise { + await this.json(`scene-create?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' }) + } + + /** The pack files that still name the entry, such as the biomes that place it. */ + async sceneUses(viewId: string, key: string): Promise { + const uses = await this.json<{ files: string[] }>(`scene-uses?${new URLSearchParams({ view: viewId, key })}`) + return uses.files + } + + /** Moves the entry's file to the trash; says where it went. */ + async sceneDelete(viewId: string, key: string): Promise { + const trashed = await this.json<{ to: string }>(`scene-delete?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' }) + return trashed.to + } + + /** What a setting naming an entry of a platform registry (reference) or a resource of the pack (resource) may be typed as, sorted. */ + suggestions(of: { reference: string } | { resource: string }): Promise { + return this.json(`suggestions?${new URLSearchParams(of)}`) + } + + sceneEntries(viewId: string): Promise { + return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`) + } + + /** Bakes the entry once more and times each step; one run of the median the studio shows. */ + sceneBake(viewId: string, key: string, signal?: AbortSignal): Promise { + return this.json(`scene-bake?${new URLSearchParams({ view: viewId, key })}`, { signal }) + } + + async scene(viewId: string, place: ScenePlace, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene?${sceneQuery(viewId, place)}`, { signal }) + 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, place: ScenePlace, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene-parts?${sceneQuery(viewId, place)}`, { signal }) + return new Int32Array(await response.arrayBuffer()) + } + + /** + * The caves of the world's generated chunks over a square {@code size} blocks across around a spot: every air block + * under the terrain, drawn as blocks coloured by height. Every chunk of the square is generated, which takes seconds. + */ + async caves(centerX: number, centerZ: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ x: String(Math.round(centerX)), z: String(Math.round(centerZ)), size: String(size) }) + this.cancelOnAbort(query, signal) + const response = await this.fetch(`caves?${query}`, { signal }) + return decodeScene(await response.arrayBuffer()) + } + + /** The pattern views the pack's modules show, such as its palettes. */ + patternViews(): Promise { + return this.json('patterns') + } + + patternEntries(viewId: string): Promise { + return this.json(`pattern-entries?${new URLSearchParams({ view: viewId })}`) + } + + /** What an entry places at {@code depth} below the top across one tile, a column every {@code blocksPerColumn} blocks. */ + async pattern(request: PatternRequest, signal: AbortSignal): Promise { + const query = new URLSearchParams({ + view: request.viewId, + key: request.key, + depth: String(request.depth), + x: String(request.tileX), + z: String(request.tileZ), + scale: String(request.blocksPerColumn), + size: String(request.columns) + }) + const response = await this.fetch(`pattern?${query}`, { signal }) + return decodePattern(await response.arrayBuffer()) + } + + /** The worlds saved on the server's disk. */ + savedWorlds(): Promise { + return this.json('saved-worlds') + } + + /** Where a saved world's view opens; reads the region nearest the origin whole, so it can take a second or two. */ + savedStart(worldId: string, signal?: AbortSignal): Promise { + return this.json(`saved-start?${new URLSearchParams({ world: worldId })}`, { signal }) + } + + async savedTile(worldId: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ world: worldId, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) }) + const response = await this.fetch(`saved-tile?${query}`, { signal }) + return decodeSavedTile(await response.arrayBuffer()) + } + + /** The pack's generators and expressions, the dimension's overlay noise, and the built-in noise styles. */ + noiseSources(): Promise { + return this.json('noise-sources') + } + + async noiseTile(sourceId: string, seed: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ source: sourceId, seed, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) }) + const response = await this.fetch(`noise-tile?${query}`, { signal }) + return { size, values: new Float32Array(await response.arrayBuffer()) } + } + + /** A file of the Minecraft client's assets, such as {@code minecraft/blockstates/stone.json}; null when there is none. */ + async asset(path: string): Promise { + try { + return await this.fetch(`assets/${path}`, {}) + } catch (error) { + if (error instanceof BridgeError && error.status === STATUS_NOT_FOUND) { + return null + } + throw error + } + } + + /** Streams the bridge's events until {@code signal} aborts or the bridge goes away. */ + async listen(events: BridgeEvents, signal: AbortSignal): Promise { + try { + const response = await this.fetch('events', { signal }) + const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader() + let pending = '' + for (;;) { + const { value, done } = await reader.read() + if (done) { + break + } + pending += value + let end: number + while ((end = pending.indexOf(EVENT_SEPARATOR)) >= 0) { + dispatch(pending.slice(0, end), events) + pending = pending.slice(end + EVENT_SEPARATOR.length) + } + } + } catch (error) { + if (signal.aborted) { + return + } + console.warn('Studio events stopped', error) + } + if (!signal.aborted) { + events.onClosed() + } + } + + private async json(endpoint: string, init: RequestInit = {}): Promise { + const response = await this.fetch(endpoint, init) + return (await response.json()) as T + } + + private async fetch(endpoint: string, init: RequestInit): Promise { + const response = await fetch(this.base + endpoint, { + ...init, + headers: { Authorization: this.authorization } + }) + if (!response.ok) { + const body = await response.json().catch(() => ({ error: response.statusText })) + throw new BridgeError(response.status, String(body.error ?? response.statusText)) + } + return response + } +} + +function sceneQuery(viewId: string, place: ScenePlace): URLSearchParams { + const query = new URLSearchParams({ view: viewId, key: place.key, variant: String(place.variant) }) + if (place.size !== null) { + query.set('size', String(place.size)) + } + return query +} + +function layerQuery(layer: MapLayerQuery, rest: Record): URLSearchParams { + const query = new URLSearchParams({ view: layer.view, ...rest }) + if (layer.preview !== null) { + query.set('preview', layer.preview) + } + return query +} + +function dispatch(block: string, events: BridgeEvents): void { + let name = 'message' + let data = '' + for (const line of block.split('\n')) { + if (line.startsWith('event: ')) { + name = line.slice('event: '.length) + } else if (line.startsWith('data: ')) { + data += line.slice('data: '.length) + } + } + if (data === '') { + return + } + if (name === 'world') { + events.onWorld((JSON.parse(data) as { running: boolean }).running) + } else if (name === 'players') { + events.onPlayers(JSON.parse(data) as Marker[]) + } else if (name === 'usage') { + events.onUsage(JSON.parse(data) as ServerUsage) + } +} diff --git a/studio/src/renderer/src/bridge/patternDecoding.test.ts b/studio/src/renderer/src/bridge/patternDecoding.test.ts new file mode 100644 index 000000000..9d57286a9 --- /dev/null +++ b/studio/src/renderer/src/bridge/patternDecoding.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { decodePattern } from './patternDecoding' +import { NO_PATTERN_BLOCK } from './types' + +function encodedPattern(header: object, picks: number[]): ArrayBuffer { + const headerBytes = new TextEncoder().encode(JSON.stringify(header)) + const picksAt = Math.ceil((4 + headerBytes.length) / 4) * 4 + const buffer = new ArrayBuffer(picksAt + picks.length * 2) + const view = new DataView(buffer) + view.setUint32(0, headerBytes.length, true) + new Uint8Array(buffer, 4).set(headerBytes) + picks.forEach((pick, index) => view.setInt16(picksAt + index * 2, pick, true)) + return buffer +} + +describe('decodePattern', () => { + it('reads the picks after the padded header, row by row, with no block as -1', () => { + const header = { + columns: 2, + blocksPerColumn: 4, + blocks: ['minecraft:grass_block[snowy=false]', 'etopia:grass_block'], + drawnAs: ['minecraft:grass_block[snowy=false]', 'minecraft:note_block[note=7]'], + noBlock: -1 + } + const pattern = decodePattern(encodedPattern(header, [0, -1, 1, 0])) + expect(pattern.columns).toBe(2) + expect(pattern.blocksPerColumn).toBe(4) + expect(pattern.blocks).toEqual(header.blocks) + expect(pattern.drawnAs).toEqual(header.drawnAs) + expect([...pattern.picks]).toEqual([0, NO_PATTERN_BLOCK, 1, 0]) + }) +}) diff --git a/studio/src/renderer/src/bridge/patternDecoding.ts b/studio/src/renderer/src/bridge/patternDecoding.ts new file mode 100644 index 000000000..9e5a05961 --- /dev/null +++ b/studio/src/renderer/src/bridge/patternDecoding.ts @@ -0,0 +1,27 @@ +import type { PatternTile } from './types' + +const ALIGNMENT_BYTES = 4 + +interface PatternHeader { + columns: number + blocksPerColumn: number + blocks: string[] + drawnAs: string[] +} + +/** + * Reads a pattern as the bridge writes it (PatternEncoding): a u32 header length, the JSON header, then from the next + * multiple of 4 bytes an i16 pick per column, row by row. The picks are a view into the buffer, not a copy. + */ +export function decodePattern(buffer: ArrayBuffer): PatternTile { + const headerLength = new DataView(buffer).getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as PatternHeader + const picksAt = Math.ceil((4 + headerLength) / ALIGNMENT_BYTES) * ALIGNMENT_BYTES + return { + columns: header.columns, + blocksPerColumn: header.blocksPerColumn, + blocks: header.blocks, + drawnAs: header.drawnAs, + picks: new Int16Array(buffer, picksAt, header.columns * header.columns) + } +} diff --git a/studio/src/renderer/src/bridge/savedTileDecoding.ts b/studio/src/renderer/src/bridge/savedTileDecoding.ts new file mode 100644 index 000000000..5e0e3db52 --- /dev/null +++ b/studio/src/renderer/src/bridge/savedTileDecoding.ts @@ -0,0 +1,41 @@ +import type { MapLabel, SavedTile } from './types' + +const ALIGNMENT_BYTES = 4 + +interface SavedTileHeader { + size: number + blocksPerPixel: number + blocks: { name: string; drawnAs: string }[] + biomes: MapLabel[] + noGround: number + noWater: number +} + +function aligned(bytes: number): number { + return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES +} + +/** + * Reads a saved tile as the bridge writes it (SavedTileEncoding): a u32 header length, the JSON header, then the ground, + * water, block and biome grids, each starting on a multiple of 4 bytes. The grids are views into the buffer. + */ +export function decodeSavedTile(buffer: ArrayBuffer): SavedTile { + const headerLength = new DataView(buffer).getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as SavedTileHeader + const pixels = header.size * header.size + const gridBytes = aligned(pixels * Int16Array.BYTES_PER_ELEMENT) + const gridAt = (index: number): Int16Array => new Int16Array(buffer, aligned(4 + headerLength) + index * gridBytes, pixels) + return { + size: header.size, + blocksPerPixel: header.blocksPerPixel, + groundY: gridAt(0), + waterSurfaceY: gridAt(1), + blocks: gridAt(2), + biomes: gridAt(3), + blockNames: header.blocks.map((block) => block.name), + blocksDrawnAs: header.blocks.map((block) => block.drawnAs), + biomeLabels: header.biomes, + noGround: header.noGround, + noWater: header.noWater + } +} diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts new file mode 100644 index 000000000..c7685e5ea --- /dev/null +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -0,0 +1,145 @@ +import type { LabelKind, MapLabel, MapTile, TileBlocks, TileRuns, TileVoxels } from './types' + +const ALIGNMENT_BYTES = 4 + +interface TileHeader { + size: number + blocksPerPixel: number + subjectKind: LabelKind + labels: MapLabel[] + heights: boolean + pickNoise: boolean + /** The blocks the ground and cover grids index; absent or null on a tile without them. */ + blocks?: string[] | null + /** How many blocks are raised over the ground of all cells together. */ + raised?: number + /** How many blocks can be seen from the open air, or -1 on a tile without them. */ + voxels?: number + /** How many runs of solid blocks the cells have together, or -1 on a tile without them. */ + runs?: number +} + +const NONE = -1 + +function aligned(bytes: number): number { + return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES +} + +/** + * Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject, + * region, height, pick noise, ground, cover and raised block grids, each starting on a multiple of 4 bytes. The grids + * are views into the buffer, not copies. + */ +export function decodeTile(buffer: ArrayBuffer): MapTile { + const view = new DataView(buffer) + const headerLength = view.getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as TileHeader + const gridSize = header.size + 2 + const cells = gridSize * gridSize + const subjectsAt = aligned(4 + headerLength) + const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT) + const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT) + const pickNoiseAt = heightsAt + (header.heights ? cells * Float32Array.BYTES_PER_ELEMENT : 0) + const groundAt = pickNoiseAt + (header.pickNoise ? cells * Float32Array.BYTES_PER_ELEMENT : 0) + return { + size: header.size, + blocksPerPixel: header.blocksPerPixel, + subjectKind: header.subjectKind, + labels: header.labels, + subjects: new Int16Array(buffer, subjectsAt, cells), + regions: new Int16Array(buffer, regionsAt, cells), + heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null, + pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null, + blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0, header.voxels ?? NONE, header.runs ?? NONE) + } +} + +function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number, voxelCount: number, runCount: number): TileBlocks { + const gridBytes = aligned(cells * Int16Array.BYTES_PER_ELEMENT) + const coverAt = groundAt + gridBytes + const raisedCountsAt = coverAt + gridBytes + const raisedYAt = raisedCountsAt + gridBytes + const raisedAt = aligned(raisedYAt + raisedCount * Int16Array.BYTES_PER_ELEMENT) + const voxelsAt = aligned(raisedAt + raisedCount * Int16Array.BYTES_PER_ELEMENT) + const runsAt = voxelsAt + (voxelCount === NONE ? 0 : voxelBytes(voxelCount)) + return { + names, + ground: new Int16Array(buffer, groundAt, cells), + cover: new Int16Array(buffer, coverAt, cells), + raisedStart: startsOf(new Int16Array(buffer, raisedCountsAt, cells)), + raisedY: new Int16Array(buffer, raisedYAt, raisedCount), + raised: new Int16Array(buffer, raisedAt, raisedCount), + voxels: voxelCount === NONE ? null : decodeVoxels(buffer, voxelsAt, voxelCount), + runs: runCount === NONE ? null : decodeRuns(buffer, runsAt, cells, runCount), + colors: [], + looks: [], + covers: [], + models: [] + } +} + +function voxelBytes(count: number): number { + return aligned(count) * 3 + aligned(count * Int16Array.BYTES_PER_ELEMENT) * 2 +} + +function decodeRuns(buffer: ArrayBuffer, countsAt: number, cells: number, count: number): TileRuns { + const bottomsAt = countsAt + aligned(cells * Int16Array.BYTES_PER_ELEMENT) + const topsAt = bottomsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const blocksAt = topsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const coversAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const coverSharesAt = coversAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const lightsAt = coverSharesAt + aligned(count) + const occlusionsAt = lightsAt + aligned(count) + return { + starts: startsOf(new Int16Array(buffer, countsAt, cells)), + bottoms: new Int16Array(buffer, bottomsAt, count), + tops: new Int16Array(buffer, topsAt, count), + blocks: new Int16Array(buffer, blocksAt, count), + covers: new Int16Array(buffer, coversAt, count), + coverShares: new Uint8Array(buffer, coverSharesAt, count), + lights: new Uint8Array(buffer, lightsAt, count), + occlusions: new Uint8Array(buffer, occlusionsAt, count) + } +} + +function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxels { + const zAt = xAt + aligned(count) + const yAt = zAt + aligned(count) + const blocksAt = yAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const facesAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const lightsAt = facesAt + aligned(count) + const shadesAt = lightsAt + aligned(count) + const faces = new Uint8Array(buffer, facesAt, count) + return { + x: new Uint8Array(buffer, xAt, count), + z: new Uint8Array(buffer, zAt, count), + y: new Int16Array(buffer, yAt, count), + blocks: new Int16Array(buffer, blocksAt, count), + faces, + lights: new Uint8Array(buffer, lightsAt, count), + shades: new Uint16Array(buffer, shadesAt, facesShown(faces)) + } +} + +function facesShown(faces: Uint8Array): number { + let shown = 0 + for (const sides of faces) { + for (let rest = sides; rest !== 0; rest &= rest - 1) { + shown++ + } + } + return shown +} + +function startsOf(counts: Int16Array): Int32Array { + const starts = new Int32Array(counts.length + 1) + for (let cell = 0; cell < counts.length; cell++) { + starts[cell + 1] = starts[cell] + counts[cell] + } + return starts +} + +/** The grid index of a pixel; pixel coordinates run from -1 to size, the ring being the neighbours'. */ +export function gridIndex(tile: MapTile, pixelX: number, pixelZ: number): number { + return (pixelZ + 1) * (tile.size + 2) + pixelX + 1 +} diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts new file mode 100644 index 000000000..fd440af25 --- /dev/null +++ b/studio/src/renderer/src/bridge/types.ts @@ -0,0 +1,436 @@ +/** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */ + +import type { BlockLook } from '../scene/blockLooks' +import type { CoverLook } from '../scene/coverLooks' + +export type LabelKind = 'BIOME' | 'REGION' + +export interface MapLabel { + kind: LabelKind + key: string + name: string + /** 0xRRGGBB */ + color: number +} + +export interface ViewInfo { + id: string + label: string + description: string + group: string + groupLabel: string +} + +/** A studio view a module of the pack shows (IrisApi StudioView): block scenes such as its objects, or patterns such as its palettes. */ +export interface ModuleViewInfo { + id: string + label: string + description: string +} + +export interface SceneEntry { + key: string + name: string + /** The folder it is listed under; empty for none. */ + group: string + variants: number +} + +/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `creatable` when they can also be created and deleted, `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 + creatable: boolean + baked: boolean + parts: boolean + /** The sizes the scenes can be built at, or null when each entry has its own. */ + sizes: SceneSizes | null +} + +/** The sizes a scene view builds its scenes at, as blocks across, smallest first, and the one shown first (IrisApi SceneSizes). */ +export interface SceneSizes { + blocksAcross: number[] + opening: number +} + +/** One timed bake of a scene entry (IrisApi BakeRun): a time per step, added up over every variant. */ +export interface BakeRun { + variantCount: number + stages: { label: string; nanos: number }[] +} + +/** Where a value sits in a JSON file: member names and element indices from the root. */ +export type JsonPath = (string | number)[] + +/** An entry's file as the node editor shows it (StudioEditors.EditorState). */ +export interface EditorState { + /** Where it is below the pack folder. */ + file: string + /** Tells this text from any other; an edit sent with an older one is refused. */ + revision: string + text: string + /** The file as nodes, or null when it can't be read as nodes and `problem` says why. */ + roots: GraphNode[] | null + problem: string | null + /** Why the file can't be edited here, such as outside a studio world; null when it can. */ + locked: string | null + types: Record +} + +export interface GraphNode { + kind: string + title: string + path: JsonPath + /** The scene part it draws, or NO_PART. */ + partId: number + roles: string[] + settings: NodeSettings[] + children: { wire: string; node: GraphNode }[] + /** The array a node moved under this one joins; null when nothing can move here. */ + childList: JsonPath | null + movable: boolean + duplicable: boolean + additions: { label: string; list: JsonPath; literal: string }[] +} + +export const NO_PART = -1 + +/** The settings of the object at `path`, of schema type `type`, without the members shown as nodes. */ +export interface NodeSettings { + title: string + path: JsonPath + type: string + shownAsNodes: string[] +} + +/** A settings type of the pack's schema (SchemaTypes.TypeWire). */ +export interface SettingsType { + description: string + options: SettingOption[] +} + +export interface SettingOption { + name: string + description: string + required: boolean + minimum: number | null + maximum: number | null + minItems: number | null + defaultValue: unknown + kind: ValueKind +} + +export type ValueKind = + | { kind: 'boolean' } + | { kind: 'integer' } + | { kind: 'decimal' } + | { kind: 'text'; format: string } + | { kind: 'reference'; reference: string; format: string } + | { kind: 'resource'; resource: string } + | { kind: 'enum'; constants: { name: string; description: string }[] } + | { kind: 'list'; element: ValueKind; unique: boolean } + | { kind: 'map'; value: ValueKind } + | { kind: 'object'; type: string } + | { kind: 'host'; type: string } + | { kind: 'any' } + +/** One change the node editor makes (GraphEditRequest). */ +export type GraphEdit = + | { op: 'set'; object: JsonPath; key: string; literal: string } + | { op: 'unset'; object: JsonPath; key: string } + | { op: 'append'; list: JsonPath; literal: string } + | { op: 'addItem'; list: JsonPath } + | { op: 'delete'; path: JsonPath } + | { op: 'duplicate'; path: JsonPath } + | { op: 'move'; path: JsonPath; toList: JsonPath } + +/** Something a pattern view lays out, such as one of a biome's palettes (IrisApi PatternEntry). */ +export interface PatternEntry { + key: string + name: string + /** The heading it is listed under, such as its biome. */ + group: string + /** How many depths below the top it has a pick for; at least 1. */ + depths: number + /** Short lines about it, such as its blocks and noise. */ + facts: string[] +} + +/** What a pattern entry places across a square of columns, row by row from the north west. */ +export interface PatternTile { + columns: number + blocksPerColumn: number + /** The block states the picks index, as BlockState keys; a plugin's block by the name the pack gives it. */ + blocks: string[] + /** Per block, the state players see and the studio draws: the block itself, or the vanilla state a plugin block borrows. */ + drawnAs: string[] + /** Each column's block, or NO_PATTERN_BLOCK where the pattern places none. */ + picks: Int16Array +} + +export const NO_PATTERN_BLOCK = -1 + +/** A world saved on the server's disk, a dimension folder of region files. */ +export interface SavedWorldInfo { + /** Its folder below the server's level folder. */ + id: string + name: string + /** Who added the dimension, such as minecraft or iris. */ + namespace: string +} + +/** One noise the noise view can show. */ +export interface NoiseSource { + id: string + name: string + category: string + /** Whether the view's seed changes it; the dimension's overlay keeps the world's. */ + usesSeed: boolean + /** What the noise spans where it is measured in blocks above the fluid; null for noise of 0 to 1. */ + blockRange: { lowest: number; highest: number } | null +} + +/** A square of noise values, a pixel's value taken at its north west corner, row by row from the north west. */ +export interface NoiseTile { + size: number + values: Float32Array +} + +/** Where a saved world's view opens: the middle of the region nearest the origin, and how its ground lies there. */ +export interface SavedStart { + centerX: number + centerZ: number + minY: number + lowestGround: number + highestGround: number + /** The water surface most water lies at, or null where the region holds none. */ + seaLevel: number | null +} + +/** A square of a saved world, one column per pixel, row by row from the north west. */ +export interface SavedTile { + size: number + blocksPerPixel: number + /** The top block of the ground under any water; {@link noGround} where nothing finished is saved. */ + groundY: Int16Array + /** The top water block over the ground; {@link noWater} where it is dry. */ + waterSurfaceY: Int16Array + /** Indices into {@link blockNames}, {@link blocksDrawnAs} and {@link biomeLabels}. */ + blocks: Int16Array + biomes: Int16Array + /** Each block without its properties; a plugin's block by the name its plugin gives it. */ + blockNames: string[] + /** Per block, the state it was saved as, which players see and the studio draws; a plugin block's is the vanilla state it borrows. */ + blocksDrawnAs: string[] + biomeLabels: MapLabel[] + noGround: number + noWater: number +} + +export interface WorldInfo { + world: string + dimension: string + dimensionName: string + seed: string + minY: number + height: number + fluidHeight: number + tileSize: number + hasPlayers: boolean + views: ViewInfo[] +} + +export interface MapHover { + worldX: number + worldZ: number + biome: MapLabel | null + caveBiome: MapLabel | null + region: MapLabel | null + vanillaBiome: string | null + height: number + fluidHeight: number + slopeDegrees: number + biomeFile: string | null + regionFile: string | null + /** How the spot got its region and the biome the view shows, region first. */ + pickPath: PickStep[] +} + +/** REGION, BIOME and CHILD were picked by noise; IMAGE_MAP, FOCUS and PREVIEW were set without a pick. */ +export type PickKind = 'REGION' | 'BIOME' | 'CHILD' | 'IMAGE_MAP' | 'FOCUS' | 'PREVIEW' + +export interface PickStep { + kind: PickKind + picked: MapLabel + /** The biome list a BIOME step picked from, such as "land". */ + list: string | null + /** The parent name a CHILD step replaced; null when the parent kept the spot. */ + replaced: string | null + /** 0 to 1; null when nothing was picked. */ + noise: number | null + bands: PickBand[] +} + +/** One option's share of a pick noise: picked from `from` up to `to`. */ +export interface PickBand { + option: MapLabel + from: number + to: number +} + +/** How the noise picks what an area of the map shows (MapPickInspection). */ +export interface PickInspection { + detail: string + sections: PickSection[] +} + +/** The picks on one region's ground; `region` is null in the region view, where the regions themselves are picked. */ +export interface PickSection { + region: MapLabel | null + /** How much of the area's picked ground the region holds. */ + share: number + biomeCount: number + spreads: PickSpread[] +} + +/** One noise in the area: its values in 50 equal steps from 0 to 1, and each option's share of it. */ +export interface PickSpread { + title: string + bands: PickBand[] + histogram: number[] + samples: number + rows: PickShare[] +} + +/** `weight`: how much of the noise picks the option; `inView`: how much of the area's values do. */ +export interface PickShare { + option: MapLabel + weight: number + inView: number +} + +/** How the region and biome views draw their picks: the labels, the noise that picked them, or the labels by noise. */ +export type PickDisplay = 'picks' | 'noise' | 'both' + +export interface Marker { + label: string + worldX: number + worldY: number + worldZ: number + /** The way it faces, in Minecraft's degrees: 0 is south, 90 is west; 0 for entities. */ + yaw: number + health: number + maxHealth: number +} + +/** What the server asks of its machine, as it sends it every second. */ +export interface ServerUsage { + /** The server's CPU use with 100 per busy thread, or null when the JVM cannot tell. */ + cpuPercent: number | null + /** The threads the server's CPU has, so the CPU can reach 100 times this. */ + threads: number + heapUsedBytes: number + heapMaxBytes: number +} + +/** + * A decoded map tile. Grids hold (size + 2)² cells, the tile's pixels inside a ring of its neighbours' edge pixels. + */ +export interface MapTile { + size: number + blocksPerPixel: number + subjectKind: LabelKind + labels: MapLabel[] + subjects: Int16Array + regions: Int16Array + heights: Float32Array | null + /** The noise value that settled each cell's pick, 0 to 1 and NaN where nothing picked it; null unless asked for. */ + pickNoise: Float32Array | null + /** The block on top of each cell's column; null unless asked for. */ + blocks: TileBlocks | null +} + +/** Where a tile's blocks come from: the chunks the server generates in memory. */ +export type BlockSource = 'generated' + +/** + * The top of each cell's column: its ground block, the terrain's top; the block standing on it, such as grass; and the + * solid blocks raised above it, such as a tree's wood and leaves. + */ +export interface TileBlocks { + /** The block states the grids index, as BlockState keys. */ + names: string[] + /** {@link NO_BLOCK} where the column holds no ground. */ + ground: Int16Array + /** {@link NO_BLOCK} where nothing stands on the ground. */ + cover: Int16Array + /** Where each cell's raised blocks start in {@link raisedY} and {@link raised}, with one more entry for where the last cell's end. */ + raisedStart: Int32Array + /** The Y of each raised block, cell after cell and each cell's highest first. */ + raisedY: Int16Array + /** Each raised block, in the order of {@link raisedY}. */ + raised: Int16Array + /** The blocks seen from the open air, where the tile is a block a column and they were asked for; else null. */ + voxels: TileVoxels | null + /** The runs of solid blocks of the area each cell stands for, where the tile is coarser and they were asked for; else null. */ + runs: TileRuns | null + /** Each named block's model with its pictures placed, for the blocks {@link voxels} names; the tile source fills it in. */ + models: (CoverLook | null)[] + /** The colour of each named block from above, as 0xRRGGBB; the tile source fills it in. */ + colors: number[] + /** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */ + looks: (BlockLook | null)[] + /** What each named block looks like standing on the ground, for the blocks {@link cover} names, on a tile that shows textures; else empty. */ + covers: (CoverLook | null)[] +} + +/** + * The blocks of a tile that can be seen from the open air, as the server found them in the chunks it generated, with + * the sides of each that face that air. + */ +export interface TileVoxels { + /** Each block's column from the tile's west edge. */ + x: Uint8Array + /** Each block's column from the tile's north edge. */ + z: Uint8Array + y: Int16Array + /** Each block's index in the tile's block names. */ + blocks: Int16Array + /** The sides of each block that face the open air, a bit each in {@link VOXEL_SIDES}' order. */ + faces: Uint8Array + /** The sky's light each block shows on faces that stand inside it, such as a plant's, 0 to 15. */ + lights: Uint8Array + /** The shade of each face {@link faces} names, block after block and side after side, as skyLight reads it. */ + shades: Uint16Array +} + +/** + * The ground of a coarser tile in 3D, as Distant Horizons draws far terrain: for each cell, the runs of solid blocks of + * the area it stands for, highest first. The last run of a cell is its ground, which reaches down out of sight. + */ +export interface TileRuns { + /** Where each cell's runs start in the arrays below, with one more entry for where the last cell's end. */ + starts: Int32Array + bottoms: Int16Array + tops: Int16Array + /** The index in the tile's block names of the block most of each run's top shows. */ + blocks: Int16Array + /** The index of the plant most often standing on each run's top, or {@link NO_BLOCK}. */ + covers: Int16Array + /** How much of each run's top plants stand on, 0 to 255 for all of it. */ + coverShares: Uint8Array + /** The sky's light on each run's top, the mean of its blocks' tops, in sixteenths of a level. */ + lights: Uint8Array + /** How many opaque cells stand around each corner of each run's top, the mean of its blocks' tops, in sixty-fourths. */ + occlusions: Uint8Array +} + +/** {@link TileRuns.lights} to a light level. */ +export const RUN_LIGHT_STEPS = 16 +/** {@link TileRuns.occlusions} to a count of opaque cells. */ +export const RUN_OCCLUSION_STEPS = 64 + +/** The order of the sides in {@link TileVoxels.faces}. */ +export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const + +export const NO_BLOCK = -1 +export const NO_LABEL = -1 diff --git a/studio/src/renderer/src/components/IdeIcon.tsx b/studio/src/renderer/src/components/IdeIcon.tsx new file mode 100644 index 000000000..beaa821e8 --- /dev/null +++ b/studio/src/renderer/src/components/IdeIcon.tsx @@ -0,0 +1,64 @@ +import { cn } from '@/lib/utils' + +// IntelliJ's expui icons and the studio's own drawn to match (see icons/NOTICE.txt): each has a light file and a "_dark" twin in its own colours. +const ICON_URLS = import.meta.glob('../icons/**/*.svg', { eager: true, query: '?url', import: 'default' }) +const DARK_SUFFIX = '_dark' + +export type IdeIconName = + | 'actualZoom' + | 'add' + | 'blocks' + | 'borders' + | 'checked' + | 'closeSmall' + | 'chevronLeft' + | 'chevronRight' + | 'decoration' + | 'delete' + | 'exit' + | 'grid' + | 'groups' + | 'help' + | 'lightning' + | 'locate' + | 'locked' + | 'memory' + | 'mob' + | 'redo' + | 'refresh' + | 'reset' + | 'search' + | 'settings' + | 'shading' + | 'stopWatch' + | 'symlink' + | 'theme' + | 'undo' + | 'web' + | 'views/biomes' + | 'views/noise' + | 'views/objects' + | 'views/palettes' + | 'views/procedural' + | 'views/regions' + | 'views/saved-world' + | 'views/world-3d' + +function iconUrl(name: string): string { + const url = ICON_URLS[`../icons/${name}.svg`] + if (url === undefined) { + throw new Error(`No icon named ${name}`) + } + return url +} + +/** An IntelliJ icon, 16 px unless sized, in the light or dark colours the window shows. */ +export function IdeIcon({ name, className }: { name: IdeIconName; className?: string }): React.JSX.Element { + const size = cn('size-4 shrink-0', className) + return ( + <> + + + + ) +} diff --git a/studio/src/renderer/src/components/ui/button.tsx b/studio/src/renderer/src/components/ui/button.tsx new file mode 100644 index 000000000..0d202d63f --- /dev/null +++ b/studio/src/renderer/src/components/ui/button.tsx @@ -0,0 +1,63 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" +import { Slot } from "radix-ui" + +const buttonVariants = cva( + "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", + outline: + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: + "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", + "icon-sm": "size-8", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot.Root : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/studio/src/renderer/src/components/ui/context-menu.tsx b/studio/src/renderer/src/components/ui/context-menu.tsx new file mode 100644 index 000000000..2c427349a --- /dev/null +++ b/studio/src/renderer/src/components/ui/context-menu.tsx @@ -0,0 +1,254 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { IdeIcon } from "@/components/IdeIcon" +import { ContextMenu as ContextMenuPrimitive } from "radix-ui" + +function ContextMenu({ + ...props +}: React.ComponentProps) { + return +} + +function ContextMenuTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuGroup({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuPortal({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuSub({ + ...props +}: React.ComponentProps) { + return +} + +function ContextMenuRadioGroup({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuSubTrigger({ + className, + inset, + children, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + {children} + + + + + ) +} + +function ContextMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + // Portalled like the menu itself: inside it, the menu's blur and scrolling would clip the submenu away. + return ( + + + + ) +} + +function ContextMenuContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +function ContextMenuItem({ + className, + inset, + variant = "default", + ...props +}: React.ComponentProps & { + inset?: boolean + variant?: "default" | "destructive" +}) { + return ( + + ) +} + +function ContextMenuCheckboxItem({ + className, + children, + checked, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function ContextMenuRadioItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function ContextMenuLabel({ + className, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + ) +} + +function ContextMenuSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuShortcut({ + className, + ...props +}: React.ComponentProps<"span">) { + return ( + + ) +} + +export { + ContextMenu, + ContextMenuTrigger, + ContextMenuContent, + ContextMenuItem, + ContextMenuCheckboxItem, + ContextMenuRadioItem, + ContextMenuLabel, + ContextMenuSeparator, + ContextMenuShortcut, + ContextMenuGroup, + ContextMenuPortal, + ContextMenuSub, + ContextMenuSubContent, + ContextMenuSubTrigger, + ContextMenuRadioGroup, +} diff --git a/studio/src/renderer/src/components/ui/dialog.tsx b/studio/src/renderer/src/components/ui/dialog.tsx new file mode 100644 index 000000000..c024d32ea --- /dev/null +++ b/studio/src/renderer/src/components/ui/dialog.tsx @@ -0,0 +1,158 @@ +"use client" + +import * as React from "react" +import { cn } from "@/lib/utils" +import { IdeIcon } from "@/components/IdeIcon" +import { Dialog as DialogPrimitive } from "radix-ui" + +import { Button } from "@/components/ui/button" + +function Dialog({ + ...props +}: React.ComponentProps) { + return +} + +function DialogTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function DialogPortal({ + ...props +}: React.ComponentProps) { + return +} + +function DialogClose({ + ...props +}: React.ComponentProps) { + return +} + +function DialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: React.ComponentProps & { + showCloseButton?: boolean +}) { + return ( + + + + {children} + {showCloseButton && ( + + + Close + + )} + + + ) +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function DialogFooter({ + className, + showCloseButton = false, + children, + ...props +}: React.ComponentProps<"div"> & { + showCloseButton?: boolean +}) { + return ( +
+ {children} + {showCloseButton && ( + + + + )} +
+ ) +} + +function DialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} diff --git a/studio/src/renderer/src/components/ui/input.tsx b/studio/src/renderer/src/components/ui/input.tsx new file mode 100644 index 000000000..1e3b93289 --- /dev/null +++ b/studio/src/renderer/src/components/ui/input.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import { cn } from "@/lib/utils" + +function Input({ className, type, ...props }: React.ComponentProps<"input">) { + return ( + + ) +} + +export { Input } diff --git a/studio/src/renderer/src/components/ui/kbd.tsx b/studio/src/renderer/src/components/ui/kbd.tsx new file mode 100644 index 000000000..95601b25b --- /dev/null +++ b/studio/src/renderer/src/components/ui/kbd.tsx @@ -0,0 +1,28 @@ +import { cn } from "@/lib/utils" + +function Kbd({ className, ...props }: React.ComponentProps<"kbd">) { + return ( + + ) +} + +function KbdGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( + + ) +} + +export { Kbd, KbdGroup } diff --git a/studio/src/renderer/src/components/ui/scroll-area.tsx b/studio/src/renderer/src/components/ui/scroll-area.tsx new file mode 100644 index 000000000..b699a24ff --- /dev/null +++ b/studio/src/renderer/src/components/ui/scroll-area.tsx @@ -0,0 +1,57 @@ +"use client" + +import * as React from "react" +import { cn } from "@/lib/utils" +import { ScrollArea as ScrollAreaPrimitive } from "radix-ui" + +function ScrollArea({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + + ) +} + +function ScrollBar({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { ScrollArea, ScrollBar } diff --git a/studio/src/renderer/src/components/ui/separator.tsx b/studio/src/renderer/src/components/ui/separator.tsx new file mode 100644 index 000000000..056d875a1 --- /dev/null +++ b/studio/src/renderer/src/components/ui/separator.tsx @@ -0,0 +1,25 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { Separator as SeparatorPrimitive } from "radix-ui" + +function Separator({ + className, + orientation = "horizontal", + decorative = true, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Separator } diff --git a/studio/src/renderer/src/components/ui/toggle-group.tsx b/studio/src/renderer/src/components/ui/toggle-group.tsx new file mode 100644 index 000000000..54d3d9019 --- /dev/null +++ b/studio/src/renderer/src/components/ui/toggle-group.tsx @@ -0,0 +1,69 @@ +import * as React from "react" +import { type VariantProps } from "class-variance-authority" +import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" +import { toggleVariants } from "@/components/ui/toggle" + +const ToggleGroupContext = React.createContext>({ + size: "default", + variant: "default", +}) + +function ToggleGroup({ + className, + variant, + size, + children, + ...props +}: React.ComponentProps & + VariantProps) { + return ( + + + {children} + + + ) +} + +function ToggleGroupItem({ + className, + children, + variant, + size, + ...props +}: React.ComponentProps & + VariantProps) { + const context = React.useContext(ToggleGroupContext) + + return ( + + {children} + + ) +} + +export { ToggleGroup, ToggleGroupItem } diff --git a/studio/src/renderer/src/components/ui/toggle.tsx b/studio/src/renderer/src/components/ui/toggle.tsx new file mode 100644 index 000000000..137c38510 --- /dev/null +++ b/studio/src/renderer/src/components/ui/toggle.tsx @@ -0,0 +1,44 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" +import { Toggle as TogglePrimitive } from "radix-ui" + +const toggleVariants = cva( + "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-transparent", + outline: + "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground", + }, + size: { + default: "h-9 min-w-9 px-2", + sm: "h-8 min-w-8 px-1.5", + lg: "h-10 min-w-10 px-2.5", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Toggle({ + className, + variant, + size, + ...props +}: React.ComponentProps & + VariantProps) { + return ( + + ) +} + +export { Toggle, toggleVariants } diff --git a/studio/src/renderer/src/components/ui/tooltip.tsx b/studio/src/renderer/src/components/ui/tooltip.tsx new file mode 100644 index 000000000..ccc8fd335 --- /dev/null +++ b/studio/src/renderer/src/components/ui/tooltip.tsx @@ -0,0 +1,55 @@ +"use client" + +import * as React from "react" +import { cn } from "@/lib/utils" +import { Tooltip as TooltipPrimitive } from "radix-ui" + +function TooltipProvider({ + delayDuration = 0, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function Tooltip({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipContent({ + className, + sideOffset = 6, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + ) +} + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } diff --git a/studio/src/renderer/src/css.d.ts b/studio/src/renderer/src/css.d.ts new file mode 100644 index 000000000..5894ae0b6 --- /dev/null +++ b/studio/src/renderer/src/css.d.ts @@ -0,0 +1 @@ +declare module '*.css' diff --git a/studio/src/renderer/src/editor/EditHistory.test.ts b/studio/src/renderer/src/editor/EditHistory.test.ts new file mode 100644 index 000000000..a0852bf6e --- /dev/null +++ b/studio/src/renderer/src/editor/EditHistory.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import { EditHistory } from './EditHistory' + +describe('EditHistory', () => { + it('undoes back to the text before an edit and redoes forward again', () => { + const history = new EditHistory() + history.edited('a') + + expect(history.nextUndo()).toBe('a') + history.undone('b') + expect(history.canUndo).toBe(false) + expect(history.nextRedo()).toBe('b') + history.redone('a') + expect(history.nextUndo()).toBe('a') + }) + + it('forgets what could be redone once a new edit is made', () => { + const history = new EditHistory() + history.edited('a') + history.undone('b') + + history.edited('a') + + expect(history.canRedo).toBe(false) + }) + + it('keeps the history as it was when an undo is never written', () => { + const history = new EditHistory() + history.edited('a') + + history.nextUndo() + + expect(history.canUndo).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/editor/EditHistory.ts b/studio/src/renderer/src/editor/EditHistory.ts new file mode 100644 index 000000000..b1b002caa --- /dev/null +++ b/studio/src/renderer/src/editor/EditHistory.ts @@ -0,0 +1,45 @@ +const KEPT_STEPS = 100 + +/** + * The texts a file had before each edit, so undoing writes an earlier text back whole. A step is only taken once its + * write succeeded, so a refused undo leaves the history as it was. + */ +export class EditHistory { + private readonly undos: string[] = [] + private readonly redos: string[] = [] + + get canUndo(): boolean { + return this.undos.length > 0 + } + + get canRedo(): boolean { + return this.redos.length > 0 + } + + edited(before: string): void { + this.undos.push(before) + if (this.undos.length > KEPT_STEPS) { + this.undos.shift() + } + this.redos.length = 0 + } + + /** The text undoing writes, if there is one. */ + nextUndo(): string | undefined { + return this.undos.at(-1) + } + + undone(before: string): void { + this.undos.pop() + this.redos.push(before) + } + + nextRedo(): string | undefined { + return this.redos.at(-1) + } + + redone(before: string): void { + this.redos.pop() + this.undos.push(before) + } +} diff --git a/studio/src/renderer/src/editor/curves.test.ts b/studio/src/renderer/src/editor/curves.test.ts new file mode 100644 index 000000000..8e00a484b --- /dev/null +++ b/studio/src/renderer/src/editor/curves.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves' + +describe('isCurve', () => { + it('holds only for keyframes and named shapes', () => { + expect(isCurve([[0, 1.3], [1, 0.2]])).toBe(true) + expect(isCurve({ shape: 'power', exponent: 3 })).toBe(true) + expect(isCurve([15, 20])).toBe(false) + expect(isCurve(4)).toBe(false) + expect(isCurve({ min: 3, max: 8 })).toBe(false) + expect(isCurve({ shape: 'zigzag' })).toBe(false) + }) +}) + +describe('samplesOf', () => { + it('runs from the start of the curve to its end', () => { + expect(samplesOf([[0, 1.3], [1, 0.2]], 3)).toEqual([1.3, 0.75, 0.2].map((expected) => expect.closeTo(expected, 9))) + }) + + it('has none for a value that is no curve', () => { + expect(samplesOf(4, 3)).toBeNull() + }) + + it('follows a named curve between its from and to', () => { + expect(curveAt({ shape: 'power', exponent: 2, from: 10, to: 20 }, 0.5)).toBeCloseTo(12.5, 9) + expect(curveAt({ shape: 'linear' }, 0.25)).toBeCloseTo(0.25, 9) + }) + + it('holds the first and last values beyond the keyframes', () => { + expect(curveAt([[0.2, 5], [0.8, 9]], 0)).toBe(5) + expect(curveAt([[0.2, 5], [0.8, 9]], 1)).toBe(9) + }) +}) + +describe('curveFrom', () => { + it('makes a number a flat curve and a range a rising one', () => { + expect(curveFrom(4)).toEqual([[0, 4], [1, 4]]) + expect(curveFrom([15, 20])).toEqual([[0, 15], [1, 20]]) + expect(curveFrom({ min: 3, max: 8 })).toEqual([[0, 3], [1, 8]]) + }) + + it('leaves what is not a number or range alone', () => { + expect(curveFrom('wood')).toBeNull() + expect(canBecomeCurve([[0, 1], [1, 2]])).toBe(false) + expect(canBecomeCurve(4)).toBe(true) + }) +}) + +describe('changing how a curve is written', () => { + it('turns keyframes into a linear shape between their ends, and back into sampled keyframes', () => { + const shape = shapeFrom([[1, 8], [0, 2]]) + + expect(shape).toEqual({ shape: 'linear', from: 2, to: 8 }) + expect(keyframesFrom(shape).map(([t, value]) => [t, value])).toEqual([[0, 2], [0.25, 3.5], [0.5, 5], [0.75, 6.5], [1, 8]]) + }) + + it('sets a shape setting, or leaves it out so the default applies', () => { + expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', 4)).toEqual({ shape: 'power', exponent: 4 }) + expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', undefined)).toEqual({ shape: 'power' }) + }) + + it('keeps from and to when the shape changes, but not the old shape settings', () => { + expect(withShape({ shape: 'power', exponent: 3, from: 1, to: 4 }, 'sine')).toEqual({ shape: 'sine', from: 1, to: 4 }) + }) +}) + +describe('editing keyframes', () => { + const keys: [number, number][] = [[0, 1], [1, 3]] + + it('adds a keyframe halfway across the widest gap, on the curve', () => { + expect(withAddedKeyframe(keys)).toEqual([[0, 1], [0.5, 2], [1, 3]]) + expect(withAddedKeyframe([[0, 1], [0.25, 1], [1, 3]])[2]).toEqual([0.625, expect.closeTo(1 + (2 * 0.375) / 0.75, 9)]) + }) + + it('gives a lone keyframe a partner at the other end', () => { + expect(withAddedKeyframe([[0, 4]])).toEqual([[0, 4], [1, 4]]) + }) + + it('sets and removes a keyframe but never removes the last one', () => { + expect(withKeyframe(keys, 1, [0.9, 5])).toEqual([[0, 1], [0.9, 5]]) + expect(withoutKeyframe(keys, 0)).toEqual([[1, 3]]) + expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]]) + }) +}) diff --git a/studio/src/renderer/src/editor/curves.ts b/studio/src/renderer/src/editor/curves.ts new file mode 100644 index 000000000..5cf2a1fc9 --- /dev/null +++ b/studio/src/renderer/src/editor/curves.ts @@ -0,0 +1,217 @@ +/** One keyframe of a curve: where it is from 0 to 1, and the value there. */ +export type Keyframe = [number, number] + +export interface ShapeParameter { + name: string + fallback: number +} + +/** A named curve (ProceduralValue.CurveShape): from 0 at t = 0 toward 1, stretched between a value's from and to. */ +export interface CurveShape { + key: string + parameters: ShapeParameter[] + at(t: number, parameter: (name: string) => number): number +} + +const DEFAULT_FROM = 0 +const DEFAULT_TO = 1 +const KEYFRAME_SIZE = 2 +const RANGE_SIZE = 2 +const NARROWEST_BELL = 1e-6 +const SHAPE_STOPS = 5 +const FIRST_STOP = 0 +const LAST_STOP = 1 + +export const CURVE_SHAPES: CurveShape[] = [ + { key: 'linear', parameters: [], at: (t) => t }, + { key: 'smooth', parameters: [], at: (t) => t * t * (3 - 2 * t) }, + { key: 'power', parameters: [{ name: 'exponent', fallback: 2 }], at: (t, p) => Math.pow(t, p('exponent')) }, + { + key: 'sigmoid', + parameters: [ + { name: 'steepness', fallback: 10 }, + { name: 'mid', fallback: 0.5 } + ], + at: (t, p) => 1 / (1 + Math.exp(-p('steepness') * (t - p('mid')))) + }, + { + key: 'bell', + parameters: [ + { name: 'mid', fallback: 0.5 }, + { name: 'width', fallback: 0.15 } + ], + at: (t, p) => Math.exp(-0.5 * Math.pow((t - p('mid')) / Math.max(NARROWEST_BELL, p('width')), 2)) + }, + { + key: 'periodic', + parameters: [ + { name: 'periods', fallback: 4 }, + { name: 'sharpness', fallback: 8 } + ], + at: (t, p) => Math.pow(Math.max(0, Math.sin(2 * Math.PI * t * p('periods'))), p('sharpness')) + }, + { key: 'sine', parameters: [{ name: 'periods', fallback: 1 }], at: (t, p) => 0.5 + 0.5 * Math.sin(2 * Math.PI * t * p('periods')) } +] + +export function shapeNamed(key: unknown): CurveShape | undefined { + return typeof key === 'string' ? CURVE_SHAPES.find((shape) => shape.key === key.toLowerCase()) : undefined +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isKeyframe(value: unknown): value is Keyframe { + return Array.isArray(value) && value.length === KEYFRAME_SIZE && value.every((part) => typeof part === 'number') +} + +/** Whether {@code value} is keyframes [[t, value], ...], which a range [min, max] and a number are not. */ +export function isKeyframes(value: unknown): value is Keyframe[] { + return Array.isArray(value) && value.length > 0 && value.every(isKeyframe) +} + +/** Whether {@code value} is a named curve {"shape": ...} the studio knows. */ +export function isShape(value: unknown): value is Record { + return isObject(value) && shapeNamed(value.shape) !== undefined +} + +/** Whether {@code value} is a curve, as opposed to a number or a [min, max] range. */ +export function isCurve(value: unknown): boolean { + return isKeyframes(value) || isShape(value) +} + +/** Whether {@code value} is a number or a range, which {@link curveFrom} makes a curve. */ +export function canBecomeCurve(value: unknown): boolean { + return typeof value === 'number' || rangeOf(value) !== null +} + +function rangeOf(value: unknown): [number, number] | null { + if (Array.isArray(value) && value.length === RANGE_SIZE && value.every((part) => typeof part === 'number')) { + return [value[0], value[1]] + } + if (isObject(value) && typeof value.min === 'number' && typeof value.max === 'number') { + return [value.min, value.max] + } + return null +} + +/** A number as a curve that stays at it, a range as a curve rising from its low end to its high end; null for anything else. */ +export function curveFrom(value: unknown): Keyframe[] | null { + if (typeof value === 'number') { + return [ + [0, value], + [1, value] + ] + } + const range = rangeOf(value) + return range === null + ? null + : [ + [0, range[0]], + [1, range[1]] + ] +} + +function numberOf(written: unknown, fallback: number): number { + return typeof written === 'number' ? written : fallback +} + +/** The value of a curve at {@code t}, from 0 to 1; NaN for a value that is no curve. */ +export function curveAt(value: unknown, t: number): number { + if (isKeyframes(value)) { + return keyframesAt(sortedKeyframes(value), t) + } + if (!isShape(value)) { + return Number.NaN + } + const shape = shapeNamed(value.shape)! + const from = numberOf(value.from, DEFAULT_FROM) + const to = numberOf(value.to, DEFAULT_TO) + const parameter = (name: string): number => numberOf(value[name], shape.parameters.find((candidate) => candidate.name === name)!.fallback) + return from + (to - from) * shape.at(Math.max(0, Math.min(1, t)), parameter) +} + +export function sortedKeyframes(keys: Keyframe[]): Keyframe[] { + return [...keys].sort((a, b) => a[0] - b[0]) +} + +function keyframesAt(keys: Keyframe[], t: number): number { + if (t <= keys[0][0]) { + return keys[0][1] + } + for (let index = 1; index < keys.length; index++) { + if (t <= keys[index][0]) { + const span = keys[index][0] - keys[index - 1][0] + const blend = span <= 0 ? 1 : (t - keys[index - 1][0]) / span + return keys[index - 1][1] + (keys[index][1] - keys[index - 1][1]) * blend + } + } + return keys[keys.length - 1][1] +} + +/** {@code count} values of the curve, from its start to its end; null for a value that is no curve. */ +export function samplesOf(value: unknown, count: number): number[] | null { + if (!isCurve(value)) { + return null + } + return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1))) +} + +/** The curve as keyframes, such as to move a named curve's shape by hand: its values at evenly spaced points. */ +export function keyframesFrom(value: unknown): Keyframe[] { + if (isKeyframes(value)) { + return value + } + const stops = Array.from({ length: SHAPE_STOPS }, (_, index) => FIRST_STOP + ((LAST_STOP - FIRST_STOP) * index) / (SHAPE_STOPS - 1)) + return stops.map((t): Keyframe => [t, curveAt(value, t)]) +} + +/** A linear named curve between the first and last keyframes' values, or the shape itself. */ +export function shapeFrom(value: unknown): Record { + if (isShape(value)) { + return value + } + const keys = isKeyframes(value) ? sortedKeyframes(value) : [] + return { shape: 'linear', from: keys.length > 0 ? keys[0][1] : DEFAULT_FROM, to: keys.length > 0 ? keys[keys.length - 1][1] : DEFAULT_TO } +} + +/** The shape with {@code key}, keeping its from and to; the other settings of the old shape do not carry over. */ +export function withShape(shape: Record, key: string): Record { + return { shape: key, from: numberOf(shape.from, DEFAULT_FROM), to: numberOf(shape.to, DEFAULT_TO) } +} + +/** The shape with {@code name} set to {@code number}, or left out when it is undefined so the shape's own default applies. */ +export function withSetting(shape: Record, name: string, number: number | undefined): Record { + const { [name]: _replaced, ...others } = shape + return number === undefined ? others : { ...others, [name]: number } +} + +/** The keyframes with the one at {@code index} (as listed) set to {@code keyframe}. */ +export function withKeyframe(keys: Keyframe[], index: number, keyframe: Keyframe): Keyframe[] { + return keys.map((existing, position) => (position === index ? keyframe : existing)) +} + +/** The keyframes without the one at {@code index}; the last one stays, since a curve needs a keyframe. */ +export function withoutKeyframe(keys: Keyframe[], index: number): Keyframe[] { + return keys.length <= 1 ? keys : keys.filter((_, position) => position !== index) +} + +/** The keyframes with one more halfway across the widest gap, on the curve as it is; a lone keyframe gets one at the other end. */ +export function withAddedKeyframe(keys: Keyframe[]): Keyframe[] { + const sorted = sortedKeyframes(keys) + if (sorted.length === 1) { + const t = sorted[0][0] === LAST_STOP ? FIRST_STOP : LAST_STOP + return sortedKeyframes([...sorted, [t, sorted[0][1]]]) + } + let widest = 0 + let before = 0 + for (let index = 1; index < sorted.length; index++) { + const gap = sorted[index][0] - sorted[index - 1][0] + if (gap > widest) { + widest = gap + before = index - 1 + } + } + const t = sorted[before][0] + widest / 2 + return sortedKeyframes([...sorted, [t, keyframesAt(sorted, t)]]) +} diff --git a/studio/src/renderer/src/editor/entryKeys.test.ts b/studio/src/renderer/src/editor/entryKeys.test.ts new file mode 100644 index 000000000..7e57836b8 --- /dev/null +++ b/studio/src/renderer/src/editor/entryKeys.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { folderPrefixOf, refusalOfNewKey } from './entryKeys' + +describe('refusalOfNewKey', () => { + it('accepts a free, plain key', () => { + expect(refusalOfNewKey('trees/oak-2', ['trees/oak'])).toBeNull() + }) + + it('refuses a key that is taken', () => { + expect(refusalOfNewKey('trees/oak', ['trees/oak'])).toBe('trees/oak already exists') + }) + + it('refuses a blank name', () => { + expect(refusalOfNewKey(' ', [])).toBe('Give it a name') + }) + + it('refuses keys that could leave the folder or are not plain', () => { + for (const key of ['Trees/Oak', 'trees//oak', '/oak', 'oak/', '../oak', 'trees/../oak', 'oak.json', 'trees\\oak']) { + expect(refusalOfNewKey(key, []), key).toMatch(/^Use lower case/) + } + }) +}) + +describe('folderPrefixOf', () => { + it('keeps the folders of a key with their closing slash', () => { + expect(folderPrefixOf('trees/oak/tall')).toBe('trees/oak/') + }) + + it('is empty for a key in no folder', () => { + expect(folderPrefixOf('oak')).toBe('') + }) +}) diff --git a/studio/src/renderer/src/editor/entryKeys.ts b/studio/src/renderer/src/editor/entryKeys.ts new file mode 100644 index 000000000..e16123e5f --- /dev/null +++ b/studio/src/renderer/src/editor/entryKeys.ts @@ -0,0 +1,18 @@ +const FOLDER_SEPARATOR = '/' +const KEY = /^[a-z0-9_-]+(\/[a-z0-9_-]+)*$/ + +/** Why `key` can't name a new entry beside the `existing` ones, or null when it can; the server checks the same. */ +export function refusalOfNewKey(key: string, existing: readonly string[]): string | null { + if (key.trim() === '') { + return 'Give it a name' + } + if (!KEY.test(key)) { + return 'Use lower case letters, digits, - and _, with / between folders' + } + return existing.includes(key) ? `${key} already exists` : null +} + +/** The folder of `key` as a start for naming a new entry in it, such as `trees/`; empty for an entry in no folder. */ +export function folderPrefixOf(key: string): string { + return key.slice(0, key.lastIndexOf(FOLDER_SEPARATOR) + 1) +} diff --git a/studio/src/renderer/src/editor/jsonValues.ts b/studio/src/renderer/src/editor/jsonValues.ts new file mode 100644 index 000000000..418f01b2d --- /dev/null +++ b/studio/src/renderer/src/editor/jsonValues.ts @@ -0,0 +1,22 @@ +import type { JsonPath } from '../bridge/types' + +/** The value at {@code path} in a parsed file; undefined where nothing is written. */ +export function valueAt(root: unknown, path: JsonPath): unknown { + let current = root + for (const step of path) { + if (current === null || typeof current !== 'object') { + return undefined + } + current = (current as Record)[step] + } + return current +} + +/** The file parsed, or undefined when it is not JSON (the editor then shows why instead). */ +export function parsedText(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return undefined + } +} diff --git a/studio/src/renderer/src/editor/nodeLayout.test.ts b/studio/src/renderer/src/editor/nodeLayout.test.ts new file mode 100644 index 000000000..78e4d8f97 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeLayout.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import type { GraphNode, JsonPath } from '../bridge/types' +import { NO_PART } from '../bridge/types' +import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout' + +function node(path: JsonPath, children: GraphNode[] = []): GraphNode { + return { + kind: 'Stem', + title: 'Stem', + path, + partId: NO_PART, + roles: [], + settings: [], + children: children.map((child) => ({ wire: '', node: child })), + childList: null, + movable: true, + duplicable: true, + additions: [] + } +} + +describe('layoutNodes', () => { + it('sets a parent level with the middle of its children, a column to their left', () => { + const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])]) + const [first, , last, parent] = layout.nodes + + expect(parent.y).toBe((first.y + last.y) / 2) + expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH) + expect(layout.wires).toHaveLength(3) + }) + + it('lays the next root out under the tree before it', () => { + const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])]) + const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))! + + expect(material.x).toBe(0) + expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y))) + }) +}) + +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) + expect(isWithin(['parts', 0], ['parts', 0])).toBe(true) + expect(isWithin(['parts', 1], ['parts', 0])).toBe(false) + }) +}) diff --git a/studio/src/renderer/src/editor/nodeLayout.ts b/studio/src/renderer/src/editor/nodeLayout.ts new file mode 100644 index 000000000..4f300a441 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeLayout.ts @@ -0,0 +1,108 @@ +import type { GraphNode, JsonPath } from '../bridge/types' + +export const NODE_WIDTH = 168 +export const NODE_HEIGHT = 46 +const COLUMN_GAP = 64 +const ROW_GAP = 10 +const TREE_GAP = 26 + +/** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */ +export interface PlacedNode { + id: string + node: GraphNode + x: number + y: number +} + +export interface PlacedWire { + from: PlacedNode + to: PlacedNode + label: string +} + +export interface NodeLayout { + nodes: PlacedNode[] + wires: PlacedWire[] + width: number + height: number +} + +export function idOf(path: JsonPath): string { + return JSON.stringify(path) +} + +/** The node at {@code path} among the trees of {@code roots}, or null when there is none, such as after it was deleted. */ +export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | null { + const id = idOf(path) + for (const root of roots) { + if (idOf(root.path) === id) { + return root + } + const found = nodeWithPath( + root.children.map((link) => link.node), + path + ) + if (found !== null) { + return found + } + } + 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) +} + +/** + * Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row + * each and a parent sits level with the middle of its children, so wires never cross. + */ +export function layoutNodes(roots: GraphNode[]): NodeLayout { + const nodes: PlacedNode[] = [] + const wires: PlacedWire[] = [] + let nextTop = 0 + let width = 0 + + const place = (node: GraphNode, depth: number): PlacedNode => { + const x = depth * (NODE_WIDTH + COLUMN_GAP) + width = Math.max(width, x + NODE_WIDTH) + const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) })) + const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2 + const placed: PlacedNode = { id: idOf(node.path), node, x, y } + nodes.push(placed) + for (const child of children) { + wires.push({ from: placed, to: child.placed, label: child.label }) + } + return placed + } + + const takeRow = (): number => { + const top = nextTop + nextTop += NODE_HEIGHT + ROW_GAP + return top + } + + for (const root of roots) { + place(root, 0) + nextTop += TREE_GAP + } + return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) } +} diff --git a/studio/src/renderer/src/editor/settingFolds.test.ts b/studio/src/renderer/src/editor/settingFolds.test.ts new file mode 100644 index 000000000..90b180090 --- /dev/null +++ b/studio/src/renderer/src/editor/settingFolds.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from 'vitest' +import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types' +import { foldedSections, idOfFold, visibleFolds } from './settingFolds' + +function option(name: string, kind: ValueKind): SettingOption { + return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } +} + +const text: ValueKind = { kind: 'text', format: 'PLAIN' } +const any: ValueKind = { kind: 'any' } + +const types: Record = { + Material: { + description: '', + options: [ + option('role', text), + option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }), + option('offset', { kind: 'object', type: 'Offset' }), + option('rules', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false }), + option('parts', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false }) + ] + }, + Offset: { description: '', options: [option('x', any), option('y', any)] }, + Rule: { description: '', options: [option('chance', any), option('face', text)] } +} + +const material: NodeSettings = { title: 'Material', path: ['materials', 0], type: 'Material', shownAsNodes: ['parts'] } +const file = { + materials: [ + { + role: 'wood', + block: 'minecraft:birch_wood', + offset: { x: 2, y: [[0, 1], [1, 0]] }, + rules: [{ chance: 0.5 }, { face: 'top' }] + } + ] +} + +describe('foldedSections', () => { + it('folds an object setting into a section, and a list of objects into a section of items', () => { + const folds = foldedSections(material, types, file) + + expect(folds.map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2']) + expect(folds.map((fold) => fold.kind)).toEqual(['own', 'group', 'list', 'item', 'item']) + expect(folds.map((fold) => fold.depth)).toEqual([0, 1, 1, 2, 2]) + expect(folds[4].path).toEqual(['materials', 0, 'rules', 1]) + expect(folds[2].holder).toEqual({ object: ['materials', 0], key: 'rules' }) + }) + + it('leaves the folded settings and the ones shown as nodes out of the fields of the section that holds them', () => { + const [own] = foldedSections(material, types, file) + + expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block']) + }) + + it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => { + const folds = foldedSections(material, types, file) + + expect(folds[0].summary).toBe('role wood · block birch_wood · rules 2') + expect(folds[1].summary).toBe('x 2 · y curve') + expect(folds[2].summary).toBe('2 items') + }) + + it('keeps a setting that is not written as an object a field', () => { + const [own, ...inside] = foldedSections(material, types, { materials: [{ role: 'wood' }] }) + + expect(inside).toEqual([]) + expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules']) + }) +}) + +describe('visibleFolds', () => { + it('hides what is inside a fold that is folded', () => { + const folds = foldedSections(material, types, file) + + expect(visibleFolds(folds, new Set()).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules']) + expect(visibleFolds(folds, new Set([idOfFold(folds[2])])).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2']) + }) +}) diff --git a/studio/src/renderer/src/editor/settingFolds.ts b/studio/src/renderer/src/editor/settingFolds.ts new file mode 100644 index 000000000..f6a9dc943 --- /dev/null +++ b/studio/src/renderer/src/editor/settingFolds.ts @@ -0,0 +1,128 @@ +import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types' +import { isCurve } from './curves' +import { isWithin } from './nodeLayout' +import { textOf } from './settingText' +import { valueAt } from './jsonValues' + +const SUMMARY_SETTINGS = 3 +const SUMMARY_SEPARATOR = ' · ' +const DEFAULT_NAMESPACE = 'minecraft:' + +/** + * What a section is: a node's own settings, a setting written as an object, a setting written as a list of objects, or + * one element of such a list. All but the first fold. + */ +export type FoldKind = 'own' | 'group' | 'list' | 'item' + +/** One object of the file whose settings the inspector shows, below the ones that hold it. */ +export interface SettingsFold { + title: string + path: JsonPath + type: string + kind: FoldKind + /** 0 for a node's own sections, one more for each object it is inside. */ + depth: number + /** A short reading of what it holds, shown while it is folded. */ + summary: string + /** The object and member that hold a group or list, to unset it; null for the rest. */ + holder: { object: JsonPath; key: string } | null + /** The settings written plainly in it, as fields; those that are folds of their own are not among them. */ + options: SettingOption[] +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isObjects(value: unknown): value is Record[] { + return Array.isArray(value) && value.every(isObject) +} + +export function idOfFold(fold: SettingsFold): string { + return JSON.stringify(fold.path) +} + +/** + * The sections of one object of a node and the objects inside it, in file order, each followed by those inside it. A + * setting that is itself an object whose type the schema describes is a section of its own one level deeper, and so is + * each element of a list of objects; one that is not written stays a field. + */ +export function foldedSections(section: NodeSettings, types: Record, values: unknown): SettingsFold[] { + const folds: SettingsFold[] = [] + addFold(folds, types, values, { title: section.title, path: section.path, type: section.type, kind: 'own', depth: 0, holder: null }, new Set(section.shownAsNodes)) + return folds +} + +type FoldHead = Pick + +function addFold(into: SettingsFold[], types: Record, values: unknown, head: FoldHead, shownAsNodes: Set): void { + const options: SettingOption[] = [] + const inside: SettingsFold[] = [] + const summary: string[] = [] + for (const option of types[head.type]?.options ?? []) { + if (shownAsNodes.has(option.name)) { + continue + } + const path = [...head.path, option.name] + const value = valueAt(values, path) + const holder = { object: head.path, key: option.name } + const objectType = option.kind.kind === 'object' ? option.kind.type : null + const itemType = option.kind.kind === 'list' && option.kind.element.kind === 'object' ? option.kind.element.type : null + if (objectType !== null && isObject(value) && types[objectType] !== undefined) { + addFold(inside, types, values, { title: option.name, path, type: objectType, kind: 'group', depth: head.depth + 1, holder }, new Set()) + continue + } + if (itemType !== null && isObjects(value) && types[itemType] !== undefined) { + addList(inside, types, values, { option, path, itemType, count: value.length, depth: head.depth + 1, holder }) + summary.push(`${option.name} ${value.length}`) + continue + } + options.push(option) + if (value !== undefined) { + summary.push(`${option.name} ${shortText(option, value)}`) + } + } + into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options }) + into.push(...inside) +} + +interface ListFold { + option: SettingOption + path: JsonPath + itemType: string + count: number + depth: number + holder: { object: JsonPath; key: string } +} + +function addList(into: SettingsFold[], types: Record, values: unknown, list: ListFold): void { + into.push({ + title: list.option.name, + path: list.path, + type: list.itemType, + kind: 'list', + depth: list.depth, + summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`, + holder: list.holder, + options: [] + }) + for (let index = 0; index < list.count; index++) { + addFold( + into, + types, + values, + { title: String(index + 1), path: [...list.path, index], type: list.itemType, kind: 'item', depth: list.depth + 1, holder: null }, + new Set() + ) + } +} + +function shortText(option: SettingOption, value: unknown): string { + return isCurve(value) ? 'curve' : textOf(option.kind, value).replaceAll(DEFAULT_NAMESPACE, '') +} + +/** The folds shown while the ones in {@code open} are unfolded: a fold inside another that is folded is hidden. */ +export function visibleFolds(folds: SettingsFold[], open: ReadonlySet): SettingsFold[] { + const foldable = folds.filter((fold) => fold.kind !== 'own') + return folds.filter((fold) => !foldable.some((outer) => outer !== fold && !open.has(idOfFold(outer)) && outer.path.length < fold.path.length && isWithin(fold.path, outer.path))) +} diff --git a/studio/src/renderer/src/editor/settingText.test.ts b/studio/src/renderer/src/editor/settingText.test.ts new file mode 100644 index 000000000..9b21e067c --- /dev/null +++ b/studio/src/renderer/src/editor/settingText.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import type { ValueKind } from '../bridge/types' +import { literalOf, textOf } from './settingText' + +const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false } + +describe('string lists', () => { + it('read as commas and are written back quoted', () => { + expect(textOf(roles, ['wood', 'leaves'])).toBe('wood, leaves') + expect(literalOf(roles, 'wood, leaves, ')).toBe('["wood","leaves"]') + expect(literalOf(roles, ',')).toBe('[]') + }) + + it('keep a list typed as JSON, and show a list of anything else as JSON', () => { + expect(literalOf(roles, '["a", "b"]')).toBe('["a", "b"]') + expect(textOf(roles, [1, 2])).toBe('[1,2]') + }) +}) + +describe('text', () => { + it('shows a string as it is and writes it quoted', () => { + const text: ValueKind = { kind: 'text', format: 'PLAIN' } + + expect(textOf(text, 'wood')).toBe('wood') + expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""') + }) +}) diff --git a/studio/src/renderer/src/editor/settingText.ts b/studio/src/renderer/src/editor/settingText.ts new file mode 100644 index 000000000..d02ebe432 --- /dev/null +++ b/studio/src/renderer/src/editor/settingText.ts @@ -0,0 +1,48 @@ +import type { ValueKind } from '../bridge/types' + +export const NOT_SET = '' +export const LIST_SEPARATOR = ', ' + +/** Whether {@code kind} is a string naming something, typed as text. */ +export function isText(kind: ValueKind): boolean { + return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource' +} + +/** Whether {@code kind} is a list of strings, such as the roles a decoration goes on, which is typed as {@code a, b}. */ +export function isStringList(kind: ValueKind): boolean { + return kind.kind === 'list' && isText(kind.element) +} + +function isStrings(value: unknown): value is string[] { + return Array.isArray(value) && value.every((element) => typeof element === 'string') +} + +/** What the field shows for the value the file holds. */ +export function textOf(kind: ValueKind, value: unknown): string { + if (value === undefined) { + return NOT_SET + } + if (isText(kind) && typeof value === 'string') { + return value + } + return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value) +} + +/** The strings a list is typed as, each trimmed, and none left empty. */ +export function itemsOf(draft: string): string[] { + return draft + .split(',') + .map((item) => item.trim()) + .filter((item) => item !== '') +} + +/** What the field holds as JSON to write; a list typed as {@code a, b} is written as an array unless it already is one. */ +export function literalOf(kind: ValueKind, draft: string): string { + if (isText(kind)) { + return JSON.stringify(draft) + } + if (isStringList(kind) && !draft.trim().startsWith('[')) { + return JSON.stringify(itemsOf(draft)) + } + return draft.trim() +} diff --git a/studio/src/renderer/src/editor/suggestionStore.test.ts b/studio/src/renderer/src/editor/suggestionStore.test.ts new file mode 100644 index 000000000..a61887c83 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestionStore.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from 'vitest' +import { SuggestionStore } from './suggestionStore' + +describe('SuggestionStore', () => { + it('asks once for a list however often it is read', async () => { + const fetch = vi.fn().mockResolvedValue(['minecraft:stone']) + const store = new SuggestionStore(fetch) + + await store.load({ from: 'reference', reference: 'BLOCK' }) + const again = await store.load({ from: 'reference', reference: 'BLOCK' }) + + expect(again).toEqual(['minecraft:stone']) + expect(fetch).toHaveBeenCalledTimes(1) + expect(fetch).toHaveBeenCalledWith({ reference: 'BLOCK' }) + }) + + it('asks again after a list could not be read', async () => { + const fetch = vi.fn().mockRejectedValueOnce(new Error('down')).mockResolvedValue(['birch']) + const store = new SuggestionStore(fetch) + + await expect(store.load({ from: 'resource', resource: 'iris:object' })).rejects.toThrow('down') + await expect(store.load({ from: 'resource', resource: 'iris:object' })).resolves.toEqual(['birch']) + expect(fetch).toHaveBeenLastCalledWith({ resource: 'iris:object' }) + }) +}) diff --git a/studio/src/renderer/src/editor/suggestionStore.ts b/studio/src/renderer/src/editor/suggestionStore.ts new file mode 100644 index 000000000..de6b89aa8 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestionStore.ts @@ -0,0 +1,23 @@ +import { sourceKey, type ListedSource } from './suggestions' + +/** What the server lists for the suggestions of a source that names platform or pack entries. */ +export type SuggestionFetch = (of: { reference: string } | { resource: string }) => Promise + +/** The suggestion lists, each asked for once; a list that could not be read is asked for again next time. */ +export class SuggestionStore { + private readonly lists = new Map>() + + constructor(private readonly fetch: SuggestionFetch) {} + + load(source: ListedSource): Promise { + const key = sourceKey(source) + const known = this.lists.get(key) + if (known !== undefined) { + return known + } + const asked = this.fetch(source.from === 'reference' ? { reference: source.reference } : { resource: source.resource }) + this.lists.set(key, asked) + asked.catch(() => this.lists.delete(key)) + return asked + } +} diff --git a/studio/src/renderer/src/editor/suggestions.test.ts b/studio/src/renderer/src/editor/suggestions.test.ts new file mode 100644 index 000000000..a2ae79600 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestions.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest' +import type { GraphNode, SettingOption } from '../bridge/types' +import { NO_PART } from '../bridge/types' +import { completed, matching, rolesOf, suggestionSourceOf, wordBeingTyped } from './suggestions' + +function option(name: string, kind: SettingOption['kind']): SettingOption { + return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } +} + +function node(roles: string[], children: GraphNode[] = []): GraphNode { + return { + kind: 'Stem', + title: 'Stem', + path: [], + partId: NO_PART, + roles, + settings: [], + children: children.map((child) => ({ wire: '', node: child })), + childList: null, + movable: false, + duplicable: false, + additions: [] + } +} + +describe('suggestionSourceOf', () => { + it('names the registry of a reference, the kind of a resource and the roles of the object', () => { + expect(suggestionSourceOf('Material', option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }))).toEqual({ from: 'reference', reference: 'BLOCK' }) + expect(suggestionSourceOf('Part', option('skin', { kind: 'resource', resource: 'iris:object' }))).toEqual({ from: 'resource', resource: 'iris:object' }) + }) + + it('takes the roles for the settings that name one', () => { + const on = option('on', { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false }) + + expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' }) + expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull() + }) + + it('takes the elements of a list of references, and nothing for free text', () => { + expect(suggestionSourceOf('Rule', option('blocks', { kind: 'list', element: { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }, unique: false }))).toEqual({ from: 'reference', reference: 'BLOCK' }) + expect(suggestionSourceOf('Rule', option('note', { kind: 'text', format: 'PLAIN' }))).toBeNull() + }) +}) + +describe('rolesOf', () => { + it('lists each role of the whole tree once, sorted', () => { + expect(rolesOf([node(['wood', 'leaves'], [node(['wood', 'bark'])]), node(['moss'])])).toEqual(['bark', 'leaves', 'moss', 'wood']) + }) +}) + +describe('matching', () => { + const blocks = ['minecraft:oak_log', 'minecraft:birch_log', 'minecraft:oak_leaves', 'minecraft:stone'] + + it('puts what starts with the typed text before what holds it', () => { + expect(matching(blocks, 'minecraft:oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves']) + expect(matching(blocks, 'oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves']) + expect(matching(['a_log', 'log'], 'log')).toEqual([]) + expect(matching(['a_log', 'logs'], 'log')).toEqual(['logs', 'a_log']) + }) + + it('suggests nothing for nothing typed or a choice that is already typed out', () => { + expect(matching(blocks, '')).toEqual([]) + expect(matching(blocks, 'MINECRAFT:STONE')).toEqual([]) + }) + + it('shows only the first few', () => { + expect(matching(Array.from({ length: 30 }, (_, index) => `block_${index}`), 'block')).toHaveLength(8) + }) +}) + +describe('the word being typed', () => { + it('is the whole text, or for a list the item after the last comma', () => { + expect(wordBeingTyped('oak', false)).toEqual({ start: 0, typed: 'oak' }) + expect(wordBeingTyped('wood, lea', true)).toEqual({ start: 6, typed: 'lea' }) + expect(wordBeingTyped('wood, ', true)).toEqual({ start: 6, typed: '' }) + }) + + it('is replaced by the choice, a list ready for its next item', () => { + expect(completed('minecraft:oa', 'minecraft:oak_log', false)).toBe('minecraft:oak_log') + expect(completed('wood, lea', 'leaves', true)).toBe('wood, leaves, ') + }) +}) diff --git a/studio/src/renderer/src/editor/suggestions.ts b/studio/src/renderer/src/editor/suggestions.ts new file mode 100644 index 000000000..cd71ead34 --- /dev/null +++ b/studio/src/renderer/src/editor/suggestions.ts @@ -0,0 +1,79 @@ +import type { GraphNode, SettingOption, ValueKind } from '../bridge/types' +import { LIST_SEPARATOR } from './settingText' + +/** What an option may be typed as: the entries of a platform registry, the keys of the pack's resources of a kind, or the roles of the object. */ +export type SuggestionSource = { from: 'reference'; reference: string } | { from: 'resource'; resource: string } | { from: 'roles' } + +/** Settings that name a role of the object being edited, by the schema type and option (ProceduralPart, ProceduralMaterial and ProceduralDecoration). */ +const ROLE_OPTIONS: ReadonlySet = new Set([ + 'art.arcane.iris.engine.procedural.part.ProceduralPart.role', + 'art.arcane.iris.engine.procedural.part.ProceduralMaterial.role', + 'art.arcane.iris.engine.procedural.part.ProceduralDecoration.on' +]) + +/** A source the server lists, as opposed to the roles, which the studio reads from the nodes. */ +export type ListedSource = Exclude + +const MOST_SHOWN = 8 + +/** Where the suggestions for {@code option} of the schema type {@code type} come from; null when it is typed freely. */ +export function suggestionSourceOf(type: string, option: SettingOption): SuggestionSource | null { + if (ROLE_OPTIONS.has(`${type}.${option.name}`)) { + return { from: 'roles' } + } + const kind: ValueKind = option.kind.kind === 'list' ? option.kind.element : option.kind + if (kind.kind === 'reference') { + return { from: 'reference', reference: kind.reference } + } + return kind.kind === 'resource' ? { from: 'resource', resource: kind.resource } : null +} + +export function sourceKey(source: ListedSource): string { + return source.from === 'reference' ? `reference:${source.reference}` : `resource:${source.resource}` +} + +/** Every role the nodes place or decorate, once each and sorted. */ +export function rolesOf(roots: GraphNode[]): string[] { + const roles = new Set() + const visit = (node: GraphNode): void => { + node.roles.forEach((role) => roles.add(role)) + node.children.forEach((link) => visit(link.node)) + } + roots.forEach(visit) + return [...roles].sort() +} + +/** The word being typed: from where it starts in {@code draft}, with what is typed of it. For a list that is the item after the last comma. */ +export function wordBeingTyped(draft: string, isList: boolean): { start: number; typed: string } { + const start = isList ? draft.lastIndexOf(',') + 1 : 0 + const typed = draft.slice(start) + return { start: start + (typed.length - typed.trimStart().length), typed: typed.trim() } +} + +/** The choices that hold what is typed, those that start with it first; none while nothing is typed or it is already a choice. */ +export function matching(choices: readonly string[], typed: string): string[] { + const wanted = typed.toLowerCase() + if (wanted === '') { + return [] + } + const starting: string[] = [] + const containing: string[] = [] + for (const choice of choices) { + const lower = choice.toLowerCase() + if (lower === wanted) { + return [] + } + if (lower.startsWith(wanted)) { + starting.push(choice) + } else if (lower.includes(wanted)) { + containing.push(choice) + } + } + return [...starting, ...containing].slice(0, MOST_SHOWN) +} + +/** The draft with the word being typed replaced by {@code choice}; a list gets its separator ready for the next item. */ +export function completed(draft: string, choice: string, isList: boolean): string { + const { start } = wordBeingTyped(draft, isList) + return draft.slice(0, start) + choice + (isList ? LIST_SEPARATOR : '') +} diff --git a/studio/src/renderer/src/editor/useNodeEditor.ts b/studio/src/renderer/src/editor/useNodeEditor.ts new file mode 100644 index 000000000..e0bd74f82 --- /dev/null +++ b/studio/src/renderer/src/editor/useNodeEditor.ts @@ -0,0 +1,122 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { BridgeError, STATUS_CONFLICT, type BridgeClient } from '../bridge/BridgeClient' +import type { EditorState, GraphEdit } from '../bridge/types' +import { EditHistory } from './EditHistory' + +export interface NodeEditor { + /** The entry's file as it is now; null while it is read. */ + state: EditorState | null + saving: boolean + canUndo: boolean + canRedo: boolean + edit(edit: GraphEdit): void + undo(): void + redo(): void +} + +/** + * Reads an entry's file as nodes and edits it. Edits are sent one after another, each on the text the one before left, + * so quick edits never refuse each other; one refused because the file changed elsewhere reads the file again. + */ +export function useNodeEditor(client: BridgeClient, viewId: string, key: string | null, packRevision: number, tell: (message: string) => void): NodeEditor { + const [state, setState] = useState(null) + const [saving, setSaving] = useState(false) + const [, setHistoryChanges] = useState(0) + const history = useRef(new EditHistory()) + const shown = useRef(null) + const queue = useRef>(Promise.resolve()) + const entry = useRef({ viewId, key }) + + const run = useCallback( + (task: (current: EditorState | null) => Promise): void => { + const asked = entry.current + queue.current = queue.current.then(async () => { + if (entry.current !== asked) { + return + } + setSaving(true) + try { + const next = await task(shown.current) + if (entry.current === asked && next !== null) { + shown.current = next + setState(next) + } + } catch (failure) { + if (entry.current !== asked) { + return + } + tell((failure as Error).message) + if (failure instanceof BridgeError && failure.status === STATUS_CONFLICT && asked.key !== null) { + const reread = await client.sceneFile(asked.viewId, asked.key).catch(() => null) + if (reread !== null && entry.current === asked) { + shown.current = reread + setState(reread) + } + } + } finally { + setSaving(false) + setHistoryChanges((changes) => changes + 1) + } + }) + }, + [client, tell] + ) + + useEffect(() => { + entry.current = { viewId, key } + history.current = new EditHistory() + shown.current = null + setState(null) + }, [viewId, key]) + + useEffect(() => { + if (key !== null) { + run(() => client.sceneFile(viewId, key)) + } + }, [client, viewId, key, packRevision, run]) + + const edit = useCallback( + (change: GraphEdit) => + run(async (current) => { + if (current === null || key === null) { + return null + } + const next = await client.sceneEdit(viewId, key, current.revision, change) + if (next.text !== current.text) { + history.current.edited(current.text) + } + return next + }), + [client, viewId, key, run] + ) + + const undo = useCallback( + () => + run(async (current) => { + const earlier = history.current.nextUndo() + if (current === null || key === null || earlier === undefined) { + return null + } + const next = await client.sceneWrite(viewId, key, current.revision, earlier) + history.current.undone(current.text) + return next + }), + [client, viewId, key, run] + ) + + const redo = useCallback( + () => + run(async (current) => { + const later = history.current.nextRedo() + if (current === null || key === null || later === undefined) { + return null + } + const next = await client.sceneWrite(viewId, key, current.revision, later) + history.current.redone(current.text) + return next + }), + [client, viewId, key, run] + ) + + return { state, saving, canUndo: history.current.canUndo, canRedo: history.current.canRedo, edit, undo, redo } +} diff --git a/studio/src/renderer/src/env.d.ts b/studio/src/renderer/src/env.d.ts new file mode 100644 index 000000000..3ab813db9 --- /dev/null +++ b/studio/src/renderer/src/env.d.ts @@ -0,0 +1,10 @@ +/// +import type { StudioHost } from '../../shared/bridge' + +declare global { + interface Window { + studio: StudioHost + } +} + +export {} diff --git a/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt b/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/studio/src/renderer/src/icons/NOTICE.txt b/studio/src/renderer/src/icons/NOTICE.txt new file mode 100644 index 000000000..e3d07cdd4 --- /dev/null +++ b/studio/src/renderer/src/icons/NOTICE.txt @@ -0,0 +1,6 @@ +The icons in this folder and its subfolders come from the IntelliJ Platform (https://github.com/JetBrains/intellij-community), +platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors, +used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt). +memory.svg is profileMemory.svg with its profiling badge removed. +theme.svg, blocks.svg, borders.svg, shading.svg, mob.svg, actualZoom.svg, decoration.svg, and in views/ biomes.svg, regions.svg, +world-3d.svg, saved-world.svg, noise.svg and objects.svg are the studio's own, drawn to match. diff --git a/studio/src/renderer/src/icons/actualZoom.svg b/studio/src/renderer/src/icons/actualZoom.svg new file mode 100644 index 000000000..08981f5e8 --- /dev/null +++ b/studio/src/renderer/src/icons/actualZoom.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/actualZoom_dark.svg b/studio/src/renderer/src/icons/actualZoom_dark.svg new file mode 100644 index 000000000..0cc5f18b6 --- /dev/null +++ b/studio/src/renderer/src/icons/actualZoom_dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/add.svg b/studio/src/renderer/src/icons/add.svg new file mode 100644 index 000000000..57eaaf561 --- /dev/null +++ b/studio/src/renderer/src/icons/add.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/add_dark.svg b/studio/src/renderer/src/icons/add_dark.svg new file mode 100644 index 000000000..397e9321b --- /dev/null +++ b/studio/src/renderer/src/icons/add_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/blocks.svg b/studio/src/renderer/src/icons/blocks.svg new file mode 100644 index 000000000..aa609f646 --- /dev/null +++ b/studio/src/renderer/src/icons/blocks.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/blocks_dark.svg b/studio/src/renderer/src/icons/blocks_dark.svg new file mode 100644 index 000000000..d215432f4 --- /dev/null +++ b/studio/src/renderer/src/icons/blocks_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/borders.svg b/studio/src/renderer/src/icons/borders.svg new file mode 100644 index 000000000..4fe3957a7 --- /dev/null +++ b/studio/src/renderer/src/icons/borders.svg @@ -0,0 +1,3 @@ + + + diff --git a/studio/src/renderer/src/icons/borders_dark.svg b/studio/src/renderer/src/icons/borders_dark.svg new file mode 100644 index 000000000..2f7ce7863 --- /dev/null +++ b/studio/src/renderer/src/icons/borders_dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/studio/src/renderer/src/icons/checked.svg b/studio/src/renderer/src/icons/checked.svg new file mode 100644 index 000000000..863bbc418 --- /dev/null +++ b/studio/src/renderer/src/icons/checked.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/checked_dark.svg b/studio/src/renderer/src/icons/checked_dark.svg new file mode 100644 index 000000000..3e1d9ecc3 --- /dev/null +++ b/studio/src/renderer/src/icons/checked_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/chevronLeft.svg b/studio/src/renderer/src/icons/chevronLeft.svg new file mode 100644 index 000000000..c6c4fa041 --- /dev/null +++ b/studio/src/renderer/src/icons/chevronLeft.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/chevronLeft_dark.svg b/studio/src/renderer/src/icons/chevronLeft_dark.svg new file mode 100644 index 000000000..d4284d234 --- /dev/null +++ b/studio/src/renderer/src/icons/chevronLeft_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/chevronRight.svg b/studio/src/renderer/src/icons/chevronRight.svg new file mode 100644 index 000000000..5120ed891 --- /dev/null +++ b/studio/src/renderer/src/icons/chevronRight.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/chevronRight_dark.svg b/studio/src/renderer/src/icons/chevronRight_dark.svg new file mode 100644 index 000000000..838142106 --- /dev/null +++ b/studio/src/renderer/src/icons/chevronRight_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/closeSmall.svg b/studio/src/renderer/src/icons/closeSmall.svg new file mode 100644 index 000000000..c375b9331 --- /dev/null +++ b/studio/src/renderer/src/icons/closeSmall.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/closeSmall_dark.svg b/studio/src/renderer/src/icons/closeSmall_dark.svg new file mode 100644 index 000000000..237d6d45d --- /dev/null +++ b/studio/src/renderer/src/icons/closeSmall_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/decoration.svg b/studio/src/renderer/src/icons/decoration.svg new file mode 100644 index 000000000..fb2a026ea --- /dev/null +++ b/studio/src/renderer/src/icons/decoration.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/decoration_dark.svg b/studio/src/renderer/src/icons/decoration_dark.svg new file mode 100644 index 000000000..0e0b87790 --- /dev/null +++ b/studio/src/renderer/src/icons/decoration_dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/delete.svg b/studio/src/renderer/src/icons/delete.svg new file mode 100644 index 000000000..a858096ac --- /dev/null +++ b/studio/src/renderer/src/icons/delete.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/delete_dark.svg b/studio/src/renderer/src/icons/delete_dark.svg new file mode 100644 index 000000000..03ff9f241 --- /dev/null +++ b/studio/src/renderer/src/icons/delete_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/exit.svg b/studio/src/renderer/src/icons/exit.svg new file mode 100644 index 000000000..8ff96d714 --- /dev/null +++ b/studio/src/renderer/src/icons/exit.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/exit_dark.svg b/studio/src/renderer/src/icons/exit_dark.svg new file mode 100644 index 000000000..e4cdd4abf --- /dev/null +++ b/studio/src/renderer/src/icons/exit_dark.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/studio/src/renderer/src/icons/grid.svg b/studio/src/renderer/src/icons/grid.svg new file mode 100644 index 000000000..8b28efaf4 --- /dev/null +++ b/studio/src/renderer/src/icons/grid.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/grid_dark.svg b/studio/src/renderer/src/icons/grid_dark.svg new file mode 100644 index 000000000..98f561847 --- /dev/null +++ b/studio/src/renderer/src/icons/grid_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/groups.svg b/studio/src/renderer/src/icons/groups.svg new file mode 100644 index 000000000..d4ab80fbb --- /dev/null +++ b/studio/src/renderer/src/icons/groups.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/groups_dark.svg b/studio/src/renderer/src/icons/groups_dark.svg new file mode 100644 index 000000000..2769c3ce0 --- /dev/null +++ b/studio/src/renderer/src/icons/groups_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/help.svg b/studio/src/renderer/src/icons/help.svg new file mode 100644 index 000000000..203346d24 --- /dev/null +++ b/studio/src/renderer/src/icons/help.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/help_dark.svg b/studio/src/renderer/src/icons/help_dark.svg new file mode 100644 index 000000000..d571baabe --- /dev/null +++ b/studio/src/renderer/src/icons/help_dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/lightning.svg b/studio/src/renderer/src/icons/lightning.svg new file mode 100644 index 000000000..4ac384edd --- /dev/null +++ b/studio/src/renderer/src/icons/lightning.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/lightning_dark.svg b/studio/src/renderer/src/icons/lightning_dark.svg new file mode 100644 index 000000000..251f75413 --- /dev/null +++ b/studio/src/renderer/src/icons/lightning_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/locate.svg b/studio/src/renderer/src/icons/locate.svg new file mode 100644 index 000000000..2343fa2e3 --- /dev/null +++ b/studio/src/renderer/src/icons/locate.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/locate_dark.svg b/studio/src/renderer/src/icons/locate_dark.svg new file mode 100644 index 000000000..a2ba607aa --- /dev/null +++ b/studio/src/renderer/src/icons/locate_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/locked.svg b/studio/src/renderer/src/icons/locked.svg new file mode 100644 index 000000000..666daddf5 --- /dev/null +++ b/studio/src/renderer/src/icons/locked.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/locked_dark.svg b/studio/src/renderer/src/icons/locked_dark.svg new file mode 100644 index 000000000..9658ca553 --- /dev/null +++ b/studio/src/renderer/src/icons/locked_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/memory.svg b/studio/src/renderer/src/icons/memory.svg new file mode 100644 index 000000000..6af68790d --- /dev/null +++ b/studio/src/renderer/src/icons/memory.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/memory_dark.svg b/studio/src/renderer/src/icons/memory_dark.svg new file mode 100644 index 000000000..92038e383 --- /dev/null +++ b/studio/src/renderer/src/icons/memory_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/mob.svg b/studio/src/renderer/src/icons/mob.svg new file mode 100644 index 000000000..bcd9e1a0e --- /dev/null +++ b/studio/src/renderer/src/icons/mob.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/mob_dark.svg b/studio/src/renderer/src/icons/mob_dark.svg new file mode 100644 index 000000000..f1b911136 --- /dev/null +++ b/studio/src/renderer/src/icons/mob_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/redo.svg b/studio/src/renderer/src/icons/redo.svg new file mode 100644 index 000000000..862b8f574 --- /dev/null +++ b/studio/src/renderer/src/icons/redo.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/redo_dark.svg b/studio/src/renderer/src/icons/redo_dark.svg new file mode 100644 index 000000000..a39093042 --- /dev/null +++ b/studio/src/renderer/src/icons/redo_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/refresh.svg b/studio/src/renderer/src/icons/refresh.svg new file mode 100644 index 000000000..7a4c73dfd --- /dev/null +++ b/studio/src/renderer/src/icons/refresh.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/refresh_dark.svg b/studio/src/renderer/src/icons/refresh_dark.svg new file mode 100644 index 000000000..3362992af --- /dev/null +++ b/studio/src/renderer/src/icons/refresh_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/reset.svg b/studio/src/renderer/src/icons/reset.svg new file mode 100644 index 000000000..de5d2b170 --- /dev/null +++ b/studio/src/renderer/src/icons/reset.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/reset_dark.svg b/studio/src/renderer/src/icons/reset_dark.svg new file mode 100644 index 000000000..28d58e10e --- /dev/null +++ b/studio/src/renderer/src/icons/reset_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/search.svg b/studio/src/renderer/src/icons/search.svg new file mode 100644 index 000000000..021b0c394 --- /dev/null +++ b/studio/src/renderer/src/icons/search.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/search_dark.svg b/studio/src/renderer/src/icons/search_dark.svg new file mode 100644 index 000000000..d5a82d9c1 --- /dev/null +++ b/studio/src/renderer/src/icons/search_dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/studio/src/renderer/src/icons/settings.svg b/studio/src/renderer/src/icons/settings.svg new file mode 100644 index 000000000..c30de8209 --- /dev/null +++ b/studio/src/renderer/src/icons/settings.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/settings_dark.svg b/studio/src/renderer/src/icons/settings_dark.svg new file mode 100644 index 000000000..62f328167 --- /dev/null +++ b/studio/src/renderer/src/icons/settings_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/shading.svg b/studio/src/renderer/src/icons/shading.svg new file mode 100644 index 000000000..c545e1d8b --- /dev/null +++ b/studio/src/renderer/src/icons/shading.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/shading_dark.svg b/studio/src/renderer/src/icons/shading_dark.svg new file mode 100644 index 000000000..cc2b121d0 --- /dev/null +++ b/studio/src/renderer/src/icons/shading_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/stopWatch.svg b/studio/src/renderer/src/icons/stopWatch.svg new file mode 100644 index 000000000..33f0d5917 --- /dev/null +++ b/studio/src/renderer/src/icons/stopWatch.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/stopWatch_dark.svg b/studio/src/renderer/src/icons/stopWatch_dark.svg new file mode 100644 index 000000000..10bec586b --- /dev/null +++ b/studio/src/renderer/src/icons/stopWatch_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/symlink.svg b/studio/src/renderer/src/icons/symlink.svg new file mode 100644 index 000000000..4c2ccbb21 --- /dev/null +++ b/studio/src/renderer/src/icons/symlink.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/symlink_dark.svg b/studio/src/renderer/src/icons/symlink_dark.svg new file mode 100644 index 000000000..fcc2390a9 --- /dev/null +++ b/studio/src/renderer/src/icons/symlink_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/theme.svg b/studio/src/renderer/src/icons/theme.svg new file mode 100644 index 000000000..3f4ab8713 --- /dev/null +++ b/studio/src/renderer/src/icons/theme.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/theme_dark.svg b/studio/src/renderer/src/icons/theme_dark.svg new file mode 100644 index 000000000..375b1b72c --- /dev/null +++ b/studio/src/renderer/src/icons/theme_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/undo.svg b/studio/src/renderer/src/icons/undo.svg new file mode 100644 index 000000000..7a98c7583 --- /dev/null +++ b/studio/src/renderer/src/icons/undo.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/undo_dark.svg b/studio/src/renderer/src/icons/undo_dark.svg new file mode 100644 index 000000000..2fa3c0d42 --- /dev/null +++ b/studio/src/renderer/src/icons/undo_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/biomes.svg b/studio/src/renderer/src/icons/views/biomes.svg new file mode 100644 index 000000000..78c98d754 --- /dev/null +++ b/studio/src/renderer/src/icons/views/biomes.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/studio/src/renderer/src/icons/views/biomes_dark.svg b/studio/src/renderer/src/icons/views/biomes_dark.svg new file mode 100644 index 000000000..731013503 --- /dev/null +++ b/studio/src/renderer/src/icons/views/biomes_dark.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/studio/src/renderer/src/icons/views/noise.svg b/studio/src/renderer/src/icons/views/noise.svg new file mode 100644 index 000000000..e735984cf --- /dev/null +++ b/studio/src/renderer/src/icons/views/noise.svg @@ -0,0 +1,3 @@ + + + diff --git a/studio/src/renderer/src/icons/views/noise_dark.svg b/studio/src/renderer/src/icons/views/noise_dark.svg new file mode 100644 index 000000000..187dd72f4 --- /dev/null +++ b/studio/src/renderer/src/icons/views/noise_dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/studio/src/renderer/src/icons/views/objects.svg b/studio/src/renderer/src/icons/views/objects.svg new file mode 100644 index 000000000..6297b050c --- /dev/null +++ b/studio/src/renderer/src/icons/views/objects.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/objects_dark.svg b/studio/src/renderer/src/icons/views/objects_dark.svg new file mode 100644 index 000000000..4e3d96e86 --- /dev/null +++ b/studio/src/renderer/src/icons/views/objects_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/palettes.svg b/studio/src/renderer/src/icons/views/palettes.svg new file mode 100644 index 000000000..67e265433 --- /dev/null +++ b/studio/src/renderer/src/icons/views/palettes.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/views/palettes_dark.svg b/studio/src/renderer/src/icons/views/palettes_dark.svg new file mode 100644 index 000000000..8d120c93e --- /dev/null +++ b/studio/src/renderer/src/icons/views/palettes_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/studio/src/renderer/src/icons/views/procedural.svg b/studio/src/renderer/src/icons/views/procedural.svg new file mode 100644 index 000000000..5ad2cdb16 --- /dev/null +++ b/studio/src/renderer/src/icons/views/procedural.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/views/procedural_dark.svg b/studio/src/renderer/src/icons/views/procedural_dark.svg new file mode 100644 index 000000000..3c5f7ed0d --- /dev/null +++ b/studio/src/renderer/src/icons/views/procedural_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/studio/src/renderer/src/icons/views/regions.svg b/studio/src/renderer/src/icons/views/regions.svg new file mode 100644 index 000000000..f2848a5ee --- /dev/null +++ b/studio/src/renderer/src/icons/views/regions.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/regions_dark.svg b/studio/src/renderer/src/icons/views/regions_dark.svg new file mode 100644 index 000000000..f28c07a18 --- /dev/null +++ b/studio/src/renderer/src/icons/views/regions_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/saved-world.svg b/studio/src/renderer/src/icons/views/saved-world.svg new file mode 100644 index 000000000..ba35672af --- /dev/null +++ b/studio/src/renderer/src/icons/views/saved-world.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/saved-world_dark.svg b/studio/src/renderer/src/icons/views/saved-world_dark.svg new file mode 100644 index 000000000..f9880f87b --- /dev/null +++ b/studio/src/renderer/src/icons/views/saved-world_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/world-3d.svg b/studio/src/renderer/src/icons/views/world-3d.svg new file mode 100644 index 000000000..233fbbd78 --- /dev/null +++ b/studio/src/renderer/src/icons/views/world-3d.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/world-3d_dark.svg b/studio/src/renderer/src/icons/views/world-3d_dark.svg new file mode 100644 index 000000000..46f0ee93d --- /dev/null +++ b/studio/src/renderer/src/icons/views/world-3d_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/web.svg b/studio/src/renderer/src/icons/web.svg new file mode 100644 index 000000000..897fab392 --- /dev/null +++ b/studio/src/renderer/src/icons/web.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/web_dark.svg b/studio/src/renderer/src/icons/web_dark.svg new file mode 100644 index 000000000..0ca6194ab --- /dev/null +++ b/studio/src/renderer/src/icons/web_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/lib/utils.ts b/studio/src/renderer/src/lib/utils.ts new file mode 100644 index 000000000..b057456de --- /dev/null +++ b/studio/src/renderer/src/lib/utils.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from 'clsx' +import { twMerge } from 'tailwind-merge' + +export function cn(...inputs: ClassValue[]): string { + return twMerge(clsx(inputs)) +} diff --git a/studio/src/renderer/src/main.tsx b/studio/src/renderer/src/main.tsx new file mode 100644 index 000000000..3ea6345e0 --- /dev/null +++ b/studio/src/renderer/src/main.tsx @@ -0,0 +1,13 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { TooltipProvider } from '@/components/ui/tooltip' +import { App } from './App' +import './styles.css' + +createRoot(document.getElementById('root')!).render( + + + + + +) diff --git a/studio/src/renderer/src/map/MapController.ts b/studio/src/renderer/src/map/MapController.ts new file mode 100644 index 000000000..fc7050740 --- /dev/null +++ b/studio/src/renderer/src/map/MapController.ts @@ -0,0 +1,386 @@ +import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' +import { gridIndex } from '../bridge/tileDecoding' +import { NO_LABEL, type BlockSource, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types' +import { countShares, type PlacedTile, type Share } from './census' +import { blockArt, type BlockArt } from '../scene/blockArt' +import { hasBlocksAt, mapTileSource, type TileLayer } from './mapTileSource' +import { drawPlayerArrow } from './playerArrow' +import { drawVisibleTiles } from './tileDrawing' +import type { Highlight, TileStyle } from './tileStyle' +import { TileStore } from './TileStore' +import { + clampBlocksPerPixel, + DEFAULT_BLOCKS_PER_PIXEL, + renderBlocksPerPixel, + screenToWorldX, + screenToWorldZ, + worldToScreenX, + worldToScreenZ, + type TileAddress, + type Viewport +} from './viewport' + +export interface MapStatus { + blocksPerPixel: number + widthBlocks: number + heightBlocks: number + tilesReady: number + tilesTotal: number + cursorX: number + cursorZ: number +} + +export interface MapListener { + onStatus(status: MapStatus): void + onShares(shares: Share[]): void + /** The world area on screen, reported with the shares: a few times a second while it moves, and once at rest. */ + onArea(area: WorldRect): void + onError(message: string): void +} + +/** The views whose spots a noise picks, so they can draw that noise. */ +const PICK_NOISE_VIEWS = new Set(['biomes', 'regions']) + +/** What the map shows at a spot, read from the tiles already drawn. */ +export interface SpotSubjects { + subject: Highlight | null + region: Highlight | null +} + +export interface MapToggles { + shading: boolean + regionBorders: boolean + grid: boolean + /** Colour the map by the block on top of each column, where it is zoomed in far enough. */ + blocks: boolean +} + +const BLOCK_SOURCE: BlockSource = 'generated' + +const CENSUS_INTERVAL_MILLIS = 250 +const CHUNK_BLOCKS = 16 +const REGION_BLOCKS = 512 +const SMALLEST_GRID_GAP_PIXELS = 8 +const CHUNK_LINE = 'rgba(255, 255, 255, 0.14)' +const REGION_LINE = 'rgba(255, 255, 255, 0.38)' +const ENTITY_FILL = '#f75464' +const MARKER_OUTLINE = '#ffffff' +const ENTITY_RADIUS_PIXELS = 3 + +/** + * The 2D map on a canvas: which tiles to fetch for the view, drawing them in the current style, and the grid and + * markers on top. Kept outside React, as it redraws on every drag and wheel step. + */ +export class MapController { + private readonly context: CanvasRenderingContext2D + private readonly art: BlockArt + private readonly store: TileStore + private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 } + private layer: TileLayer + private toggles: MapToggles = { shading: true, regionBorders: false, grid: false, blocks: false } + private pickDisplay: PickDisplay = 'picks' + private highlight: Highlight | null = null + private players: Marker[] = [] + private entities: Marker[] = [] + private cursor: { x: number; y: number } | null = null + private frameRequested = false + private lastCensusMillis = 0 + private censusTimer: number | undefined + private closed = false + + constructor( + private readonly canvas: HTMLCanvasElement, + client: BridgeClient, + private readonly world: WorldInfo, + view: string, + private readonly listener: MapListener + ) { + this.context = canvas.getContext('2d')! + this.layer = { view, preview: null, heights: this.needsHeights(this.toggles), pickNoise: false, blocks: null, revision: 0 } + this.art = blockArt(client, false) + this.store = new TileStore(mapTileSource(client, world.tileSize, this.art), () => this.redraw(), (message) => listener.onError(message)) + } + + close(): void { + this.closed = true + this.art.dispose() + window.clearTimeout(this.censusTimer) + this.store.clear() + } + + resize(width: number, height: number): void { + const ratio = window.devicePixelRatio + this.canvas.width = Math.round(width * ratio) + this.canvas.height = Math.round(height * ratio) + this.view.width = width + this.view.height = height + this.redraw() + } + + /** Shows a view; the region view previews {@code preview} everywhere when it is not null. */ + setView(view: string, preview: string | null = null): void { + this.layer = { + ...this.layer, + view, + preview: view === 'regions' ? preview : null, + pickNoise: this.needsPickNoise(view, this.pickDisplay) + } + this.redraw() + } + + setPickDisplay(display: PickDisplay): void { + this.pickDisplay = display + this.layer = { ...this.layer, pickNoise: this.needsPickNoise(this.layer.view, display) } + this.redraw() + } + + // Tiles only carry their pick noise while it is drawn, so drawing the picks alone costs nothing extra. + private needsPickNoise(view: string, display: PickDisplay): boolean { + return display !== 'picks' && PICK_NOISE_VIEWS.has(view) + } + + setToggles(toggles: MapToggles): void { + this.toggles = toggles + this.layer = { ...this.layer, heights: this.needsHeights(toggles), blocks: toggles.blocks ? BLOCK_SOURCE : null } + this.redraw() + } + + /** Whether the map is zoomed in far enough for its tiles to carry blocks. */ + showsBlocks(): boolean { + return hasBlocksAt(this.renderScale()) + } + + // Heights are the costly part of a tile, so they are only asked for when something draws with them: the relief, and + // the sea over the blocks. + private needsHeights(toggles: MapToggles): boolean { + return toggles.shading || toggles.blocks + } + + setHighlight(highlight: Highlight | null): void { + this.highlight = highlight + this.redraw() + } + + setMarkers(players: Marker[], entities: Marker[]): void { + this.players = players + this.entities = entities + this.redraw() + } + + setCursor(cursor: { x: number; y: number } | null): void { + this.cursor = cursor + this.reportStatus() + } + + /** Draws everything again from the server, after the pack changed. */ + refresh(): void { + this.store.clear() + this.layer = { ...this.layer, revision: this.layer.revision + 1 } + this.redraw() + } + + panBy(screenDeltaX: number, screenDeltaZ: number): void { + this.view.centerX -= screenDeltaX * this.view.blocksPerPixel + this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel + this.redraw() + } + + centerOn(worldX: number, worldZ: number): void { + this.view.centerX = worldX + this.view.centerZ = worldZ + this.redraw() + } + + /** Zooms by {@code factor} (above 1 zooms in) keeping the world spot under the screen point where it is. */ + zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void { + const worldX = screenToWorldX(this.view, screenX) + const worldZ = screenToWorldZ(this.view, screenZ) + this.view.blocksPerPixel = clampBlocksPerPixel(this.view.blocksPerPixel / factor) + this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel + this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel + this.redraw() + } + + resetZoom(): void { + this.view.blocksPerPixel = DEFAULT_BLOCKS_PER_PIXEL + this.redraw() + } + + worldAt(screenX: number, screenZ: number): { x: number; z: number } { + return { x: screenToWorldX(this.view, screenX), z: screenToWorldZ(this.view, screenZ) } + } + + /** The biome or region and the region at a screen point, from the tile drawn there; nulls before it arrived. */ + subjectsAt(screenX: number, screenZ: number): SpotSubjects { + const worldX = screenToWorldX(this.view, screenX) + const worldZ = screenToWorldZ(this.view, screenZ) + const scale = this.renderScale() + const span = this.world.tileSize * scale + const address = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale } + const tile = this.store.get(address, this.layer) + if (tile === null) { + return { subject: null, region: null } + } + const pixelX = Math.min(tile.size - 1, Math.floor((worldX - address.tileX * span) / scale)) + const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale)) + const cell = gridIndex(tile, pixelX, pixelZ) + const region = labelAt(tile.labels, tile.regions[cell]) + return { subject: labelAt(tile.labels, tile.subjects[cell]), region } + } + + private renderScale(): number { + return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio) + } + + private style(): TileStyle { + return { + byBlock: this.toggles.blocks, + shading: this.toggles.shading, + regionBorders: this.toggles.regionBorders, + highlight: this.highlight, + seaLevel: this.world.fluidHeight, + pickDisplay: this.pickDisplay + } + } + + private redraw(): void { + if (this.frameRequested || this.closed) { + return + } + this.frameRequested = true + requestAnimationFrame(() => { + this.frameRequested = false + if (!this.closed) { + this.draw() + } + }) + } + + private draw(): void { + const ratio = window.devicePixelRatio + const context = this.context + context.setTransform(ratio, 0, 0, ratio, 0, 0) + context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a' + context.fillRect(0, 0, this.view.width, this.view.height) + + const style = this.style() + const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.world.tileSize, (address) => + this.store.picture(address, this.layer, style) + ) + this.store.want(drawn.wanted, this.layer) + if (this.toggles.grid) { + this.drawGrid() + } + this.drawMarkers() + this.reportStatus(drawn.ready, drawn.tiles.length) + this.scheduleCensus(drawn.tiles) + } + + private drawGrid(): void { + this.drawLines(CHUNK_BLOCKS, CHUNK_LINE, 1) + this.drawLines(REGION_BLOCKS, REGION_LINE, 1.5) + } + + private drawLines(gapBlocks: number, color: string, width: number): void { + if (gapBlocks / this.view.blocksPerPixel < SMALLEST_GRID_GAP_PIXELS) { + return + } + const context = this.context + context.strokeStyle = color + context.lineWidth = width + context.beginPath() + const firstX = Math.ceil(screenToWorldX(this.view, 0) / gapBlocks) * gapBlocks + for (let worldX = firstX; worldX <= screenToWorldX(this.view, this.view.width); worldX += gapBlocks) { + const screenX = Math.round(worldToScreenX(this.view, worldX)) + 0.5 + context.moveTo(screenX, 0) + context.lineTo(screenX, this.view.height) + } + const firstZ = Math.ceil(screenToWorldZ(this.view, 0) / gapBlocks) * gapBlocks + for (let worldZ = firstZ; worldZ <= screenToWorldZ(this.view, this.view.height); worldZ += gapBlocks) { + const screenZ = Math.round(worldToScreenZ(this.view, worldZ)) + 0.5 + context.moveTo(0, screenZ) + context.lineTo(this.view.width, screenZ) + } + context.stroke() + } + + private drawMarkers(): void { + for (const entity of this.entities) { + this.drawEntity(entity) + } + for (const player of this.players) { + drawPlayerArrow(this.context, worldToScreenX(this.view, player.worldX), worldToScreenZ(this.view, player.worldZ), player.yaw, player.label) + } + } + + private drawEntity(entity: Marker): void { + const context = this.context + context.beginPath() + context.arc(worldToScreenX(this.view, entity.worldX), worldToScreenZ(this.view, entity.worldZ), ENTITY_RADIUS_PIXELS, 0, Math.PI * 2) + context.fillStyle = ENTITY_FILL + context.fill() + context.lineWidth = 2 + context.strokeStyle = MARKER_OUTLINE + context.stroke() + } + + private lastReady = 0 + private lastTotal = 0 + + private reportStatus(ready = this.lastReady, total = this.lastTotal): void { + this.lastReady = ready + this.lastTotal = total + const cursor = this.cursor === null ? { x: this.view.width / 2, y: this.view.height / 2 } : this.cursor + this.listener.onStatus({ + blocksPerPixel: this.view.blocksPerPixel, + widthBlocks: Math.round(this.view.width * this.view.blocksPerPixel), + heightBlocks: Math.round(this.view.height * this.view.blocksPerPixel), + tilesReady: ready, + tilesTotal: total, + cursorX: Math.floor(screenToWorldX(this.view, cursor.x)), + cursorZ: Math.floor(screenToWorldZ(this.view, cursor.y)) + }) + } + + // Counting what is on screen is cheap but not free, so it runs at most a few times a second and once more at rest. + private scheduleCensus(tiles: TileAddress[]): void { + window.clearTimeout(this.censusTimer) + const wait = Math.max(0, this.lastCensusMillis + CENSUS_INTERVAL_MILLIS - performance.now()) + this.censusTimer = window.setTimeout(() => { + this.lastCensusMillis = performance.now() + this.listener.onShares(this.census(tiles)) + this.listener.onArea(this.screenArea()) + }, wait) + } + + private screenArea(): WorldRect { + return { + minX: screenToWorldX(this.view, 0), + minZ: screenToWorldZ(this.view, 0), + maxX: screenToWorldX(this.view, this.view.width), + maxZ: screenToWorldZ(this.view, this.view.height) + } + } + + private census(tiles: TileAddress[]): Share[] { + const placed: PlacedTile[] = [] + for (const address of tiles) { + const tile = this.store.get(address, this.layer) + if (tile !== null) { + const span = this.world.tileSize * address.blocksPerPixel + placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span }) + } + } + const screen = this.screenArea() + const area = { minimumX: screen.minX, minimumZ: screen.minZ, maximumX: screen.maxX, maximumZ: screen.maxZ } + return countShares(placed, area) + } +} + +function labelAt(labels: MapLabel[], index: number): Highlight | null { + if (index === NO_LABEL) { + return null + } + const label = labels[index] + return { kind: label.kind, key: label.key, name: label.name } +} diff --git a/studio/src/renderer/src/map/TileStore.ts b/studio/src/renderer/src/map/TileStore.ts new file mode 100644 index 000000000..89a920bf3 --- /dev/null +++ b/studio/src/renderer/src/map/TileStore.ts @@ -0,0 +1,200 @@ +import { BridgeError } from '../bridge/BridgeClient' +import type { TileAddress } from './viewport' + +/** What a store's tiles are, where they come from, and how one is drawn in a style. */ +export interface TileSource { + /** Tells layers apart; a layer that changes on hotload carries its revision here, so older tiles are not used again. */ + layerKey(layer: Layer): string + fetch(address: TileAddress, layer: Layer, signal: AbortSignal): Promise + bytesOf(tile: Tile): number + /** Only for sources whose tiles are drawn as pictures. */ + styleKey?(style: Style): string + pixels?(tile: Tile, style: Style): ImageData +} + +interface StoredTile { + tile: Tile + address: TileAddress + layerKey: string + bytes: number + lastUsed: number + picture: HTMLCanvasElement | null + pictureStyle: string +} + +// Drawing a few hundred tiles at once only queues them on the server; a handful in flight keeps it busy. +const MAXIMUM_IN_FLIGHT = 6 +// A 3D view holds a couple of hundred tiles of blocks, half a megabyte each, and turning back should not sample them again. +const CACHE_BYTES = 1024 * 1024 * 1024 + +/** + * Tiles fetched from the bridge as a view needs them, kept within a memory budget, and drawn as the current style + * asks. A tile that leaves the view before it arrives is not fetched. + */ +export class TileStore { + private readonly tiles = new Map>() + private readonly inFlight = new Map() + /** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */ + private readonly failed = new Set() + private wanted: { key: string; address: TileAddress; layer: Layer }[] = [] + private storedBytes = 0 + private useClock = 0 + private changes = 0 + + constructor( + private readonly source: TileSource, + private readonly onChange: () => void, + private readonly onError: (message: string) => void + ) {} + + key(address: TileAddress, layer: Layer): string { + return `${this.source.layerKey(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}` + } + + /** The tile if it has arrived, marked as just used. */ + get(address: TileAddress, layer: Layer): Tile | null { + const stored = this.tiles.get(this.key(address, layer)) + if (stored === undefined) { + return null + } + stored.lastUsed = ++this.useClock + return stored.tile + } + + /** Whether the tile has arrived; unlike {@link get}, asking does not count as using it. */ + has(address: TileAddress, layer: Layer): boolean { + return this.tiles.has(this.key(address, layer)) + } + + /** Where the layer's tiles that have arrived lie; asking does not count as using them. */ + addressesOf(layer: Layer): TileAddress[] { + const layerKey = this.source.layerKey(layer) + return [...this.tiles.values()].filter((stored) => stored.layerKey === layerKey).map((stored) => stored.address) + } + + /** Changes whenever a tile arrives or is let go, so what is worked out from the stored tiles is worked out again. */ + get version(): number { + return this.changes + } + + /** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */ + picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null { + const stored = this.tiles.get(this.key(address, layer)) + if (stored === undefined || this.source.styleKey === undefined || this.source.pixels === undefined) { + return null + } + stored.lastUsed = ++this.useClock + const wantedStyle = this.source.styleKey(style) + if (stored.picture === null || stored.pictureStyle !== wantedStyle) { + stored.picture = stored.picture ?? document.createElement('canvas') + paint(stored.picture, this.source.pixels(stored.tile, style)) + stored.pictureStyle = wantedStyle + } + return stored.picture + } + + /** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */ + want(addresses: TileAddress[], layer: Layer): void { + this.wantEach(addresses.map((address) => ({ address, layer }))) + } + + /** As {@link want}, each tile of its own layer. */ + wantEach(tiles: { address: TileAddress; layer: Layer }[]): void { + this.wanted = tiles + .map(({ address, layer }) => ({ key: this.key(address, layer), address, layer })) + .filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key)) + const stillWanted = new Set(this.wanted.map((entry) => entry.key)) + for (const [key, request] of this.inFlight) { + if (!stillWanted.has(key)) { + request.controller.abort() + this.inFlight.delete(key) + } + } + this.startRequests() + } + + /** How many of the wanted tiles are still on their way. */ + pending(): number { + return this.wanted.length + } + + clear(): void { + for (const request of this.inFlight.values()) { + request.controller.abort() + } + this.inFlight.clear() + this.failed.clear() + this.tiles.clear() + this.wanted = [] + this.storedBytes = 0 + this.changes++ + } + + // Each layer has its own requests in flight, so tiles of a slow layer, which take a minute, never hold up a quick one's. + private startRequests(): void { + const inFlightByLayer = new Map() + for (const { layerKey } of this.inFlight.values()) { + inFlightByLayer.set(layerKey, (inFlightByLayer.get(layerKey) ?? 0) + 1) + } + for (const entry of this.wanted) { + const layerKey = this.source.layerKey(entry.layer) + const inFlight = inFlightByLayer.get(layerKey) ?? 0 + if (this.inFlight.has(entry.key) || inFlight >= MAXIMUM_IN_FLIGHT) { + continue + } + inFlightByLayer.set(layerKey, inFlight + 1) + this.fetchTile(entry.key, layerKey, entry.address, entry.layer) + } + } + + private fetchTile(key: string, layerKey: string, address: TileAddress, layer: Layer): void { + const controller = new AbortController() + this.inFlight.set(key, { controller, layerKey }) + this.source + .fetch(address, layer, controller.signal) + .then((tile) => this.store(key, address, layer, tile)) + .catch((error: unknown) => { + if (!controller.signal.aborted) { + this.failed.add(key) + this.onError(error instanceof BridgeError ? error.message : 'The server did not answer') + } + }) + .finally(() => { + if (this.inFlight.get(key)?.controller === controller) { + this.inFlight.delete(key) + } + this.wanted = this.wanted.filter((entry) => entry.key !== key) + this.startRequests() + this.onChange() + }) + } + + private store(key: string, address: TileAddress, layer: Layer, tile: Tile): void { + const bytes = this.source.bytesOf(tile) + this.tiles.set(key, { tile, address, layerKey: this.source.layerKey(layer), bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' }) + this.storedBytes += bytes + this.changes++ + this.evictOldest() + } + + private evictOldest(): void { + if (this.storedBytes <= CACHE_BYTES) { + return + } + const byAge = [...this.tiles.entries()].sort((first, second) => first[1].lastUsed - second[1].lastUsed) + for (const [key, stored] of byAge) { + if (this.storedBytes <= CACHE_BYTES * 0.8) { + return + } + this.tiles.delete(key) + this.storedBytes -= stored.bytes + this.changes++ + } + } +} + +function paint(canvas: HTMLCanvasElement, pixels: ImageData): void { + canvas.width = pixels.width + canvas.height = pixels.height + canvas.getContext('2d')!.putImageData(pixels, 0, 0) +} diff --git a/studio/src/renderer/src/map/TiledView.ts b/studio/src/renderer/src/map/TiledView.ts new file mode 100644 index 000000000..faedff9dc --- /dev/null +++ b/studio/src/renderer/src/map/TiledView.ts @@ -0,0 +1,188 @@ +import { drawVisibleTiles } from './tileDrawing' +import { TileStore, type TileSource } from './TileStore' +import { + MAXIMUM_BLOCKS_PER_PIXEL, + MINIMUM_VIEW_BLOCKS_PER_PIXEL, + renderBlocksPerPixel, + screenToWorldX, + screenToWorldZ, + type TileAddress, + type Viewport +} from './viewport' + +export interface TiledViewOptions { + source: TileSource + tileSize: number + defaultBlocksPerPixel: number + /** The finest scale tiles are asked for at; closer views magnify them. */ + finestRenderBlocksPerPixel: number + /** How far the view may zoom out. */ + coarsestBlocksPerPixel?: number + onFrame(frame: TiledFrame): void + onError(message: string): void +} + +export interface TiledFrame { + blocksPerPixel: number + tilesReady: number + tilesTotal: number + /** The world spot under the cursor, or under the middle when the cursor is away. */ + cursorX: number + cursorZ: number +} + +/** A tile and the pixel of it at a world spot. */ +export interface TileSpot { + tile: Tile + pixelX: number + pixelZ: number +} + +/** Where a view looks and the scale its tiles are drawn at. */ +export interface TiledFraming { + centerX: number + centerZ: number + renderScale: number +} + +/** + * A pan and zoom view of tiles on a canvas, fetched as the view moves and drawn in the current style. Kept outside + * React, as it redraws on every drag and wheel step. + */ +export class TiledView { + private readonly context: CanvasRenderingContext2D + private readonly store: TileStore + private readonly view: Viewport + private layer: Layer | null = null + private style: Style | null = null + private cursor: { x: number; y: number } | null = null + private drawn = { tilesReady: 0, tilesTotal: 0 } + private frameRequested = false + private closed = false + + constructor( + private readonly canvas: HTMLCanvasElement, + private readonly options: TiledViewOptions + ) { + this.context = canvas.getContext('2d')! + this.view = { centerX: 0, centerZ: 0, blocksPerPixel: options.defaultBlocksPerPixel, width: 1, height: 1 } + this.store = new TileStore(options.source, () => this.redraw(), options.onError) + } + + close(): void { + this.closed = true + this.store.clear() + } + + resize(width: number, height: number): void { + const ratio = window.devicePixelRatio + this.canvas.width = Math.round(width * ratio) + this.canvas.height = Math.round(height * ratio) + this.view.width = width + this.view.height = height + this.redraw() + } + + show(layer: Layer | null, style: Style): void { + this.layer = layer + this.style = style + this.redraw() + } + + panBy(screenDeltaX: number, screenDeltaZ: number): void { + this.view.centerX -= screenDeltaX * this.view.blocksPerPixel + this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel + this.redraw() + } + + /** Zooms by {@code factor} (above 1 zooms in) keeping the spot under the screen point where it is. */ + zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void { + const worldX = screenToWorldX(this.view, screenX) + const worldZ = screenToWorldZ(this.view, screenZ) + const coarsest = this.options.coarsestBlocksPerPixel ?? MAXIMUM_BLOCKS_PER_PIXEL + this.view.blocksPerPixel = Math.min(coarsest, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, this.view.blocksPerPixel / factor)) + this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel + this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel + this.redraw() + } + + resetView(): void { + this.view.centerX = 0 + this.view.centerZ = 0 + this.view.blocksPerPixel = this.options.defaultBlocksPerPixel + this.redraw() + } + + setCursor(cursor: { x: number; y: number } | null): void { + this.cursor = cursor + this.reportFrame() + } + + framing(): TiledFraming { + return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() } + } + + /** The tile drawn at a world spot at the current scale and its pixel there; null before it arrived. */ + spotAt(worldX: number, worldZ: number): TileSpot | null { + if (this.layer === null) { + return null + } + const scale = this.renderScale() + const span = this.options.tileSize * scale + const address: TileAddress = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale } + const tile = this.store.get(address, this.layer) + if (tile === null) { + return null + } + const last = this.options.tileSize - 1 + const pixelX = Math.min(last, Math.floor((worldX - address.tileX * span) / scale)) + const pixelZ = Math.min(last, Math.floor((worldZ - address.tileZ * span) / scale)) + return { tile, pixelX, pixelZ } + } + + private renderScale(): number { + return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, this.options.finestRenderBlocksPerPixel) + } + + private redraw(): void { + if (this.frameRequested || this.closed) { + return + } + this.frameRequested = true + requestAnimationFrame(() => { + this.frameRequested = false + if (!this.closed) { + this.draw() + } + }) + } + + private draw(): void { + const ratio = window.devicePixelRatio + const context = this.context + context.setTransform(ratio, 0, 0, ratio, 0, 0) + context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a' + context.fillRect(0, 0, this.view.width, this.view.height) + const layer = this.layer + const style = this.style + if (layer === null || style === null) { + this.drawn = { tilesReady: 0, tilesTotal: 0 } + this.reportFrame() + return + } + const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.options.tileSize, (address) => this.store.picture(address, layer, style)) + this.store.want(drawn.wanted, layer) + this.drawn = { tilesReady: drawn.ready, tilesTotal: drawn.tiles.length } + this.reportFrame() + } + + private reportFrame(): void { + const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 } + this.options.onFrame({ + blocksPerPixel: this.view.blocksPerPixel, + ...this.drawn, + cursorX: screenToWorldX(this.view, cursor.x), + cursorZ: screenToWorldZ(this.view, cursor.y) + }) + } +} diff --git a/studio/src/renderer/src/map/census.ts b/studio/src/renderer/src/map/census.ts new file mode 100644 index 000000000..7a00c1a7b --- /dev/null +++ b/studio/src/renderer/src/map/census.ts @@ -0,0 +1,85 @@ +import { gridIndex } from '../bridge/tileDecoding' +import { NO_LABEL, type MapTile } from '../bridge/types' +import { bandIndexOf, HEIGHT_BANDS } from './heightColors' +import type { Highlight } from './tileStyle' + +/** How much of the screen one biome, region or height band covers. */ +export interface Share { + subject: Highlight + color: number + fraction: number +} + +/** A loaded tile and where its top left pixel lies in the world. */ +export interface PlacedTile { + tile: MapTile + worldX: number + worldZ: number +} + +export interface WorldArea { + minimumX: number + minimumZ: number + maximumX: number + maximumZ: number +} + +// Enough samples that a share is right to a fraction of a percent, few enough to count every frame the map settles. +const MAXIMUM_COUNTED_PIXELS = 250_000 + +/** + * The shares of what the tiles show inside {@code area}, largest first: their subjects, which are biomes or regions. + */ +export function countShares(tiles: PlacedTile[], area: WorldArea): Share[] { + const counts = new Map() + const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0) + const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS))) + let counted = 0 + for (const { tile, worldX, worldZ } of tiles) { + const scale = tile.blocksPerPixel + const firstX = Math.max(0, Math.ceil((area.minimumX - worldX) / scale)) + const endX = Math.min(tile.size, Math.ceil((area.maximumX - worldX) / scale)) + const firstZ = Math.max(0, Math.ceil((area.minimumZ - worldZ) / scale)) + const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale)) + for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) { + for (let pixelX = firstX; pixelX < endX; pixelX += stride) { + const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ)) + if (subject === null) { + continue + } + const id = `${subject.subject.kind}:${subject.subject.key}` + const entry = counts.get(id) ?? { ...subject, count: 0 } + entry.count++ + counts.set(id, entry) + counted++ + } + } + } + return [...counts.values()] + .map((entry) => ({ subject: entry.subject, color: entry.color, fraction: entry.count / Math.max(1, counted) })) + .sort((first, second) => second.fraction - first.fraction) +} + +/** The shares of the height bands the {@code heights} fall in, highest band first. */ +export function heightBandShares(heights: readonly number[], seaLevel: number): Share[] { + const counts = new Map() + for (const height of heights) { + const band = bandIndexOf(height, seaLevel) + counts.set(band, (counts.get(band) ?? 0) + 1) + } + return [...counts] + .sort(([firstBand], [secondBand]) => secondBand - firstBand) + .map(([band, count]) => { + const { key, name, color } = HEIGHT_BANDS[band] + return { subject: { kind: 'HEIGHT', key, name }, color, fraction: count / heights.length } + }) +} + +function subjectAt(tile: MapTile, cell: number): { subject: Highlight; color: number } | null { + const index = tile.subjects[cell] + if (index === NO_LABEL) { + return null + } + const label = tile.labels[index] + return { subject: { kind: label.kind, key: label.key, name: label.name }, color: label.color } +} diff --git a/studio/src/renderer/src/map/heightColors.ts b/studio/src/renderer/src/map/heightColors.ts new file mode 100644 index 000000000..de14ad17e --- /dev/null +++ b/studio/src/renderer/src/map/heightColors.ts @@ -0,0 +1,76 @@ +/** The height scale of the map, from deep water to snowy peaks, measured from sea level (v3e HeightColors). */ + +export const DEEPEST_BELOW_SEA_BLOCKS = 90 +export const HIGHEST_ABOVE_SEA_BLOCKS = 300 +const DEPTH_BLOCKS = [0, 10, 40, DEEPEST_BELOW_SEA_BLOCKS] +const DEPTH_COLORS = [0x7db8d8, 0x4c8dba, 0x2a5e8f, 0x15304f] +const ABOVE_SEA_BLOCKS = [0, 8, 30, 70, 130, 200, HIGHEST_ABOVE_SEA_BLOCKS] +const LAND_COLORS = [0x7fa35a, 0x5e8c44, 0x8fa65a, 0xc2ae78, 0x8e7663, 0xa9a6a2, 0xf4f4f4] +// Where each band ends, in blocks above sea; they follow the colour stops, merging the deepest two. +const BAND_TOPS_ABOVE_SEA = [-40, -10, 0, 8, 30, 70, 130, 200, 300, Number.POSITIVE_INFINITY] + +/** A stretch of heights between two of the scale's stops, for telling how much ground lies at each height. */ +export interface HeightBand { + /** The band's place from the deepest, as text that sorts the same way. */ + key: string + name: string + color: number +} + +export function heightColor(height: number, seaLevel: number): number { + if (height <= seaLevel) { + return along(DEPTH_BLOCKS, DEPTH_COLORS, seaLevel - height) + } + return along(ABOVE_SEA_BLOCKS, LAND_COLORS, height - seaLevel) +} + +export const HEIGHT_BANDS: readonly HeightBand[] = createBands() + +export function bandIndexOf(height: number, seaLevel: number): number { + const aboveSea = height - seaLevel + const index = BAND_TOPS_ABOVE_SEA.findIndex((top) => aboveSea <= top) + return index < 0 ? BAND_TOPS_ABOVE_SEA.length - 1 : index +} + +function createBands(): HeightBand[] { + const bands: HeightBand[] = [] + let bottom = -DEEPEST_BELOW_SEA_BLOCKS + BAND_TOPS_ABOVE_SEA.forEach((top, band) => { + const colorHeight = Number.isFinite(top) ? (bottom + top) / 2 : bottom + bands.push({ key: String(band).padStart(2, '0'), name: bandName(band, bottom, top), color: heightColor(colorHeight, 0) }) + bottom = top + }) + return bands +} + +function bandName(band: number, bottom: number, top: number): string { + if (band === 0) { + return `${Math.round(-top)}+ below sea` + } + if (!Number.isFinite(top)) { + return `${Math.round(bottom)}+ above sea` + } + if (top <= 0) { + return `${Math.round(-top)}–${Math.round(-bottom)} below sea` + } + return `${Math.round(bottom)}–${Math.round(top)} above sea` +} + +function along(stops: number[], colors: number[], blocks: number): number { + if (blocks <= stops[0]) { + return colors[0] + } + for (let stop = 1; stop < stops.length; stop++) { + if (blocks <= stops[stop]) { + return blend(colors[stop - 1], colors[stop], (blocks - stops[stop - 1]) / (stops[stop] - stops[stop - 1])) + } + } + return colors[colors.length - 1] +} + +export function blend(first: number, second: number, amount: number): number { + const red = Math.round(((first >> 16) & 0xff) * (1 - amount) + ((second >> 16) & 0xff) * amount) + const green = Math.round(((first >> 8) & 0xff) * (1 - amount) + ((second >> 8) & 0xff) * amount) + const blue = Math.round((first & 0xff) * (1 - amount) + (second & 0xff) * amount) + return (red << 16) | (green << 8) | blue +} diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts new file mode 100644 index 000000000..4ad7b8a0c --- /dev/null +++ b/studio/src/renderer/src/map/map.test.ts @@ -0,0 +1,323 @@ +import { describe, expect, it } from 'vitest' +import { decodeTile, gridIndex } from '../bridge/tileDecoding' +import type { MapLabel, MapTile, TileBlocks } from '../bridge/types' +import { countShares, heightBandShares } from './census' +import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors' +import { arrowCorners } from './playerArrow' +import { stylePixels, type TileStyle } from './tileStyle' +import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visibleTiles, worldToScreenX, type Viewport } from './viewport' + +const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 } +const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 } +const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 } +const FLAT: TileStyle = { byBlock: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' } + +/** A tile whose left half is plains and right half desert, all in one region, at height 70. */ +function splitTile(size = 4): MapTile { + const cells = (size + 2) ** 2 + const subjects = new Int16Array(cells) + for (let cell = 0; cell < cells; cell++) { + subjects[cell] = cell % (size + 2) <= size / 2 ? 0 : 1 + } + return { + size, + blocksPerPixel: 1, + subjectKind: 'BIOME', + labels: [PLAINS, DESERT, WARM], + subjects, + regions: new Int16Array(cells).fill(2), + heights: new Float32Array(cells).fill(70), + pickNoise: null, + blocks: null + } +} + +/** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */ +function encode(size: number, withHeights: boolean, withPickNoise = false): ArrayBuffer { + const header = new TextEncoder().encode( + JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights, pickNoise: withPickNoise }) + ) + const cells = (size + 2) ** 2 + const align = (bytes: number): number => Math.ceil(bytes / 4) * 4 + const subjectsAt = align(4 + header.length) + const regionsAt = align(subjectsAt + cells * 2) + const heightsAt = align(regionsAt + cells * 2) + const pickNoiseAt = heightsAt + (withHeights ? cells * 4 : 0) + const buffer = new ArrayBuffer(pickNoiseAt + (withPickNoise ? cells * 4 : 0)) + new DataView(buffer).setUint32(0, header.length, true) + new Uint8Array(buffer, 4).set(header) + new Int16Array(buffer, subjectsAt, cells).fill(0) + new Int16Array(buffer, regionsAt, cells).fill(-1) + if (withHeights) { + new Float32Array(buffer, heightsAt, cells).fill(81.5) + } + if (withPickNoise) { + new Float32Array(buffer, pickNoiseAt, cells).fill(0.25) + } + return buffer +} + +function nothingRaised(cells: number): Pick { + return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0), voxels: null, runs: null, models: [] } +} + +/** A tile of one pixel with its blocks as the bridge sends them: ground, cover and the raised blocks' counts, heights and blocks. */ +function encodeBlocks(raisedCounts: number[], raisedY: number[], raised: number[]): ArrayBuffer { + const size = 1 + const cells = (size + 2) ** 2 + const header = new TextEncoder().encode( + JSON.stringify({ size, blocksPerPixel: 1, subjectKind: 'BIOME', labels: [PLAINS], heights: false, pickNoise: false, blocks: ['stone', 'leaves', 'log'], raised: raised.length }) + ) + const align = (bytes: number): number => Math.ceil(bytes / 4) * 4 + const grid = align(cells * 2) + const groundAt = align(4 + header.length) + grid * 2 + const raisedYAt = groundAt + grid * 3 + const raisedAt = align(raisedYAt + raised.length * 2) + const buffer = new ArrayBuffer(raisedAt + align(raised.length * 2)) + new DataView(buffer).setUint32(0, header.length, true) + new Uint8Array(buffer, 4).set(header) + new Int16Array(buffer, groundAt + grid, cells).fill(-1) + new Int16Array(buffer, groundAt + grid * 2, cells).set(raisedCounts) + new Int16Array(buffer, raisedYAt, raised.length).set(raisedY) + new Int16Array(buffer, raisedAt, raised.length).set(raised) + return buffer +} + +describe('tile decoding', () => { + it('reads the raised blocks of each cell after the cover grid', () => { + const blocks = decodeTile(encodeBlocks([0, 0, 0, 0, 2, 0, 0, 1, 0], [70, 69, 66], [1, 2, 1])).blocks! + + expect([...blocks.raisedStart]).toEqual([0, 0, 0, 0, 0, 2, 2, 2, 3, 3]) + expect([...blocks.raisedY]).toEqual([70, 69, 66]) + expect([...blocks.raised]).toEqual([1, 2, 1]) + expect(blocks.cover[4]).toBe(-1) + }) + + it('reads the header and views each grid where the bridge put it', () => { + const tile = decodeTile(encode(3, true)) + + expect(tile.size).toBe(3) + expect(tile.blocksPerPixel).toBe(2) + expect(tile.labels[0].key).toBe('plains') + expect(tile.subjects.length).toBe(25) + expect(tile.regions[0]).toBe(-1) + expect(tile.heights?.[24]).toBe(81.5) + }) + + it('has no heights when the header says so', () => { + expect(decodeTile(encode(3, false)).heights).toBeNull() + }) + + it('reads the pick noise after the heights, or in their place without them', () => { + expect(decodeTile(encode(3, true, true)).pickNoise?.[24]).toBe(0.25) + expect(decodeTile(encode(3, false, true)).pickNoise?.[0]).toBe(0.25) + expect(decodeTile(encode(3, true)).pickNoise).toBeNull() + }) +}) + +describe('pick noise', () => { + function noisyTile(noise: number): MapTile { + const tile = splitTile() + return { ...tile, pickNoise: new Float32Array(tile.subjects.length).fill(noise) } + } + + it('draws the bare noise from dark to white', () => { + const pixels = stylePixels(noisyTile(1), { ...FLAT, pickDisplay: 'noise' }) + + expect([pixels[0], pixels[1], pixels[2]]).toEqual([255, 255, 255]) + }) + + it('draws the picks darker where their noise is lower', () => { + const pixels = stylePixels(noisyTile(0), { ...FLAT, pickDisplay: 'both' }) + + expect(pixels[1]).toBe(Math.floor(255 * 0.3)) + }) + + it('leaves a spot nothing picked in its own colour', () => { + const pixels = stylePixels(noisyTile(Number.NaN), { ...FLAT, pickDisplay: 'noise' }) + + expect([pixels[0], pixels[1], pixels[2]]).toEqual([0, 255, 0]) + }) +}) + +describe('height colours', () => { + it('runs from deep water to snow and stays at the ends beyond them', () => { + expect(heightColor(63, 63)).toBe(0x7db8d8) + expect(heightColor(-1000, 63)).toBe(0x15304f) + expect(heightColor(1000, 63)).toBe(0xf4f4f4) + }) + + it('puts each height in the band the legend names', () => { + expect(HEIGHT_BANDS[bandIndexOf(63, 63)].name).toBe('0–10 below sea') + expect(HEIGHT_BANDS[bandIndexOf(64, 63)].name).toBe('0–8 above sea') + expect(HEIGHT_BANDS[bandIndexOf(500, 63)].name).toBe('300+ above sea') + expect(HEIGHT_BANDS[bandIndexOf(-500, 63)].name).toBe('40+ below sea') + }) +}) + +describe('tile style', () => { + const pixel = (pixels: Uint8ClampedArray, size: number, x: number, z: number): number => { + const at = (z * size + x) * 4 + return (pixels[at] << 16) | (pixels[at + 1] << 8) | pixels[at + 2] + } + + it('paints each pixel in its label colour', () => { + const pixels = stylePixels(splitTile(), FLAT) + + expect(pixel(pixels, 4, 0, 0)).toBe(PLAINS.color) + expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color) + }) + + it('paints each pixel in the colour of what stands on its ground, or of the ground itself', () => { + const tile = splitTile() + const cells = tile.subjects.length + const cover = new Int16Array(cells).fill(-1) + cover[gridIndex(tile, 3, 3)] = 1 + const blocks = { ...nothingRaised(cells), names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [], covers: [] } + const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true }) + + expect(pixel(pixels, 4, 0, 0)).toBe(0x808080) + expect(pixel(pixels, 4, 3, 3)).toBe(0xff0000) + }) + + it('paints a column with blocks raised over its ground in the colour of the highest', () => { + const tile = splitTile() + const cells = tile.subjects.length + const raisedStart = new Int32Array(cells + 1) + raisedStart.fill(2, gridIndex(tile, 3, 3) + 1) + const blocks = { + names: ['stone', 'leaves', 'log'], + ground: new Int16Array(cells).fill(0), + cover: new Int16Array(cells).fill(-1), + raisedStart, + raisedY: Int16Array.of(70, 69), + raised: Int16Array.of(1, 2), + voxels: null, + runs: null, + colors: [0x808080, 0x00ff00, 0x654321], + looks: [], + covers: [], + models: [] + } + const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true }) + + expect(pixel(pixels, 4, 0, 0)).toBe(0x808080) + expect(pixel(pixels, 4, 3, 3)).toBe(0x00ff00) + }) + + it('keeps the label colours of a tile without blocks', () => { + expect(pixel(stylePixels(splitTile(), { ...FLAT, byBlock: true }), 4, 0, 0)).toBe(PLAINS.color) + }) + + it('dims everything but the highlight, and tints the highlight edge', () => { + const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } }) + + expect(pixel(pixels, 4, 3, 3)).not.toBe(DESERT.color) + expect(pixel(pixels, 4, 0, 1)).toBe(PLAINS.color) + expect(pixel(pixels, 4, 1, 1)).not.toBe(PLAINS.color) + }) + + it('leaves flat ground almost as it is when shading', () => { + const pixels = stylePixels(splitTile(), { ...FLAT, shading: true }) + const green = (pixel(pixels, 4, 0, 0) >> 8) & 0xff + + expect(green).toBeGreaterThan(200) + }) +}) + +describe('viewport', () => { + const view: Viewport = { centerX: 100, centerZ: -50, blocksPerPixel: 2, width: 800, height: 600 } + + it('maps screen and world both ways', () => { + expect(screenToWorldX(view, 400)).toBe(100) + expect(worldToScreenX(view, screenToWorldX(view, 123))).toBe(123) + }) + + it('draws tiles at the power of two nearest a device pixel, never finer than a block', () => { + expect(renderBlocksPerPixel(4, 1)).toBe(4) + expect(renderBlocksPerPixel(4, 2)).toBe(2) + expect(renderBlocksPerPixel(0.25, 1)).toBe(1) + expect(renderBlocksPerPixel(5.5, 1)).toBe(4) + }) + + it('covers the screen, starting from the middle', () => { + const tiles = visibleTiles(view, 2, 128) + + // 1600 × 1200 blocks around (100, -50) in tiles of 256 blocks: x -3 to 3, z -3 to 2. + expect(tiles.length).toBe(7 * 6) + expect(tiles[0]).toEqual({ tileX: 0, tileZ: -1, blocksPerPixel: 2 }) + }) + + it('finds the coarser tile that covers a tile', () => { + expect(coarserTile({ tileX: -3, tileZ: 5, blocksPerPixel: 2 }, 2)).toEqual({ tileX: -1, tileZ: 1, blocksPerPixel: 8 }) + }) + + it('previews four blank tiles with one tile a level out, never past the coarsest scale', () => { + const blank = [ + { tileX: 0, tileZ: 0, blocksPerPixel: 2 }, + { tileX: 1, tileZ: 0, blocksPerPixel: 2 }, + { tileX: 0, tileZ: 1, blocksPerPixel: 2 }, + { tileX: -1, tileZ: 0, blocksPerPixel: 2 }, + { tileX: 0, tileZ: 0, blocksPerPixel: 4096 } + ] + + expect(previewsFor(blank)).toEqual([ + { tileX: 0, tileZ: 0, blocksPerPixel: 4 }, + { tileX: -1, tileZ: 0, blocksPerPixel: 4 } + ]) + }) +}) + +describe('census', () => { + it('shares the visible pixels between the labels', () => { + const tile = splitTile(4) + const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }) + + expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains']) + expect(shares[0].fraction).toBeCloseTo(0.5) + expect(gridIndex(tile, -1, -1)).toBe(0) + }) + + it('counts only the part of a tile inside the area, largest share first', () => { + const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }) + + expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert']) + expect(shares[0].fraction).toBeCloseTo(2 / 3) + }) + + it('shares spot heights between their bands, highest band first', () => { + const shares = heightBandShares([64, 64, 64, 500, 30], 63) + + expect(shares.map((share) => share.subject.name)).toEqual(['300+ above sea', '0–8 above sea', '10–40 below sea']) + expect(shares.map((share) => share.fraction)).toEqual([0.2, 0.6, 0.2]) + expect(shares[1].color).toBe(HEIGHT_BANDS[bandIndexOf(64, 63)].color) + }) + + it('has no shares for no heights', () => { + expect(heightBandShares([], 63)).toEqual([]) + }) +}) + +describe('player arrow', () => { + const tipAt = (yaw: number) => arrowCorners(yaw, 10, 7, 3)[0] + + it('points the tip south, down the map, at yaw 0', () => { + expect(tipAt(0).x).toBeCloseTo(0) + expect(tipAt(0).z).toBeCloseTo(10) + }) + + it('points west at 90, north at 180 and east at 270', () => { + expect(tipAt(90).x).toBeCloseTo(-10) + expect(tipAt(90).z).toBeCloseTo(0) + expect(tipAt(180).z).toBeCloseTo(-10) + expect(tipAt(270).x).toBeCloseTo(10) + }) + + it('keeps its shape while turning', () => { + const [tip, right, notch, left] = arrowCorners(37, 10, 7, 3) + + expect(Math.hypot(tip.x, tip.z)).toBeCloseTo(10) + expect(Math.hypot(right.x - left.x, right.z - left.z)).toBeCloseTo(14) + expect(Math.hypot(notch.x, notch.z)).toBeCloseTo(7) + }) +}) diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts new file mode 100644 index 000000000..d887cb1f0 --- /dev/null +++ b/studio/src/renderer/src/map/mapTileSource.ts @@ -0,0 +1,61 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { BlockSource, MapTile } from '../bridge/types' +import type { BlockArt } from '../scene/blockArt' +import { stylePixels, styleKey, type TileStyle } from './tileStyle' +import type { TileSource } from './TileStore' + +/** What one map tile request needs besides where the tile is. */ +export interface TileLayer { + view: string + /** The region the region view previews everywhere, or null for the world as it is. */ + preview: string | null + heights: boolean + pickNoise: boolean + /** Where the tiles' blocks come from, or null for tiles without them. */ + blocks: BlockSource | null + /** Whether tiles with blocks also carry the ground's shape in 3D, to draw it as blocks and runs of blocks. */ + shape?: boolean + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +/** + * The coarsest tiles the map asks for blocks; coarser ones come without. Every chunk under a tile is generated for its + * blocks, so a map zoomed out over a few screens would keep the server busy for minutes. + */ +const MAP_MOST_BLOCKS_PER_PIXEL = 1 +const TEXTURED_BLOCKS_PER_PIXEL = 1 + +function voxelBytesOf(tile: MapTile): number { + const voxels = tile.blocks?.voxels + return voxels === null || voxels === undefined ? 0 : voxels.x.byteLength * 3 + voxels.y.byteLength * 2 +} + +/** Whether the map's tiles this coarse carry blocks. */ +export function hasBlocksAt(blocksPerPixel: number): boolean { + return blocksPerPixel <= MAP_MOST_BLOCKS_PER_PIXEL +} + +/** + * The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}. + * + * @param mostBlocksPerPixel the coarsest tiles that carry blocks; at most the 8 the server generates them for + */ +export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt, mostBlocksPerPixel = MAP_MOST_BLOCKS_PER_PIXEL): TileSource { + return { + layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? '', layer.shape === true].join('/'), + fetch: async (address, layer, signal) => { + const blocks = layer.blocks !== null && address.blocksPerPixel <= mostBlocksPerPixel ? layer.blocks : null + const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal) + if (tile.blocks !== null) { + // Runs show each block's sides in the colours of its pictures, so their looks are read too. + await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL || tile.blocks.runs !== null) + } + return tile + }, + bytesOf: (tile) => + tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + (tile.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.byteLength ?? 0) * 2 + voxelBytesOf(tile) + tile.size * tile.size * 4, + styleKey, + pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size) + } +} diff --git a/studio/src/renderer/src/map/playerArrow.ts b/studio/src/renderer/src/map/playerArrow.ts new file mode 100644 index 000000000..cb9f4bb99 --- /dev/null +++ b/studio/src/renderer/src/map/playerArrow.ts @@ -0,0 +1,85 @@ +export interface ScreenPoint { + x: number + z: number +} + +const MINECRAFT_YAW_TO_SCREEN_DEGREES = 180 +const ARROW_HALF_LENGTH_PIXELS = 9.5 +const ARROW_HALF_WIDTH_PIXELS = 7.5 +const ARROW_NOTCH_PIXELS = 3.5 +const ARROW_EDGE_WIDTH_PIXELS = 1.75 +const ARROW_OUTLINE_WIDTH_PIXELS = 1 +const ARROW_SHADOW_OFFSET_PIXELS = 1.5 +const ARROW_REACH_PIXELS = ARROW_HALF_LENGTH_PIXELS + ARROW_EDGE_WIDTH_PIXELS + ARROW_OUTLINE_WIDTH_PIXELS +const ARROW_FILL = '#3574f0' +const ARROW_EDGE = '#ffffff' +const ARROW_OUTLINE = 'rgba(0, 0, 0, 0.59)' +const ARROW_SHADOW = 'rgba(0, 0, 0, 0.35)' +const LABEL_GAP_PIXELS = 5 +const LABEL_HEIGHT_PIXELS = 18 +const LABEL_PADDING_X_PIXELS = 7 +const LABEL_FONT = '600 12px Inter, "Segoe UI", system-ui, sans-serif' +const LABEL_BACKGROUND = 'rgba(30, 31, 34, 0.86)' +const LABEL_BORDER = 'rgba(255, 255, 255, 0.22)' +const LABEL_TEXT = '#ffffff' + +/** + * The corners of a player's arrow around the origin: tip, right wing, notch, left wing. Minecraft's yaw 0 faces + * south and 90 west, which on the map is down and left, so the heading is (-sin, cos) in (x, z). + */ +export function arrowCorners(yawDegrees: number, halfLength: number, halfWidth: number, notch: number): ScreenPoint[] { + const turn = ((yawDegrees + MINECRAFT_YAW_TO_SCREEN_DEGREES) * Math.PI) / 180 + const sine = Math.sin(turn) + const cosine = Math.cos(turn) + const upright: ScreenPoint[] = [ + { x: 0, z: -halfLength }, + { x: halfWidth, z: halfLength }, + { x: 0, z: halfLength - notch }, + { x: -halfWidth, z: halfLength } + ] + return upright.map((corner) => ({ x: corner.x * cosine - corner.z * sine, z: corner.x * sine + corner.z * cosine })) +} + +/** A blue arrow with a white edge, dark outline and shadow pointing where the player looks, and their name in a pill above. */ +export function drawPlayerArrow(context: CanvasRenderingContext2D, x: number, z: number, yawDegrees: number, name: string): void { + const corners = arrowCorners(yawDegrees, ARROW_HALF_LENGTH_PIXELS, ARROW_HALF_WIDTH_PIXELS, ARROW_NOTCH_PIXELS) + context.save() + context.lineJoin = 'round' + context.fillStyle = ARROW_SHADOW + context.fill(arrowPath(corners, x, z + ARROW_SHADOW_OFFSET_PIXELS)) + const arrow = arrowPath(corners, x, z) + // Strokes are centred on the outline, so each ring is drawn twice its width and the next one covers its inner half. + context.lineWidth = (ARROW_EDGE_WIDTH_PIXELS + ARROW_OUTLINE_WIDTH_PIXELS) * 2 + context.strokeStyle = ARROW_OUTLINE + context.stroke(arrow) + context.lineWidth = ARROW_EDGE_WIDTH_PIXELS * 2 + context.strokeStyle = ARROW_EDGE + context.stroke(arrow) + context.fillStyle = ARROW_FILL + context.fill(arrow) + drawNamePill(context, name, x, z - ARROW_REACH_PIXELS - LABEL_GAP_PIXELS) + context.restore() +} + +function arrowPath(corners: ScreenPoint[], x: number, z: number): Path2D { + const path = new Path2D() + corners.forEach((corner, index) => (index === 0 ? path.moveTo(x + corner.x, z + corner.z) : path.lineTo(x + corner.x, z + corner.z))) + path.closePath() + return path +} + +function drawNamePill(context: CanvasRenderingContext2D, name: string, centerX: number, bottom: number): void { + context.font = LABEL_FONT + context.textAlign = 'center' + context.textBaseline = 'middle' + const width = context.measureText(name).width + LABEL_PADDING_X_PIXELS * 2 + const pill = new Path2D() + pill.roundRect(centerX - width / 2, bottom - LABEL_HEIGHT_PIXELS, width, LABEL_HEIGHT_PIXELS, LABEL_HEIGHT_PIXELS / 2) + context.fillStyle = LABEL_BACKGROUND + context.fill(pill) + context.lineWidth = 1 + context.strokeStyle = LABEL_BORDER + context.stroke(pill) + context.fillStyle = LABEL_TEXT + context.fillText(name, centerX, bottom - LABEL_HEIGHT_PIXELS / 2) +} diff --git a/studio/src/renderer/src/map/tileDrawing.ts b/studio/src/renderer/src/map/tileDrawing.ts new file mode 100644 index 000000000..ac3b9545a --- /dev/null +++ b/studio/src/renderer/src/map/tileDrawing.ts @@ -0,0 +1,82 @@ +import { coarserTile, previewsFor, visibleTiles, worldToScreenX, worldToScreenZ, type TileAddress, type Viewport } from './viewport' + +// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out. +const COARSER_FALLBACK_LEVELS = 6 + +export interface DrawnTiles { + /** Every tile the view covers, nearest the centre first. */ + tiles: TileAddress[] + ready: number + /** What to fetch, in order: a coarser preview for each blank stretch first, then the tiles themselves. */ + wanted: TileAddress[] +} + +/** + * Draws the tiles covering the view at {@code renderScale}, from {@code pictureOf}; where one hasn't arrived, the part + * of a coarser one that covers it. + */ +export function drawVisibleTiles( + context: CanvasRenderingContext2D, + view: Viewport, + renderScale: number, + tileSize: number, + pictureOf: (address: TileAddress) => HTMLCanvasElement | null +): DrawnTiles { + const tiles = visibleTiles(view, renderScale, tileSize) + context.imageSmoothingEnabled = view.blocksPerPixel > renderScale + let ready = 0 + const blank: TileAddress[] = [] + for (const address of tiles) { + const picture = pictureOf(address) + if (picture !== null) { + drawTile(context, view, tileSize, picture, address, 0, 0, picture.width) + ready++ + } else if (!drawFallback(context, view, tileSize, address, pictureOf)) { + blank.push(address) + } + } + return { tiles, ready, wanted: [...previewsFor(blank), ...tiles] } +} + +/** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */ +function drawTile( + context: CanvasRenderingContext2D, + view: Viewport, + tileSize: number, + picture: HTMLCanvasElement, + address: TileAddress, + sourceX: number, + sourceZ: number, + sourceSize: number +): void { + const span = tileSize * address.blocksPerPixel + const left = Math.round(worldToScreenX(view, address.tileX * span)) + const top = Math.round(worldToScreenZ(view, address.tileZ * span)) + const right = Math.round(worldToScreenX(view, (address.tileX + 1) * span)) + const bottom = Math.round(worldToScreenZ(view, (address.tileZ + 1) * span)) + context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top) +} + +/** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */ +function drawFallback( + context: CanvasRenderingContext2D, + view: Viewport, + tileSize: number, + address: TileAddress, + pictureOf: (address: TileAddress) => HTMLCanvasElement | null +): boolean { + for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) { + const coarser = coarserTile(address, levels) + const picture = pictureOf(coarser) + if (picture === null) { + continue + } + const factor = 2 ** levels + const sourceSize = picture.width / factor + const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize + const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize + drawTile(context, view, tileSize, picture, address, sourceX, sourceZ, sourceSize) + return true + } + return false +} diff --git a/studio/src/renderer/src/map/tileStyle.ts b/studio/src/renderer/src/map/tileStyle.ts new file mode 100644 index 000000000..229f4a60a --- /dev/null +++ b/studio/src/renderer/src/map/tileStyle.ts @@ -0,0 +1,193 @@ +import { gridIndex } from '../bridge/tileDecoding' +import { NO_BLOCK, NO_LABEL, type MapTile, type PickDisplay, type TileBlocks } from '../bridge/types' +import { WATER_SURFACE_COLOR } from '../scene/waterTint' +import { blend } from './heightColors' + +const WATER_OVER_GROUND = 0.65 + +/** What a highlight picks out: a biome or region by key, or a height band in the 3D world's legend. */ +export interface Highlight { + kind: 'BIOME' | 'REGION' | 'HEIGHT' + key: string + name: string +} + +export interface TileStyle { + /** Colour by the block on top of each column instead of by label, where the tile carries its blocks. */ + byBlock: boolean + shading: boolean + regionBorders: boolean + highlight: Highlight | null + seaLevel: number + /** How tiles that carry their pick noise draw it. */ + pickDisplay: PickDisplay +} + +export function styleKey(style: TileStyle): string { + const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}` + return `${style.byBlock}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}` +} + +const UNKNOWN_SUBJECT = 0x5a5c62 +const SHADING_EXAGGERATION = 2 +const LIGHT_X = -0.5 +const LIGHT_Y = 0.7 +const LIGHT_Z = -0.5 +const LIGHT_LENGTH = Math.sqrt(LIGHT_X * LIGHT_X + LIGHT_Y * LIGHT_Y + LIGHT_Z * LIGHT_Z) +const AMBIENT_LIGHT = 0.35 +const DIRECT_LIGHT = 0.75 +const DARKEST_SHADE = 0.25 +const BRIGHTEST_SHADE = 1.15 +// Water lies flat over the seafloor, so only a hint of the relief beneath shows through. +const UNDERWATER_RELIEF = 0.15 +const DIM_TARGET = 0x1e1f22 +const DIM_AMOUNT = 0.72 +const DIM_DESATURATION = 0.6 +const HIGHLIGHT_EDGE = 0xffffff +// A solid outline turns biomes that are scattered pixel by pixel into white noise, so the edge only tints. +const HIGHLIGHT_EDGE_STRENGTH = 0.55 +const REGION_BORDER = 0x101114 +const REGION_BORDER_STRENGTH = 0.6 +const NOISE_LOW = 0x050505 +const NOISE_HIGH = 0xffffff +// Picks drawn by their noise keep some colour where the noise is low, so they still read as the pick. +const DARKEST_PICK_SHADE = 0.3 + +/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */ +export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray { + const { size } = tile + const pixels = new Uint8ClampedArray(size * size * 4) + const colors = tile.labels.map((label) => label.color) + const blocks = style.byBlock ? tile.blocks : null + const heights = blocks === null || tile.heights === null ? tile.heights : heightsSeenFromAbove(tile.heights, blocks) + const pickNoise = style.pickDisplay === 'picks' || blocks !== null ? null : tile.pickNoise + // The bare noise is read by its brightness, which relief shading would mix up. + const shading = style.shading && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise') + const highlighted = highlightCells(tile, style) + for (let pixelZ = 0; pixelZ < size; pixelZ++) { + for (let pixelX = 0; pixelX < size; pixelX++) { + const cell = gridIndex(tile, pixelX, pixelZ) + let color = blocks === null ? labelColor(colors, tile.subjects[cell]) : blockColor(blocks, cell, heights, style.seaLevel) + if (pickNoise !== null) { + color = byNoise(color, pickNoise[cell], style.pickDisplay) + } + if (shading) { + color = shade(tile, heights, cell, color, style.seaLevel) + } + if (highlighted !== null) { + color = highlight(tile, highlighted, cell, color) + } + if (style.regionBorders && isRegionEdge(tile, cell)) { + color = blend(color, REGION_BORDER, REGION_BORDER_STRENGTH) + } + const at = (pixelZ * size + pixelX) * 4 + pixels[at] = (color >> 16) & 0xff + pixels[at + 1] = (color >> 8) & 0xff + pixels[at + 2] = color & 0xff + pixels[at + 3] = 0xff + } + } + return pixels +} + +function labelColor(colors: number[], index: number): number { + return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index] +} + +// Seen from above, the highest block raised over the ground hides it, and what stands on the ground hides the ground; +// what lies under the sea shows through its water. +function blockColor(blocks: TileBlocks, cell: number, heights: Float32Array | null, seaLevel: number): number { + const top = blockSeenFromAbove(blocks, cell) + const color = top === NO_BLOCK ? UNKNOWN_SUBJECT : blocks.colors[top] + return heights !== null && heights[cell] < seaLevel ? blend(color, WATER_SURFACE_COLOR, WATER_OVER_GROUND) : color +} + +function blockSeenFromAbove(blocks: TileBlocks, cell: number): number { + const highestRaised = blocks.raisedStart[cell] + if (highestRaised < blocks.raisedStart[cell + 1]) { + return blocks.raised[highestRaised] + } + return blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell] +} + +// The ground's heights with each column's highest raised block in place of its ground, so trees stand out in relief. +function heightsSeenFromAbove(groundHeights: Float32Array, blocks: TileBlocks): Float32Array { + const heights = Float32Array.from(groundHeights) + for (let cell = 0; cell < heights.length; cell++) { + const highestRaised = blocks.raisedStart[cell] + if (highestRaised < blocks.raisedStart[cell + 1]) { + heights[cell] = blocks.raisedY[highestRaised] + } + } + return heights +} + +// Where nothing picked the spot, as on an image map, it keeps its colour. +function byNoise(color: number, noise: number, display: PickDisplay): number { + if (Number.isNaN(noise)) { + return color + } + const value = Math.min(1, Math.max(0, noise)) + return display === 'noise' ? blend(NOISE_LOW, NOISE_HIGH, value) : scale(color, DARKEST_PICK_SHADE + (1 - DARKEST_PICK_SHADE) * value) +} + +// Lit from the north west like a relief map, so slopes read as hills and valleys at a glance. +function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number { + const row = tile.size + 2 + const slopeX = (heights[cell + 1] - heights[cell - 1]) / (2 * tile.blocksPerPixel) + const slopeZ = (heights[cell + row] - heights[cell - row]) / (2 * tile.blocksPerPixel) + const normalX = -slopeX * SHADING_EXAGGERATION + const normalZ = -slopeZ * SHADING_EXAGGERATION + const normalLength = Math.sqrt(normalX * normalX + 1 + normalZ * normalZ) + const light = (normalX * LIGHT_X + LIGHT_Y + normalZ * LIGHT_Z) / (normalLength * LIGHT_LENGTH) + let factor = Math.min(BRIGHTEST_SHADE, Math.max(DARKEST_SHADE, AMBIENT_LIGHT + DIRECT_LIGHT * light)) + if (heights[cell] <= seaLevel) { + factor = 1 - (1 - factor) * UNDERWATER_RELIEF + } + return scale(color, factor) +} + +/** Which cells the highlight covers, as one flag per grid cell; null when nothing is highlighted. */ +function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null { + const target = style.highlight + if (target === null) { + return null + } + const cells = new Uint8Array(tile.subjects.length) + // Every view knows its regions, so a region can be highlighted in a biome view too. + const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null + const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key) + if (grid !== null && index >= 0) { + grid.forEach((label, cell) => { + cells[cell] = label === index ? 1 : 0 + }) + } + return cells +} + +function highlight(tile: MapTile, highlighted: Uint8Array, cell: number, color: number): number { + if (highlighted[cell] === 0) { + return dim(color) + } + const row = tile.size + 2 + const edge = highlighted[cell + 1] === 0 || highlighted[cell - 1] === 0 || highlighted[cell + row] === 0 || highlighted[cell - row] === 0 + return edge ? blend(color, HIGHLIGHT_EDGE, HIGHLIGHT_EDGE_STRENGTH) : color +} + +function isRegionEdge(tile: MapTile, cell: number): boolean { + const region = tile.regions[cell] + return tile.regions[cell + 1] !== region || tile.regions[cell + tile.size + 2] !== region +} + +function dim(color: number): number { + const gray = Math.floor((((color >> 16) & 0xff) + ((color >> 8) & 0xff) + (color & 0xff)) / 3) + const desaturated = blend(color, (gray << 16) | (gray << 8) | gray, DIM_DESATURATION) + return blend(desaturated, DIM_TARGET, DIM_AMOUNT) +} + +function scale(color: number, factor: number): number { + const red = Math.min(255, Math.floor(((color >> 16) & 0xff) * factor)) + const green = Math.min(255, Math.floor(((color >> 8) & 0xff) * factor)) + const blue = Math.min(255, Math.floor((color & 0xff) * factor)) + return (red << 16) | (green << 8) | blue +} diff --git a/studio/src/renderer/src/map/viewport.ts b/studio/src/renderer/src/map/viewport.ts new file mode 100644 index 000000000..c243ff9ac --- /dev/null +++ b/studio/src/renderer/src/map/viewport.ts @@ -0,0 +1,97 @@ +/** Where the map looks and how far it is zoomed; screen sizes are CSS pixels. */ +export interface Viewport { + centerX: number + centerZ: number + blocksPerPixel: number + width: number + height: number +} + +export interface TileAddress { + tileX: number + tileZ: number + blocksPerPixel: number +} + +export const MINIMUM_VIEW_BLOCKS_PER_PIXEL = 1 / 8 +export const MAXIMUM_BLOCKS_PER_PIXEL = 4096 +export const DEFAULT_BLOCKS_PER_PIXEL = 4 +// Iris has nothing finer than a block, so closer views magnify the block-sized tiles. +const MINIMUM_RENDER_BLOCKS_PER_PIXEL = 1 + +export function clampBlocksPerPixel(blocksPerPixel: number): number { + return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, blocksPerPixel)) +} + +export function screenToWorldX(view: Viewport, screenX: number): number { + return view.centerX + (screenX - view.width / 2) * view.blocksPerPixel +} + +export function screenToWorldZ(view: Viewport, screenZ: number): number { + return view.centerZ + (screenZ - view.height / 2) * view.blocksPerPixel +} + +export function worldToScreenX(view: Viewport, worldX: number): number { + return (worldX - view.centerX) / view.blocksPerPixel + view.width / 2 +} + +export function worldToScreenZ(view: Viewport, worldZ: number): number { + return (worldZ - view.centerZ) / view.blocksPerPixel + view.height / 2 +} + +/** + * The scale tiles are drawn at for a view: the nearest power of two to one tile pixel per device pixel, so tiles stay + * sharp on dense screens and every zoom between two levels reuses the same tiles. + */ +export function renderBlocksPerPixel( + viewBlocksPerPixel: number, + devicePixelRatio: number, + finestBlocksPerPixel = MINIMUM_RENDER_BLOCKS_PER_PIXEL +): number { + const level = 2 ** Math.round(Math.log2(viewBlocksPerPixel / devicePixelRatio)) + return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(finestBlocksPerPixel, level)) +} + +/** The tiles covering the view, nearest the centre first so the middle of the screen fills in first. */ +export function visibleTiles(view: Viewport, renderScale: number, tileSize: number): TileAddress[] { + const span = tileSize * renderScale + const firstX = Math.floor(screenToWorldX(view, 0) / span) + const lastX = Math.floor(screenToWorldX(view, view.width) / span) + const firstZ = Math.floor(screenToWorldZ(view, 0) / span) + const lastZ = Math.floor(screenToWorldZ(view, view.height) / span) + const middleX = view.centerX / span - 0.5 + const middleZ = view.centerZ / span - 0.5 + const tiles: TileAddress[] = [] + for (let tileZ = firstZ; tileZ <= lastZ; tileZ++) { + for (let tileX = firstX; tileX <= lastX; tileX++) { + tiles.push({ tileX, tileZ, blocksPerPixel: renderScale }) + } + } + const distance = (tile: TileAddress): number => (tile.tileX - middleX) ** 2 + (tile.tileZ - middleZ) ** 2 + return tiles.sort((first, second) => distance(first) - distance(second)) +} + +/** + * One tile a level out for each group of blank tiles, in their order: a quarter of the pixels, so the screen fills + * about four times sooner and sharpens as the tiles themselves arrive. + */ +export function previewsFor(blankTiles: TileAddress[]): TileAddress[] { + const previews = new Map() + for (const tile of blankTiles) { + const preview = coarserTile(tile, 1) + if (preview.blocksPerPixel <= MAXIMUM_BLOCKS_PER_PIXEL) { + previews.set(`${preview.tileX}/${preview.tileZ}/${preview.blocksPerPixel}`, preview) + } + } + return [...previews.values()] +} + +/** The coarser tile that covers {@code tile}, {@code levels} zoom levels out. */ +export function coarserTile(tile: TileAddress, levels: number): TileAddress { + const factor = 2 ** levels + return { + tileX: Math.floor(tile.tileX / factor), + tileZ: Math.floor(tile.tileZ / factor), + blocksPerPixel: tile.blocksPerPixel * factor + } +} diff --git a/studio/src/renderer/src/noise/noise.test.ts b/studio/src/renderer/src/noise/noise.test.ts new file mode 100644 index 000000000..f86197394 --- /dev/null +++ b/studio/src/renderer/src/noise/noise.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import type { NoiseSource } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import { INVALID_NOISE_COLOR, noiseScale } from './noiseScale' +import { NoiseTerrain } from './noiseTerrain' + +const UNIT_NOISE: NoiseSource = { id: 'style:SIMPLEX', name: 'Simplex', category: 'Simplex', usesSeed: true, blockRange: null } +const BLOCK_NOISE: NoiseSource = { id: 'world:overlay', name: 'Overlay noise', category: 'Pack generators', usesSeed: false, blockRange: { lowest: -20, highest: 40 } } + +describe('noise scale', () => { + it('spans the palette for noise of 0 to 1 and takes its end colours past it', () => { + const terrain = noiseScale('terrain', UNIT_NOISE) + expect([terrain.minimum, terrain.maximum]).toEqual([0, 1]) + expect(terrain.colorOf(0)).toBe(0x071a2f) + expect(terrain.colorOf(1)).toBe(0xf4f1de) + expect(terrain.colorOf(7)).toBe(0xf4f1de) + expect(noiseScale('signed', UNIT_NOISE).minimum).toBe(-1) + }) + + it('spans the block range for noise in blocks, coloured as heights above the fluid', () => { + const height = noiseScale('height', BLOCK_NOISE) + expect([height.minimum, height.maximum]).toEqual([-20, 40]) + expect(height.colorOf(-20)).toBe(heightColor(-20, 0)) + expect(height.colorOf(40)).toBe(heightColor(40, 0)) + }) + + it('marks a value the noise could not give', () => { + expect(noiseScale('grayscale', UNIT_NOISE).colorOf(Number.NaN)).toBe(INVALID_NOISE_COLOR) + }) +}) + +describe('noise terrain', () => { + const tile = (values: number[]) => ({ size: 2, values: Float32Array.from(values) }) + const place = { level: 1, tileX: 1, tileZ: -2 } + + it('raises noise of 0 to 1 to the relief, without water', () => { + const terrain = new NoiseTerrain(tile([0, 0.5, 1, Number.NaN]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64) + expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null]) + expect(terrain.waterAt(0, 0)).toBeNull() + }) + + it('places its columns where the tile lies, as wide as its level', () => { + const terrain = new NoiseTerrain(tile([0, 0, 0, 0]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64) + expect([terrain.originX, terrain.originZ, terrain.blocksPerColumn]).toEqual([256, -512, 2]) + }) + + it('stands noise in blocks at its own height, under water below the fluid', () => { + const terrain = new NoiseTerrain(tile([-5, 12, 0, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64) + expect(terrain.groundAt(0, 0)).toBe(-5) + expect(terrain.waterAt(0, 0)).toBe(0) + expect(terrain.waterAt(1, 0)).toBeNull() + }) + + it('fills each column up to the block its noise reaches into', () => { + const terrain = new NoiseTerrain(tile([-0.5, 12.9, 0.4, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64) + expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1)]).toEqual([-1, 12, 0]) + expect(terrain.waterAt(0, 0)).toBe(0) + expect(terrain.waterAt(0, 1)).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/noise/noiseScale.ts b/studio/src/renderer/src/noise/noiseScale.ts new file mode 100644 index 000000000..4c5026bef --- /dev/null +++ b/studio/src/renderer/src/noise/noiseScale.ts @@ -0,0 +1,81 @@ +import type { NoiseSource } from '../bridge/types' +import { DEEPEST_BELOW_SEA_BLOCKS, heightColor, HIGHEST_ABOVE_SEA_BLOCKS } from '../map/heightColors' + +export type NoisePaletteId = 'terrain' | 'signed' | 'grayscale' | 'height' | 'green' + +interface NoisePalette { + id: NoisePaletteId + label: string + minimum: number + maximum: number + /** Colours from the minimum to the maximum, evenly spaced; null for the map's height colours. */ + stops: number[] | null +} + +/** v3e's noise palettes, each with the values it spans when the noise is not measured in blocks. */ +export const NOISE_PALETTES: readonly NoisePalette[] = [ + { id: 'terrain', label: 'Terrain', minimum: 0, maximum: 1, stops: [0x071a2f, 0x155e75, 0x2a9d8f, 0xe9c46a, 0xf4f1de] }, + { id: 'signed', label: 'Signed', minimum: -1, maximum: 1, stops: [0x173b66, 0x4f86c6, 0xe7edf3, 0xe89555, 0x9d3b35] }, + { id: 'grayscale', label: 'Grayscale', minimum: 0, maximum: 1, stops: [0x050505, 0xffffff] }, + { id: 'height', label: 'Height', minimum: 0, maximum: 1, stops: null }, + { id: 'green', label: 'Green', minimum: 0, maximum: 1, stops: [0x2a3330, 0x5fd3a8] } +] + +/** The colour of a value the noise couldn't give, so it stands out from every palette. */ +export const INVALID_NOISE_COLOR = 0xff2daa +const LOOKUP_SIZE = 256 + +/** How values become colours: the span the palette covers, and the colour of a value. */ +export interface NoiseScale { + minimum: number + maximum: number + /** Over and under the span take the end colours. */ + colorOf(value: number): number + /** The colour a fraction of the way along the span, for the legend. */ + colorAlong(fraction: number): number +} + +/** + * The scale for a palette and a source: noise of 0 to 1 spans the palette's own range; noise in blocks spans its block + * range, and the height palette then colours it as the map colours heights above the fluid. + */ +export function noiseScale(paletteId: NoisePaletteId, source: NoiseSource | null): NoiseScale { + const palette = NOISE_PALETTES.find((candidate) => candidate.id === paletteId)! + const blocks = source?.blockRange ?? null + const minimum = blocks?.lowest ?? palette.minimum + const maximum = blocks?.highest ?? palette.maximum + const colorAlong = paletteColors(palette, blocks === null ? null : [blocks.lowest, blocks.highest]) + const span = maximum - minimum + return { + minimum, + maximum, + colorAlong, + colorOf: (value) => (Number.isFinite(value) ? colorAlong(span <= 0 ? 0.5 : (value - minimum) / span) : INVALID_NOISE_COLOR) + } +} + +function paletteColors(palette: NoisePalette, blockSpan: [number, number] | null): (fraction: number) => number { + if (palette.stops === null) { + const [lowest, highest] = blockSpan ?? [-DEEPEST_BELOW_SEA_BLOCKS, HIGHEST_ABOVE_SEA_BLOCKS] + return (fraction) => heightColor(lowest + (highest - lowest) * clampUnit(fraction), 0) + } + const lookup = lookupOf(palette.stops) + return (fraction) => lookup[Math.round(clampUnit(fraction) * (LOOKUP_SIZE - 1))] +} + +function lookupOf(stops: number[]): number[] { + return Array.from({ length: LOOKUP_SIZE }, (_, index) => { + const position = (index / (LOOKUP_SIZE - 1)) * (stops.length - 1) + const lower = Math.min(stops.length - 2, Math.floor(position)) + return mix(stops[lower], stops[lower + 1], position - lower) + }) +} + +function mix(from: number, to: number, fraction: number): number { + const channel = (shift: number): number => Math.round(((from >>> shift) & 0xff) + (((to >>> shift) & 0xff) - ((from >>> shift) & 0xff)) * fraction) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} + +function clampUnit(fraction: number): number { + return Math.min(1, Math.max(0, fraction)) +} diff --git a/studio/src/renderer/src/noise/noiseTerrain.ts b/studio/src/renderer/src/noise/noiseTerrain.ts new file mode 100644 index 000000000..b4d969c5f --- /dev/null +++ b/studio/src/renderer/src/noise/noiseTerrain.ts @@ -0,0 +1,62 @@ +import type { NoiseSource, NoiseTile } from '../bridge/types' +import type { TerrainSurface } from '../scene/terrainMesh' +import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from '../scene/terrainTiles' +import type { NoiseScale } from './noiseScale' + +// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height. +const FLUID_BLOCKS = 0 + +/** + * One tile of noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the + * fluid; other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water. + */ +export class NoiseTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + readonly originX: number + readonly originZ: number + readonly blocksPerColumn: number + + constructor( + private readonly tile: NoiseTile, + place: TerrainTile, + private readonly source: NoiseSource, + private readonly scale: NoiseScale, + private readonly reliefBlocks: number + ) { + this.columns = tile.size + this.rows = tile.size + this.originX = originXOf(place) + this.originZ = originZOf(place) + this.blocksPerColumn = blocksPerColumn(place.level) + } + + groundAt(column: number, row: number): number | null { + const value = this.valueAt(column, row) + return Number.isFinite(value) ? Math.floor(this.heightOf(value)) : null + } + + waterAt(column: number, row: number): number | null { + if (this.source.blockRange === null) { + return null + } + const ground = this.groundAt(column, row) + return ground !== null && ground < FLUID_BLOCKS ? FLUID_BLOCKS : null + } + + colorAt(column: number, row: number): number { + return this.scale.colorOf(this.valueAt(column, row)) + } + + private heightOf(value: number): number { + if (this.source.blockRange !== null) { + return value + } + const span = this.scale.maximum - this.scale.minimum + return ((value - this.scale.minimum) / span) * this.reliefBlocks + } + + private valueAt(column: number, row: number): number { + return this.tile.values[row * this.tile.size + column] + } +} diff --git a/studio/src/renderer/src/noise/noiseTiles.ts b/studio/src/renderer/src/noise/noiseTiles.ts new file mode 100644 index 000000000..9465a0106 --- /dev/null +++ b/studio/src/renderer/src/noise/noiseTiles.ts @@ -0,0 +1,77 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { NoiseTile } from '../bridge/types' +import { TiledView, type TiledFrame } from '../map/TiledView' +import type { TileSource } from '../map/TileStore' +import type { NoiseScale } from './noiseScale' + +/** Which noise the tiles hold. */ +export interface NoiseLayer { + sourceId: string + /** A 64 bit seed, as text so no digit is lost. */ + seed: string + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +export interface NoiseStyle { + /** Tells styles apart, so a tile is recoloured only when its style changed. */ + key: string + scale: NoiseScale +} + +export type NoiseView = TiledView + +export interface NoiseStatus extends TiledFrame { + /** The noise at the cursor, or null before its tile arrived. */ + value: number | null +} + +export interface NoiseListener { + onStatus(status: NoiseStatus): void + onError(message: string): void +} + +export const NOISE_TILE_PIXELS = 128 +const DEFAULT_NOISE_BLOCKS_PER_PIXEL = 1 +// Noise has detail finer than a block, so it is drawn finer than the world map's one block per pixel. +const FINEST_NOISE_BLOCKS_PER_PIXEL = 1 / 16 + +export function createNoiseView(canvas: HTMLCanvasElement, client: BridgeClient, listener: NoiseListener): NoiseView { + const view: NoiseView = new TiledView(canvas, { + source: noiseTileSource(client), + tileSize: NOISE_TILE_PIXELS, + defaultBlocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL, + finestRenderBlocksPerPixel: FINEST_NOISE_BLOCKS_PER_PIXEL, + onFrame: (frame) => listener.onStatus({ ...frame, value: valueAt(view, frame.cursorX, frame.cursorZ) }), + onError: (message) => listener.onError(message) + }) + return view +} + +function valueAt(view: NoiseView, worldX: number, worldZ: number): number | null { + const spot = view.spotAt(worldX, worldZ) + return spot === null ? null : spot.tile.values[spot.pixelZ * spot.tile.size + spot.pixelX] +} + +export function noiseTileSource(client: BridgeClient): TileSource { + return { + layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`, + fetch: (address, layer, signal) => + client.noiseTile(layer.sourceId, layer.seed, address.tileX, address.tileZ, address.blocksPerPixel, NOISE_TILE_PIXELS, signal), + bytesOf: (tile) => tile.values.byteLength + tile.size * tile.size * 4, + styleKey: (style) => style.key, + pixels: (tile, style) => noisePixels(tile, style.scale) + } +} + +function noisePixels(tile: NoiseTile, scale: NoiseScale): ImageData { + const pixels = new ImageData(tile.size, tile.size) + for (let index = 0; index < tile.values.length; index++) { + const color = scale.colorOf(tile.values[index]) + pixels.data[index * 4] = (color >> 16) & 0xff + pixels.data[index * 4 + 1] = (color >> 8) & 0xff + pixels.data[index * 4 + 2] = color & 0xff + pixels.data[index * 4 + 3] = 0xff + } + return pixels +} diff --git a/studio/src/renderer/src/pattern/patternTiles.ts b/studio/src/renderer/src/pattern/patternTiles.ts new file mode 100644 index 000000000..896a603aa --- /dev/null +++ b/studio/src/renderer/src/pattern/patternTiles.ts @@ -0,0 +1,152 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import { NO_PATTERN_BLOCK, type PatternTile } from '../bridge/types' +import { TiledView, type TiledFrame } from '../map/TiledView' +import type { TileSource } from '../map/TileStore' +import type { TileAddress } from '../map/viewport' +import type { BlockColors } from '../scene/blockColors' + +/** Which entry, at which depth, the tiles lay out. */ +export interface PatternLayer { + viewId: string + key: string + depth: number + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +/** A pattern tile with what it needs to be drawn: each block's colour, and its texture once a block spans pixels. */ +export interface PatternPicture { + pattern: PatternTile + colors: number[] + /** Per block, its top texture; empty while a block is a pixel or smaller. */ + textures: (ImageData | null)[] + /** How many pixels across a column is drawn; 1 when it is a pixel or smaller. */ + pixelsPerColumn: number +} + +/** Patterns have one look; the style only satisfies the tile store. */ +export type PatternStyle = 'blocks' +export type PatternView = TiledView + +/** What is under the cursor: a block, nothing placed there, or not known before its tile arrived. */ +export type PatternSpot = { kind: 'block'; block: string } | { kind: 'none' } | { kind: 'unknown' } + +export interface PatternStatus extends TiledFrame { + spot: PatternSpot +} + +/** The blocks a tile placed, each with the state it is drawn as, and whether it left some columns without a block. */ +export interface PatternBlocks { + drawnAs: Map + someNone: boolean +} + +export interface PatternListener { + onStatus(status: PatternStatus): void + /** What a tile of the layer showed, for the legend. */ + onBlocks(layer: PatternLayer, blocks: PatternBlocks): void + onError(message: string): void +} + +export const PATTERN_TILE_PIXELS = 128 +const DEFAULT_PATTERN_BLOCKS_PER_PIXEL = 1 +// A block texture is 16 pixels across; drawing a block that wide shows it whole. +const FINEST_PATTERN_BLOCKS_PER_PIXEL = 1 / 16 +// The bridge lays out a column at most every 64 blocks; views stop a level short so their previews stay within it. +const COARSEST_PATTERN_BLOCKS_PER_PIXEL = 32 +const NO_COLOR = 0x000000 +const OPAQUE = 0xff +const OPAQUE_ENOUGH_ALPHA = 128 + +export function createPatternView(canvas: HTMLCanvasElement, client: BridgeClient, blockColors: BlockColors, listener: PatternListener): PatternView { + const view: PatternView = new TiledView(canvas, { + source: patternTileSource(client, blockColors, listener), + tileSize: PATTERN_TILE_PIXELS, + defaultBlocksPerPixel: DEFAULT_PATTERN_BLOCKS_PER_PIXEL, + finestRenderBlocksPerPixel: FINEST_PATTERN_BLOCKS_PER_PIXEL, + coarsestBlocksPerPixel: COARSEST_PATTERN_BLOCKS_PER_PIXEL, + onFrame: (frame) => listener.onStatus({ ...frame, spot: spotAt(view, frame.cursorX, frame.cursorZ) }), + onError: (message) => listener.onError(message) + }) + return view +} + +function spotAt(view: PatternView, worldX: number, worldZ: number): PatternSpot { + const spot = view.spotAt(worldX, worldZ) + if (spot === null) { + return { kind: 'unknown' } + } + const { pattern, pixelsPerColumn } = spot.tile + const column = Math.floor(spot.pixelX / pixelsPerColumn) + const row = Math.floor(spot.pixelZ / pixelsPerColumn) + const pick = pattern.picks[row * pattern.columns + column] + return pick === NO_PATTERN_BLOCK ? { kind: 'none' } : { kind: 'block', block: pattern.blocks[pick] } +} + +function patternTileSource(client: BridgeClient, blockColors: BlockColors, listener: PatternListener): TileSource { + return { + layerKey: (layer) => `${layer.revision}/${layer.viewId}/${layer.key}/${layer.depth}`, + fetch: async (address, layer, signal) => { + const picture = await fetchPicture(client, blockColors, address, layer, signal) + listener.onBlocks(layer, { + drawnAs: new Map(picture.pattern.blocks.map((block, index) => [block, picture.pattern.drawnAs[index]])), + someNone: picture.pattern.picks.includes(NO_PATTERN_BLOCK) + }) + return picture + }, + bytesOf: (picture) => picture.pattern.picks.byteLength + PATTERN_TILE_PIXELS * PATTERN_TILE_PIXELS * 4, + styleKey: (style) => style, + pixels: (picture) => patternPixels(picture) + } +} + +/** + * A tile a pixel per column where a column is a pixel or more, and otherwise a column per block, each drawn a few + * pixels wide in its texture. + */ +async function fetchPicture(client: BridgeClient, blockColors: BlockColors, address: TileAddress, layer: PatternLayer, signal: AbortSignal): Promise { + const blocksPerColumn = Math.max(1, address.blocksPerPixel) + const pixelsPerColumn = Math.round(blocksPerColumn / address.blocksPerPixel) + const columns = PATTERN_TILE_PIXELS / pixelsPerColumn + const pattern = await client.pattern({ ...layer, tileX: address.tileX, tileZ: address.tileZ, blocksPerColumn, columns }, signal) + const colors = await Promise.all(pattern.drawnAs.map((block) => blockColors.colorOf(block))) + const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.drawnAs.map((block) => blockColors.topTexture(block))) : [] + return { pattern, colors, textures, pixelsPerColumn } +} + +function patternPixels(picture: PatternPicture): ImageData { + const pixels = new ImageData(PATTERN_TILE_PIXELS, PATTERN_TILE_PIXELS) + const { pattern, pixelsPerColumn } = picture + for (let pixelZ = 0; pixelZ < PATTERN_TILE_PIXELS; pixelZ++) { + for (let pixelX = 0; pixelX < PATTERN_TILE_PIXELS; pixelX++) { + const pick = pattern.picks[Math.floor(pixelZ / pixelsPerColumn) * pattern.columns + Math.floor(pixelX / pixelsPerColumn)] + if (pick !== NO_PATTERN_BLOCK) { + writePixel(pixels, (pixelZ * PATTERN_TILE_PIXELS + pixelX) * 4, picture, pick, pixelX % pixelsPerColumn, pixelZ % pixelsPerColumn) + } + } + } + return pixels +} + +/** + * The block's texture at a spot within its column, and its colour where it has no texture or the texture is see + * through, such as between leaves, so a palette reads as solid ground. + */ +function writePixel(pixels: ImageData, offset: number, picture: PatternPicture, pick: number, insideX: number, insideZ: number): void { + const texture = picture.textures[pick] ?? null + if (texture !== null) { + const textureX = Math.floor((insideX * texture.width) / picture.pixelsPerColumn) + const textureZ = Math.floor((insideZ * texture.height) / picture.pixelsPerColumn) + const from = (textureZ * texture.width + textureX) * 4 + if (texture.data[from + 3] >= OPAQUE_ENOUGH_ALPHA) { + pixels.data.set(texture.data.subarray(from, from + 3), offset) + pixels.data[offset + 3] = OPAQUE + return + } + } + const color = picture.colors[pick] ?? NO_COLOR + pixels.data[offset] = (color >> 16) & 0xff + pixels.data[offset + 1] = (color >> 8) & 0xff + pixels.data[offset + 2] = color & 0xff + pixels.data[offset + 3] = OPAQUE +} diff --git a/studio/src/renderer/src/scene/BridgeAssets.ts b/studio/src/renderer/src/scene/BridgeAssets.ts new file mode 100644 index 000000000..e6fc40d6d --- /dev/null +++ b/studio/src/renderer/src/scene/BridgeAssets.ts @@ -0,0 +1,44 @@ +import { BridgeError, STATUS_UNAVAILABLE, type BridgeClient } from '../bridge/BridgeClient' +import type { AssetSource } from './blockModels' +import type { ImageSource } from './textureAtlas' + +const RETRY_MILLIS = 2000 +const LONGEST_WAIT_MILLIS = 10 * 60 * 1000 + +/** + * The Minecraft client's assets through the bridge. The server fetches the client the first time anyone asks, so + * until it has it every request waits, telling {@code onWaiting} why. + */ +export class BridgeAssets implements AssetSource, ImageSource { + constructor( + private readonly client: BridgeClient, + private readonly onWaiting: (reason: string | null) => void + ) {} + + async json(path: string): Promise { + const response = await this.fetch(path) + return response === null ? null : response.json() + } + + async image(path: string): Promise { + const response = await this.fetch(path) + return response === null ? null : createImageBitmap(await response.blob()) + } + + private async fetch(path: string): Promise { + const giveUpAt = Date.now() + LONGEST_WAIT_MILLIS + for (;;) { + try { + const response = await this.client.asset(path) + this.onWaiting(null) + return response + } catch (error) { + if (!(error instanceof BridgeError) || error.status !== STATUS_UNAVAILABLE || Date.now() > giveUpAt) { + throw error + } + this.onWaiting(error.message) + await new Promise((resume) => window.setTimeout(resume, RETRY_MILLIS)) + } + } + } +} diff --git a/studio/src/renderer/src/scene/bakeTiming.test.ts b/studio/src/renderer/src/scene/bakeTiming.test.ts new file mode 100644 index 000000000..7c1e4c283 --- /dev/null +++ b/studio/src/renderer/src/scene/bakeTiming.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest' +import type { BakeRun } from '../bridge/types' +import { BAKE_RUN_COUNT, bakeWeightOf, formatMillis, measureBake, medianRun, meterFill, runMillis, slowestStageIndex } from './bakeTiming' + +const NANOS_PER_MILLI = 1_000_000 + +function runOf(...stageMillis: number[]): BakeRun { + return { variantCount: 4, stages: stageMillis.map((millis, index) => ({ label: `Stage ${index}`, nanos: millis * NANOS_PER_MILLI })) } +} + +describe('bake timing', () => { + it('adds the stages of a run up to its time in milliseconds', () => { + expect(runMillis(runOf(2, 3, 5))).toBe(10) + }) + + it('keeps the run in the middle by time, not the fastest, the slowest or the first', () => { + const slowFirstRun = runOf(900) + const median = runOf(40) + const runs = [slowFirstRun, runOf(10), runOf(300), median, runOf(25)] + expect(medianRun(runs)).toBe(median) + expect(runs[0]).toBe(slowFirstRun) + }) + + it('times five runs one after the other and keeps the median', async () => { + const times = [90, 10, 50, 30, 70] + let asked = 0 + const median = await measureBake(async () => runOf(times[asked++]), () => true) + expect(asked).toBe(BAKE_RUN_COUNT) + expect(median === null ? null : runMillis(median)).toBe(50) + }) + + it('stops asking once another entry is opened', async () => { + let asked = 0 + const median = await measureBake( + async () => runOf(asked++), + () => asked < 2 + ) + expect(median).toBeNull() + expect(asked).toBe(2) + }) + + it('drops the result of runs that finished after the entry was left', async () => { + let wanted = true + const median = await measureBake( + async () => { + wanted = false + return runOf(1) + }, + () => wanted + ) + expect(median).toBeNull() + }) + + it('rates a bake against a server tick of 50 ms', () => { + expect(bakeWeightOf(0.4).label).toBe('Light') + expect(bakeWeightOf(49.9).label).toBe('Light') + expect(bakeWeightOf(50).label).toBe('Moderate') + expect(bakeWeightOf(500).label).toBe('Heavy') + expect(bakeWeightOf(60_000).label).toBe('Heavy') + }) + + it('fills the meter on a logarithmic scale, a third for each weight', () => { + expect(meterFill(0)).toBe(0) + expect(meterFill(50)).toBeCloseTo(1 / 3) + expect(meterFill(500)).toBeCloseTo(2 / 3) + expect(meterFill(5000)).toBeCloseTo(1) + expect(meterFill(1_000_000)).toBeCloseTo(1) + expect(meterFill(Math.sqrt(50))).toBeCloseTo(1 / 6) + }) + + it('formats times with the digits they need', () => { + expect(formatMillis(2.34)).toBe('2.3 ms') + expect(formatMillis(48.6)).toBe('49 ms') + expect(formatMillis(1250)).toBe('1.3 s') + }) + + it('points at the slowest stage, the first when none took time', () => { + expect(slowestStageIndex(runOf(1, 9, 4))).toBe(1) + expect(slowestStageIndex(runOf(0, 0))).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/bakeTiming.ts b/studio/src/renderer/src/scene/bakeTiming.ts new file mode 100644 index 000000000..0c38f7ade --- /dev/null +++ b/studio/src/renderer/src/scene/bakeTiming.ts @@ -0,0 +1,87 @@ +import type { BakeRun } from '../bridge/types' + +const NANOS_PER_MILLI = 1_000_000 +const SECOND_IN_MILLIS = 1000 +const FINE_MILLIS_DIGITS_BELOW = 10 + +/** How many times a bake is timed; the run in the middle is the one shown. */ +export const BAKE_RUN_COUNT = 5 + +/** How long a bake stalls the chunk that first places it, against a server tick of 50 ms (v3 BakeWeight). */ +export interface BakeWeight { + label: string + /** Where the weight starts, in milliseconds. */ + fromMillis: number + /** Where the meter is full within the weight, in milliseconds. */ + meterFullAtMillis: number + /** The text colour class of the weight. */ + textClass: string + /** The fill colour class of the weight. */ + fillClass: string +} + +export const BAKE_WEIGHTS: readonly BakeWeight[] = [ + { label: 'Light', fromMillis: 1, meterFullAtMillis: 50, textClass: 'text-success', fillClass: 'bg-success' }, + { label: 'Moderate', fromMillis: 50, meterFullAtMillis: 500, textClass: 'text-warning', fillClass: 'bg-warning' }, + { label: 'Heavy', fromMillis: 500, meterFullAtMillis: 5000, textClass: 'text-destructive', fillClass: 'bg-destructive' } +] + +export function bakeWeightIndex(millis: number): number { + const index = BAKE_WEIGHTS.findIndex((weight) => millis < weight.meterFullAtMillis) + return index < 0 ? BAKE_WEIGHTS.length - 1 : index +} + +export function bakeWeightOf(millis: number): BakeWeight { + return BAKE_WEIGHTS[bakeWeightIndex(millis)] +} + +/** How full the meter is, from 0 to 1: each weight takes an equal share, filled on a logarithmic scale since bakes span thousands of times. */ +export function meterFill(millis: number): number { + const index = bakeWeightIndex(millis) + const weight = BAKE_WEIGHTS[index] + const clamped = Math.min(Math.max(millis, weight.fromMillis), weight.meterFullAtMillis) + const withinWeight = Math.log(clamped / weight.fromMillis) / Math.log(weight.meterFullAtMillis / weight.fromMillis) + return (index + withinWeight) / BAKE_WEIGHTS.length +} + +export function runMillis(run: BakeRun): number { + return run.stages.reduce((total, stage) => total + stage.nanos, 0) / NANOS_PER_MILLI +} + +/** The run in the middle by total time. The first run is slow while the JIT compiles the baker, and the garbage collector or chunk generation can slow any other, so neither ends up in the middle. */ +export function medianRun(runs: readonly BakeRun[]): BakeRun { + const byTime = [...runs].sort((first, second) => runMillis(first) - runMillis(second)) + return byTime[Math.floor(byTime.length / 2)] +} + +/** + * Times a bake {@link BAKE_RUN_COUNT} times, one run after the other, and keeps the median; null once {@code stillWanted} + * says another entry was opened. + */ +export async function measureBake(bakeOnce: () => Promise, stillWanted: () => boolean): Promise { + const runs: BakeRun[] = [] + while (runs.length < BAKE_RUN_COUNT) { + if (!stillWanted()) { + return null + } + runs.push(await bakeOnce()) + } + return stillWanted() ? medianRun(runs) : null +} + +export function formatMillis(millis: number): string { + if (millis >= SECOND_IN_MILLIS) { + return `${(millis / SECOND_IN_MILLIS).toFixed(1)} s` + } + return `${millis.toFixed(millis < FINE_MILLIS_DIGITS_BELOW ? 1 : 0)} ms` +} + +/** Where light turns to heavy, as the tooltip tells it. */ +export function weightScale(): string { + return `Light under ${formatMillis(BAKE_WEIGHTS[1].fromMillis)}, heavy from ${formatMillis(BAKE_WEIGHTS[2].fromMillis)}` +} + +/** The index of the stage that took longest; the first when none took any time. */ +export function slowestStageIndex(run: BakeRun): number { + return run.stages.reduce((slowest, stage, index) => (stage.nanos > run.stages[slowest].nanos ? index : slowest), 0) +} diff --git a/studio/src/renderer/src/scene/blockArt.ts b/studio/src/renderer/src/scene/blockArt.ts new file mode 100644 index 000000000..f9b2948dd --- /dev/null +++ b/studio/src/renderer/src/scene/blockArt.ts @@ -0,0 +1,57 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import { NO_BLOCK, type TileBlocks } from '../bridge/types' +import { BlockColors } from './blockColors' +import { BlockLooks } from './blockLooks' +import { BlockModels } from './blockModels' +import { BridgeAssets } from './BridgeAssets' +import { TerrainAtlas } from './terrainAtlas' + +/** What a tile's blocks are drawn with: each block's colour from above, and its textures where columns show them. */ +export interface BlockArt { + /** The atlas the looks' pictures lie in; null for art that only colours. */ + readonly atlas: TerrainAtlas | null + /** Fills in the colours of the tile's blocks, and their looks when {@code textured}. */ + paint(blocks: TileBlocks, textured: boolean): Promise + dispose(): void +} + +// Only these have their whole model's pictures placed, so the ground's blocks take no room in the atlas for faces a column never shows. +function namesStandingOnGround(blocks: TileBlocks): string[] { + const standing = new Set(blocks.cover) + standing.delete(NO_BLOCK) + return [...standing].map((index) => blocks.names[index]) +} + +// A tile drawn block by block places the whole models of the blocks it shows. +function namesSeenOneByOne(blocks: TileBlocks): string[] { + if (blocks.voxels === null) { + return [] + } + return [...new Set(blocks.voxels.blocks)].map((index) => blocks.names[index]) +} + +/** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */ +export function blockArt(client: BridgeClient, textured: boolean): BlockArt { + const images = new BridgeAssets(client, () => {}) + const models = new BlockModels(images) + const colors = new BlockColors(models, images) + const atlas = textured ? new TerrainAtlas(images) : null + const looks = atlas === null ? null : new BlockLooks(models, atlas) + return { + atlas, + paint: async (blocks, withLooks) => { + const shownLooks = withLooks ? looks : null + const [colorOf, lookOf, coverOf, modelOf] = await Promise.all([ + colors.colorsOf(blocks.names), + shownLooks?.looksOf(blocks.names) ?? null, + shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null, + shownLooks?.coversOf(namesSeenOneByOne(blocks)) ?? null + ]) + blocks.colors = blocks.names.map((name) => colorOf.get(name)!) + blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null) + blocks.covers = coverOf === null ? [] : blocks.names.map((name) => coverOf.get(name) ?? null) + blocks.models = modelOf === null ? [] : blocks.names.map((name) => modelOf.get(name) ?? null) + }, + dispose: () => atlas?.dispose() + } +} diff --git a/studio/src/renderer/src/scene/blockColors.ts b/studio/src/renderer/src/scene/blockColors.ts new file mode 100644 index 000000000..e8c3fbae1 --- /dev/null +++ b/studio/src/renderer/src/scene/blockColors.ts @@ -0,0 +1,100 @@ +import { blockTint } from './blockTints' +import { parseState, type BlockModels } from './blockModels' +import { texturePath, type ImageSource } from './textureAtlas' + +const UNKNOWN_BLOCK_COLOR = 0x7f7f7f +const OPAQUE_ENOUGH_ALPHA = 128 +const NO_TINT = 0xffffff + +/** Each block seen from above: its top face's texture tinted as the client tints it, and that texture's average colour, read once. */ +export class BlockColors { + private readonly textures = new Map>() + private readonly colors = new Map>() + + constructor( + private readonly models: BlockModels, + private readonly images: ImageSource + ) {} + + /** The first frame of the block's top face texture, tinted; null when the block has no model or texture. */ + topTexture(block: string): Promise { + let texture = this.textures.get(block) + if (texture === undefined) { + texture = this.readTopTexture(block).catch(() => null) + this.textures.set(block, texture) + } + return texture + } + + colorOf(block: string): Promise { + let color = this.colors.get(block) + if (color === undefined) { + color = this.topTexture(block).then((texture) => (texture === null ? UNKNOWN_BLOCK_COLOR : averageColor(texture))) + this.colors.set(block, color) + } + return color + } + + /** Every block's colour, by name. */ + async colorsOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const colors = await Promise.all(names.map((name) => this.colorOf(name))) + return new Map(names.map((name, index) => [name, colors[index]])) + } + + private async readTopTexture(block: string): Promise { + const model = await this.models.model(block) + const top = model?.quads.filter((quad) => quad.facing === 'up').at(-1) + const texture = top?.texture ?? model?.particle + if (texture === undefined || texture === null) { + return null + } + const bitmap = await this.images.image(texturePath(texture)) + if (bitmap === null) { + return null + } + const state = parseState(block) + return tinted(firstFrame(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1)) + } +} + +// An animated texture stacks its frames downwards. +function firstFrame(bitmap: ImageBitmap): ImageData { + const side = bitmap.width + const canvas = new OffscreenCanvas(side, side) + const drawing = canvas.getContext('2d', { willReadFrequently: true })! + drawing.drawImage(bitmap, 0, 0, side, side, 0, 0, side, side) + return drawing.getImageData(0, 0, side, side) +} + +function tinted(texture: ImageData, tint: number): ImageData { + if (tint === NO_TINT) { + return texture + } + const pixels = texture.data + const [red, green, blue] = [(tint >> 16) & 0xff, (tint >> 8) & 0xff, tint & 0xff] + for (let offset = 0; offset < pixels.length; offset += 4) { + pixels[offset] = Math.round((pixels[offset] * red) / 255) + pixels[offset + 1] = Math.round((pixels[offset + 1] * green) / 255) + pixels[offset + 2] = Math.round((pixels[offset + 2] * blue) / 255) + } + return texture +} + +/** The mean colour of the pixels that are opaque enough, as 0xRRGGBB. */ +export function averageColor(texture: ImageData): number { + const pixels = texture.data + let [red, green, blue, counted] = [0, 0, 0, 0] + for (let offset = 0; offset < pixels.length; offset += 4) { + if (pixels[offset + 3] >= OPAQUE_ENOUGH_ALPHA) { + red += pixels[offset] + green += pixels[offset + 1] + blue += pixels[offset + 2] + counted++ + } + } + if (counted === 0) { + return UNKNOWN_BLOCK_COLOR + } + return (Math.round(red / counted) << 16) | (Math.round(green / counted) << 8) | Math.round(blue / counted) +} diff --git a/studio/src/renderer/src/scene/blockLooks.test.ts b/studio/src/renderer/src/scene/blockLooks.test.ts new file mode 100644 index 000000000..19869b86b --- /dev/null +++ b/studio/src/renderer/src/scene/blockLooks.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from 'vitest' +import { BlockLooks, faceTexturesOf } from './blockLooks' +import { BlockModels, type AssetSource } from './blockModels' +import { cellAt, type PictureSource, type UvCell } from './terrainAtlas' + +const SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] +const GRASS_TINT = 0x91bd59 + +// Grass as the client has it: a dirt side with a tinted overlay element over it, a tinted top, and the dirt's bottom. +const FILES: Record = { + 'minecraft/blockstates/dirt.json': { variants: { '': { model: 'minecraft:block/dirt' } } }, + 'minecraft/models/block/dirt.json': { + textures: { particle: 'minecraft:block/dirt' }, + elements: [{ from: [0, 0, 0], to: [16, 16, 16], faces: Object.fromEntries(SIDES.map((side) => [side, { texture: 'minecraft:block/dirt', cullface: side }])) }] + }, + 'minecraft/blockstates/grass_block.json': { variants: { '': { model: 'minecraft:block/grass_block' } } }, + 'minecraft/models/block/grass_block.json': { + textures: { particle: 'minecraft:block/dirt' }, + elements: [ + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { + down: { texture: 'minecraft:block/dirt', cullface: 'down' }, + up: { texture: 'minecraft:block/grass_block_top', cullface: 'up', tintindex: 0 }, + north: { texture: 'minecraft:block/grass_block_side', cullface: 'north' }, + south: { texture: 'minecraft:block/grass_block_side', cullface: 'south' }, + west: { texture: 'minecraft:block/grass_block_side', cullface: 'west' }, + east: { texture: 'minecraft:block/grass_block_side', cullface: 'east' } + } + }, + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { north: { texture: 'minecraft:block/grass_block_side_overlay', tintindex: 0 } } + } + ] + }, + 'minecraft/blockstates/log.json': { variants: { '': { model: 'minecraft:block/log' } } }, + 'minecraft/models/block/log.json': { + textures: { particle: 'minecraft:block/log' }, + elements: [ + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { + down: { texture: 'minecraft:block/log_top', cullface: 'down' }, + up: { texture: 'minecraft:block/log_top', cullface: 'up' }, + north: { texture: 'minecraft:block/log', cullface: 'north' } + } + } + ] + }, + 'minecraft/blockstates/chest.json': { variants: { '': { model: 'minecraft:block/chest' } } }, + 'minecraft/models/block/chest.json': { textures: { particle: 'minecraft:block/oak_planks' } }, + 'minecraft/blockstates/glass.json': { variants: { '': { model: 'minecraft:block/glass' } } }, + 'minecraft/models/block/glass.json': {} +} + +const assets: AssetSource = { json: async (path) => FILES[path] ?? null } + +// Every texture is placed in the next cell, with a grey as light as its number, except the ones named missing. +function pictures(missing: string[] = []): PictureSource { + const cells = new Map() + return { + cellOf: async (textureId) => { + if (missing.includes(textureId)) { + return null + } + if (!cells.has(textureId)) { + cells.set(textureId, cellAt(cells.size + 1, (cells.size + 1) * 0x101010)) + } + return cells.get(textureId)! + } + } +} + +async function modelOf(block: string): ReturnType { + return new BlockModels(assets).model(block) +} + +describe('block faces', () => { + it('takes the top, the untinted side layer and the dirt under a block that caps dirt', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:grass_block'))!, 'minecraft:block/dirt') + + expect(faces).toEqual({ + top: { texture: 'minecraft:block/grass_block_top', tintIndex: 0 }, + side: { texture: 'minecraft:block/grass_block_side', tintIndex: -1 }, + below: { texture: 'minecraft:block/dirt', tintIndex: -1 } + }) + }) + + it('shows the side below the top block when the block does not cap dirt', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:log'))!, 'minecraft:block/dirt') + + expect(faces!.below).toEqual(faces!.side) + expect(faces!.side.texture).toBe('minecraft:block/log') + }) + + it('stands the particle texture in for a block the client draws without a model', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:chest'))!, null) + + expect(faces).toEqual({ + top: { texture: 'minecraft:block/oak_planks', tintIndex: -1 }, + side: { texture: 'minecraft:block/oak_planks', tintIndex: -1 }, + below: { texture: 'minecraft:block/oak_planks', tintIndex: -1 } + }) + }) + + it('has none for a model without any texture', async () => { + expect(faceTexturesOf((await modelOf('minecraft:glass'))!, null)).toBeNull() + }) +}) + +describe('block looks', () => { + it('gives each face the cell of its texture and tints the faces that take a tint', async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures()) + + const grass = (await looks.lookOf('minecraft:grass_block[snowy=false]'))! + + const dirt = (await looks.lookOf('minecraft:dirt'))! + + expect(grass.top.tint).toBe(GRASS_TINT) + expect(grass.side.tint).toBe(0xffffff) + expect(grass.below.cell).toBe(dirt.top.cell) + expect(grass.side.cell).not.toBe(grass.top.cell) + }) + + it("colours a face with its picture's average under the tint", async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures()) + + const grass = (await looks.lookOf('minecraft:grass_block'))! + + expect(grass.top.color).toBe(multiplied(grass.top.cell.average, GRASS_TINT)) + expect(grass.side.color).toBe(grass.side.cell.average) + }) + + it('has no look for a block without a model, or one whose picture cannot be placed', async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures(['minecraft:block/log_top'])) + + const found = await looks.looksOf(['minecraft:unknown_block', 'minecraft:log', 'minecraft:dirt', 'minecraft:dirt']) + + expect([...found.keys()]).toEqual(['minecraft:unknown_block', 'minecraft:log', 'minecraft:dirt']) + expect(found.get('minecraft:unknown_block')).toBeNull() + expect(found.get('minecraft:log')).toBeNull() + expect(found.get('minecraft:dirt')).not.toBeNull() + }) +}) + +function multiplied(color: number, tint: number): number { + const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} diff --git a/studio/src/renderer/src/scene/blockLooks.ts b/studio/src/renderer/src/scene/blockLooks.ts new file mode 100644 index 000000000..496a00b3f --- /dev/null +++ b/studio/src/renderer/src/scene/blockLooks.ts @@ -0,0 +1,151 @@ +import { parseState, type BlockModel, type Direction, type ParsedState } from './blockModels' +import { blockTint } from './blockTints' +import { coverLookOf, type CoverLook } from './coverLooks' +import type { PictureSource, UvCell } from './terrainAtlas' + +const NO_TINT_INDEX = -1 +const DIRT = 'minecraft:dirt' +const WHITE = 0xffffff + +/** One face of a block as the terrain draws it: its picture, the colour that tints the picture, and the picture's tinted average. */ +export interface FaceLook { + cell: UvCell + tint: number + color: number +} + +/** A block seen on a column: from above, on the side of its top block, and on the sides of the blocks under it. */ +export interface BlockLook { + top: FaceLook + side: FaceLook + below: FaceLook +} + +/** The texture a face takes from a block's model, and which of the block's tints colours it. */ +export interface FaceTexture { + texture: string + tintIndex: number +} + +export interface BlockFaceTextures { + top: FaceTexture + side: FaceTexture + below: FaceTexture +} + +/** Where block models come from. */ +export interface ModelSource { + model(stateKey: string): Promise +} + +/** + * The textures a column of the block shows. A side can be drawn in layers, like grass over dirt, and the untinted layer is + * the one that reads on its own. A column is one block drawn as tall as its side shows, so a grassy edge would repeat all + * the way down a cliff: blocks capping dirt show dirt under their top block instead. Null where the model has no texture. + */ +export function faceTexturesOf(model: BlockModel, dirtBottom: string | null): BlockFaceTextures | null { + const stood = model.particle === null ? null : { texture: model.particle, tintIndex: NO_TINT_INDEX } + const top = lastFacing(model, 'up') ?? stood + if (top === null) { + return null + } + const side = untintedFacing(model, 'north') ?? top + const bottom = lastFacing(model, 'down') + const below = bottom !== null && bottom.texture === dirtBottom ? bottom : side + return { top, side, below } +} + +function lastFacing(model: BlockModel, facing: Direction): FaceTexture | null { + const quad = model.quads.filter((candidate) => candidate.facing === facing).at(-1) + return quad === undefined ? null : { texture: quad.texture, tintIndex: quad.tintIndex } +} + +function untintedFacing(model: BlockModel, facing: Direction): FaceTexture | null { + const quads = model.quads.filter((candidate) => candidate.facing === facing) + const quad = quads.find((candidate) => candidate.tintIndex === NO_TINT_INDEX) ?? quads[0] + return quad === undefined ? null : { texture: quad.texture, tintIndex: quad.tintIndex } +} + +/** The look of each block state the terrain draws, read once. */ +export class BlockLooks { + private readonly looks = new Map>() + private readonly covers = new Map>() + private dirtBottom: Promise | null = null + + constructor( + private readonly models: ModelSource, + private readonly pictures: PictureSource + ) {} + + /** The block's look; null when it has no model or texture, or one of its pictures cannot be placed. */ + lookOf(block: string): Promise { + let look = this.looks.get(block) + if (look === undefined) { + look = this.read(block).catch(() => null) + this.looks.set(block, look) + } + return look + } + + /** What each block looks like standing on the ground, by name; null for one that is not drawn there. */ + async coversOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const looks = await Promise.all(names.map((name) => this.coverOf(name))) + return new Map(names.map((name, index) => [name, looks[index]])) + } + + private coverOf(block: string): Promise { + let cover = this.covers.get(block) + if (cover === undefined) { + cover = this.models + .model(block) + .then((model) => coverLookOf(block, model, this.pictures)) + .catch(() => null) + this.covers.set(block, cover) + } + return cover + } + + /** Every block's look, by name. */ + async looksOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const looks = await Promise.all(names.map((name) => this.lookOf(name))) + return new Map(names.map((name, index) => [name, looks[index]])) + } + + private async read(block: string): Promise { + const model = await this.models.model(block) + if (model === null) { + return null + } + const textures = faceTexturesOf(model, await this.dirtBottomTexture()) + if (textures === null) { + return null + } + const state = parseState(block) + const [top, side, below] = await Promise.all([textures.top, textures.side, textures.below].map((face) => this.faceLook(face, state))) + return top === null || side === null || below === null ? null : { top, side, below } + } + + private async faceLook(face: FaceTexture, state: ParsedState): Promise { + const cell = await this.pictures.cellOf(face.texture) + if (cell === null) { + return null + } + const tint = blockTint(state.name, state.properties, face.tintIndex) + return { cell, tint, color: multiplied(cell.average, tint) } + } + + private dirtBottomTexture(): Promise { + this.dirtBottom ??= this.models.model(DIRT).then((model) => (model === null ? null : lastFacing(model, 'down')?.texture ?? null)) + return this.dirtBottom + } +} + +function multiplied(color: number, tint: number): number { + if (tint === WHITE) { + return color + } + const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} diff --git a/studio/src/renderer/src/scene/blockModels.test.ts b/studio/src/renderer/src/scene/blockModels.test.ts new file mode 100644 index 000000000..7cf4570bd --- /dev/null +++ b/studio/src/renderer/src/scene/blockModels.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { BlockModels, parseState, type AssetSource } from './blockModels' + +const CUBE_ALL = { + textures: { particle: '#all' }, + elements: [ + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: Object.fromEntries(['down', 'up', 'north', 'south', 'west', 'east'].map((side) => [side, { texture: '#all', cullface: side }])) + } + ] +} + +const FILES: Record = { + 'minecraft/blockstates/stone.json': { variants: { '': { model: 'minecraft:block/stone' } } }, + 'minecraft/models/block/stone.json': { parent: 'block/cube_all', textures: { all: 'minecraft:block/stone' } }, + 'minecraft/models/block/cube_all.json': CUBE_ALL, + 'minecraft/blockstates/oak_log.json': { + variants: { 'axis=y': { model: 'block/oak_log' }, 'axis=x': { model: 'block/oak_log', x: 90, y: 90 } } + }, + 'minecraft/models/block/oak_log.json': { parent: 'block/cube_all', textures: { all: 'block/oak_log' } }, + 'minecraft/blockstates/fence.json': { + multipart: [{ apply: { model: 'block/stone' } }, { when: { north: 'true' }, apply: { model: 'block/stone' } }, { when: { OR: [{ east: 'true' }, { west: 'true|x' }] }, apply: { model: 'block/stone' } }] + }, + 'minecraft/blockstates/chest.json': { variants: { '': { model: 'block/chest' } } }, + 'minecraft/models/block/chest.json': { textures: { particle: 'block/oak_planks' } } +} + +const assets: AssetSource = { json: async (path) => FILES[path] ?? null } + +describe('block models', () => { + it('reads a block state key', () => { + expect(parseState('minecraft:oak_log[axis=y]')).toEqual({ namespace: 'minecraft', name: 'oak_log', properties: { axis: 'y' } }) + expect(parseState('stone')).toEqual({ namespace: 'minecraft', name: 'stone', properties: {} }) + }) + + it('fills a model from its parents and keeps its six faces culled by their sides', async () => { + const stone = (await new BlockModels(assets).model('minecraft:stone'))! + + expect(stone.fullCube).toBe(true) + expect(stone.particle).toBe('minecraft:block/stone') + expect(stone.quads.map((quad) => quad.texture)).toEqual(Array(6).fill('minecraft:block/stone')) + expect(stone.quads.find((quad) => quad.facing === 'up')!.corners.every(([, y]) => y === 1)).toBe(true) + }) + + it('turns a variant: x first, then y, so a log lying along x shows its top to the east', async () => { + const log = (await new BlockModels(assets).model('minecraft:oak_log[axis=x]'))! + const top = log.quads.find((quad) => quad.cullFace === 'east')! + + expect(top.facing).toBe('east') + expect(top.corners.every(([x]) => Math.abs(x - 1) < 1e-9)).toBe(true) + }) + + it('applies the multipart pieces whose conditions the state meets', async () => { + const models = new BlockModels(assets) + + expect((await models.model('minecraft:fence[east=false,north=false,west=false]'))!.quads).toHaveLength(6) + expect((await models.model('minecraft:fence[east=false,north=true,west=x]'))!.quads).toHaveLength(18) + }) + + it('knows a model without elements, and no model at all', async () => { + const models = new BlockModels(assets) + + expect(await models.model('minecraft:chest')).toEqual({ quads: [], fullCube: false, particle: 'minecraft:block/oak_planks' }) + expect(await models.model('minecraft:nothing')).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/scene/blockModels.ts b/studio/src/renderer/src/scene/blockModels.ts new file mode 100644 index 000000000..abecc1a4c --- /dev/null +++ b/studio/src/renderer/src/scene/blockModels.ts @@ -0,0 +1,389 @@ +/** + * Minecraft's block models, read the way the client reads them: a block state picks variants or multipart pieces from + * its blockstate file, each a model whose parents fill in textures and elements, turned in steps of 90 degrees. + */ + +export type Direction = 'down' | 'up' | 'north' | 'south' | 'west' | 'east' +export type Vec3 = [number, number, number] + +/** Where a block model's files come from: the bridge's copy of the client's assets. */ +export interface AssetSource { + /** The JSON file at {@code path} below the assets folder, or null when there is none. */ + json(path: string): Promise +} + +/** One textured face of a block, in block units from its lowest corner (0 to 1 on each axis). */ +export interface Quad { + /** Top left, bottom left, bottom right, top right as the texture lies on the face, seen from outside. */ + corners: [Vec3, Vec3, Vec3, Vec3] + /** The texture's coordinates at each corner, 0 to 1 from its top left. */ + uvs: [[number, number], [number, number], [number, number], [number, number]] + /** Such as minecraft:block/stone. */ + texture: string + /** Which of the block's tints colours the face, or -1 for none. */ + tintIndex: number + /** The side whose neighbour, when it is a solid block, hides the face; null when nothing hides it. */ + cullFace: Direction | null + /** The side the face looks toward, for its light. */ + facing: Direction + shade: boolean +} + +export interface BlockModel { + quads: Quad[] + /** A single element filling the whole block on every side, which hides the faces it touches if its textures are solid. */ + fullCube: boolean + /** The texture the client breaks the block with, which stands in for blocks the client draws without a model. */ + particle: string | null +} + +export interface ParsedState { + namespace: string + name: string + properties: Record +} + +type Json = Record + +interface Variant { + model: string + x: number + y: number +} + +interface ModelFile { + parent?: string + textures?: Record + elements?: ElementJson[] +} + +interface ElementJson { + from: Vec3 + to: Vec3 + rotation?: { origin: Vec3; axis: 'x' | 'y' | 'z'; angle: number; rescale?: boolean } + shade?: boolean + faces: Partial> +} + +interface FaceJson { + uv?: [number, number, number, number] + texture: string + cullface?: Direction + rotation?: number + tintindex?: number +} + +const PIXELS = 16 +const DEFAULT_NAMESPACE = 'minecraft' +const MAX_PARENT_DEPTH = 32 +const DIRECTIONS: Direction[] = ['down', 'up', 'north', 'south', 'west', 'east'] +const DIRECTION_VECTORS: Record = { + down: [0, -1, 0], + up: [0, 1, 0], + north: [0, 0, -1], + south: [0, 0, 1], + west: [-1, 0, 0], + east: [1, 0, 0] +} + +/** Reads {@code minecraft:oak_log[axis=y]}. */ +export function parseState(key: string): ParsedState { + const open = key.indexOf('[') + const id = open < 0 ? key : key.slice(0, open) + const colon = id.indexOf(':') + const properties: Record = {} + if (open >= 0) { + for (const pair of key.slice(open + 1, -1).split(',')) { + const equals = pair.indexOf('=') + if (equals > 0) { + properties[pair.slice(0, equals)] = pair.slice(equals + 1) + } + } + } + return colon < 0 + ? { namespace: DEFAULT_NAMESPACE, name: id, properties } + : { namespace: id.slice(0, colon), name: id.slice(colon + 1), properties } +} + +/** Resolves and keeps the models of block states; one per connection, as its assets are one Minecraft version's. */ +export class BlockModels { + private readonly models = new Map>() + private readonly files = new Map>() + + constructor(private readonly assets: AssetSource) {} + + /** The model of a block state, or null when the client has no blockstate file for the block. */ + model(stateKey: string): Promise { + let model = this.models.get(stateKey) + if (model === undefined) { + model = this.resolve(parseState(stateKey)) + this.models.set(stateKey, model) + } + return model + } + + private async resolve(state: ParsedState): Promise { + const blockstate = (await this.assets.json(`${state.namespace}/blockstates/${state.name}.json`)) as Json | null + if (blockstate === null) { + return null + } + const variants = pickVariants(blockstate, state.properties) + const pieces = await Promise.all(variants.map((variant) => this.piece(variant))) + const quads = pieces.flatMap((piece) => piece.quads) + return { quads, fullCube: pieces.length === 1 && pieces[0].fullCube, particle: pieces[0]?.particle ?? null } + } + + private async piece(variant: Variant): Promise { + const chain = await this.parentChain(variant.model) + const textures: Record = {} + for (const file of [...chain].reverse()) { + Object.assign(textures, file.textures ?? {}) + } + const elements = chain.find((file) => file.elements !== undefined)?.elements ?? [] + const quads = elements.flatMap((element) => elementQuads(element, textures)) + const turned = quads.map((quad) => turn(quad, variant.x, variant.y)) + return { quads: turned, fullCube: elements.length === 1 && isFullCube(elements[0]), particle: textureOf('#particle', textures) } + } + + private async parentChain(modelId: string): Promise { + const chain: ModelFile[] = [] + let next: string | undefined = modelId + while (next !== undefined && chain.length < MAX_PARENT_DEPTH) { + const file = await this.file(next) + if (file === null) { + break + } + chain.push(file) + next = file.parent + } + return chain + } + + private file(modelId: string): Promise { + let file = this.files.get(modelId) + if (file === undefined) { + const { namespace, path } = splitId(modelId) + file = this.assets.json(`${namespace}/models/${path}.json`) as Promise + this.files.set(modelId, file) + } + return file + } +} + +/** A whole block with {@code texture} on every side, for blocks the client draws without a model. */ +export function cubeModel(texture: string): BlockModel { + const faces = Object.fromEntries(DIRECTIONS.map((direction) => [direction, { texture: '#all', cullface: direction }])) + const quads = elementQuads({ from: [0, 0, 0], to: [PIXELS, PIXELS, PIXELS], faces }, { all: texture }) + return { quads, fullCube: true, particle: texture } +} + +/** The variant a block state picks, or the multipart pieces whose conditions it meets; the first of weighted choices. */ +function pickVariants(blockstate: Json, properties: Record): Variant[] { + const variants = blockstate.variants as Record | undefined + if (variants !== undefined) { + for (const [condition, choice] of Object.entries(variants)) { + if (matchesVariantKey(condition, properties)) { + return [variantOf(choice)] + } + } + return [] + } + const multipart = blockstate.multipart as { when?: Json; apply: unknown }[] | undefined + return (multipart ?? []).filter((part) => part.when === undefined || meets(part.when, properties)).map((part) => variantOf(part.apply)) +} + +function matchesVariantKey(condition: string, properties: Record): boolean { + if (condition === '') { + return true + } + return condition.split(',').every((pair) => { + const [name, value] = pair.split('=') + return properties[name] === value + }) +} + +function meets(condition: Json, properties: Record): boolean { + if (Array.isArray(condition.OR)) { + return (condition.OR as Json[]).some((part) => meets(part, properties)) + } + if (Array.isArray(condition.AND)) { + return (condition.AND as Json[]).every((part) => meets(part, properties)) + } + return Object.entries(condition).every(([name, allowed]) => String(allowed).split('|').includes(properties[name])) +} + +function variantOf(choice: unknown): Variant { + const picked = (Array.isArray(choice) ? choice[0] : choice) as Json + return { model: String(picked.model), x: Number(picked.x ?? 0), y: Number(picked.y ?? 0) } +} + +function splitId(id: string): { namespace: string; path: string } { + const colon = id.indexOf(':') + return colon < 0 ? { namespace: DEFAULT_NAMESPACE, path: id } : { namespace: id.slice(0, colon), path: id.slice(colon + 1) } +} + +function isFullCube(element: ElementJson): boolean { + const fills = element.from.every((value) => value === 0) && element.to.every((value) => value === PIXELS) + return fills && element.rotation === undefined && DIRECTIONS.every((direction) => element.faces[direction] !== undefined) +} + +function elementQuads(element: ElementJson, textures: Record): Quad[] { + const quads: Quad[] = [] + for (const direction of DIRECTIONS) { + const face = element.faces[direction] + if (face === undefined) { + continue + } + const texture = textureOf(face.texture, textures) + if (texture === null) { + continue + } + const corners = faceCorners(direction, element.from, element.to).map((corner) => rotateInElement(corner, element)) as Quad['corners'] + quads.push({ + corners, + uvs: faceUvs(face, direction, element.from, element.to), + texture, + tintIndex: face.tintindex ?? -1, + cullFace: face.cullface ?? null, + facing: direction, + shade: element.shade ?? true + }) + } + return quads +} + +/** Follows {@code #name} references through the model's textures to a texture id. */ +function textureOf(reference: string, textures: Record): string | null { + let current = reference + for (let step = 0; step < MAX_PARENT_DEPTH && current.startsWith('#'); step++) { + const next = textures[current.slice(1)] + if (next === undefined) { + return null + } + current = next + } + if (current.startsWith('#')) { + return null + } + const { namespace, path } = splitId(current) + return `${namespace}:${path}` +} + +/** A face's corners in pixels, top left first and counter-clockwise seen from outside, as {@link Quad#corners}. */ +function faceCorners(direction: Direction, from: Vec3, to: Vec3): Vec3[] { + const [x1, y1, z1] = from.map((value) => value / PIXELS) + const [x2, y2, z2] = to.map((value) => value / PIXELS) + switch (direction) { + case 'north': + return [[x2, y2, z1], [x2, y1, z1], [x1, y1, z1], [x1, y2, z1]] + case 'south': + return [[x1, y2, z2], [x1, y1, z2], [x2, y1, z2], [x2, y2, z2]] + case 'west': + return [[x1, y2, z1], [x1, y1, z1], [x1, y1, z2], [x1, y2, z2]] + case 'east': + return [[x2, y2, z2], [x2, y1, z2], [x2, y1, z1], [x2, y2, z1]] + case 'up': + return [[x1, y2, z1], [x1, y2, z2], [x2, y2, z2], [x2, y2, z1]] + case 'down': + return [[x1, y1, z2], [x1, y1, z1], [x2, y1, z1], [x2, y1, z2]] + } +} + +function faceUvs(face: FaceJson, direction: Direction, from: Vec3, to: Vec3): Quad['uvs'] { + const [u1, v1, u2, v2] = (face.uv ?? defaultUv(direction, from, to)).map((value) => value / PIXELS) + const uvs: Quad['uvs'] = [[u1, v1], [u1, v2], [u2, v2], [u2, v1]] + const steps = (((face.rotation ?? 0) / 90) % 4 + 4) % 4 + return uvs.map((_, corner) => uvs[(corner + steps) % 4]) as Quad['uvs'] +} + +// Minecraft's own default: the face shows the part of the texture its element covers, seen from outside. +function defaultUv(direction: Direction, [x1, y1, z1]: Vec3, [x2, y2, z2]: Vec3): [number, number, number, number] { + switch (direction) { + case 'down': + return [x1, PIXELS - z2, x2, PIXELS - z1] + case 'up': + return [x1, z1, x2, z2] + case 'north': + return [PIXELS - x2, PIXELS - y2, PIXELS - x1, PIXELS - y1] + case 'south': + return [x1, PIXELS - y2, x2, PIXELS - y1] + case 'west': + return [z1, PIXELS - y2, z2, PIXELS - y1] + case 'east': + return [PIXELS - z2, PIXELS - y2, PIXELS - z1, PIXELS - y1] + } +} + +function rotateInElement(corner: Vec3, element: ElementJson): Vec3 { + const rotation = element.rotation + if (rotation === undefined || rotation.angle === 0) { + return corner + } + const origin = rotation.origin.map((value) => value / PIXELS) as Vec3 + const radians = (rotation.angle * Math.PI) / 180 + const relative: Vec3 = [corner[0] - origin[0], corner[1] - origin[1], corner[2] - origin[2]] + const turned = rotateAboutAxis(relative, rotation.axis, radians) + if (rotation.rescale === true) { + const stretch = 1 / Math.cos(Math.abs(radians)) + for (const axis of [0, 1, 2]) { + if (axis !== 'xyz'.indexOf(rotation.axis)) { + turned[axis] *= stretch + } + } + } + return [turned[0] + origin[0], turned[1] + origin[1], turned[2] + origin[2]] +} + +function rotateAboutAxis([x, y, z]: Vec3, axis: 'x' | 'y' | 'z', radians: number): Vec3 { + const cos = Math.cos(radians) + const sin = Math.sin(radians) + switch (axis) { + case 'x': + return [x, y * cos - z * sin, y * sin + z * cos] + case 'y': + return [x * cos + z * sin, y, -x * sin + z * cos] + case 'z': + return [x * cos - y * sin, x * sin + y * cos, z] + } +} + +/** A variant's turn: {@code x} first, then {@code y}, each in steps of 90 degrees about the block's centre. */ +function turn(quad: Quad, xDegrees: number, yDegrees: number): Quad { + const xSteps = quarterTurns(xDegrees) + const ySteps = quarterTurns(yDegrees) + if (xSteps === 0 && ySteps === 0) { + return quad + } + const turnPoint = (point: Vec3): Vec3 => offsetFromCentre(turnVector(offsetFromCentre(point, -0.5), xSteps, ySteps), 0.5) + return { + ...quad, + corners: quad.corners.map(turnPoint) as Quad['corners'], + cullFace: quad.cullFace === null ? null : directionOf(turnVector(DIRECTION_VECTORS[quad.cullFace], xSteps, ySteps)), + facing: directionOf(turnVector(DIRECTION_VECTORS[quad.facing], xSteps, ySteps)) + } +} + +function quarterTurns(degrees: number): number { + return ((Math.round(degrees / 90) % 4) + 4) % 4 +} + +function offsetFromCentre([x, y, z]: Vec3, by: number): Vec3 { + return [x + by, y + by, z + by] +} + +// A quarter turn about x takes north to down; one about y takes north to east, as Minecraft turns its variants. +function turnVector(vector: Vec3, xSteps: number, ySteps: number): Vec3 { + let [x, y, z] = vector + for (let step = 0; step < xSteps; step++) { + ;[y, z] = [z, -y] + } + for (let step = 0; step < ySteps; step++) { + ;[x, z] = [-z, x] + } + return [x, y, z] +} + +function directionOf([x, y, z]: Vec3): Direction { + const rounded = [Math.round(x), Math.round(y), Math.round(z)].join(',') + return DIRECTIONS.find((direction) => DIRECTION_VECTORS[direction].join(',') === rounded) ?? 'up' +} 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/blockTints.ts b/studio/src/renderer/src/scene/blockTints.ts new file mode 100644 index 000000000..e1d7a4f09 --- /dev/null +++ b/studio/src/renderer/src/scene/blockTints.ts @@ -0,0 +1,51 @@ +/** + * The colour each tinted face of a block is multiplied with, as Minecraft's BlockColors give it (v3e + * MinecraftBlockTints). Scenes stand in no biome, so the biome tints are the plains' colours. + */ + +const NO_TINT = 0xffffff +const PLAINS_GRASS = 0x91bd59 +const PLAINS_FOLIAGE = 0x77ab2f +const PLAINS_DRY_FOLIAGE = 0xa0804b +const PLAINS_WATER = 0x3f76e4 + +const GRASS_TINTED = new Set(['grass_block', 'short_grass', 'fern', 'potted_fern', 'bush', 'tall_grass', 'large_fern', 'sugar_cane']) +const GRASS_TINTED_ON_SECOND_LAYER = new Set(['pink_petals', 'wildflowers']) +const FOLIAGE_TINTED = new Set(['oak_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves', 'vine', 'mangrove_leaves']) +const WATER_TINTED = new Set(['water', 'bubble_column', 'water_cauldron']) +const GROWING_STEMS = new Set(['melon_stem', 'pumpkin_stem']) +const FIXED_TINTS: Record = { + spruce_leaves: 0x619961, + birch_leaves: 0x80a755, + attached_melon_stem: 0xe0c71c, + attached_pumpkin_stem: 0xe0c71c, + lily_pad: 0x208030 +} + +/** The tint of one face of block {@code name}, as 0xRRGGBB; white for an untinted face. */ +export function blockTint(name: string, properties: Record, tintIndex: number): number { + // The client tints water when it draws the fluid, which has no model, so its stand-in is tinted whole. + if (WATER_TINTED.has(name)) { + return PLAINS_WATER + } + if (GRASS_TINTED_ON_SECOND_LAYER.has(name)) { + return tintIndex === 1 ? PLAINS_GRASS : NO_TINT + } + if (tintIndex !== 0) { + return NO_TINT + } + if (GRASS_TINTED.has(name)) { + return PLAINS_GRASS + } + if (FOLIAGE_TINTED.has(name)) { + return PLAINS_FOLIAGE + } + if (name === 'leaf_litter') { + return PLAINS_DRY_FOLIAGE + } + if (GROWING_STEMS.has(name)) { + const age = Number(properties.age ?? '0') + return ((age * 32) << 16) | ((255 - age * 8) << 8) | (age * 4) + } + return FIXED_TINTS[name] ?? NO_TINT +} diff --git a/studio/src/renderer/src/scene/cameraSight.ts b/studio/src/renderer/src/scene/cameraSight.ts new file mode 100644 index 000000000..41e4e6981 --- /dev/null +++ b/studio/src/renderer/src/scene/cameraSight.ts @@ -0,0 +1,130 @@ +import { Box3, Frustum, Vector3, type PerspectiveCamera } from 'three' +import { blocksPerColumn, originXOf, originZOf, tileBlocks, tileContaining, type TerrainTile } from './terrainTiles' + +/** What a camera looks through: its size in CSS pixels and how far it orbits from what is in the middle. */ +export interface SightView { + camera: PerspectiveCamera + width: number + height: number + orbitDistance: number +} + +const NDC_MIDDLE_DEPTH = 0.5 + +/** + * What the camera sees of ground that lies between {@code floorY} and {@code topY}: which terrain tiles land in the + * view, or within a margin around it, and how wide their columns look from where the camera stands. + */ +export class CameraSight { + private readonly frustums = new Map() + private readonly position = new Vector3() + private readonly lookedAt: Vector3 + + constructor( + private readonly view: SightView, + readonly floorY: number, + readonly topY: number + ) { + view.camera.updateMatrixWorld() + view.camera.getWorldPosition(this.position) + this.lookedAt = this.groundInMiddleOfView() + } + + get orbitDistance(): number { + return this.view.orbitDistance + } + + /** How many pixels the view has, with {@code margin} of its size added on every side. */ + pixelsWithin(margin: number): number { + const widening = 1 + 2 * margin + return this.view.width * this.view.height * widening * widening + } + + /** Whether any of the tile, from the floor to the top, lands in the view widened by {@code margin} of its size on every side. */ + sees(tile: TerrainTile, margin: number): boolean { + return this.frustumWith(margin).intersectsBox(this.boxOf(tile)) + } + + /** How many pixels wide a column of the tile looks at the nearest ground of it. */ + columnPixels(tile: TerrainTile): number { + const distance = Math.max(this.boxOf(tile).distanceToPoint(this.position), this.view.camera.near) + const pixelsPerBlock = this.view.height / (2 * distance * Math.tan((this.view.camera.fov * Math.PI) / 360)) + return blocksPerColumn(tile.level) * pixelsPerBlock + } + + /** How many blocks the tile lies from the ground in the middle of the view; nothing for the tile that ground is in. */ + distanceFromLookedAt(tile: TerrainTile): number { + const size = tileBlocks(tile.level) + const x = originXOf(tile) + const z = originZOf(tile) + const pastX = Math.max(x - this.lookedAt.x, 0, this.lookedAt.x - (x + size)) + const pastZ = Math.max(z - this.lookedAt.z, 0, this.lookedAt.z - (z + size)) + return Math.hypot(pastX, pastZ) + } + + // Where the line of sight comes down to the middle height of the ground, or under the camera when it never does. + private groundInMiddleOfView(): Vector3 { + const direction = this.view.camera.getWorldDirection(new Vector3()) + const distance = ((this.floorY + this.topY) / 2 - this.position.y) / direction.y + if (!Number.isFinite(distance) || distance < 0) { + return this.position.clone() + } + return direction.multiplyScalar(Math.min(distance, this.view.camera.far)).add(this.position) + } + + /** The tiles of {@code level} in sight, widened by {@code margin}. */ + tilesAt(level: number, margin: number): TerrainTile[] { + const { first, last } = this.footprint(level, margin) + const inSight: TerrainTile[] = [] + for (let tileZ = first.tileZ; tileZ <= last.tileZ; tileZ++) { + for (let tileX = first.tileX; tileX <= last.tileX; tileX++) { + const tile = { level, tileX, tileZ } + if (this.sees(tile, margin)) { + inSight.push(tile) + } + } + } + return inSight + } + + // The corners of the widened view, cast onto the floor and the top of the ground, bound the tiles that can be in it. + private footprint(level: number, margin: number): { first: TerrainTile; last: TerrainTile } { + const { camera } = this.view + const reach = camera.far + const widening = 1 + 2 * margin + let [minX, minZ, maxX, maxZ] = [Infinity, Infinity, -Infinity, -Infinity] + for (const [cornerX, cornerY] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { + const direction = new Vector3(cornerX * widening, cornerY * widening, NDC_MIDDLE_DEPTH).unproject(camera).sub(this.position).normalize() + for (const groundY of [this.floorY, this.topY]) { + const distance = direction.y < 0 ? Math.min(reach, (groundY - this.position.y) / direction.y) : reach + const point = direction.clone().multiplyScalar(Math.max(0, distance)).add(this.position) + minX = Math.min(minX, point.x) + maxX = Math.max(maxX, point.x) + minZ = Math.min(minZ, point.z) + maxZ = Math.max(maxZ, point.z) + } + } + return { first: tileContaining(minX, minZ, level), last: tileContaining(maxX, maxZ, level) } + } + + private frustumWith(margin: number): Frustum { + let frustum = this.frustums.get(margin) + if (frustum === undefined) { + const { camera } = this.view + const widening = 1 + 2 * margin + const projection = camera.projectionMatrix.clone() + projection.elements[0] /= widening + projection.elements[5] /= widening + frustum = new Frustum().setFromProjectionMatrix(projection.multiply(camera.matrixWorldInverse)) + this.frustums.set(margin, frustum) + } + return frustum + } + + private boxOf(tile: TerrainTile): Box3 { + const size = tileBlocks(tile.level) + const x = originXOf(tile) + const z = originZOf(tile) + return new Box3(new Vector3(x, this.floorY, z), new Vector3(x + size, this.topY, z + size)) + } +} diff --git a/studio/src/renderer/src/scene/columnFaces.ts b/studio/src/renderer/src/scene/columnFaces.ts new file mode 100644 index 000000000..31298bc7f --- /dev/null +++ b/studio/src/renderer/src/scene/columnFaces.ts @@ -0,0 +1,214 @@ +import type { BlockLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { QuadBatch, type Picture, type Vec3 } from './quadBatch' +import { submergedTint, sunk, tintAt } from './waterTint' + +// Light on each face, as Minecraft shades blocks: tops full, north and south sides lighter than east and west. +const TOP_LIGHT = 1 +const NORTH_SOUTH_LIGHT = 0.8 +const EAST_WEST_LIGHT = 0.6 +const WATER_COLOR = 0 +// Textured sides stop this many blocks under the top of their column; what lies deeper is one quad in the average colour of its picture. +const MOST_TEXTURED_SIDE_BLOCKS = 16 + +interface Span { + bottom: number + top: number + color: number + /** The top face of the water the span lies under, or null where it lies in the open. */ + water: number | null + /** What the column's block looks like, or null where it shows its colour. */ + look: BlockLook | null +} + +interface Side { + /** Which way the side looks, as a step to the neighbouring column. */ + columnStep: number + rowStep: number + light: number +} + +const SIDES: readonly Side[] = [ + { columnStep: 0, rowStep: -1, light: NORTH_SOUTH_LIGHT }, + { columnStep: 0, rowStep: 1, light: NORTH_SOUTH_LIGHT }, + { columnStep: -1, rowStep: 0, light: EAST_WEST_LIGHT }, + { columnStep: 1, rowStep: 0, light: EAST_WEST_LIGHT } +] + +/** + * The ground as block faces: the top of every column, and the sides where a column stands above its neighbour, or + * above {@code base} at the field's edge and next to columns where nothing is known. Neighbouring columns showing the + * same face in the same colour are one face. Ground under water is sunk toward a deep colour, the more the further down + * it lies. + */ +export function groundFaces(field: ColumnField, base: number): QuadBatch { + const batch = new QuadBatch(true, field.pictures?.plain ?? null) + addTops(field, batch, (column, row) => { + const top = field.hasGround(column, row) ? field.groundTop[field.indexOf(column, row)] : null + const index = field.indexOf(column, row) + return top === null ? null : { bottom: top, top, color: field.color[index], water: field.waterTopAt(column, row), look: field.looks[index] } + }) + addSides(field, batch, (column, row, side) => { + if (!field.hasGround(column, row)) { + return null + } + const top = field.groundTop[field.indexOf(column, row)] + const [nextColumn, nextRow] = [column + side.columnStep, row + side.rowStep] + const bottom = field.hasGround(nextColumn, nextRow) ? field.groundTop[field.indexOf(nextColumn, nextRow)] : base + if (bottom >= top) { + return null + } + const water = field.waterTopAt(column, row) ?? field.waterTopAt(nextColumn, nextRow) + const index = field.indexOf(column, row) + return { bottom, top, color: field.color[index], water, look: field.looks[index] } + }) + return batch +} + +/** + * The water over the ground: its top where a column holds some, and the sides where it stands above what lies next + * to it, down to its own ground. Water at the edge of the field or beside columns where nothing is known has no side, + * as it goes on in the field next to it. Drawn without colour; the water has one. + */ +export function waterFaces(field: ColumnField): QuadBatch { + const batch = new QuadBatch(false) + addTops(field, batch, (column, row) => { + const top = field.waterTopAt(column, row) + return top === null ? null : { bottom: top, top, color: WATER_COLOR, water: null, look: null } + }) + addSides(field, batch, (column, row, side) => { + const top = field.waterTopAt(column, row) + if (top === null) { + return null + } + const next = field.surfaceTop(column + side.columnStep, row + side.rowStep) + if (next === null) { + return null + } + const bottom = Math.max(next, field.groundTop[field.indexOf(column, row)]) + return bottom < top ? { bottom, top, color: WATER_COLOR, water: null, look: null } : null + }) + return batch +} + +function addTops(field: ColumnField, batch: QuadBatch, spanAt: (column: number, row: number) => Span | null): void { + for (let row = 0; row < field.rows; row++) { + mergeRuns(field.columns, (column) => spanAt(column, row), (first, count, span) => { + const step = field.blocksPerColumn + const color = topColor(span) + const picture: Picture | null = span.look === null ? null : { cell: span.look.top.cell, standing: false } + batch.add([field.originX + first * step, span.top, field.originZ + row * step], [count * step, 0, 0], [0, 0, step], color, color, picture) + }) + } +} + +function addSides(field: ColumnField, batch: QuadBatch, spanAt: (column: number, row: number, side: Side) => Span | null): void { + for (const side of SIDES) { + const runsAlongRow = side.rowStep !== 0 + const lanes = runsAlongRow ? field.rows : field.columns + const length = runsAlongRow ? field.columns : field.rows + for (let lane = 0; lane < lanes; lane++) { + const columnOf = (step: number): number => (runsAlongRow ? step : lane) + const rowOf = (step: number): number => (runsAlongRow ? lane : step) + mergeRuns(length, (step) => spanAt(columnOf(step), rowOf(step), side), (first, count, span) => { + for (const part of sideParts(span)) { + if (span.look !== null) { + addTexturedSide(batch, field, side, columnOf(first), rowOf(first), part, span.look, span.top) + continue + } + const light = shaded(span.color, side.light) + batch.add(...sideQuad(field, side, columnOf(first), rowOf(first), count, part), sunk(light, part.bottomTint), sunk(light, part.topTint)) + } + }) + } + } +} + +function topColor(span: Span): Vec3 { + const light = shaded(span.look === null ? span.color : span.look.top.tint, TOP_LIGHT) + return span.water === null ? light : sunk(light, tintAt(span.water - span.top)) +} + +interface SidePart extends Span { + /** How much of the deep colour covers the bottom and the top of the part. */ + bottomTint: number + topTint: number +} + +// A side reaching above the water is cut at its surface: only the part below sinks, deeper toward its bottom. +function sideParts(span: Span): SidePart[] { + const { bottom, top, water } = span + if (water === null || water <= bottom) { + return [{ ...span, bottomTint: 0, topTint: 0 }] + } + if (water >= top) { + return [{ ...span, bottomTint: submergedTint(water - bottom), topTint: submergedTint(water - top) }] + } + return [ + { ...span, top: water, bottomTint: submergedTint(water - bottom), topTint: submergedTint(0) }, + { ...span, bottom: water, bottomTint: 0, topTint: 0 } + ] +} + +// One picture to a block: the column's top block in its side's, the blocks under it in theirs. Under the textured depth +// the rest is a single quad in the colour of the picture. +function addTexturedSide(batch: QuadBatch, field: ColumnField, side: Side, column: number, row: number, part: SidePart, look: BlockLook, columnTop: number): void { + const tintAt = (y: number): number => part.bottomTint + ((part.topTint - part.bottomTint) * (y - part.bottom)) / (part.top - part.bottom) + const texturedFloor = Math.max(part.bottom, columnTop - MOST_TEXTURED_SIDE_BLOCKS) + for (let top = part.top; top > texturedFloor; top--) { + const face = top === columnTop ? look.side : look.below + const light = shaded(face.tint, side.light) + const picture: Picture = { cell: face.cell, standing: true } + batch.add(...sideQuad(field, side, column, row, 1, { ...part, bottom: top - 1, top }), sunk(light, tintAt(top - 1)), sunk(light, tintAt(top)), picture) + } + const deepTop = Math.min(part.top, texturedFloor) + if (deepTop > part.bottom) { + const light = shaded(look.below.color, side.light) + batch.add(...sideQuad(field, side, column, row, 1, { ...part, top: deepTop }), sunk(light, part.bottomTint), sunk(light, tintAt(deepTop))) + } +} + +// The corner a side starts from is the one on its left as seen from outside, so it runs and rises into view. +function sideQuad(field: ColumnField, side: Side, column: number, row: number, count: number, span: Span): [Vec3, Vec3, Vec3] { + const step = field.blocksPerColumn + const x = field.originX + column * step + const z = field.originZ + row * step + const length = count * step + const up: Vec3 = [0, span.top - span.bottom, 0] + if (side.rowStep < 0) { + return [[x, span.bottom, z], [length, 0, 0], up] + } + if (side.rowStep > 0) { + return [[x + length, span.bottom, z + step], [-length, 0, 0], up] + } + if (side.columnStep < 0) { + return [[x, span.bottom, z + length], [0, 0, -length], up] + } + return [[x + step, span.bottom, z], [0, 0, length], up] +} + +function mergeRuns(length: number, spanAt: (index: number) => Span | null, emit: (first: number, count: number, span: Span) => void): void { + let first = 0 + while (first < length) { + const span = spanAt(first) + if (span === null) { + first++ + continue + } + let end = first + 1 + while (end < length && sameSpan(span, spanAt(end))) { + end++ + } + emit(first, end - first, span) + first = end + } +} + +function sameSpan(span: Span, other: Span | null): boolean { + return span.look === null && other !== null && other.look === null && other.top === span.top && other.bottom === span.bottom && other.color === span.color && other.water === span.water +} + +/** A 0xRRGGBB colour in a light, as red, green and blue from 0 to 1. */ +export function shaded(color: number, light: number): Vec3 { + return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light] +} diff --git a/studio/src/renderer/src/scene/columnField.ts b/studio/src/renderer/src/scene/columnField.ts new file mode 100644 index 000000000..3039b9a27 --- /dev/null +++ b/studio/src/renderer/src/scene/columnField.ts @@ -0,0 +1,185 @@ +import type { BlockLook } from './blockLooks' +import type { CoverLook } from './coverLooks' +import type { TerrainPictures } from './terrainAtlas' +import { isSeeThrough } from './raisedFaces' +import type { RaisedBlock, TerrainSurface } from './terrainMesh' +import type { ColumnArea } from './terrainTiles' + +const NO_VALUE = Number.NaN +const NOTHING_RAISED: readonly RaisedBlock[] = [] + +/** + * The surface read once into columns: where each column's ground and water faces stand, and its colour. A top face + * stands one above the block's Y, so ground and water sit where a player stands on them. Where nothing is known, or + * where the columns are {@code holes} left to finer ground, the column has no ground and no water. + */ +/** Where a field's ground and water stand, without the looks it was drawn with. */ +export interface FieldShape { + columns: number + rows: number + originX: number + originZ: number + blocksPerColumn: number + groundTop: Float32Array + waterTop: Float32Array + topRange: { lowest: number; highest: number } | null +} + +export class ColumnField { + readonly columns: number + readonly rows: number + readonly originX: number + readonly originZ: number + readonly blocksPerColumn: number + readonly groundTop: Float32Array + readonly waterTop: Float32Array + readonly color: Int32Array + /** What each column's block looks like, or null to show its colour. */ + readonly looks: (BlockLook | null)[] + /** What stands on each column's ground, or null for nothing that is drawn. */ + readonly covers: (CoverLook | null)[] + /** The solid blocks above each column's ground, highest first, each without a look where the field has no atlas. */ + readonly raised: (readonly RaisedBlock[])[] + /** The atlas of the looks, or null where no column has one. */ + readonly pictures: TerrainPictures | null + /** How low and high the top faces stand, ground and water alike; null where no column has ground. */ + readonly topRange: { lowest: number; highest: number } | null + + constructor(surface: TerrainSurface, holes: readonly ColumnArea[] = []) { + this.columns = surface.columns + this.rows = surface.rows + this.originX = surface.originX + this.originZ = surface.originZ + this.blocksPerColumn = surface.blocksPerColumn + const count = this.columns * this.rows + this.groundTop = new Float32Array(count).fill(NO_VALUE) + this.waterTop = new Float32Array(count).fill(NO_VALUE) + this.color = new Int32Array(count) + this.looks = new Array(count).fill(null) + this.covers = new Array(count).fill(null) + this.raised = new Array(count).fill(NOTHING_RAISED) + const hasPictures = surface.pictures !== undefined + let anyLook = false + let [lowestTop, highestTop] = [Infinity, -Infinity] + const inHole = this.holeMask(holes) + for (let row = 0; row < this.rows; row++) { + for (let column = 0; column < this.columns; column++) { + const index = this.indexOf(column, row) + const ground = inHole[index] === 1 ? null : surface.groundAt(column, row) + if (ground === null) { + continue + } + const water = surface.waterAt(column, row) + this.groundTop[index] = ground + 1 + this.waterTop[index] = water === null ? NO_VALUE : water + 1 + this.color[index] = surface.colorAt(column, row) + const look = hasPictures ? (surface.lookAt?.(column, row) ?? null) : null + this.looks[index] = look + this.covers[index] = hasPictures ? (surface.coverAt?.(column, row) ?? null) : null + const raised = surface.raisedAt?.(column, row) ?? NOTHING_RAISED + this.raised[index] = hasPictures ? raised : raised.map((block) => ({ ...block, look: null })) + anyLook ||= look !== null || this.raised[index].some((block) => block.look !== null) + lowestTop = Math.min(lowestTop, ground + 1) + highestTop = Math.max(highestTop, ground + 1, water === null ? ground : water + 1) + } + } + this.pictures = anyLook ? (surface.pictures ?? null) : null + this.topRange = lowestTop === Infinity ? null : { lowest: lowestTop, highest: highestTop } + } + + /** Where the field's ground and water stand, as plain data that can be sent to and from a worker. */ + shape(): FieldShape { + const { columns, rows, originX, originZ, blocksPerColumn, groundTop, waterTop, topRange } = this + return { columns, rows, originX, originZ, blocksPerColumn, groundTop, waterTop, topRange } + } + + /** A field rebuilt from its {@link shape}, which answers where its ground and water stand but holds no looks to draw. */ + static ofShape(shape: FieldShape): ColumnField { + const count = shape.columns * shape.rows + return Object.assign(Object.create(ColumnField.prototype) as ColumnField, { + ...shape, + color: new Int32Array(count), + looks: [], + covers: [], + raised: [], + pictures: null + }) + } + + indexOf(column: number, row: number): number { + return row * this.columns + column + } + + contains(column: number, row: number): boolean { + return column >= 0 && row >= 0 && column < this.columns && row < this.rows + } + + hasGround(column: number, row: number): boolean { + return this.contains(column, row) && !Number.isNaN(this.groundTop[this.indexOf(column, row)]) + } + + /** + * Whether the block at {@code y} in the column hides what touches it: the column's ground, or a block raised over it + * that nothing shows through. False outside the field. + */ + isOpaqueAt(column: number, row: number, y: number): boolean { + if (!this.hasGround(column, row)) { + return false + } + const index = this.indexOf(column, row) + return y < this.groundTop[index] || this.raised[index].some((block) => block.y === y && !isSeeThrough(block)) + } + + /** Whether any column has ground. */ + hasAnyGround(): boolean { + return this.groundTop.some((top) => !Number.isNaN(top)) + } + + /** The top face of the water over the column, or null where it is dry, holds none or lies outside the field. */ + waterTopAt(column: number, row: number): number | null { + if (!this.contains(column, row)) { + return null + } + const top = this.waterTop[this.indexOf(column, row)] + return Number.isNaN(top) ? null : top + } + + /** The face the column shows to the sky: its water where it has some, else its ground; null where nothing is known. */ + surfaceTop(column: number, row: number): number | null { + if (!this.hasGround(column, row)) { + return null + } + const index = this.indexOf(column, row) + return Number.isNaN(this.waterTop[index]) ? this.groundTop[index] : this.waterTop[index] + } + + /** The face shown to the sky over the world block, or null where the field has none. */ + surfaceTopOver(worldX: number, worldZ: number): number | null { + return this.surfaceTop(this.columnOf(worldX), this.rowOf(worldZ)) + } + + /** The top face of the ground under any water over the world block, or null where the field has none. */ + groundTopOver(worldX: number, worldZ: number): number | null { + const column = this.columnOf(worldX) + const row = this.rowOf(worldZ) + return this.hasGround(column, row) ? this.groundTop[this.indexOf(column, row)] : null + } + + private columnOf(worldX: number): number { + return Math.floor((worldX - this.originX) / this.blocksPerColumn) + } + + private rowOf(worldZ: number): number { + return Math.floor((worldZ - this.originZ) / this.blocksPerColumn) + } + + private holeMask(holes: readonly ColumnArea[]): Uint8Array { + const mask = new Uint8Array(this.columns * this.rows) + for (const hole of holes) { + for (let row = hole.fromRow; row < hole.toRow; row++) { + mask.fill(1, this.indexOf(hole.fromColumn, row), this.indexOf(hole.toColumn - 1, row) + 1) + } + } + return mask + } +} diff --git a/studio/src/renderer/src/scene/compactGeometry.test.ts b/studio/src/renderer/src/scene/compactGeometry.test.ts new file mode 100644 index 000000000..b8189b147 --- /dev/null +++ b/studio/src/renderer/src/scene/compactGeometry.test.ts @@ -0,0 +1,37 @@ +import { BufferAttribute, BufferGeometry, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { compacted, geometryOfCompact } from './compactGeometry' + +function geometryOf(positions: number[], colors: number[], uvs: number[]): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3)) + geometry.setAttribute('color', new BufferAttribute(Float32Array.from(colors), 3)) + geometry.setAttribute('uv', new BufferAttribute(Float32Array.from(uvs), 2)) + geometry.setIndex(new BufferAttribute(Uint32Array.of(0, 1, 2), 1)) + return geometry +} + +// Where a corner of the packed geometry lands once placed. +function placedCorner(arrays: ReturnType, corner: number): Vector3 { + const position = geometryOfCompact(arrays).getAttribute('position') + const { origin, scale } = arrays.placement + return new Vector3(origin[0] + position.getX(corner) * scale[0], origin[1] + position.getY(corner) * scale[1], origin[2] + position.getZ(corner) * scale[2]) +} + +describe('compact geometry', () => { + it('keeps the corners of block models where they were, to a sixteenth of a block', () => { + const arrays = compacted(geometryOf([100, 64, 200, 100.3125, 65, 200, 101, 64.5, 201], [0, 0.5, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0.5, 0.25, 1, 1]), 1) + + expect(placedCorner(arrays, 1).toArray()).toEqual([100.3125, 65, 200]) + expect(placedCorner(arrays, 2).toArray()).toEqual([101, 64.5, 201]) + expect(geometryOfCompact(arrays).getAttribute('color').getY(0)).toBeCloseTo(0.5, 2) + expect(geometryOfCompact(arrays).getAttribute('uv').getX(1)).toBeCloseTo(0.5, 4) + }) + + it('fits ground reaching far down by taking longer steps up and down', () => { + const arrays = compacted(geometryOf([0, -2048, 0, 1, 2048, 0, 0, 0, 1], new Array(9).fill(0), new Array(6).fill(0)), 1) + + expect(placedCorner(arrays, 1).y).toBeCloseTo(2048, 0) + expect(placedCorner(arrays, 0).y).toBe(-2048) + }) +}) diff --git a/studio/src/renderer/src/scene/compactGeometry.ts b/studio/src/renderer/src/scene/compactGeometry.ts new file mode 100644 index 000000000..55d4bfbc0 --- /dev/null +++ b/studio/src/renderer/src/scene/compactGeometry.ts @@ -0,0 +1,68 @@ +import { BufferAttribute, BufferGeometry, type Vector3Tuple } from 'three' + +// Positions are kept in sixteenths of a block, the finest step a block model uses, from the geometry's lowest corner. +const STEPS_PER_BLOCK = 16 +const MOST_STEPS = 32_767 + +/** Where a compact geometry's corner lies in the world and how far one of its steps goes along each axis. */ +export interface CompactPlacement { + origin: Vector3Tuple + scale: Vector3Tuple +} + +/** A geometry's arrays packed small: positions in whole steps, colours a byte a channel, picture places in 16 bits. */ +export interface CompactArrays { + position: Int16Array + color: Uint8Array | null + uv: Uint16Array | null + index: Uint32Array + placement: CompactPlacement +} + +/** + * The geometry's arrays in about half the bytes, which the GPU takes in half the time: a tile's corners are whole steps + * of a sixteenth of a block, or of a column across wider columns, from the tile's lowest corner; colours and picture + * places are fractions packed into integers. A geometry too tall for that many steps takes longer steps up and down. + */ +export function compacted(geometry: BufferGeometry, blocksPerColumn: number): CompactArrays { + const positions = geometry.getAttribute('position').array as Float32Array + const min: Vector3Tuple = [Infinity, Infinity, Infinity] + const max: Vector3Tuple = [-Infinity, -Infinity, -Infinity] + for (let at = 0; at < positions.length; at += 3) { + for (let axis = 0; axis < 3; axis++) { + min[axis] = Math.min(min[axis], positions[at + axis]) + max[axis] = Math.max(max[axis], positions[at + axis]) + } + } + const horizontal = blocksPerColumn / STEPS_PER_BLOCK + const stepFor = (axis: number, finest: number): number => Math.max(finest, (max[axis] - min[axis]) / MOST_STEPS) + const scale: Vector3Tuple = [stepFor(0, horizontal), stepFor(1, 1 / STEPS_PER_BLOCK), stepFor(2, horizontal)] + const position = new Int16Array(positions.length) + for (let at = 0; at < positions.length; at++) { + const axis = at % 3 + position[at] = Math.round((positions[at] - min[axis]) / scale[axis]) + } + const color = geometry.getAttribute('color')?.array as Float32Array | undefined + const uv = geometry.getAttribute('uv')?.array as Float32Array | undefined + return { + position, + color: color === undefined ? null : Uint8Array.from(color, (channel) => Math.round(Math.min(1, Math.max(0, channel)) * 255)), + uv: uv === undefined ? null : Uint16Array.from(uv, (place) => Math.round(Math.min(1, Math.max(0, place)) * 65_535)), + index: geometry.getIndex()!.array as Uint32Array, + placement: { origin: min, scale } + } +} + +/** The geometry the compact arrays hold, in the steps they were packed in; draw it placed by their placement. */ +export function geometryOfCompact(arrays: CompactArrays): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(arrays.position, 3)) + if (arrays.color !== null) { + geometry.setAttribute('color', new BufferAttribute(arrays.color, 3, true)) + } + if (arrays.uv !== null) { + geometry.setAttribute('uv', new BufferAttribute(arrays.uv, 2, true)) + } + geometry.setIndex(new BufferAttribute(arrays.index, 1)) + return geometry +} diff --git a/studio/src/renderer/src/scene/coverFaces.ts b/studio/src/renderer/src/scene/coverFaces.ts new file mode 100644 index 000000000..9d5e1b3ab --- /dev/null +++ b/studio/src/renderer/src/scene/coverFaces.ts @@ -0,0 +1,45 @@ +import { BufferAttribute, BufferGeometry } from 'three' +import type { ColumnField } from './columnField' + +const CORNERS_PER_FACE = 4 +const INDICES_PER_FACE = 6 + +/** + * What stands on the ground, such as grass, flowers and layers of snow: each column's cover as its block's own model, + * set on the column's top face. Null where no column has a cover. + */ +export function coverGeometry(field: ColumnField): BufferGeometry | null { + const faces = field.covers.reduce((count, cover) => count + (cover?.faces.length ?? 0), 0) + if (faces === 0) { + return null + } + const positions = new Float32Array(faces * CORNERS_PER_FACE * 3) + const uvs = new Float32Array(faces * CORNERS_PER_FACE * 2) + const colors = new Float32Array(faces * CORNERS_PER_FACE * 3) + const indices = new Uint32Array(faces * INDICES_PER_FACE) + const step = field.blocksPerColumn + let face = 0 + for (let row = 0; row < field.rows; row++) { + for (let column = 0; column < field.columns; column++) { + const index = field.indexOf(column, row) + const [x, y, z] = [field.originX + column * step, field.groundTop[index], field.originZ + row * step] + for (const { corners, uvs: faceUvs, cell, color } of field.covers[index]?.faces ?? []) { + const first = face * CORNERS_PER_FACE + for (let corner = 0; corner < CORNERS_PER_FACE; corner++) { + const [cornerX, cornerY, cornerZ] = corners[corner] + positions.set([x + cornerX * step, y + cornerY, z + cornerZ * step], (first + corner) * 3) + uvs.set([cell.u + faceUvs[corner][0] * cell.width, cell.v + faceUvs[corner][1] * cell.height], (first + corner) * 2) + colors.set(color, (first + corner) * 3) + } + indices.set([first, first + 1, first + 2, first, first + 2, first + 3], face * INDICES_PER_FACE) + face++ + } + } + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(positions, 3)) + geometry.setAttribute('uv', new BufferAttribute(uvs, 2)) + geometry.setAttribute('color', new BufferAttribute(colors, 3)) + geometry.setIndex(new BufferAttribute(indices, 1)) + return geometry +} diff --git a/studio/src/renderer/src/scene/coverLooks.ts b/studio/src/renderer/src/scene/coverLooks.ts new file mode 100644 index 000000000..ab929f01d --- /dev/null +++ b/studio/src/renderer/src/scene/coverLooks.ts @@ -0,0 +1,46 @@ +import { parseState, type BlockModel, type Direction, type Quad } from './blockModels' +import { blockTint } from './blockTints' +import type { PictureSource, UvCell } from './terrainAtlas' + +/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */ +export const FACE_LIGHT: Record = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 } + +/** One face of a block that stands on the ground, in block units from the block's lowest corner. */ +export interface CoverFace { + corners: Quad['corners'] + uvs: Quad['uvs'] + cell: UvCell + /** The face's tint in its light, as red, green and blue from 0 to 1. */ + color: readonly [number, number, number] + /** The side whose neighbour, when it is a solid block, hides the face; null when nothing hides it. */ + cullFace: Direction | null +} + +/** A block standing on a column's ground, such as grass, a flower or a layer of snow, as the faces of its model. */ +export interface CoverLook { + faces: CoverFace[] +} + +/** + * The block's model with its pictures placed; null for a block the client draws without a model, such as a chest, or + * when one of its pictures cannot be placed, so a cover is drawn whole or not at all. + */ +export async function coverLookOf(block: string, model: BlockModel | null, pictures: PictureSource): Promise { + if (model === null || model.quads.length === 0) { + return null + } + const state = parseState(block) + const faces = await Promise.all( + model.quads.map(async (quad): Promise => { + const cell = await pictures.cellOf(quad.texture) + if (cell === null) { + return null + } + const tint = blockTint(state.name, state.properties, quad.tintIndex) + const light = quad.shade ? FACE_LIGHT[quad.facing] : 1 + const color = [(((tint >> 16) & 0xff) / 255) * light, (((tint >> 8) & 0xff) / 255) * light, ((tint & 0xff) / 255) * light] as const + return { corners: quad.corners, uvs: quad.uvs, cell, color, cullFace: quad.cullFace } + }) + ) + return faces.includes(null) ? null : { faces: faces as CoverFace[] } +} diff --git a/studio/src/renderer/src/scene/farLeaves.test.ts b/studio/src/renderer/src/scene/farLeaves.test.ts new file mode 100644 index 000000000..c58c31e14 --- /dev/null +++ b/studio/src/renderer/src/scene/farLeaves.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { countFarLeaves, isFarLeaf } from './farLeaves' +import type { BlockScene } from './sceneDecoding' + +function sceneOf(palette: string[], ...indexes: number[]): BlockScene { + const blocks = new Int32Array(indexes.flatMap((index, position) => [position, 0, 0, index])) + return { palette, blocks, min: [0, 0, 0], max: [indexes.length, 1, 1] } +} + +describe('far leaves', () => { + it('takes a leaf with the persistent property at distance 7', () => { + expect(isFarLeaf('minecraft:oak_leaves[distance=7,persistent=true,waterlogged=false]')).toBe(true) + expect(isFarLeaf('minecraft:oak_leaves[distance=7,persistent=false]')).toBe(true) + }) + + it('leaves out leaves near wood, leaves without the persistent property, and other blocks', () => { + expect(isFarLeaf('minecraft:oak_leaves[distance=6,persistent=true]')).toBe(false) + expect(isFarLeaf('minecraft:oak_leaves[distance=7]')).toBe(false) + expect(isFarLeaf('minecraft:oak_log[axis=y]')).toBe(false) + expect(isFarLeaf('minecraft:stone')).toBe(false) + }) + + it('counts the blocks of the scene that are far leaves, not the palette entries', () => { + const scene = sceneOf(['minecraft:stone', 'minecraft:oak_leaves[distance=7,persistent=true]', 'minecraft:oak_leaves[distance=1,persistent=false]'], 1, 0, 1, 2, 1) + + expect(countFarLeaves(scene)).toBe(3) + }) + + it('counts none in a scene without leaves', () => { + expect(countFarLeaves(sceneOf(['minecraft:stone'], 0, 0))).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/farLeaves.ts b/studio/src/renderer/src/scene/farLeaves.ts new file mode 100644 index 000000000..6f1cd7d1a --- /dev/null +++ b/studio/src/renderer/src/scene/farLeaves.ts @@ -0,0 +1,26 @@ +import { parseState } from './blockModels' +import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding' + +const PERSISTENT_PROPERTY = 'persistent' +const DISTANCE_PROPERTY = 'distance' + +/** The distance vanilla gives a leaf with no wood near enough to keep it; IrisProceduralBlocks.UNREACHED_LEAF_DISTANCE. */ +const UNREACHED_LEAF_DISTANCE = '7' + +/** Whether a block state is a leaf baked with no wood near enough for vanilla to keep it; the rule of IrisProceduralBlocks.isLeafTooFarFromWood. */ +export function isFarLeaf(state: string): boolean { + const { properties } = parseState(state) + return PERSISTENT_PROPERTY in properties && properties[DISTANCE_PROPERTY] === UNREACHED_LEAF_DISTANCE +} + +/** How many blocks of the scene are leaves too far from wood. */ +export function countFarLeaves(scene: BlockScene): number { + const far = scene.palette.map(isFarLeaf) + let count = 0 + for (let offset = 3; offset < scene.blocks.length; offset += INTS_PER_BLOCK) { + if (far[scene.blocks[offset]]) { + count++ + } + } + return count +} diff --git a/studio/src/renderer/src/scene/groundInView.test.ts b/studio/src/renderer/src/scene/groundInView.test.ts new file mode 100644 index 000000000..0cb83389e --- /dev/null +++ b/studio/src/renderer/src/scene/groundInView.test.ts @@ -0,0 +1,62 @@ +import { PerspectiveCamera, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { ColumnField } from './columnField' +import { groundInView } from './groundInView' + +const GROUND = 70 +const CEILING = 128 +const FIELD_BLOCKS = 4000 +const BLOCKS_PER_COLUMN = 8 +const VIEW_WIDTH = 1280 +const VIEW_HEIGHT = 800 + +// A square of flat ground from the origin, with a ridge ten blocks higher along its eastern edge. +const RIDGE_FROM_X = 3000 +const ground = new ColumnField({ + columns: FIELD_BLOCKS / BLOCKS_PER_COLUMN, + rows: FIELD_BLOCKS / BLOCKS_PER_COLUMN, + originX: 0, + originZ: 0, + blocksPerColumn: BLOCKS_PER_COLUMN, + groundAt: (column) => (column * BLOCKS_PER_COLUMN >= RIDGE_FROM_X ? GROUND + 10 : GROUND), + waterAt: () => null, + colorAt: () => 0 +}) + +function lookDownFrom(position: Vector3, lookedAt: Vector3): { camera: PerspectiveCamera; width: number; height: number; orbitDistance: number } { + const camera = new PerspectiveCamera(45, VIEW_WIDTH / VIEW_HEIGHT, 1, 20_000) + camera.position.copy(position) + camera.lookAt(lookedAt) + camera.updateMatrixWorld() + return { camera, width: VIEW_WIDTH, height: VIEW_HEIGHT, orbitDistance: position.distanceTo(lookedAt) } +} + +const drawn = { + surfaceTopOver: (x: number, z: number) => ground.surfaceTopOver(x, z), + groundTopOver: (x: number, z: number) => ground.groundTopOver(x, z) +} + +describe('ground in view', () => { + it('boxes the ground the camera looks down at and reads its height', () => { + const seen = groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, GROUND, 1000)), CEILING, drawn)! + + expect(seen.heights.length).toBeGreaterThan(100) + expect(new Set(seen.heights)).toEqual(new Set([GROUND])) + expect(seen.area.minX).toBeLessThan(1000) + expect(seen.area.maxX).toBeGreaterThan(1000) + expect(seen.area.minZ).toBeLessThan(1000) + expect(seen.area.maxZ).toBeGreaterThan(1000) + expect(seen.area.maxX).toBeLessThan(FIELD_BLOCKS) + }) + + it('reads the height of every kind of ground in view', () => { + const seen = groundInView(lookDownFrom(new Vector3(3000, 400, 1400), new Vector3(3000, GROUND, 1000)), CEILING, drawn)! + + expect(new Set(seen.heights)).toEqual(new Set([GROUND, GROUND + 10])) + }) + + it('sees no ground over where nothing is drawn, or when looking at the sky', () => { + expect(groundInView(lookDownFrom(new Vector3(9000, 400, 1400), new Vector3(9000, GROUND, 1000)), CEILING, drawn)).toBeNull() + expect(groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, 900, 1000)), CEILING, drawn)).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/scene/groundInView.ts b/studio/src/renderer/src/scene/groundInView.ts new file mode 100644 index 000000000..84e108122 --- /dev/null +++ b/studio/src/renderer/src/scene/groundInView.ts @@ -0,0 +1,66 @@ +import { Ray, Vector3 } from 'three' +import type { WorldRect } from '../bridge/BridgeClient' +import type { SightView } from './cameraSight' +import { marchOntoSurface } from './surfaceMarch' + +/** Where the ground drawn so far stands: over a block, what the sky sees there, and the ground under any water. Null where nothing is known. */ +export interface DrawnGround { + surfaceTopOver(worldX: number, worldZ: number): number | null + groundTopOver(worldX: number, worldZ: number): number | null +} + +/** The ground the camera looks at: the box around it, and the height of the ground at each spot looked at. */ +export interface GroundInView { + area: WorldRect + heights: number[] +} + +// The spots are laid across the longer side of the view, as many along the shorter side as keeps them evenly apart. +const SPOTS_ALONG_LONGER_SIDE = 32 +const NDC_MIDDLE_DEPTH = 0.5 +const NDC_SPAN = 2 +const SMALLEST_AREA_SIDE_BLOCKS = 1 + +/** + * What the camera sees of {@code ground}: rays through an even grid of spots on the screen, each met where it comes + * down onto the ground, and the box around the places they meet. Null when no ray meets any ground. + * + * @param ceilingY the height above which no ground stands + */ +export function groundInView(view: SightView, ceilingY: number, ground: DrawnGround): GroundInView | null { + const { camera } = view + camera.updateMatrixWorld() + const eye = camera.getWorldPosition(new Vector3()) + const longer = Math.max(view.width, view.height) + const spotsAcross = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.width) / longer)) + const spotsDown = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.height) / longer)) + const heights: number[] = [] + let [minX, minZ, maxX, maxZ] = [Infinity, Infinity, -Infinity, -Infinity] + for (let spotZ = 0; spotZ < spotsDown; spotZ++) { + for (let spotX = 0; spotX < spotsAcross; spotX++) { + const through = new Vector3(centreOf(spotX, spotsAcross), -centreOf(spotZ, spotsDown), NDC_MIDDLE_DEPTH).unproject(camera) + const ray = new Ray(eye, through.sub(eye).normalize()) + const hit = marchOntoSurface(ray, camera.far, ceilingY, (x, z) => ground.surfaceTopOver(x, z)) + const groundTop = hit === null ? null : ground.groundTopOver(hit.x, hit.z) + if (hit === null || groundTop === null) { + continue + } + heights.push(groundTop - 1) + minX = Math.min(minX, hit.x) + maxX = Math.max(maxX, hit.x) + minZ = Math.min(minZ, hit.z) + maxZ = Math.max(maxZ, hit.z) + } + } + if (heights.length === 0) { + return null + } + return { + area: { minX, minZ, maxX: Math.max(maxX, minX + SMALLEST_AREA_SIDE_BLOCKS), maxZ: Math.max(maxZ, minZ + SMALLEST_AREA_SIDE_BLOCKS) }, + heights + } +} + +function centreOf(spot: number, spots: number): number { + return -1 + ((spot + 0.5) * NDC_SPAN) / spots +} diff --git a/studio/src/renderer/src/scene/mapTerrain.test.ts b/studio/src/renderer/src/scene/mapTerrain.test.ts new file mode 100644 index 000000000..b3c4aa734 --- /dev/null +++ b/studio/src/renderer/src/scene/mapTerrain.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import type { MapTile, TileBlocks } from '../bridge/types' +import { MapTerrain } from './mapTerrain' + +const SIZE = 2 +const CELLS = (SIZE + 2) ** 2 +const GROUND_Y = 64 +const LEAF_Y = 70 +const STONE = 0x808080 +const LEAVES = 0x00ff00 +// The tile's first column, past the ring of its neighbours' cells. +const FIRST_CELL = SIZE + 2 + 1 + +// A tile of stone at one height, with a leaf raised over its first column. +function tileWithALeaf(): MapTile { + const raisedStart = new Int32Array(CELLS + 1) + raisedStart.fill(1, FIRST_CELL + 1) + const blocks: TileBlocks = { + names: ['stone', 'leaves'], + ground: new Int16Array(CELLS), + cover: new Int16Array(CELLS).fill(-1), + raisedStart, + raisedY: Int16Array.of(LEAF_Y), + raised: Int16Array.of(1), + voxels: null, + runs: null, + colors: [STONE, LEAVES], + looks: [], + covers: [], + models: [] + } + return { + size: SIZE, + blocksPerPixel: 1, + subjectKind: 'BIOME', + labels: [], + subjects: new Int16Array(CELLS), + regions: new Int16Array(CELLS), + heights: new Float32Array(CELLS).fill(GROUND_Y), + pickNoise: null, + blocks + } +} + +function terrainAt(level: number): MapTerrain { + return new MapTerrain(tileWithALeaf(), { tileX: 0, tileZ: 0, level }, 'blocks', 0) +} + +describe('map terrain', () => { + it('stands raised blocks on columns a block wide, over the ground they stand on', () => { + const terrain = terrainAt(0) + + expect(terrain.groundAt(0, 0)).toBe(GROUND_Y) + expect(terrain.colorAt(0, 0)).toBe(STONE) + expect(terrain.raisedAt(0, 0)).toEqual([{ y: LEAF_Y, color: LEAVES, look: null }]) + }) + + it('takes the highest raised block as the top of a column wider than a block', () => { + const terrain = terrainAt(3) + + expect(terrain.groundAt(0, 0)).toBe(LEAF_Y) + expect(terrain.colorAt(0, 0)).toBe(LEAVES) + expect(terrain.raisedAt(0, 0)).toEqual([]) + expect(terrain.groundAt(1, 0)).toBe(GROUND_Y) + }) +}) diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts new file mode 100644 index 000000000..9e87cf105 --- /dev/null +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -0,0 +1,150 @@ +import { NO_BLOCK, NO_LABEL, type MapTile } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import type { BlockLook } from './blockLooks' +import type { CoverLook } from './coverLooks' +import type { TerrainPictures } from './terrainAtlas' +import type { RaisedBlock, TerrainSurface } from './terrainMesh' +import type { SurfaceRuns } from './runFaces' +import type { SurfaceVoxels } from './voxelMesh' +import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' + +export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks' + +const UNLABELLED_COLOR = 0x5a5f6b +const WATER_NAME = 'minecraft:water' + +function isWater(block: string): boolean { + return block === WATER_NAME || block.startsWith(`${WATER_NAME}[`) +} + +/** + * One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the + * sea fills up to fluid height. Coloured by blocks, a tile that carries them shows their colours, and their textures + * where it has their looks; one too coarse to carry them keeps its biomes' colours. Blocks raised over the ground stand + * as blocks on columns a block wide, and are the top of wider ones. + */ +export class MapTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + readonly originX: number + readonly originZ: number + readonly blocksPerColumn: number + + constructor( + private readonly tile: MapTile, + place: TerrainTile, + private readonly coloring: MapTerrainColoring, + private readonly fluidHeight: number, + readonly pictures?: TerrainPictures + ) { + this.columns = tile.size + this.rows = tile.size + this.originX = originXOf(place) + this.originZ = originZOf(place) + this.blocksPerColumn = blocksPerColumn(place.level) + } + + groundAt(column: number, row: number): number { + const highestRaised = this.highestFoldedRaisedAt(column, row) + return highestRaised === null ? Math.floor(this.heightAt(column, row)) : this.tile.blocks!.raisedY[highestRaised] + } + + waterAt(column: number, row: number): number | null { + return this.heightAt(column, row) < this.fluidHeight ? Math.floor(this.fluidHeight) : null + } + + lookAt(column: number, row: number): BlockLook | null { + const top = this.topBlockAt(column, row) + return top === NO_BLOCK ? null : (this.tile.blocks!.looks[top] ?? null) + } + + coverAt(column: number, row: number): CoverLook | null { + if (this.groundBlockAt(column, row) === NO_BLOCK || this.highestFoldedRaisedAt(column, row) !== null) { + return null + } + const cover = this.tile.blocks!.cover[this.cellAt(column, row)] + return cover === NO_BLOCK ? null : (this.tile.blocks!.covers[cover] ?? null) + } + + raisedAt(column: number, row: number): readonly RaisedBlock[] { + const blocks = this.coloring === 'blocks' ? this.tile.blocks : null + if (blocks === null || this.foldsRaisedBlocks()) { + return [] + } + const cell = this.cellAt(column, row) + const raised: RaisedBlock[] = [] + for (let at = blocks.raisedStart[cell]; at < blocks.raisedStart[cell + 1]; at++) { + const block = blocks.raised[at] + raised.push({ y: blocks.raisedY[at], color: blocks.colors[block], look: blocks.looks[block] ?? null }) + } + return raised + } + + voxels(): SurfaceVoxels | null { + const blocks = this.coloring === 'blocks' && this.blocksPerColumn === 1 ? this.tile.blocks : null + if (blocks === null || blocks.voxels === null || blocks.models.length === 0) { + return null + } + return { + voxels: blocks.voxels, + models: blocks.models, + looks: blocks.looks, + colors: blocks.colors, + isWater: blocks.names.map(isWater) + } + } + + runs(): SurfaceRuns | null { + const blocks = this.coloring === 'blocks' ? this.tile.blocks : null + if (blocks === null || blocks.runs === null) { + return null + } + return { runs: blocks.runs, cellAt: (column, row) => this.cellAt(column, row), looks: blocks.looks, colors: blocks.colors } + } + + colorAt(column: number, row: number): number { + if (this.coloring === 'height') { + return heightColor(this.heightAt(column, row), this.fluidHeight) + } + const top = this.topBlockAt(column, row) + if (top !== NO_BLOCK) { + return this.tile.blocks!.colors[top] + } + const index = this.coloring === 'regions' ? this.tile.regions[this.cellAt(column, row)] : this.tile.subjects[this.cellAt(column, row)] + return index === NO_LABEL ? UNLABELLED_COLOR : this.tile.labels[index].color + } + + // A block raised on a column wider than a block would stand as a slab as wide as the column, so such columns take + // their highest raised block as their top, as a forest seen from afar is its canopy. + private foldsRaisedBlocks(): boolean { + return this.blocksPerColumn > 1 + } + + /** Where the column's highest raised block lies in the tile's raised blocks, where the column takes it as its top. */ + private highestFoldedRaisedAt(column: number, row: number): number | null { + if (!this.foldsRaisedBlocks() || this.groundBlockAt(column, row) === NO_BLOCK) { + return null + } + const cell = this.cellAt(column, row) + const { raisedStart } = this.tile.blocks! + return raisedStart[cell] < raisedStart[cell + 1] ? raisedStart[cell] : null + } + + private topBlockAt(column: number, row: number): number { + const highestRaised = this.highestFoldedRaisedAt(column, row) + return highestRaised === null ? this.groundBlockAt(column, row) : this.tile.blocks!.raised[highestRaised] + } + + private groundBlockAt(column: number, row: number): number { + return this.coloring === 'blocks' && this.tile.blocks !== null ? this.tile.blocks.ground[this.cellAt(column, row)] : NO_BLOCK + } + + private heightAt(column: number, row: number): number { + return this.tile.heights![this.cellAt(column, row)] + } + + private cellAt(column: number, row: number): number { + const gridSize = this.tile.size + 2 + return (row + 1) * gridSize + column + 1 + } +} 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/pendingWork.test.ts b/studio/src/renderer/src/scene/pendingWork.test.ts new file mode 100644 index 000000000..66f5061da --- /dev/null +++ b/studio/src/renderer/src/scene/pendingWork.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { PendingWork } from './pendingWork' + +describe('PendingWork', () => { + it('measures against the most pending since last done', () => { + const work = new PendingWork() + expect(work.completion(200)).toBeCloseTo(0) + expect(work.completion(50)).toBeCloseTo(0.75) + expect(work.completion(0)).toBe(1) + }) + + it('starts over after the work is done', () => { + const work = new PendingWork() + work.completion(200) + work.completion(0) + expect(work.completion(10)).toBeCloseTo(0) + expect(work.completion(5)).toBeCloseTo(0.5) + }) +}) diff --git a/studio/src/renderer/src/scene/pendingWork.ts b/studio/src/renderer/src/scene/pendingWork.ts new file mode 100644 index 000000000..d405659cf --- /dev/null +++ b/studio/src/renderer/src/scene/pendingWork.ts @@ -0,0 +1,17 @@ +/** + * How far along work is when only what is still left is known: measured against the most that was left at once since + * the work was last done. + */ +export class PendingWork { + private mostPending = 0 + + /** @return 0 to 1, where 1 means nothing is left */ + completion(pending: number): number { + if (pending <= 0) { + this.mostPending = 0 + return 1 + } + this.mostPending = Math.max(this.mostPending, pending) + return 1 - pending / this.mostPending + } +} diff --git a/studio/src/renderer/src/scene/quadBatch.ts b/studio/src/renderer/src/scene/quadBatch.ts new file mode 100644 index 000000000..bb6ffa64b --- /dev/null +++ b/studio/src/renderer/src/scene/quadBatch.ts @@ -0,0 +1,118 @@ +import { BufferAttribute, BufferGeometry } from 'three' +import type { UvCell } from './terrainAtlas' + +const VERTICES_PER_QUAD = 4 +const INDICES_PER_QUAD = 6 +const COMPONENTS = 3 +const UV_COMPONENTS = 2 +const FIRST_CAPACITY_QUADS = 1024 + +/** + * A picture on a quad. A standing picture is upright seen from outside, as on a side: it runs from the far end of + * {@code along} on its left to the near end on its right, with its top edge at the far end of {@code up}. A lying one is + * as seen from above, as on a top: left to right along {@code along}, its top edge at the near end of {@code up}. + */ +export interface Picture { + cell: UvCell + standing: boolean +} + +/** + * Flat quads gathered for one geometry; vertices are not shared, so every quad keeps its own colour and shade. A batch + * given a {@code plain} cell is textured: quads without a picture show that cell, so their colour alone is seen. + */ +export class QuadBatch { + private positions = new Float32Array(FIRST_CAPACITY_QUADS * VERTICES_PER_QUAD * COMPONENTS) + private colors: Float32Array | null + private uvs: Float32Array | null + private quads = 0 + + constructor( + coloured: boolean, + private readonly plain: UvCell | null = null + ) { + this.colors = coloured ? new Float32Array(this.positions.length) : null + this.uvs = plain === null ? null : new Float32Array(FIRST_CAPACITY_QUADS * VERTICES_PER_QUAD * UV_COMPONENTS) + } + + get count(): number { + return this.quads + } + + /** + * A quad from {@code origin} along {@code along} and {@code up}; it faces the way {@code up} crosses {@code along}. + * Colours are red, green and blue from 0 to 1; the corners at the far end of {@code up} take {@code topColor}. + */ + add(origin: Vec3, along: Vec3, up: Vec3, color: Vec3 | null, topColor: Vec3 | null = color, picture: Picture | null = null): void { + this.reserveOne() + const first = this.quads * VERTICES_PER_QUAD * COMPONENTS + for (let corner = 0; corner < VERTICES_PER_QUAD; corner++) { + const [alongSteps, upSteps] = [corner >> 1, corner & 1] + for (let axis = 0; axis < COMPONENTS; axis++) { + const at = first + corner * COMPONENTS + axis + this.positions[at] = origin[axis] + along[axis] * alongSteps + up[axis] * upSteps + const cornerColor = upSteps === 1 ? topColor : color + if (this.colors !== null && cornerColor !== null) { + this.colors[at] = cornerColor[axis] + } + } + this.setUv(this.quads * VERTICES_PER_QUAD + corner, alongSteps, upSteps, picture) + } + this.quads++ + } + + geometry(): BufferGeometry { + const geometry = new BufferGeometry() + const used = this.quads * VERTICES_PER_QUAD * COMPONENTS + geometry.setAttribute('position', new BufferAttribute(this.positions.slice(0, used), COMPONENTS)) + if (this.colors !== null) { + geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, used), COMPONENTS)) + } + if (this.uvs !== null) { + geometry.setAttribute('uv', new BufferAttribute(this.uvs.slice(0, this.quads * VERTICES_PER_QUAD * UV_COMPONENTS), UV_COMPONENTS)) + } + const indices = new Uint32Array(this.quads * INDICES_PER_QUAD) + for (let quad = 0; quad < this.quads; quad++) { + const first = quad * VERTICES_PER_QUAD + indices.set([first, first + 1, first + 2, first + 2, first + 1, first + 3], quad * INDICES_PER_QUAD) + } + geometry.setIndex(new BufferAttribute(indices, 1)) + return geometry + } + + private setUv(vertex: number, alongSteps: number, upSteps: number, picture: Picture | null): void { + if (this.uvs === null || this.plain === null) { + return + } + const at = vertex * UV_COMPONENTS + if (picture === null) { + this.uvs[at] = this.plain.u + this.plain.width / 2 + this.uvs[at + 1] = this.plain.v + this.plain.height / 2 + return + } + const [rightSteps, downSteps] = picture.standing ? [1 - alongSteps, 1 - upSteps] : [alongSteps, upSteps] + this.uvs[at] = picture.cell.u + rightSteps * picture.cell.width + this.uvs[at + 1] = picture.cell.v + downSteps * picture.cell.height + } + + private reserveOne(): void { + if ((this.quads + 1) * VERTICES_PER_QUAD * COMPONENTS <= this.positions.length) { + return + } + this.positions = grown(this.positions) + if (this.colors !== null) { + this.colors = grown(this.colors) + } + if (this.uvs !== null) { + this.uvs = grown(this.uvs) + } + } +} + +export type Vec3 = readonly [number, number, number] + +function grown(values: Float32Array): Float32Array { + const bigger = new Float32Array(values.length * 2) + bigger.set(values) + return bigger +} diff --git a/studio/src/renderer/src/scene/raisedFaces.ts b/studio/src/renderer/src/scene/raisedFaces.ts new file mode 100644 index 000000000..0abb19fad --- /dev/null +++ b/studio/src/renderer/src/scene/raisedFaces.ts @@ -0,0 +1,71 @@ +import type { FaceLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { shaded } from './columnFaces' +import { FACE_LIGHT } from './coverLooks' +import type { Picture, QuadBatch, Vec3 } from './quadBatch' +import type { RaisedBlock } from './terrainMesh' +import { sunk, tintAt } from './waterTint' + +/** One face of a whole block: the step to the block it touches, and its quad on a block of {@code step} wide. */ +interface BlockFace { + columnStep: number + yStep: number + rowStep: number + light: number + /** Which of the block's pictures the face shows, and whether that picture stands upright. */ + picture: (look: NonNullable) => FaceLook + standing: boolean + /** The quad's corner, along and up from the block's lowest north west corner; it faces the way up crosses along. */ + quad: (step: number) => [Vec3, Vec3, Vec3] +} + +// A block's bottom shows the picture of its top, as the end of a log does. +const BLOCK_FACES: readonly BlockFace[] = [ + { columnStep: 0, yStep: 1, rowStep: 0, light: FACE_LIGHT.up, picture: (look) => look.top, standing: false, quad: (step) => [[0, 1, 0], [step, 0, 0], [0, 0, step]] }, + { columnStep: 0, yStep: -1, rowStep: 0, light: FACE_LIGHT.down, picture: (look) => look.top, standing: false, quad: (step) => [[0, 0, 0], [0, 0, step], [step, 0, 0]] }, + { columnStep: 0, yStep: 0, rowStep: -1, light: FACE_LIGHT.north, picture: (look) => look.side, standing: true, quad: (step) => [[0, 0, 0], [step, 0, 0], [0, 1, 0]] }, + { columnStep: 0, yStep: 0, rowStep: 1, light: FACE_LIGHT.south, picture: (look) => look.side, standing: true, quad: (step) => [[step, 0, step], [-step, 0, 0], [0, 1, 0]] }, + { columnStep: -1, yStep: 0, rowStep: 0, light: FACE_LIGHT.west, picture: (look) => look.side, standing: true, quad: (step) => [[0, 0, step], [0, 0, -step], [0, 1, 0]] }, + { columnStep: 1, yStep: 0, rowStep: 0, light: FACE_LIGHT.east, picture: (look) => look.side, standing: true, quad: (step) => [[step, 0, 0], [0, 0, step], [0, 1, 0]] } +] + +/** Whether what lies behind a raised block shows through its pictures, as through leaves; never for one shown in its colour. */ +export function isSeeThrough(block: RaisedBlock): boolean { + return block.look !== null && (block.look.top.cell.hasGaps || block.look.side.cell.hasGaps) +} + +/** + * The blocks raised above the ground, such as trees, as whole blocks: each face that touches neither the ground nor an + * opaque raised block. Blocks that are seen through, such as leaves, go to {@code seeThrough}, to be drawn cut out, and + * hide nothing they touch, as Minecraft draws leaves with fancy graphics. A face at the field's edge is drawn, as the + * field next to it is not known here. Blocks under water sink toward its deep colour as the ground does. + */ +export function addRaisedFaces(field: ColumnField, opaque: QuadBatch, seeThrough: QuadBatch): void { + const step = field.blocksPerColumn + for (let row = 0; row < field.rows; row++) { + for (let column = 0; column < field.columns; column++) { + const index = field.indexOf(column, row) + const water = field.waterTopAt(column, row) + for (const block of field.raised[index]) { + const corner: Vec3 = [field.originX + column * step, block.y, field.originZ + row * step] + const batch = isSeeThrough(block) ? seeThrough : opaque + for (const face of BLOCK_FACES) { + if (field.isOpaqueAt(column + face.columnStep, row + face.rowStep, block.y + face.yStep)) { + continue + } + addFace(batch, face, corner, step, block, water) + } + } + } + } +} + +function addFace(batch: QuadBatch, face: BlockFace, corner: Vec3, step: number, block: RaisedBlock, water: number | null): void { + const [start, along, up] = face.quad(step) + const origin: Vec3 = [corner[0] + start[0], corner[1] + start[1], corner[2] + start[2]] + const look = block.look === null ? null : face.picture(block.look) + const light = shaded(look === null ? block.color : look.tint, face.light) + const color = water === null ? light : sunk(light, tintAt(water - (block.y + start[1]))) + const picture: Picture | null = look === null ? null : { cell: look.cell, standing: face.standing } + batch.add(origin, along, up, color, color, picture) +} diff --git a/studio/src/renderer/src/scene/runFaces.test.ts b/studio/src/renderer/src/scene/runFaces.test.ts new file mode 100644 index 000000000..065299a1f --- /dev/null +++ b/studio/src/renderer/src/scene/runFaces.test.ts @@ -0,0 +1,121 @@ +import { Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { ColumnField } from './columnField' +import { runFaces, uncovered, type SurfaceRuns } from './runFaces' +import type { TerrainSurface } from './terrainMesh' + +const GROUND = 10 +const BASE = 0 +const CANOPY_BOTTOM = 14 +const CANOPY_TOP = 15 +const FULLY_LIT = 15 * 16 + +// Two columns of plain ground side by side, their tops lit and darkened as given. +function flatRuns(lights: Uint8Array, occlusions: Uint8Array): SurfaceRuns['runs'] { + return { + starts: Int32Array.of(0, 1, 2), + bottoms: Int16Array.of(0, 0), + tops: Int16Array.of(GROUND, GROUND), + blocks: Int16Array.of(0, 0), + covers: Int16Array.of(-1, -1), + coverShares: new Uint8Array(2), + lights, + occlusions + } +} + +// Two columns side by side, a block each: plain ground on the west, ground with a canopy floating over it on the east. +const surface: TerrainSurface = { + columns: 2, + rows: 1, + originX: 0, + originZ: 0, + blocksPerColumn: 1, + groundAt: () => GROUND, + waterAt: () => null, + colorAt: () => 0x808080 +} + +const runs: SurfaceRuns = { + runs: { + starts: Int32Array.of(0, 1, 3), + bottoms: Int16Array.of(0, CANOPY_BOTTOM, 0), + tops: Int16Array.of(GROUND, CANOPY_TOP, GROUND), + blocks: Int16Array.of(0, 1, 0), + covers: Int16Array.of(-1, -1, -1), + coverShares: new Uint8Array(3), + lights: new Uint8Array(3).fill(FULLY_LIT), + occlusions: new Uint8Array(3) + }, + cellAt: (column) => column, + looks: [null, null], + colors: [0x808080, 0x00ff00] +} + +function faces(): { middle: Vector3; normal: Vector3 }[] { + const geometry = runFaces(new ColumnField(surface), runs, BASE).geometry() + const positions = geometry.getAttribute('position') + const found: { middle: Vector3; normal: Vector3 }[] = [] + for (let first = 0; first < positions.count; first += 4) { + const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, first + index) + const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)] + found.push({ middle: origin.clone().add(far).multiplyScalar(0.5), normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize() }) + } + return found +} + +describe('run faces', () => { + it('finds the parts of a span its neighbours leave open', () => { + expect(uncovered({ bottom: 0, top: 10 }, [{ bottom: 3, top: 5 }])).toEqual([{ bottom: 0, top: 2 }, { bottom: 6, top: 10 }]) + expect(uncovered({ bottom: -Infinity, top: 10 }, [{ bottom: -Infinity, top: 12 }])).toEqual([]) + }) + + it('draws the tops of neighbouring columns at one height in one block as one face', () => { + const flat: SurfaceRuns = { ...runs, runs: flatRuns(new Uint8Array(2).fill(FULLY_LIT), new Uint8Array(2)) } + const geometry = runFaces(new ColumnField(surface), flat, BASE).geometry() + const positions = geometry.getAttribute('position') + const tops = [] + for (let first = 0; first < positions.count; first += 4) { + if (positions.getY(first) === GROUND + 1 && positions.getY(first + 3) === GROUND + 1) { + tops.push(Math.abs(positions.getX(first + 3) - positions.getX(first))) + } + } + + expect(tops).toEqual([2]) + }) + + it('darkens a top by the mean light and corner shade of the blocks it stands for', () => { + const shaded: SurfaceRuns = { ...runs, runs: flatRuns(Uint8Array.of(FULLY_LIT, 10 * 16), Uint8Array.of(0, 32)) } + const geometry = runFaces(new ColumnField(surface), shaded, BASE).geometry() + const positions = geometry.getAttribute('position') + const colors = geometry.getAttribute('color') + const topColorAt = (x: number): number => { + for (let first = 0; first < positions.count; first += 4) { + if (positions.getY(first) === GROUND + 1 && positions.getY(first + 3) === GROUND + 1 && Math.min(positions.getX(first), positions.getX(first + 3)) === x) { + return colors.getX(first) + } + } + return NaN + } + + expect(topColorAt(1)).toBeLessThan(topColorAt(0) * 0.7) + }) + + it('floats a canopy over the ground with its underside showing', () => { + const drawn = faces() + + expect(drawn.some((face) => face.normal.y === -1 && face.middle.y === CANOPY_BOTTOM && face.middle.x === 1.5)).toBe(true) + expect(drawn.some((face) => face.normal.y === 1 && face.middle.y === CANOPY_TOP + 1 && face.middle.x === 1.5)).toBe(true) + }) + + it('shows the side of a run toward a neighbour where the neighbour leaves it open, and walls the field edge down to the base', () => { + const drawn = faces() + const canopyWest = drawn.filter((face) => face.normal.x === -1 && face.middle.x === 1) + const groundBetween = drawn.filter((face) => face.normal.x !== 0 && face.middle.x === 1 && face.middle.y <= GROUND + 1) + + expect(canopyWest.map((face) => face.middle.y).sort()).toEqual([CANOPY_BOTTOM + 0.5, CANOPY_TOP + 0.5]) + expect(groundBetween).toEqual([]) + // Under the top block's side, the wall at the field's edge reaches from the base to the ground's top block. + expect(drawn.some((face) => face.normal.x === -1 && face.middle.x === 0 && face.middle.y === (BASE + GROUND) / 2)).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/scene/runFaces.ts b/studio/src/renderer/src/scene/runFaces.ts new file mode 100644 index 000000000..6576756eb --- /dev/null +++ b/studio/src/renderer/src/scene/runFaces.ts @@ -0,0 +1,258 @@ +import { NO_BLOCK, RUN_LIGHT_STEPS, RUN_OCCLUSION_STEPS, type TileRuns } from '../bridge/types' +import { brightnessOfCorner, brightnessOfLight } from './skyLight' +import type { Direction } from './blockModels' +import type { BlockLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { shaded } from './columnFaces' +import { FACE_LIGHT } from './coverLooks' +import { QuadBatch, type Vec3 } from './quadBatch' +import { sunk, tintAt } from './waterTint' + +/** A coarser tile's runs of solid blocks, and how to colour the blocks they name. */ +export interface SurfaceRuns { + runs: TileRuns + /** Where a column's runs lie in {@link runs}, by its column and row. */ + cellAt(column: number, row: number): number + looks: readonly (BlockLook | null)[] + colors: readonly number[] +} + +interface Side { + direction: Direction + columnStep: number + rowStep: number +} + +const SIDES: readonly Side[] = [ + { direction: 'north', columnStep: 0, rowStep: -1 }, + { direction: 'south', columnStep: 0, rowStep: 1 }, + { direction: 'west', columnStep: -1, rowStep: 0 }, + { direction: 'east', columnStep: 1, rowStep: 0 } +] + +/** A span of heights, both ends included. */ +interface Span { + bottom: number + top: number +} + +/** + * A coarser tile's ground in 3D: each run of solid blocks of each column as a box as wide as the column, with its top, + * its underside where it floats, and its sides where the columns beside it leave them in the open. The ground reaches + * down to the run under its neighbours' tops, or to {@code base} at the field's edge and beside holes, so tiles next to + * each other leave no cracks. Each face takes the average colour of its block's picture on that side, as the textures of + * finer ground fade to it with distance, so the change from one to the other cannot be seen. Faces of neighbouring + * columns that lie in one plane over the same heights in the same colour are one face. + */ +export function runFaces(field: ColumnField, surface: SurfaceRuns, base: number): QuadBatch { + const faces = new MergedFaces(field) + for (let row = 0; row < field.rows; row++) { + for (let column = 0; column < field.columns; column++) { + if (field.hasGround(column, row)) { + addColumn(faces, field, surface, column, row, base) + } + } + } + return faces.batch() +} + +function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns, column: number, row: number, base: number): void { + const { runs } = surface + const cell = surface.cellAt(column, row) + const first = runs.starts[cell] + const last = runs.starts[cell + 1] - 1 + const water = field.waterTopAt(column, row) + for (let run = first; run <= last; run++) { + const isGround = run === last + const top = runs.tops[run] + const bottom = runs.bottoms[run] + const block = runs.blocks[run] + const light = brightnessOfLight(runs.lights[run] / RUN_LIGHT_STEPS) + if (run === first || runs.bottoms[run - 1] !== top + 1) { + const topLight = light * brightnessOfCorner(runs.occlusions[run] / RUN_OCCLUSION_STEPS) + const color = underWater(lit(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), topLight), top + 1, water) + faces.add('up', row, column, top + 1, top + 1, color, color) + } + if (!isGround && (run === last || runs.tops[run + 1] !== bottom - 1)) { + const color = underWater(lit(colorOf(surface, block, 'top', FACE_LIGHT.down), light), bottom, water) + faces.add('down', row, column, bottom, bottom, color, color) + } + for (const side of SIDES) { + const neighbour = [column + side.columnStep, row + side.rowStep] as const + const known = field.hasGround(...neighbour) && hasRuns(surface, surface.cellAt(...neighbour)) + const lowest = isGround ? (known ? -Infinity : base) : bottom + const covered = known ? spansOf(surface, surface.cellAt(...neighbour)) : [] + for (const open of uncovered({ bottom: lowest, top }, covered)) { + addSide(faces, surface, column, row, side, open, top, block, water, light) + } + } + } +} + +function hasRuns(surface: SurfaceRuns, cell: number): boolean { + return surface.runs.starts[cell + 1] > surface.runs.starts[cell] +} + +// The heights of a column its runs fill, the ground's reaching all the way down. +function spansOf(surface: SurfaceRuns, cell: number): Span[] { + const { runs } = surface + const spans: Span[] = [] + const last = runs.starts[cell + 1] - 1 + for (let run = runs.starts[cell]; run <= last; run++) { + spans.push({ bottom: run === last ? -Infinity : runs.bottoms[run], top: runs.tops[run] }) + } + return spans +} + +/** The parts of {@code span} none of {@code covered} fills, lowest first. */ +export function uncovered(span: Span, covered: readonly Span[]): Span[] { + let open: Span[] = [span] + for (const cover of covered) { + open = open.flatMap((part) => { + if (cover.top < part.bottom || cover.bottom > part.top) { + return [part] + } + const left: Span[] = [] + if (cover.bottom > part.bottom) { + left.push({ bottom: part.bottom, top: cover.bottom - 1 }) + } + if (cover.top < part.top) { + left.push({ bottom: cover.top + 1, top: part.top }) + } + return left + }) + } + return open.filter((part) => part.top >= part.bottom).sort((first, second) => first.bottom - second.bottom) +} + +// The top block of a run shows its side picture; the blocks under it, the picture of the blocks under a column's top. +// Sides take the light of the run's top, as the open air beside it mostly holds. +function addSide( + faces: MergedFaces, + surface: SurfaceRuns, + column: number, + row: number, + side: Side, + open: Span, + runTop: number, + block: number, + water: number | null, + skyLight: number +): void { + const light = side.direction === 'north' || side.direction === 'south' ? FACE_LIGHT.north : FACE_LIGHT.west + if (open.top === runTop) { + const color = lit(colorOf(surface, block, 'side', light), skyLight) + faces.add(side.direction, row, column, runTop, runTop + 1, underWater(color, runTop, water), underWater(color, runTop + 1, water)) + } + const belowTop = open.top === runTop ? runTop - 1 : open.top + if (belowTop >= open.bottom) { + const color = lit(colorOf(surface, block, 'below', light), skyLight) + faces.add(side.direction, row, column, open.bottom, belowTop + 1, underWater(color, open.bottom, water), underWater(color, belowTop + 1, water)) + } +} + +function lit(color: Vec3, brightness: number): Vec3 { + return [color[0] * brightness, color[1] * brightness, color[2] * brightness] +} + +function colorOf(surface: SurfaceRuns, block: number, face: 'top' | 'side' | 'below', light: number): Vec3 { + const look = surface.looks[block] + return shaded(look === null || look === undefined ? surface.colors[block] : look[face].color, light) +} + +// Seen from afar, the plants on a block hide this much of its top where they stand. +const PLANT_COVER = 0.5 +const WHOLE_SHARE = 255 + +// Near ground draws its grass and flowers, which colour it seen from afar; the run's top takes their colour as they would. +function withPlants(surface: SurfaceRuns, run: number, color: Vec3): Vec3 { + const plant = surface.runs.covers[run] + if (plant === NO_BLOCK) { + return color + } + const share = (surface.runs.coverShares[run] / WHOLE_SHARE) * PLANT_COVER + const plantColor = shaded(surface.colors[plant], FACE_LIGHT.up) + return [color[0] + (plantColor[0] - color[0]) * share, color[1] + (plantColor[1] - color[1]) * share, color[2] + (plantColor[2] - color[2]) * share] +} + +function underWater(color: Vec3, y: number, water: number | null): Vec3 { + return water === null ? color : sunk(color, tintAt(water - y)) +} + +/** Faces that lie along one line of columns in one plane, over the same heights in the same colours, and where along it they stand. */ +interface FaceLine { + direction: Direction + /** The row of the line, or its column for faces looking west or east. */ + lane: number + from: number + to: number + bottomColor: Vec3 + topColor: Vec3 + /** The columns along the line, or rows for faces looking west or east, in the order they were added. */ + places: number[] +} + +/** + * Column faces gathered first and drawn as few quads as they allow: faces of columns next to each other along a row, or + * along a column for faces looking west or east, that lie at the same heights in the same colours become one. + */ +class MergedFaces { + private readonly lines = new Map() + + constructor(private readonly field: ColumnField) {} + + /** A face of the column; tops and undersides lie at {@code from}, sides reach from {@code from} to {@code to}. */ + add(direction: Direction, row: number, column: number, from: number, to: number, bottomColor: Vec3, topColor: Vec3): void { + const alongColumns = direction !== 'west' && direction !== 'east' + const lane = alongColumns ? row : column + const key = `${direction}|${lane}|${from}|${to}|${bottomColor.join(',')}|${topColor.join(',')}` + let line = this.lines.get(key) + if (line === undefined) { + line = { direction, lane, from, to, bottomColor, topColor, places: [] } + this.lines.set(key, line) + } + line.places.push(alongColumns ? column : row) + } + + batch(): QuadBatch { + const batch = new QuadBatch(true) + for (const line of this.lines.values()) { + let start = 0 + for (let at = 1; at <= line.places.length; at++) { + if (at === line.places.length || line.places[at] !== line.places[at - 1] + 1) { + this.addQuad(batch, line, line.places[start], at - start) + start = at + } + } + } + return batch + } + + private addQuad(batch: QuadBatch, line: FaceLine, first: number, count: number): void { + const step = this.field.blocksPerColumn + const { originX, originZ } = this.field + const length = count * step + const lane = line.lane * step + const along = first * step + const height: Vec3 = [0, line.to - line.from, 0] + switch (line.direction) { + case 'up': + batch.add([originX + along, line.from, originZ + lane], [length, 0, 0], [0, 0, step], line.bottomColor, line.topColor) + return + case 'down': + batch.add([originX + along, line.from, originZ + lane], [0, 0, step], [length, 0, 0], line.bottomColor, line.topColor) + return + case 'north': + batch.add([originX + along, line.from, originZ + lane], [length, 0, 0], height, line.bottomColor, line.topColor) + return + case 'south': + batch.add([originX + along + length, line.from, originZ + lane + step], [-length, 0, 0], height, line.bottomColor, line.topColor) + return + case 'west': + batch.add([originX + lane, line.from, originZ + along + length], [0, 0, -length], height, line.bottomColor, line.topColor) + return + case 'east': + batch.add([originX + lane + step, line.from, originZ + along], [0, 0, length], height, line.bottomColor, line.topColor) + } + } +} diff --git a/studio/src/renderer/src/scene/savedTerrain.test.ts b/studio/src/renderer/src/scene/savedTerrain.test.ts new file mode 100644 index 000000000..4387f1167 --- /dev/null +++ b/studio/src/renderer/src/scene/savedTerrain.test.ts @@ -0,0 +1,64 @@ +import { Texture } from 'three' +import { describe, expect, it } from 'vitest' +import type { SavedTile } from '../bridge/types' +import type { BlockLook } from './blockLooks' +import { SavedTerrain, type ReadSavedTile, type SavedTerrainColoring } from './savedTerrain' +import { cellAt, type TerrainPictures } from './terrainAtlas' + +const GRASS = 'minecraft:grass_block[snowy=false]' +const STONE = 'minecraft:stone' +const FACE = { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 } +const LOOK: BlockLook = { top: FACE, side: FACE, below: FACE } +const pictures: TerrainPictures = { texture: new Texture(), cutouts: new Texture(), plain: cellAt(0, 0xffffff) } + +// Two by two columns: grass, stone, then two of stone. +const tile = { + size: 2, + blocksPerPixel: 1, + groundY: Int16Array.of(64, 64, 64, 64), + waterSurfaceY: Int16Array.of(-1, -1, -1, -1), + blocks: Int16Array.of(0, 1, 1, 1), + biomes: Int16Array.of(0, 0, 0, 0), + blockNames: ['minecraft:grass_block', STONE], + blocksDrawnAs: [GRASS, STONE], + biomeLabels: [{ color: 0x00ff00 }], + noGround: -32768, + noWater: -1 +} as unknown as SavedTile + +const read: ReadSavedTile = { + tile, + blockColors: new Map([ + [GRASS, 0x4a7a2a], + [STONE, 0x7f7f7f] + ]), + blockLooks: new Map([[GRASS, LOOK]]) +} + +function terrain(coloring: SavedTerrainColoring, level = 0): SavedTerrain { + return new SavedTerrain(read, { level, tileX: 0, tileZ: 0 }, coloring, null, pictures) +} + +describe('saved terrain looks', () => { + it('shows the look of the block of a column when coloured by blocks and a column is a block', () => { + expect(terrain('blocks').lookAt(0, 0)).toBe(LOOK) + }) + + it('has no look for a block without one', () => { + expect(terrain('blocks').lookAt(1, 0)).toBeNull() + }) + + it('has none in the other colourings', () => { + expect(terrain('biomes').lookAt(0, 0)).toBeNull() + expect(terrain('height').lookAt(0, 0)).toBeNull() + }) + + it('has none where a column is wider than a block', () => { + expect(terrain('blocks', 1).lookAt(0, 0)).toBeNull() + }) + + it('still colours by block where there is no look', () => { + expect(terrain('blocks').colorAt(0, 0)).toBe(0x4a7a2a) + expect(terrain('blocks').colorAt(1, 0)).toBe(0x7f7f7f) + }) +}) diff --git a/studio/src/renderer/src/scene/savedTerrain.ts b/studio/src/renderer/src/scene/savedTerrain.ts new file mode 100644 index 000000000..aef9a2992 --- /dev/null +++ b/studio/src/renderer/src/scene/savedTerrain.ts @@ -0,0 +1,81 @@ +import type { SavedTile } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import type { BlockLook } from './blockLooks' +import type { TerrainPictures } from './terrainAtlas' +import type { TerrainSurface } from './terrainMesh' +import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' + +export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height' + +/** A saved tile, the colour of every state its blocks are drawn as, and the look of each where the tile is fine enough to show textures. */ +export interface ReadSavedTile { + tile: SavedTile + blockColors: Map + blockLooks: Map +} + +// A world without water is measured from where vanilla's sea would be. +const VANILLA_SEA_LEVEL = 63 +const UNKNOWN_BLOCK_COLOR = 0x7f7f7f +export const FINEST_BLOCKS_PER_COLUMN = 1 + +/** + * One saved tile as a surface, a column to a pixel, so each is the block it was read from. Coloured by blocks, columns a + * block wide show their blocks' textures. + */ +export class SavedTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + readonly originX: number + readonly originZ: number + readonly blocksPerColumn: number + + constructor( + private readonly read: ReadSavedTile, + place: TerrainTile, + private readonly coloring: SavedTerrainColoring, + private readonly seaLevel: number | null, + readonly pictures: TerrainPictures + ) { + this.columns = read.tile.size + this.rows = read.tile.size + this.originX = originXOf(place) + this.originZ = originZOf(place) + this.blocksPerColumn = blocksPerColumn(place.level) + } + + groundAt(column: number, row: number): number | null { + const ground = this.read.tile.groundY[this.pixelAt(column, row)] + return ground === this.read.tile.noGround ? null : ground + } + + waterAt(column: number, row: number): number | null { + const water = this.read.tile.waterSurfaceY[this.pixelAt(column, row)] + return water === this.read.tile.noWater ? null : water + } + + lookAt(column: number, row: number): BlockLook | null { + if (this.coloring !== 'blocks' || this.blocksPerColumn !== FINEST_BLOCKS_PER_COLUMN) { + return null + } + const { tile, blockLooks } = this.read + return blockLooks.get(tile.blocksDrawnAs[tile.blocks[this.pixelAt(column, row)]]) ?? null + } + + colorAt(column: number, row: number): number { + const { tile, blockColors } = this.read + const pixel = this.pixelAt(column, row) + switch (this.coloring) { + case 'height': + return heightColor(tile.groundY[pixel], this.seaLevel ?? VANILLA_SEA_LEVEL) + case 'blocks': + return blockColors.get(tile.blocksDrawnAs[tile.blocks[pixel]]) ?? UNKNOWN_BLOCK_COLOR + case 'biomes': + return tile.biomeLabels[tile.biomes[pixel]].color + } + } + + private pixelAt(column: number, row: number): number { + return row * this.read.tile.size + column + } +} diff --git a/studio/src/renderer/src/scene/savedTileSource.ts b/studio/src/renderer/src/scene/savedTileSource.ts new file mode 100644 index 000000000..5adf56a00 --- /dev/null +++ b/studio/src/renderer/src/scene/savedTileSource.ts @@ -0,0 +1,31 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { TileSource } from '../map/TileStore' +import type { BlockColors } from './blockColors' +import type { BlockLook, BlockLooks } from './blockLooks' +import { FINEST_BLOCKS_PER_COLUMN, type ReadSavedTile } from './savedTerrain' +import { TILE_COLUMNS } from './terrainTiles' + +/** Which saved world the tiles are read from. */ +export interface SavedLayer { + worldId: string + /** Bumped to read the region files again, so older tiles are not used again. */ + readings: number +} + +// The block and biome names and colours a tile carries, as far as they add up. +const ESTIMATED_EXTRA_BYTES_PER_COLUMN = 4 + +/** A saved world's tiles, each with the colour of every block in it, and their looks where a column is one block. */ +export function savedTileSource(client: BridgeClient, blockColors: BlockColors, blockLooks: BlockLooks): TileSource { + return { + layerKey: (layer) => `${layer.worldId}/${layer.readings}`, + fetch: async (address, layer, signal) => { + const tile = await client.savedTile(layer.worldId, address.tileX, address.tileZ, address.blocksPerPixel, TILE_COLUMNS, signal) + const textured = address.blocksPerPixel === FINEST_BLOCKS_PER_COLUMN + const [colors, looks] = await Promise.all([blockColors.colorsOf(tile.blocksDrawnAs), textured ? blockLooks.looksOf(tile.blocksDrawnAs) : new Map()]) + return { tile, blockColors: colors, blockLooks: looks } + }, + bytesOf: ({ tile }) => + tile.groundY.byteLength + tile.waterSurfaceY.byteLength + tile.blocks.byteLength + tile.biomes.byteLength + tile.size * tile.size * ESTIMATED_EXTRA_BYTES_PER_COLUMN + } +} diff --git a/studio/src/renderer/src/scene/sceneDecoding.ts b/studio/src/renderer/src/scene/sceneDecoding.ts new file mode 100644 index 000000000..6a06858ea --- /dev/null +++ b/studio/src/renderer/src/scene/sceneDecoding.ts @@ -0,0 +1,32 @@ +/** A block scene as the bridge encodes it (Iris SceneEncoding). */ +export interface BlockScene { + /** The block states the scene uses, once each. */ + palette: string[] + /** Four numbers per block: x, y, z from the scene's anchor, then the index of its state in the palette. */ + blocks: Int32Array + /** The lowest corner from the anchor, inclusive; {@code max} the highest, exclusive. */ + min: [number, number, number] + max: [number, number, number] +} + +interface Header { + palette: string[] + blockCount: number + min: [number, number, number] + max: [number, number, number] +} + +export const INTS_PER_BLOCK = 4 +const ALIGNMENT_BYTES = 4 + +export function decodeScene(buffer: ArrayBuffer): BlockScene { + const headerLength = new DataView(buffer).getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as Header + const blocksAt = Math.ceil((4 + headerLength) / ALIGNMENT_BYTES) * ALIGNMENT_BYTES + return { + palette: header.palette, + blocks: new Int32Array(buffer, blocksAt, header.blockCount * INTS_PER_BLOCK), + min: header.min, + max: header.max + } +} diff --git a/studio/src/renderer/src/scene/sceneMesh.ts b/studio/src/renderer/src/scene/sceneMesh.ts new file mode 100644 index 000000000..6c96c4259 --- /dev/null +++ b/studio/src/renderer/src/scene/sceneMesh.ts @@ -0,0 +1,201 @@ +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' +import { FACE_LIGHT } from './coverLooks' +import { countFarLeaves, isFarLeaf } from './farLeaves' +import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding' +import { TextureAtlas, type ImageSource } from './textureAtlas' + +export interface SceneMesh { + content: ViewportContent + /** Block states the client has no blockstate file for, drawn as magenta and black cubes. */ + unknownStates: string[] + /** Frees the mesh's geometry, material and atlas. */ + dispose(): void +} + +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 + +const MISSING_TEXTURE = 'iris:missing' +const NEIGHBOUR_OFFSETS: Record = { + down: [0, -1, 0], + up: [0, 1, 0], + north: [0, 0, -1], + south: [0, 0, 1], + west: [-1, 0, 0], + east: [1, 0, 0] +} +const CORNERS_PER_QUAD = 4 +const INDICES_PER_QUAD = 6 + +interface PaletteEntry { + model: BlockModel + name: string + properties: Record + /** Hides the faces of its neighbours that touch it. */ + solid: boolean + /** Whether its blocks are drawn at all. */ + 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. 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, + 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) + const drawn = resolved.map((model) => drawnModel(model)) + const atlas = await TextureAtlas.of( + drawn.flatMap((model) => model.quads.map((quad) => quad.texture)), + images + ) + const palette = drawn.map((model, index): PaletteEntry => { + const state = parseState(scene.palette[index]) + const shown = !singlingOutFarLeaves || isFarLeaf(scene.palette[index]) + 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 { 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, bounds }, + unknownStates, + dispose: () => { + solidGeometry.dispose() + faintGeometry.dispose() + solidMaterial.dispose() + faintMaterial.dispose() + atlas.dispose() + } + } +} + +// The client draws chests, signs, water and the like without a block model; their break texture stands in for them. +function drawnModel(model: BlockModel | null): BlockModel { + if (model === null) { + return cubeModel(MISSING_TEXTURE) + } + if (model.quads.length === 0) { + return cubeModel(model.particle ?? MISSING_TEXTURE) + } + return model +} + +// 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]] + const entry = palette[paletteIndex] + 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 + } + 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) + const indices = new Uint32Array(visible.length * INDICES_PER_QUAD) + visible.forEach(({ quad, entry, x, y, z }, quadIndex) => { + const cell = atlas.cell(quad.texture) + const light = quad.shade ? FACE_LIGHT[quad.facing] : 1 + const tint = blockTint(entry.name, entry.properties, quad.tintIndex) + const [red, green, blue] = [((tint >> 16) & 0xff) / 255, ((tint >> 8) & 0xff) / 255, (tint & 0xff) / 255] + for (let corner = 0; corner < CORNERS_PER_QUAD; corner++) { + const vertex = quadIndex * CORNERS_PER_QUAD + corner + const [cornerX, cornerY, cornerZ] = quad.corners[corner] + positions.set([x + cornerX, y + cornerY, z + cornerZ], vertex * 3) + uvs.set([cell.u + quad.uvs[corner][0] * cell.width, cell.v + quad.uvs[corner][1] * cell.height], vertex * 2) + colors.set([red * light, green * light, blue * light], vertex * 3) + } + const first = quadIndex * CORNERS_PER_QUAD + indices.set([first, first + 1, first + 2, first, first + 2, first + 3], quadIndex * INDICES_PER_QUAD) + }) + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(positions, 3)) + geometry.setAttribute('uv', new BufferAttribute(uvs, 2)) + geometry.setAttribute('color', new BufferAttribute(colors, 3)) + geometry.setIndex(new BufferAttribute(indices, 1)) + geometry.computeBoundingSphere() + return geometry +} + +/** Which spots of the scene hold a solid block, in a grid over its bounds. */ +class SolidBlocks { + private readonly solid: Uint8Array + private readonly sizeX: number + private readonly sizeY: number + private readonly sizeZ: number + + 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) { + 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 + } + } + } + + besides(x: number, y: number, z: number, side: Direction): boolean { + const [dx, dy, dz] = NEIGHBOUR_OFFSETS[side] + const index = this.indexOf(x + dx, y + dy, z + dz) + return index >= 0 && this.solid[index] === 1 + } + + private indexOf(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]] + if (localX < 0 || localY < 0 || localZ < 0 || localX >= this.sizeX || localY >= this.sizeY || localZ >= this.sizeZ) { + return -1 + } + return (localX * this.sizeY + localY) * this.sizeZ + localZ + } +} diff --git a/studio/src/renderer/src/scene/skyLight.ts b/studio/src/renderer/src/scene/skyLight.ts new file mode 100644 index 000000000..e4c921121 --- /dev/null +++ b/studio/src/renderer/src/scene/skyLight.ts @@ -0,0 +1,39 @@ +/** + * How bright the server's sky light and corner darkening make a face, as Minecraft's smooth lighting shows them. A + * face's shade holds the sky's light in the cell it faces, 0 to {@link FULL_LIGHT}, in its lowest bits, then for each of + * its corners how many of the three cells around it are opaque. + */ + +export const FULL_LIGHT = 15 +const LIGHT_BITS = 4 +const CORNER_BITS = 2 +const LIGHT_MASK = (1 << LIGHT_BITS) - 1 +const CORNER_MASK = (1 << CORNER_BITS) - 1 +// Between Minecraft's Moody and Bright, so shade under trees reads without the forest floor going black. +const LIFT = 0.5 +// What a cell the sky never reaches still shows, so a cave mouth is dark but not a hole. +const DARKEST = 0.12 +// Each opaque cell around a corner takes this off its brightness; linear, so a far area's mean darkens as its blocks do. +const DARKENING_PER_OPAQUE_CELL = 0.2 + +/** The brightness of a cell lit at {@code light}, which may lie between levels, from {@link DARKEST} to 1. */ +export function brightnessOfLight(light: number): number { + const level = Math.min(FULL_LIGHT, Math.max(0, light)) / FULL_LIGHT + const moody = level / (4 - 3 * level) + const bright = 1 - (1 - moody) ** 4 + return DARKEST + (1 - DARKEST) * (moody + (bright - moody) * LIFT) +} + +/** How much a corner keeps of its brightness with {@code opaque} cells around it, which may be a mean. */ +export function brightnessOfCorner(opaque: number): number { + return 1 - DARKENING_PER_OPAQUE_CELL * opaque +} + +export function lightOf(shade: number): number { + return shade & LIGHT_MASK +} + +/** How many cells around a face's corner are opaque, the corners in the order the face's corners are drawn. */ +export function opaqueAround(shade: number, corner: number): number { + return (shade >> (LIGHT_BITS + corner * CORNER_BITS)) & CORNER_MASK +} diff --git a/studio/src/renderer/src/scene/surfaceMarch.test.ts b/studio/src/renderer/src/scene/surfaceMarch.test.ts new file mode 100644 index 000000000..3d258ef39 --- /dev/null +++ b/studio/src/renderer/src/scene/surfaceMarch.test.ts @@ -0,0 +1,72 @@ +import { Ray, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { ColumnField } from './columnField' +import { marchOntoSurface } from './surfaceMarch' + +const GROUND = 10 +const POND_GROUND = 7 +const WATER = 9 +const REACH = 500 +const CEILING = 100 + +// Three by three columns from (100, 200): nothing known at the north west corner, a pond at the middle column. +const field = new ColumnField({ + columns: 3, + rows: 3, + originX: 100, + originZ: 200, + blocksPerColumn: 1, + groundAt: (column, row) => (column === 0 && row === 0 ? null : column === 1 && row === 1 ? POND_GROUND : GROUND), + waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null), + colorAt: () => 0 +}) + +function pick(origin: Vector3, direction: Vector3): Vector3 | null { + return marchOntoSurface(new Ray(origin, direction.normalize()), REACH, CEILING, (x, z) => field.surfaceTopOver(x, z)) +} + +describe('marching onto the surface', () => { + it('finds the water over the pond and the top of the ground beside it', () => { + const water = pick(new Vector3(101.5, 30, 201.5), new Vector3(0, -1, 0))! + expect(water.x).toBeCloseTo(101.5, 3) + expect(water.y).toBeCloseTo(WATER + 1, 3) + expect(water.z).toBeCloseTo(201.5, 3) + expect(pick(new Vector3(102.5, 30, 201.5), new Vector3(0, -1, 0))!.y).toBeCloseTo(GROUND + 1, 3) + }) + + it('finds where a slanted ray meets the side of a column', () => { + expect(pick(new Vector3(95, GROUND, 202.5), new Vector3(1, -0.01, 0))!.x).toBeCloseTo(100, 1) + }) + + it('finds nothing over an unknown column, beside the field, or from below the ground', () => { + expect(pick(new Vector3(100.5, 30, 200.5), new Vector3(0, -1, 0))).toBeNull() + expect(pick(new Vector3(300, 30, 202.5), new Vector3(0, -1, 0))).toBeNull() + expect(pick(new Vector3(102.5, GROUND - 2, 202.5), new Vector3(0, 1, 0))).toBeNull() + }) + + it('meets the side where a ray comes in from the side below the top', () => { + const hit = pick(new Vector3(90, GROUND - 1, 202.5), new Vector3(1, 0, 0))! + expect(hit.x).toBeCloseTo(100, 3) + expect(hit.y).toBeCloseTo(GROUND - 1, 3) + }) + + it('gives up on a ray that climbs above the highest ground', () => { + expect(pick(new Vector3(95, 50, 202.5), new Vector3(1, 1, 0))).toBeNull() + }) + + it('reaches ground far away, where it steps further at a time', () => { + const far = new ColumnField({ + columns: 1, + rows: 1, + originX: 400, + originZ: 0, + blocksPerColumn: 64, + groundAt: () => GROUND, + waterAt: () => null, + colorAt: () => 0 + }) + const hit = marchOntoSurface(new Ray(new Vector3(0, 100, 30), new Vector3(1, -0.2, 0).normalize()), 5000, CEILING, (x, z) => far.surfaceTopOver(x, z))! + expect(hit.y).toBeCloseTo(GROUND + 1, 2) + expect(hit.x).toBeGreaterThan(400) + }) +}) diff --git a/studio/src/renderer/src/scene/surfaceMarch.ts b/studio/src/renderer/src/scene/surfaceMarch.ts new file mode 100644 index 000000000..d7ac5fc24 --- /dev/null +++ b/studio/src/renderer/src/scene/surfaceMarch.ts @@ -0,0 +1,47 @@ +import { Vector3, type Ray } from 'three' + +const FINEST_STEP_BLOCKS = 0.5 +// Further off, a step is longer: what lies there is drawn in coarser columns. +const STEP_PER_DISTANCE = 0.01 +const REFINEMENTS = 16 + +/** + * Where the ray first comes down onto the surface within {@code reach}, found by marching along it, so a pick does not + * have to test every face. {@code surfaceTopOver} says where the surface stands over a block, or null where nothing is + * known. A ray that starts below the surface, or leaves above {@code ceilingY}, finds nothing. + */ +export function marchOntoSurface(ray: Ray, reach: number, ceilingY: number, surfaceTopOver: (worldX: number, worldZ: number) => number | null): Vector3 | null { + const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(ray.origin) + const isBelow = (point: Vector3): boolean => { + const top = surfaceTopOver(point.x, point.z) + return top !== null && point.y <= top + } + if (isBelow(ray.origin)) { + return null + } + let above = 0 + while (above < reach) { + const below = Math.min(reach, above + Math.max(FINEST_STEP_BLOCKS, above * STEP_PER_DISTANCE)) + const point = pointAt(below) + if (isBelow(point)) { + return refined(above, below, pointAt, isBelow) + } + if (point.y > ceilingY && ray.direction.y >= 0) { + return null + } + above = below + } + return null +} + +function refined(above: number, below: number, pointAt: (distance: number) => Vector3, isBelow: (point: Vector3) => boolean): Vector3 { + for (let refinement = 0; refinement < REFINEMENTS; refinement++) { + const middle = (above + below) / 2 + if (isBelow(pointAt(middle))) { + below = middle + } else { + above = middle + } + } + return pointAt(below) +} diff --git a/studio/src/renderer/src/scene/surfacePick.test.ts b/studio/src/renderer/src/scene/surfacePick.test.ts new file mode 100644 index 000000000..d958b0e2d --- /dev/null +++ b/studio/src/renderer/src/scene/surfacePick.test.ts @@ -0,0 +1,34 @@ +import { Box3, BoxGeometry, Group, Mesh, MeshBasicMaterial, Ray, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import type { ViewportContent } from '../studio/SceneViewport' +import { surfaceAlong } from './surfacePick' + +const REACH = 100 + +function boxContent(): ViewportContent { + const object = new Group() + object.add(new Mesh(new BoxGeometry(2, 2, 2), new MeshBasicMaterial())) + object.updateMatrixWorld(true) + return { object, bounds: new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)) } +} + +function lookingDownTheDepth(x: number): Ray { + return new Ray(new Vector3(x, 0, 10), new Vector3(0, 0, -1)) +} + +describe('surface picking', () => { + it('finds the nearest face of the drawn meshes along the ray', () => { + expect(surfaceAlong(boxContent(), lookingDownTheDepth(0), REACH)!.toArray()).toEqual([0, 0, 1]) + }) + + it('finds nothing where the ray passes by or the surface lies beyond its reach', () => { + expect(surfaceAlong(boxContent(), lookingDownTheDepth(5), REACH)).toBeNull() + expect(surfaceAlong(boxContent(), lookingDownTheDepth(0), 5)).toBeNull() + }) + + it('asks the content when it knows its own surface', () => { + const known = new Vector3(1, 2, 3) + const content: ViewportContent = { ...boxContent(), surfaceAlong: () => known } + expect(surfaceAlong(content, lookingDownTheDepth(5), REACH)).toBe(known) + }) +}) diff --git a/studio/src/renderer/src/scene/surfacePick.ts b/studio/src/renderer/src/scene/surfacePick.ts new file mode 100644 index 000000000..84814a1ba --- /dev/null +++ b/studio/src/renderer/src/scene/surfacePick.ts @@ -0,0 +1,12 @@ +import { Raycaster, type Ray, type Vector3 } from 'three' +import type { ViewportContent } from '../studio/SceneViewport' + +/** Where the ray first meets what the content draws within {@code reach}, or null when it passes by. */ +export function surfaceAlong(content: ViewportContent, ray: Ray, reach: number): Vector3 | null { + if (content.surfaceAlong !== undefined) { + return content.surfaceAlong(ray, reach) + } + const caster = new Raycaster(ray.origin, ray.direction, 0, reach) + const [nearest] = caster.intersectObject(content.object, true) + return nearest === undefined ? null : nearest.point +} diff --git a/studio/src/renderer/src/scene/terrainAtlas.test.ts b/studio/src/renderer/src/scene/terrainAtlas.test.ts new file mode 100644 index 000000000..d1b0993cd --- /dev/null +++ b/studio/src/renderer/src/scene/terrainAtlas.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { cellAt, MOST_CELLS } from './terrainAtlas' + +const CELLS_PER_SIDE = Math.sqrt(MOST_CELLS) + +describe('terrain atlas cells', () => { + it('counts cells row by row from the top left', () => { + expect(cellAt(0, 0)).toMatchObject({ u: 0, v: 0 }) + expect(cellAt(1, 0).u).toBe(1 / CELLS_PER_SIDE) + expect(cellAt(CELLS_PER_SIDE, 0)).toMatchObject({ u: 0, v: 1 / CELLS_PER_SIDE }) + }) + + it('keeps every cell inside the atlas and apart from the others', () => { + const last = cellAt(MOST_CELLS - 1, 0) + expect(last.u + last.width).toBeCloseTo(1) + expect(last.v + last.height).toBeCloseTo(1) + expect(cellAt(5, 0).width).toBe(1 / CELLS_PER_SIDE) + }) + + it('carries the average colour of its picture', () => { + expect(cellAt(3, 0x336699).average).toBe(0x336699) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainAtlas.ts b/studio/src/renderer/src/scene/terrainAtlas.ts new file mode 100644 index 000000000..dd78cbdd1 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainAtlas.ts @@ -0,0 +1,207 @@ +import { CanvasTexture, NearestFilter, NearestMipmapLinearFilter, type Texture } from 'three' +import { averageColor } from './blockColors' +import { texturePath, type ImageSource } from './textureAtlas' + +/** Where one picture lies in the atlas, as a rectangle of it from 0 to 1, and the picture's average colour as 0xRRGGBB. */ +export interface UvCell { + u: number + v: number + width: number + height: number + average: number + /** Whether the picture is open in places, as leaves are between their twigs, so what lies behind shows through. */ + hasGaps: boolean +} + +/** The atlas as the terrain draws it. */ +export interface TerrainPictures { + readonly texture: Texture + /** Laid out as {@link texture}: white where a picture is drawn and black where it is open, for faces that are cut out. */ + readonly cutouts: Texture + /** A cell of plain white, for faces that show only their colour. */ + readonly plain: UvCell +} + +/** Where block pictures are placed. */ +export interface PictureSource { + /** The cell of the texture such as {@code minecraft:block/stone}, or null when it is missing or the atlas is full. */ + cellOf(textureId: string): Promise +} + +const CELL_PIXELS = 16 +const CELLS_PER_SIDE = 64 +const ATLAS_PIXELS = CELLS_PER_SIDE * CELL_PIXELS +const PLAIN_CELL = 0 +const WHITE = '#ffffff' +const WHITE_COLOR = 0xffffff +const OPAQUE_ALPHA = 255 +// The same line blockColors draws between a pixel that counts toward a picture's colour and one that does not. +const OPAQUE_ENOUGH_ALPHA = 128 +const GAP_SHADE = 0.6 + +/** The cell with this number, counted row by row from the top left. */ +export function cellAt(index: number, average: number, hasGaps = false): UvCell { + return { + u: (index % CELLS_PER_SIDE) / CELLS_PER_SIDE, + v: Math.floor(index / CELLS_PER_SIDE) / CELLS_PER_SIDE, + width: 1 / CELLS_PER_SIDE, + height: 1 / CELLS_PER_SIDE, + average, + hasGaps + } +} + +/** The most pictures one atlas holds, the plain cell among them. */ +export const MOST_CELLS = CELLS_PER_SIDE * CELLS_PER_SIDE + +/** + * Block textures of the terrain in one image, each scaled to 16 pixels and placed the first time it is asked for, so + * the atlas grows as tiles arrive; an animated texture shows its first frame. + */ +export class TerrainAtlas implements TerrainPictures, PictureSource { + readonly texture: CanvasTexture + readonly cutouts: CanvasTexture + readonly plain = cellAt(PLAIN_CELL, WHITE_COLOR) + + private readonly drawing: CanvasRenderingContext2D + private readonly cutoutDrawing: CanvasRenderingContext2D + /** The texture halved again and again, down to a pixel a picture. */ + private readonly smallerDrawings: CanvasRenderingContext2D[] + private readonly cells = new Map>() + private used = PLAIN_CELL + 1 + + constructor(private readonly images: ImageSource) { + ;[this.drawing, this.texture] = sheet() + ;[this.cutoutDrawing, this.cutouts] = sheet() + this.smallerDrawings = withSmallerSheets(this.texture) + for (const [level, drawing] of [this.drawing, ...this.smallerDrawings].entries()) { + drawing.fillStyle = WHITE + drawing.fillRect(0, 0, CELL_PIXELS >> level, CELL_PIXELS >> level) + } + this.cutoutDrawing.fillStyle = WHITE + this.cutoutDrawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS) + } + + cellOf(textureId: string): Promise { + let cell = this.cells.get(textureId) + if (cell === undefined) { + cell = this.place(textureId) + this.cells.set(textureId, cell) + } + return cell + } + + dispose(): void { + this.texture.dispose() + this.cutouts.dispose() + } + + private async place(textureId: string): Promise { + const bitmap = await this.images.image(texturePath(textureId)).catch(() => null) + if (bitmap === null || this.used >= MOST_CELLS) { + return null + } + const index = this.used++ + const placed = cellAt(index, WHITE_COLOR) + const left = placed.u * ATLAS_PIXELS + const top = placed.v * ATLAS_PIXELS + this.drawing.drawImage(bitmap, 0, 0, bitmap.width, Math.min(bitmap.width, bitmap.height), left, top, CELL_PIXELS, CELL_PIXELS) + const picture = this.drawing.getImageData(left, top, CELL_PIXELS, CELL_PIXELS) + const average = averageColor(picture) + const hasGaps = isOpenInPlaces(picture) + this.cutoutDrawing.putImageData(cutoutOf(picture), left, top) + let smaller = withGapsFilled(picture, average) + this.drawing.putImageData(smaller, left, top) + for (const [index, drawing] of this.smallerDrawings.entries()) { + smaller = halved(smaller) + drawing.putImageData(smaller, left >> (index + 1), top >> (index + 1)) + } + this.texture.needsUpdate = true + this.cutouts.needsUpdate = true + return { ...placed, average, hasGaps } + } +} + +function sheet(): [CanvasRenderingContext2D, CanvasTexture] { + const canvas = document.createElement('canvas') + canvas.width = ATLAS_PIXELS + canvas.height = ATLAS_PIXELS + const drawing = canvas.getContext('2d', { willReadFrequently: true })! + drawing.imageSmoothingEnabled = false + const texture = new CanvasTexture(canvas) + texture.magFilter = NearestFilter + texture.minFilter = NearestFilter + texture.generateMipmaps = false + texture.flipY = false + return [drawing, texture] +} + +// Far off, a texture is drawn smaller, down to a pixel a picture: its average, as the coarser ground's flat colour is, +// so the ground looks the same where it changes from textured blocks to coloured columns. Halving no further keeps every +// level's pictures apart, and the nearest pixel of a level never reaches into the picture beside it. +function withSmallerSheets(texture: CanvasTexture): CanvasRenderingContext2D[] { + const drawings: CanvasRenderingContext2D[] = [] + for (let level = 1; CELL_PIXELS >> level >= 1; level++) { + const canvas = document.createElement('canvas') + canvas.width = ATLAS_PIXELS >> level + canvas.height = ATLAS_PIXELS >> level + drawings.push(canvas.getContext('2d', { willReadFrequently: true })!) + } + texture.mipmaps = [texture.image, ...drawings.map((drawing) => drawing.canvas)] + texture.minFilter = NearestMipmapLinearFilter + return drawings +} + +/** The picture at half its size, each pixel the average of the four it covers. */ +export function halved(picture: ImageData): ImageData { + const width = Math.max(1, picture.width >> 1) + const height = Math.max(1, picture.height >> 1) + const half = new ImageData(width, height) + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let channel = 0; channel < 4; channel++) { + let sum = 0 + for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) { + sum += picture.data[((y * 2 + dy) * picture.width + x * 2 + dx) * 4 + channel] + } + half.data[(y * width + x) * 4 + channel] = Math.round(sum / 4) + } + } + } + return half +} + +function isOpenInPlaces(picture: ImageData): boolean { + for (let offset = 3; offset < picture.data.length; offset += 4) { + if (picture.data[offset] < OPAQUE_ENOUGH_ALPHA) { + return true + } + } + return false +} + +// A canvas keeps no colour under a transparent pixel, so the picture cannot carry both its filled gaps and where they were. +function cutoutOf(picture: ImageData): ImageData { + const cutout = new ImageData(picture.width, picture.height) + for (let offset = 0; offset < picture.data.length; offset += 4) { + const shade = picture.data[offset + 3] < OPAQUE_ENOUGH_ALPHA ? 0 : 255 + cutout.data.set([shade, shade, shade, OPAQUE_ALPHA], offset) + } + return cutout +} + +// The terrain draws whole faces, so what a picture leaves open, as leaves do between their twigs, would show as black: +// it takes the picture's own colour instead, darker, as the shade seen through the gaps. +function withGapsFilled(picture: ImageData, average: number): ImageData { + const pixels = picture.data + const gap = [(average >> 16) & 0xff, (average >> 8) & 0xff, average & 0xff].map((channel) => Math.round(channel * GAP_SHADE)) + for (let offset = 0; offset < pixels.length; offset += 4) { + if (pixels[offset + 3] < OPAQUE_ENOUGH_ALPHA) { + pixels[offset] = gap[0] + pixels[offset + 1] = gap[1] + pixels[offset + 2] = gap[2] + } + pixels[offset + 3] = OPAQUE_ALPHA + } + return picture +} diff --git a/studio/src/renderer/src/scene/terrainCover.test.ts b/studio/src/renderer/src/scene/terrainCover.test.ts new file mode 100644 index 000000000..d29e5a665 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainCover.test.ts @@ -0,0 +1,151 @@ +import { PerspectiveCamera, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { CameraSight } from './cameraSight' +import { planCover, type DrawnTile, type TileState } from './terrainCover' +import { addressOf, blocksPerColumn, columnsUnder, isInside, originXOf, originZOf, tileBlocks, tileKey, type TerrainTile } from './terrainTiles' + +const COARSEST_LEVEL = 12 +const LOOKED_AT = new Vector3(0, 64, 0) +const SAMPLE_RADIUS_BLOCKS = 300 +const SAMPLE_STEP_BLOCKS = 23 + +// Looks down at the ground around the origin from {@code height} blocks above it, from the south. +function sightFrom(height: number): CameraSight { + const camera = new PerspectiveCamera(45, 1.6, height * 0.01, height * 20) + camera.position.set(0, 64 + height, height * 0.6) + camera.lookAt(LOOKED_AT) + camera.updateMatrixWorld() + return new CameraSight({ camera, width: 1280, height: 800, orbitDistance: camera.position.distanceTo(LOOKED_AT) }, 0, 128) +} + +const nothingReady = (): TileState => 'none' +const everythingReady = (): TileState => 'fresh' + +function holeContains(draw: DrawnTile, x: number, z: number): boolean { + const step = blocksPerColumn(draw.tile.level) + const column = Math.floor((x - originXOf(draw.tile)) / step) + const row = Math.floor((z - originZOf(draw.tile)) / step) + return draw.holes.some((hole) => column >= hole.fromColumn && column < hole.toColumn && row >= hole.fromRow && row < hole.toRow) +} + +// How many drawn tiles show the ground at the block: one when finer tiles take over exactly where coarser ones have holes. +function drawnOver(draws: DrawnTile[], x: number, z: number): number { + return draws.filter((draw) => { + const size = tileBlocks(draw.tile.level) + const inside = x >= originXOf(draw.tile) && x < originXOf(draw.tile) + size && z >= originZOf(draw.tile) && z < originZOf(draw.tile) + size + return inside && !holeContains(draw, x, z) + }).length +} + +function expectEverySpotDrawnOnce(draws: DrawnTile[]): void { + for (let x = -SAMPLE_RADIUS_BLOCKS; x <= SAMPLE_RADIUS_BLOCKS; x += SAMPLE_STEP_BLOCKS) { + for (let z = -SAMPLE_RADIUS_BLOCKS; z <= SAMPLE_RADIUS_BLOCKS; z += SAMPLE_STEP_BLOCKS) { + expect(drawnOver(draws, x + 0.5, z + 0.5), `${x}, ${z}`).toBe(1) + } + } +} + +describe('terrain cover', () => { + it('asks for the coarse backdrop first, once for each tile', () => { + const { draws, wanted } = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL) + expect(draws).toEqual([]) + expect(wanted[0].level).toBe(Math.max(...wanted.map((tile) => tile.level))) + expect(new Set(wanted.map(tileKey)).size).toBe(wanted.length) + expect(Math.min(...wanted.map((tile) => tile.level))).toBeLessThan(wanted[0].level) + }) + + it('draws a quick stand-in only where no truer tile of any level is known', () => { + const sight = sightFrom(2000) + const backdrop = planCover(sight, nothingReady, COARSEST_LEVEL).wanted[0] + const quickEverywhere = (): TileState => 'quick' + const trueBackdrop = (tile: TerrainTile): TileState => (tileKey(tile) === tileKey(backdrop) ? 'fresh' : 'quick') + + const quickOnly = planCover(sight, quickEverywhere, COARSEST_LEVEL).draws + const withTrueBackdrop = planCover(sight, trueBackdrop, COARSEST_LEVEL).draws + + expect(quickOnly.length).toBeGreaterThan(0) + expectEverySpotDrawnOnce(quickOnly) + expect(withTrueBackdrop.some((draw) => tileKey(draw.tile) === tileKey(backdrop))).toBe(true) + expect(withTrueBackdrop.some((draw) => isInside(draw.tile, backdrop))).toBe(false) + }) + + it('keeps the true ground drawn from closer up, however much finer, until its coarser tile is as true', () => { + const sight = sightFrom(3000) + const nearGround = { level: 0, tileX: 0, tileZ: 0 } + const known = (tile: TerrainTile): TileState => (tileKey(tile) === tileKey(nearGround) ? 'fresh' : 'quick') + const knownInside = (tile: TerrainTile): TerrainTile[] => (isInside(nearGround, tile) ? [nearGround] : []) + + const { draws } = planCover(sight, known, COARSEST_LEVEL, knownInside) + + expect(draws.some((draw) => tileKey(draw.tile) === tileKey(nearGround))).toBe(true) + expect(drawnOver(draws, 5.5, 5.5)).toBe(1) + }) + + it('wants nothing once every tile it needs is sampled', () => { + expect(planCover(sightFrom(2000), everythingReady, COARSEST_LEVEL).wanted).toEqual([]) + }) + + it('draws ground close to the camera in single blocks and far above it in wider columns', () => { + const near = planCover(sightFrom(150), everythingReady, COARSEST_LEVEL).draws + const far = planCover(sightFrom(30_000), everythingReady, COARSEST_LEVEL).draws + expect(Math.min(...near.map((draw) => draw.tile.level))).toBe(0) + expect(Math.min(...far.map((draw) => draw.tile.level))).toBeGreaterThanOrEqual(3) + }) + + it('never asks for more than a backdrop, a preview and detail of 256 tiles each', () => { + for (const height of [60, 600, 6000, 600_000]) { + const { wanted } = planCover(sightFrom(height), nothingReady, COARSEST_LEVEL) + expect(wanted.length).toBeLessThanOrEqual(3 * 256) + } + }) + + it('leaves a hole in each coarser tile where a finer one is drawn, so every spot is drawn once', () => { + const { draws } = planCover(sightFrom(2000), everythingReady, COARSEST_LEVEL) + for (const coarse of draws) { + for (const finer of draws.filter((other) => isInside(other.tile, coarse.tile))) { + expect(coarse.holes).toContainEqual(columnsUnder(coarse.tile, finer.tile)) + } + } + expectEverySpotDrawnOnce(draws) + }) + + it('shows the backdrop alone until finer tiles are sampled', () => { + const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted + const backdropLevel = wanted[0].level + const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel ? 'fresh' : 'none') + const { draws } = planCover(sightFrom(2000), state, COARSEST_LEVEL) + expect(draws.length).toBeGreaterThan(0) + expect(draws.every((draw) => draw.tile.level === backdropLevel && draw.holes.length === 0)).toBe(true) + expectEverySpotDrawnOnce(draws) + }) + + it('lets any tiles that are sampled stand in for the rest without gaps or overlaps', () => { + const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted + const backdropLevel = wanted[0].level + const sampled = new Set(wanted.filter((_, index) => index % 3 === 0).map(tileKey)) + const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel || sampled.has(tileKey(tile)) ? 'fresh' : 'none') + expectEverySpotDrawnOnce(planCover(sightFrom(2000), state, COARSEST_LEVEL).draws) + }) + + it('draws finer tiles left over from before in place of one not sampled yet', () => { + const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted + const backdropLevel = wanted[0].level + const leaf = wanted.find((tile) => tile.level > 0 && tile.level < backdropLevel)! + const leftOver = new Set([tileKey({ level: leaf.level - 1, tileX: leaf.tileX * 2, tileZ: leaf.tileZ * 2 })]) + const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel || leftOver.has(tileKey(tile)) ? 'standIn' : 'none') + const { draws } = planCover(sightFrom(2000), state, COARSEST_LEVEL) + expect(draws.map((draw) => tileKey(draw.tile))).toContain([...leftOver][0]) + expectEverySpotDrawnOnce(draws) + }) + + it('asks again for ground that only stands in', () => { + const standIn = (): TileState => 'standIn' + const { wanted } = planCover(sightFrom(2000), standIn, COARSEST_LEVEL) + expect(wanted.length).toBeGreaterThan(0) + }) + + it('addresses each wanted tile by the blocks it holds', () => { + const { wanted } = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL) + expect(wanted.map(addressOf).every((address) => Number.isInteger(Math.log2(address.blocksPerPixel)))).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainCover.ts b/studio/src/renderer/src/scene/terrainCover.ts new file mode 100644 index 000000000..c15326469 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainCover.ts @@ -0,0 +1,164 @@ +import type { CameraSight } from './cameraSight' +import { + ancestorAt, + childrenOf, + columnsUnder, + isInside, + MOST_LEVELS_FINER, + TILE_COLUMNS, + tileKey, + type ColumnArea, + type TerrainTile +} from './terrainTiles' + +/** + * What is known of a tile: its ground; ground left over from before the layer changed that stands in until it is + * sampled anew; only a quick, rougher stand-in, drawn where nothing truer of any level is known; or nothing. + */ +export type TileState = 'none' | 'quick' | 'standIn' | 'fresh' + +export interface DrawnTile { + tile: TerrainTile + /** The columns finer tiles draw instead. */ + holes: ColumnArea[] +} + +export interface Cover { + draws: DrawnTile[] + /** What to sample, most needed first: the backdrop, then a level finer than the detail, then the detail. */ + wanted: TerrainTile[] +} + +// Tuned for a workstation GPU, which draws tens of millions of triangles a frame. A column is drawn at most a quarter of +// a pixel wide, so ground drawn block by block goes on until its blocks are far too small to tell apart from the runs +// coarser tiles draw, and the change between them cannot be seen. +const MOST_COLUMN_PIXELS = 0.25 +// Columns finer than a pixel still decide the colour each pixel takes, so the view holds many to a pixel. +const MOST_COLUMNS_PER_PIXEL = 16 +const MOST_TILES_IN_SIGHT = 256 +// The backdrop reaches to the horizon, where a few coarse tiles do; the rest of the tiles go to ground that is near. +const MOST_BACKDROP_TILES = 16 +const DETAIL_MARGIN = 0.15 +const BACKDROP_MARGIN = 0.5 +const PREVIEW_LEVELS_ABOVE_DETAIL = 1 +const MOST_LEVELS_FINER_LEFT_OVER = 2 +const BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK = 1 +const COLUMNS_PER_TILE = TILE_COLUMNS * TILE_COLUMNS + +type StateOf = (tile: TerrainTile) => TileState + +/** + * What to draw for one camera, and which tiles it still needs. Detail tiles in sight have columns about a pixel wide, + * nearer ground finer than far ground; backdrop tiles cover the view and more with coarser columns. Until detail is + * sampled the nearest sampled tile of a coarser level stands in, with holes where finer tiles are ready, and detail + * left over from before zooming out stands in for the coarser tile that is not sampled yet. + * + * Quick stand-ins are drawn only where no truer tile of any level is known, so ground once sampled stays in sight until + * what replaces it is as true. + * + * @param coarsestLevel the coarsest level the source can sample + * @param knownInside the tiles finer than a tile, inside it, whose ground is known, however much finer; where not + * given, the ones up to a couple of levels finer that {@code stateOf} knows + */ +export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number, knownInside?: (tile: TerrainTile) => TerrainTile[]): Cover { + const backdropLevel = backdropLevelFor(sight, coarsestLevel) + const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER) + const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_BACKDROP_TILES) + const detail = detailTiles(sight, backdrop, finestLevel) + const isTrue = (tile: TerrainTile): boolean => stateOf(tile) === 'fresh' || stateOf(tile) === 'standIn' + const leftOverInside = knownInside ?? ((tile: TerrainTile) => finerLeftOver(tile, finestLevel, stateOf, MOST_LEVELS_FINER_LEFT_OVER)) + const candidates = candidatesOf(backdrop, detail, backdropLevel, isTrue, (tile) => leftOverInside(tile).filter((finer) => finer.level >= finestLevel && isTrue(finer))) + const ready = candidates.filter(isTrue) + const quickFill = candidates.filter((tile) => stateOf(tile) === 'quick' && !ready.some((truer) => isInside(tile, truer))) + const drawn = [...ready, ...quickFill] + return { + draws: drawn.map((tile) => ({ tile, holes: drawn.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })), + wanted: wantedInOrder(sight, backdrop, detail, backdropLevel, stateOf) + } +} + +// The backdrop tiles are about as wide as the camera is far from what is in the middle, which puts a few of them in sight. +function backdropLevelFor(sight: CameraSight, coarsestLevel: number): number { + const wanted = Math.ceil(Math.log2(Math.max(1, (sight.orbitDistance * BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK) / TILE_COLUMNS))) + let level = Math.min(coarsestLevel, Math.max(0, wanted)) + while (level < coarsestLevel && sight.tilesAt(level, BACKDROP_MARGIN).length > MOST_BACKDROP_TILES) { + level++ + } + return level +} + +// The tile whose columns look widest is split into finer ones, again and again, until no column looks wider than a +// pixel or the view has as many tiles as it may. A camera that moves a little so changes a tile or two, not all of them. +function detailTiles(sight: CameraSight, backdrop: TerrainTile[], finestLevel: number): TerrainTile[] { + const tilesThePixelsCanShow = Math.floor((sight.pixelsWithin(DETAIL_MARGIN) * MOST_COLUMNS_PER_PIXEL) / COLUMNS_PER_TILE) + const mostTiles = Math.min(MOST_TILES_IN_SIGHT, Math.max(backdrop.length, tilesThePixelsCanShow)) + const detail = backdrop.map((tile) => ({ tile, columnPixels: sight.columnPixels(tile) })) + for (;;) { + const widest = detail + .filter((entry) => entry.tile.level > finestLevel && entry.columnPixels > MOST_COLUMN_PIXELS) + .reduce<(typeof detail)[number] | null>((most, entry) => (most === null || entry.columnPixels > most.columnPixels ? entry : most), null) + if (widest === null) { + break + } + const finer = childrenOf(widest.tile).filter((child) => sight.sees(child, DETAIL_MARGIN)) + if (detail.length - 1 + finer.length > mostTiles) { + break + } + detail.splice(detail.indexOf(widest), 1, ...finer.map((tile) => ({ tile, columnPixels: sight.columnPixels(tile) }))) + } + return detail.map((entry) => entry.tile) +} + +// Everything that may be drawn for the view: the backdrop, the detail and the levels between that happen to be there, +// and, where a tile's true ground is missing, finer tiles left over from before. None is finer than a backdrop tile can +// be cut a hole for. +function candidatesOf( + backdrop: TerrainTile[], + detail: TerrainTile[], + backdropLevel: number, + isTrue: (tile: TerrainTile) => boolean, + leftOverInside: (tile: TerrainTile) => TerrainTile[] +): TerrainTile[] { + const candidates = new Map() + const add = (tile: TerrainTile): void => void candidates.set(tileKey(tile), tile) + const addLeftOverWhereMissing = (tile: TerrainTile): void => { + if (!isTrue(tile)) { + leftOverInside(tile).forEach(add) + } + } + backdrop.forEach(add) + backdrop.forEach(addLeftOverWhereMissing) + for (const tile of detail) { + add(tile) + for (let level = tile.level + 1; level <= backdropLevel; level++) { + add(ancestorAt(tile, level)) + } + addLeftOverWhereMissing(tile) + } + return [...candidates.values()] +} + +function finerLeftOver(tile: TerrainTile, finestLevel: number, stateOf: StateOf, levels: number): TerrainTile[] { + if (levels === 0 || tile.level <= finestLevel) { + return [] + } + return childrenOf(tile).flatMap((child) => [...(stateOf(child) === 'none' ? [] : [child]), ...finerLeftOver(child, finestLevel, stateOf, levels - 1)]) +} + +function wantedInOrder(sight: CameraSight, backdrop: TerrainTile[], detail: TerrainTile[], backdropLevel: number, stateOf: StateOf): TerrainTile[] { + const previews = detail + .filter((tile) => tile.level + PREVIEW_LEVELS_ABOVE_DETAIL < backdropLevel) + .map((tile) => ancestorAt(tile, tile.level + PREVIEW_LEVELS_ABOVE_DETAIL)) + const wanted = new Map() + for (const group of [backdrop, previews, detail]) { + group + .filter((tile) => stateOf(tile) !== 'fresh') + .sort(nearestFirst(sight)) + .forEach((tile) => wanted.set(tileKey(tile), wanted.get(tileKey(tile)) ?? tile)) + } + return [...wanted.values()] +} + +function nearestFirst(sight: CameraSight): (first: TerrainTile, second: TerrainTile) => number { + return (first, second) => sight.distanceFromLookedAt(first) - sight.distanceFromLookedAt(second) +} diff --git a/studio/src/renderer/src/scene/terrainMesh.test.ts b/studio/src/renderer/src/scene/terrainMesh.test.ts new file mode 100644 index 000000000..5951d2cda --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMesh.test.ts @@ -0,0 +1,216 @@ +import { Vector3, type BufferGeometry, type Mesh } from 'three' +import { describe, expect, it } from 'vitest' +import { buildTerrainMesh, type RaisedBlock, type TerrainSurface } from './terrainMesh' +import { submergedTint, tintAt } from './waterTint' + +const GROUND = 10 +const POND_GROUND = 7 +const WATER = 9 +const BASE_DEPTH = 8 +const BASE = POND_GROUND + 1 - BASE_DEPTH +const GREY = 0x808080 +const RED = 0xff0000 +const GREY_LIGHT = 0x80 / 255 +const SIDE_LIGHT = 0.6 +const DEEP_RED = 0x0f / 255 + +// Three by three columns: nothing known at the north west corner, a pond at the middle column. +function surfaceOf(colorAt: TerrainSurface['colorAt'] = () => GREY): TerrainSurface { + return { + columns: 3, + rows: 3, + originX: 100, + originZ: 200, + blocksPerColumn: 1, + groundAt: (column, row) => { + if (column === 0 && row === 0) { + return null + } + return column === 1 && row === 1 ? POND_GROUND : GROUND + }, + waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null), + colorAt + } +} + +const surface = surfaceOf() +const dry: TerrainSurface = { ...surface, waterAt: () => null } + +function meshes(terrain: TerrainSurface = surface): { ground: Mesh; water: Mesh } { + const [ground, water] = buildTerrainMesh(terrain, BASE).object.children as Mesh[] + return { ground, water } +} + +function quads(mesh: Mesh): number { + return mesh.geometry.getIndex()!.count / 6 +} + +// The quads of a geometry as the point in the middle of each and the way it faces. +function faces(geometry: BufferGeometry): { middle: Vector3; normal: Vector3 }[] { + const positions = geometry.getAttribute('position') + const found: { middle: Vector3; normal: Vector3 }[] = [] + for (let first = 0; first < positions.count; first += 4) { + const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, first + index) + const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)] + found.push({ + middle: origin.clone().add(far).multiplyScalar(0.5), + normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize() + }) + } + return found +} + +function redOf(geometry: BufferGeometry, vertex: number): number { + return geometry.getAttribute('color').getX(vertex) +} + +// The red of the grey ground after sinking by the tint, lit as given. +function sunkRed(tint: number, light = 1): number { + return GREY_LIGHT * light + (DEEP_RED - GREY_LIGHT * light) * tint +} + +describe('terrain mesh', () => { + it('draws one top for each run of neighbouring columns at one height', () => { + const { ground } = meshes() + const tops = faces(ground.geometry).filter((face) => face.normal.y === 1) + expect(tops).toHaveLength(5) + expect(tops.filter((top) => top.middle.y === GROUND + 1)).toHaveLength(4) + }) + + it('draws a side only where a column stands above its neighbour or beside nothing known', () => { + const { ground } = meshes(dry) + expect(quads(ground) - faces(ground.geometry).filter((face) => face.normal.y === 1).length).toBe(10) + }) + + it('keeps columns of other colours apart', () => { + const striped = surfaceOf((column) => (column === 2 ? RED : GREY)) + const tops = faces(meshes(striped).ground.geometry).filter((face) => face.normal.y === 1) + expect(tops).toHaveLength(7) + }) + + it('faces every side outwards from the column it belongs to', () => { + const { ground } = meshes(dry) + const sides = faces(ground.geometry).filter((face) => face.normal.y === 0) + const pondSide = sides.find((side) => side.middle.x === 101 + 1 && side.normal.x === -1 && side.middle.z === 201.5)! + expect(pondSide.middle.y).toBe((POND_GROUND + 1 + GROUND + 1) / 2) + const edge = sides.find((side) => side.normal.z === -1 && side.middle.z === 200)! + expect(edge.middle.y).toBe((GROUND + 1 + POND_GROUND + 1 - BASE_DEPTH) / 2) + }) + + it('lights tops fully and sides less', () => { + const colors = meshes(dry).ground.geometry.getAttribute('color') + const lights = new Set() + for (let vertex = 0; vertex < colors.count; vertex += 4) { + lights.add(Math.round((colors.getX(vertex) * 255 * 100) / 0x80) / 100) + } + expect([...lights].sort()).toEqual([0.6, 0.8, 1]) + }) + + it('draws the water of a column as its top, and no side where the ground beside it stands higher', () => { + const { water } = meshes() + expect(quads(water)).toBe(1) + expect(faces(water.geometry)[0].middle.toArray()).toEqual([101.5, WATER + 1, 201.5]) + }) + + it('draws a water side where the water stands above what lies beside it, but not beside nothing known', () => { + const lake = { ...surface, groundAt: (column: number, row: number) => (column === 1 && row === 1 ? POND_GROUND : column === 0 && row === 1 ? null : WATER - 3) } + const sides = faces(meshes(lake).water.geometry).filter((face) => face.normal.y === 0) + expect(sides).toHaveLength(3) + expect(sides.every((side) => side.middle.y === (POND_GROUND + 1 + WATER + 1) / 2)).toBe(true) + }) + + it('draws no water side at the edge of the field, where the water goes on in the next one', () => { + const shore = { ...surface, groundAt: () => WATER - 3, waterAt: () => WATER } + const sides = faces(meshes(shore).water.geometry).filter((face) => face.normal.y === 0) + expect(sides).toHaveLength(0) + }) + + it('spreads columns over as many blocks as they are wide', () => { + const coarse = { ...surface, blocksPerColumn: 4 } + const tops = faces(meshes(coarse).ground.geometry).filter((face) => face.normal.y === 1) + const xs = tops.map((top) => top.middle.x) + expect(Math.min(...xs)).toBeGreaterThanOrEqual(100) + expect(Math.max(...xs)).toBeLessThanOrEqual(112) + expect(faces(meshes(coarse).water.geometry)[0].middle.toArray()).toEqual([106, WATER + 1, 206]) + }) + + it('leaves out the columns of a hole and walls what stands beside it', () => { + const holed = buildTerrainMesh(surface, BASE, [{ fromColumn: 2, fromRow: 2, toColumn: 3, toRow: 3 }]) + const [ground] = holed.object.children as Mesh[] + const tops = faces(ground.geometry).filter((face) => face.normal.y === 1) + expect(tops.every((top) => !(top.middle.x === 102.5 && top.middle.z === 202.5))).toBe(true) + expect(holed.field.surfaceTop(2, 2)).toBeNull() + expect(faces(ground.geometry).filter((face) => face.normal.y === 0 && face.middle.x === 102.5 && face.middle.z === 202)).toHaveLength(1) + }) + + it('sinks the ground under water toward the deep colour, the more the deeper it lies', () => { + const pondTopRed = (terrain: TerrainSurface): number => { + const ground = meshes(terrain).ground.geometry + const pond = faces(ground).findIndex((face) => face.normal.y === 1 && face.middle.x === 101.5 && face.middle.z === 201.5) + return redOf(ground, pond * 4) + } + const shallow = pondTopRed(surface) + const deep = pondTopRed({ ...surface, waterAt: () => POND_GROUND + 30 }) + expect(pondTopRed(dry)).toBeCloseTo(GREY_LIGHT) + expect(shallow).toBeCloseTo(sunkRed(tintAt(WATER - POND_GROUND))) + expect(deep).toBeLessThan(shallow) + }) + + it('leaves ground level with the water dry', () => { + const level = { ...surface, waterAt: (column: number, row: number) => (column === 1 && row === 1 ? POND_GROUND : null) } + const ground = meshes(level).ground.geometry + const pond = faces(ground).findIndex((face) => face.normal.y === 1 && face.middle.x === 101.5 && face.middle.z === 201.5) + expect(redOf(ground, pond * 4)).toBeCloseTo(GREY_LIGHT) + expect(tintAt(0)).toBe(0) + }) + + it('sinks only the part of a side under the water, deeper toward its bottom', () => { + const ground = meshes().ground.geometry + const toPond = faces(ground) + .map((face, quad) => ({ ...face, quad })) + .filter((face) => face.normal.x === -1 && face.middle.x === 102 && face.middle.z === 201.5) + expect(toPond).toHaveLength(2) + const [wet, above] = toPond.sort((first, second) => first.middle.y - second.middle.y) + const [wetBottom, wetTop] = [redOf(ground, wet.quad * 4), redOf(ground, wet.quad * 4 + 1)] + expect(wet.middle.y).toBe((POND_GROUND + 1 + WATER + 1) / 2) + expect(wetBottom).toBeLessThan(wetTop) + expect(wetTop).toBeCloseTo(sunkRed(submergedTint(0), SIDE_LIGHT)) + expect(redOf(ground, above.quad * 4)).toBeCloseTo(GREY_LIGHT * SIDE_LIGHT) + expect(redOf(ground, above.quad * 4 + 1)).toBeCloseTo(GREY_LIGHT * SIDE_LIGHT) + }) + + it('has no mesh where no column has ground', () => { + const nothing = buildTerrainMesh({ ...surface, groundAt: () => null }, BASE) + expect(nothing.object.children).toHaveLength(0) + }) +}) + +describe('raised blocks', () => { + const raisedAt = (y: number): RaisedBlock => ({ y, color: RED, look: null }) + // The faces drawn for the raised blocks, which come after the ground's. + const raisedFaces = (raised: TerrainSurface['raisedAt']): ReturnType => + faces(meshes({ ...dry, raisedAt: raised }).ground.geometry).slice(quads(meshes(dry).ground)) + + it('stands a raised block as a whole block, each face looking away from it', () => { + const leaf = raisedFaces((column, row) => (column === 2 && row === 2 ? [raisedAt(GROUND + 4)] : [])) + const middle = new Vector3(102.5, GROUND + 4.5, 202.5) + + expect(leaf).toHaveLength(6) + for (const face of leaf) { + expect(face.middle.clone().sub(middle).normalize().dot(face.normal)).toBeCloseTo(1) + } + }) + + it('leaves out the faces that touch the ground or another raised block', () => { + const tree = raisedFaces((column, row) => { + if (column === 2 && row === 1) { + return [raisedAt(GROUND + 2), raisedAt(GROUND + 1)] + } + return column === 2 && row === 2 ? [raisedAt(GROUND + 2)] : [] + }) + + // The trunk's lower block shows four sides, its upper one three and its top, the leaf all but the side on the trunk. + expect(tree).toHaveLength(13) + expect(tree.some((face) => face.normal.y === -1 && face.middle.y === GROUND + 1)).toBe(false) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts new file mode 100644 index 000000000..53ab5b37a --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -0,0 +1,173 @@ +import { DoubleSide, FrontSide, Group, Mesh, MeshBasicMaterial, ShaderChunk, type BufferGeometry } from 'three' +import type { BlockLook } from './blockLooks' +import { groundFaces, waterFaces } from './columnFaces' +import { ColumnField } from './columnField' +import { coverGeometry } from './coverFaces' +import type { CoverLook } from './coverLooks' +import { QuadBatch } from './quadBatch' +import { addRaisedFaces } from './raisedFaces' +import type { CompactPlacement } from './compactGeometry' +import { runFaces, type SurfaceRuns } from './runFaces' +import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' + +import type { TerrainPictures } from './terrainAtlas' +import type { ColumnArea } from './terrainTiles' +import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint' + +/** + * Terrain to draw as columns, row by row from the north west: the ground, the water over it, and the ground's colour. + * Heights are the Y of the top block, so a column of 64 has its top face at 65. Where nothing is known, the ground is + * null and the column is left out. + */ +export interface TerrainSurface { + readonly columns: number + readonly rows: number + /** The world block of the first column and of the first row. */ + readonly originX: number + readonly originZ: number + /** How many blocks wide and deep a column is. */ + readonly blocksPerColumn: number + groundAt(column: number, row: number): number | null + /** The Y of the water's top block over the column, or null where it is dry. */ + waterAt(column: number, row: number): number | null + colorAt(column: number, row: number): number + /** The atlas that {@link lookAt}'s pictures lie in; a surface without one is drawn in colour alone. */ + readonly pictures?: TerrainPictures + /** What the block of the column looks like, or null to show the column in its colour. */ + lookAt?(column: number, row: number): BlockLook | null + /** What stands on the column's ground, such as grass or a flower, or null for nothing that is drawn. */ + coverAt?(column: number, row: number): CoverLook | null + /** The solid blocks above the column's ground, such as a tree's wood and leaves, highest first. */ + raisedAt?(column: number, row: number): readonly RaisedBlock[] + /** + * Every block seen from the open air, to draw one by one in place of the columns, which then only answer where the + * ground lies; null to draw the columns. + */ + voxels?(): SurfaceVoxels | null + /** The runs of solid blocks of each column's area, to draw in place of the columns' tops; null to draw the columns. */ + runs?(): SurfaceRuns | null +} + +/** A solid block above a column's ground, drawn as a whole block. */ +export interface RaisedBlock { + y: number + color: number + /** What the block looks like, or null to show its colour. */ + look: BlockLook | null +} + +const CUTOUT_ALPHA = 0.5 + +export interface TerrainMesh { + object: Group + field: ColumnField + dispose(): void +} + +/** + * The surface as columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft shades + * blocks, with the ground under water sunk toward a deep colour and a light sheet of water over it. Sides on the edge reach down to {@code base}, so tiles of ground next to + * each other leave no cracks. The columns in {@code holes} are left out, for finer ground to fill. Columns with a look + * show their block's textures, one picture to a block face. Blocks raised above the ground, such as trees, stand as + * whole blocks; what is seen through, such as leaves, is cut out along its pictures. + */ +export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainMesh { + const geometry = buildTerrainGeometry(surface, base, holes) + return meshOfGeometry(geometry, geometry.field.pictures) +} + +/** How a part of a tile's geometry is drawn: in its colours alone, textured, cut out along its pictures, or as water. */ +export type GeometryKind = 'coloured' | 'textured' | 'cutOut' | 'water' + +/** A tile's faces, ready to draw in materials of their kinds, in the order they are drawn; water comes last. */ +export interface TerrainGeometry { + field: ColumnField + /** Each part's faces; where a part has a placement, its corners are in the steps of a compact geometry. */ + parts: { kind: GeometryKind; geometry: BufferGeometry; placement?: CompactPlacement }[] +} + +/** The faces {@link buildTerrainMesh} draws, without materials, so they can be built away from where they are drawn. */ +export function buildTerrainGeometry(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainGeometry { + const field = new ColumnField(surface, holes) + if (!field.hasAnyGround()) { + return { field, parts: [] } + } + const voxels = field.pictures === null ? null : (surface.voxels?.() ?? null) + if (voxels !== null && field.pictures !== null) { + const { opaque, cutOut, water } = voxelGeometries(field, voxels, field.pictures.plain) + return { field, parts: present([part('textured', opaque), part('cutOut', cutOut), part('water', water)]) } + } + const runs = surface.runs?.() ?? null + if (runs !== null) { + return { field, parts: [{ kind: 'coloured', geometry: runFaces(field, runs, base).geometry() }, { kind: 'water', geometry: waterFaces(field).geometry() }] } + } + const groundBatch = groundFaces(field, base) + const seeThroughBatch = new QuadBatch(true, field.pictures?.plain ?? null) + addRaisedFaces(field, groundBatch, seeThroughBatch) + const cutOut = field.pictures === null ? [] : present([part('cutOut', coverGeometry(field)), part('cutOut', seeThroughBatch.count === 0 ? null : seeThroughBatch.geometry())]) + return { + field, + parts: [{ kind: field.pictures === null ? 'coloured' : 'textured', geometry: groundBatch.geometry() }, ...cutOut, { kind: 'water', geometry: waterFaces(field).geometry() }] + } +} + +function part(kind: GeometryKind, geometry: BufferGeometry | null): { kind: GeometryKind; geometry: BufferGeometry } | null { + return geometry === null ? null : { kind, geometry } +} + +function present(parts: (T | null)[]): T[] { + return parts.filter((found): found is T => found !== null) +} + +/** The geometry drawn in its materials; textured and cut-out parts need {@code pictures}. */ +export function meshOfGeometry({ field, parts }: TerrainGeometry, pictures: TerrainPictures | null): TerrainMesh { + const group = new Group() + const materials = parts.map(({ kind }) => materialOf(kind, pictures)) + parts.forEach(({ geometry, placement }, index) => { + const mesh = new Mesh(geometry, materials[index]) + if (placement !== undefined) { + mesh.position.set(...placement.origin) + mesh.scale.set(...placement.scale) + } + group.add(mesh) + }) + return { + object: group, + field, + dispose: () => { + parts.forEach(({ geometry }) => geometry.dispose()) + materials.forEach((material) => material.dispose()) + } + } +} + +// Cut-out parts are drawn where their pictures are not open, so the grass between its blades and the leaves between their +// twigs show what lies behind. +function materialOf(kind: GeometryKind, pictures: TerrainPictures | null): MeshBasicMaterial { + switch (kind) { + case 'coloured': + return new MeshBasicMaterial({ vertexColors: true, side: FrontSide }) + case 'textured': + return withPicturesReadInsideFaces(new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: pictures?.texture ?? null })) + case 'cutOut': + return withPicturesReadInsideFaces( + new MeshBasicMaterial({ vertexColors: true, map: pictures?.texture ?? null, alphaMap: pictures?.cutouts ?? null, alphaTest: CUTOUT_ALPHA, side: FrontSide }) + ) + case 'water': + return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) + } +} + +const PICTURE_COORDINATES = /varying vec2 (vMapUv|vAlphaMapUv);/g +const CENTROID_COORDINATES = 'centroid varying vec2 $1;' + +// With antialiasing, a pixel only partly on a face is shaded at its centre, which can lie off the face, and the picture +// is read past the face's edge. Far off, where a block face is a pixel or less, that is the picture beside it in the atlas, +// and the ground and trees are speckled with other blocks' colours. Centroid coordinates are read where the face is. +function withPicturesReadInsideFaces(material: MeshBasicMaterial): MeshBasicMaterial { + material.onBeforeCompile = (shader) => { + shader.vertexShader = shader.vertexShader.replace('#include ', ShaderChunk.uv_pars_vertex.replace(PICTURE_COORDINATES, CENTROID_COORDINATES)) + shader.fragmentShader = shader.fragmentShader.replace('#include ', ShaderChunk.uv_pars_fragment.replace(PICTURE_COORDINATES, CENTROID_COORDINATES)) + } + return material +} diff --git a/studio/src/renderer/src/scene/terrainMeshWorker.ts b/studio/src/renderer/src/scene/terrainMeshWorker.ts new file mode 100644 index 000000000..7eeac987a --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMeshWorker.ts @@ -0,0 +1,56 @@ +/// +import type { MapTile } from '../bridge/types' +import { compacted, type CompactArrays } from './compactGeometry' +import type { FieldShape } from './columnField' +import { MapTerrain, type MapTerrainColoring } from './mapTerrain' +import type { TerrainPictures, UvCell } from './terrainAtlas' +import { buildTerrainGeometry, type GeometryKind } from './terrainMesh' +import type { ColumnArea, TerrainTile } from './terrainTiles' + +/** One map tile to build the faces of, as the studio's 3D world draws it. */ +export interface MeshRequest { + id: number + tile: MapTile + place: TerrainTile + coloring: MapTerrainColoring + fluidHeight: number + /** The atlas's plain cell, or null to draw the tile in colour alone. */ + plain: UvCell | null + base: number + holes: ColumnArea[] +} + +/** A built geometry's arrays, packed small, as a worker sends them back. */ +export interface GeometryArrays { + kind: GeometryKind + arrays: CompactArrays +} + +export interface MeshResult { + id: number + field: FieldShape + parts: GeometryArrays[] +} + +// The faces are built from the atlas's cell layout alone; the textures themselves stay where they are drawn. +function picturesOf(plain: UvCell | null): TerrainPictures | undefined { + return plain === null ? undefined : ({ plain, texture: null, cutouts: null } as unknown as TerrainPictures) +} + +self.onmessage = (event: MessageEvent) => { + const { id, tile, place, coloring, fluidHeight, plain, base, holes } = event.data + const surface = new MapTerrain(tile, place, coloring, fluidHeight, picturesOf(plain)) + const { field, parts } = buildTerrainGeometry(surface, base, holes) + const packed: GeometryArrays[] = parts.map(({ kind, geometry }) => ({ kind, arrays: compacted(geometry, field.blocksPerColumn) })) + const shape = field.shape() + const buffers = new Set([shape.groundTop.buffer as ArrayBuffer, shape.waterTop.buffer as ArrayBuffer]) + for (const { arrays } of packed) { + for (const array of [arrays.position, arrays.color, arrays.uv, arrays.index]) { + if (array !== null) { + buffers.add(array.buffer as ArrayBuffer) + } + } + } + const result: MeshResult = { id, field: shape, parts: packed } + self.postMessage(result, [...buffers]) +} diff --git a/studio/src/renderer/src/scene/terrainMeshWorkers.ts b/studio/src/renderer/src/scene/terrainMeshWorkers.ts new file mode 100644 index 000000000..1510f8041 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMeshWorkers.ts @@ -0,0 +1,74 @@ +import { ColumnField } from './columnField' +import { geometryOfCompact } from './compactGeometry' +import type { TerrainGeometry } from './terrainMesh' +import type { MeshRequest, MeshResult } from './terrainMeshWorker' + +const MOST_WORKERS = 6 + +/** + * Map tiles' faces built on worker threads, so a tile arriving never holds up a frame: the main thread only wraps the + * arrays a worker sends back, without copying them. Tiles are built in the order they are asked for. + */ +export class TerrainMeshWorkers { + private readonly workers: Worker[] = [] + private readonly idle: Worker[] = [] + private readonly queue: { request: MeshRequest; resolve(geometry: TerrainGeometry): void; reject(error: Error): void }[] = [] + private readonly running = new Map() + private nextId = 0 + + constructor() { + const count = Math.max(1, Math.min(MOST_WORKERS, (navigator.hardwareConcurrency || 2) - 1)) + for (let index = 0; index < count; index++) { + const worker = new Worker(new URL('./terrainMeshWorker.ts', import.meta.url), { type: 'module' }) + worker.onmessage = (event: MessageEvent) => this.finished(worker, event.data) + worker.onerror = (event) => this.failed(worker, new Error(event.message)) + this.workers.push(worker) + this.idle.push(worker) + } + } + + build(request: Omit): Promise { + return new Promise((resolve, reject) => { + this.queue.push({ request: { ...request, id: this.nextId++ }, resolve, reject }) + this.startNext() + }) + } + + dispose(): void { + this.workers.forEach((worker) => worker.terminate()) + this.queue.forEach((job) => job.reject(new Error('The terrain is no longer drawn'))) + this.queue.length = 0 + } + + private startNext(): void { + while (this.idle.length > 0 && this.queue.length > 0) { + const worker = this.idle.pop()! + const job = this.queue.shift()! + this.running.set(worker, job) + worker.postMessage(job.request) + } + } + + private finished(worker: Worker, result: MeshResult): void { + const job = this.running.get(worker) + this.running.delete(worker) + this.idle.push(worker) + job?.resolve(geometryOf(result)) + this.startNext() + } + + private failed(worker: Worker, error: Error): void { + const job = this.running.get(worker) + this.running.delete(worker) + this.idle.push(worker) + job?.reject(error) + this.startNext() + } +} + +function geometryOf(result: MeshResult): TerrainGeometry { + return { + field: ColumnField.ofShape(result.field), + parts: result.parts.map(({ kind, arrays }) => ({ kind, geometry: geometryOfCompact(arrays), placement: arrays.placement })) + } +} diff --git a/studio/src/renderer/src/scene/terrainStream.test.ts b/studio/src/renderer/src/scene/terrainStream.test.ts new file mode 100644 index 000000000..534d5812f --- /dev/null +++ b/studio/src/renderer/src/scene/terrainStream.test.ts @@ -0,0 +1,285 @@ +import { PerspectiveCamera, Ray, Vector3, type Mesh } from 'three' +import { describe, expect, it, vi } from 'vitest' +import type { TileSource } from '../map/TileStore' +import type { CameraLink } from '../studio/SceneViewport' +import { buildTerrainMesh } from './terrainMesh' +import { focusAround, TerrainStream, type TerrainStyle } from './terrainStream' + +interface FlatTile { + height: number +} + +interface FlatLayer { + name: string + height: number + /** Resolves the tiles of the layer once called; they stay on their way until then. */ + gate: Promise + /** Where given, the gate of the tiles this many blocks a column, in place of {@link gate}. */ + gateAt?: (blocksPerPixel: number) => Promise +} + +const COARSEST_LEVEL = 8 +// A source that cannot sample coarser has more tiles in sight than it may draw, so it has to pick the right ones. +const COARSEST_SAVED_LEVEL = 4 +const LOOKED_AT = new Vector3(0, 64, 0) +const open = Promise.resolve() + +const flatStyle: TerrainStyle = { + surfaceOf: (tile, place) => ({ + columns: 128, + rows: 128, + originX: place.tileX * 128 * 2 ** place.level, + originZ: place.tileZ * 128 * 2 ** place.level, + blocksPerColumn: 2 ** place.level, + groundAt: () => tile.height, + waterAt: () => null, + colorAt: () => 0x808080 + }), + floorY: 0, + topY: 128 +} + +function setUp( + coarsestLevel = COARSEST_LEVEL, + quickLayerOf?: (layer: FlatLayer) => FlatLayer | null +): { + stream: TerrainStream + camera: PerspectiveCamera + moved(): void + requested: number[] + requestedLayers: string[] + pendingCounts: number[] + stopFollowing: () => void +} { + const requested: number[] = [] + const requestedLayers: string[] = [] + const pendingCounts: number[] = [] + const source: TileSource = { + layerKey: (layer) => layer.name, + fetch: async (address, layer) => { + requested.push(address.blocksPerPixel) + requestedLayers.push(layer.name) + await (layer.gateAt?.(address.blocksPerPixel) ?? layer.gate) + return { height: layer.height } + }, + bytesOf: () => 1 + } + const stream = new TerrainStream({ + source, + coarsestLevel, + quickLayerOf, + focus: focusAround(0, 0, 0, 128), + onPending: (pending) => pendingCounts.push(pending), + onError: (message) => { + throw new Error(message) + } + }) + const camera = new PerspectiveCamera(45, 1.6, 4, 40_000) + camera.position.set(0, 664, 360) + camera.lookAt(LOOKED_AT) + const listeners = new Set<() => void>() + const link: CameraLink = { + view: () => ({ camera, width: 1280, height: 800, orbitDistance: camera.position.distanceTo(LOOKED_AT) }), + onMoved: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + redraw: vi.fn() + } + const stopFollowing = stream.content.follow!(link) + return { stream, camera, moved: () => listeners.forEach((listener) => listener()), requested, requestedLayers, pendingCounts, stopFollowing } +} + +async function settle(): Promise { + for (let turn = 0; turn < 30; turn++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +const meshesOf = (stream: TerrainStream): Mesh[] => stream.content.object.children.flatMap((tile) => tile.children as Mesh[]) + +describe('terrain stream', () => { + it('draws nothing until it has a layer and a style, then the tiles in sight as they arrive', async () => { + const { stream, requested } = setUp() + await settle() + expect(requested).toEqual([]) + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + expect(requested.length).toBeGreaterThan(0) + expect(stream.content.object.children.length).toBeGreaterThan(0) + }) + + it('asks for the coarsest tiles first and reports what is still on its way', async () => { + const { stream, requested, pendingCounts } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + expect(requested[0]).toBe(Math.max(...requested)) + expect(pendingCounts[0]).toBeGreaterThan(0) + expect(pendingCounts.at(-1)).toBe(0) + }) + + it('keeps the ground it drew while the tiles of another layer are on their way', async () => { + const { stream } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + const drawn = stream.content.object.children.length + let release = (): void => {} + stream.showLayer({ name: 'two', height: 90, gate: new Promise((resolve) => (release = resolve)) }) + await settle() + expect(stream.content.object.children.length).toBe(drawn) + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) + release() + await settle() + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(91, 3) + }) + + it('draws the quick stand-in of a slow layer at once, and asks for the slow tiles finest first', async () => { + let release = (): void => {} + const slow: FlatLayer = { name: 'slow', height: 90, gate: new Promise((resolve) => (release = resolve)) } + const quick: FlatLayer = { name: 'quick', height: 70, gate: open } + const { stream, requested, requestedLayers } = setUp(COARSEST_LEVEL, (layer) => (layer === slow ? quick : null)) + stream.restyle(flatStyle) + stream.showLayer(slow) + await settle() + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(requestedLayers[0]).toBe('quick') + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) + const slowScales = requested.filter((_, at) => requestedLayers[at] === 'slow') + expect(slowScales.length).toBeGreaterThan(0) + expect(slowScales).toEqual([...slowScales].sort((first, second) => first - second)) + release() + await settle() + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(91, 3) + }) + + it('draws the tiles again in another style without asking for them again', async () => { + const { stream, requested } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + const asked = requested.length + stream.restyle({ ...flatStyle, surfaceOf: (tile, place) => ({ ...flatStyle.surfaceOf(tile, place), groundAt: () => tile.height + 10 }) }) + await settle() + expect(requested.length).toBe(asked) + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(81, 3) + }) + + it('finds the ground a ray meets, and nothing where it passes by', async () => { + const { stream } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + const down = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(stream.content.surfaceAlong!(down, 1000)!.toArray().map(Math.round)).toEqual([10, 71, 10]) + const up = new Ray(new Vector3(10, 300, 10), new Vector3(0, 1, 0)) + expect(stream.content.surfaceAlong!(up, 1000)).toBeNull() + }) + + it('draws more tiles when the camera moves to ground it has not drawn', async () => { + const { stream, camera, moved } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + const ray = new Ray(new Vector3(40_000, 300, 0), new Vector3(0, -1, 0)) + expect(stream.content.surfaceAlong!(ray, 1000)).toBeNull() + camera.position.set(40_000, 664, 360) + camera.lookAt(new Vector3(40_000, 64, 0)) + moved() + await settle() + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) + }) + + it('reads the height of the ground the camera looks at once it is drawn, and tells when the view may have changed', async () => { + const { stream, camera, moved } = setUp() + const sightChanges = vi.fn() + stream.onSightChanged(sightChanges) + stream.restyle(flatStyle) + expect(stream.groundInView()).toBeNull() + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + expect(sightChanges).toHaveBeenCalled() + const seen = stream.groundInView()! + expect(new Set(seen.heights)).toEqual(new Set([70])) + expect(seen.area.maxX).toBeGreaterThan(seen.area.minX) + + camera.position.set(40_000, 664, 360) + camera.lookAt(new Vector3(40_000, 64, 0)) + moved() + await settle() + expect(stream.groundInView()!.area.minX).toBeGreaterThan(seen.area.maxX) + }) + + it('draws the ground under a camera that is close to it in a world with a tall sky', async () => { + const { stream, camera, moved } = setUp(COARSEST_SAVED_LEVEL) + stream.restyle({ ...flatStyle, floorY: -64, topY: 1024 }) + stream.showLayer({ name: 'one', height: 70, gate: open }) + camera.position.set(250, 260, 300) + camera.lookAt(new Vector3(36, 71, 47)) + moved() + await settle() + const sight = new Ray(camera.position.clone(), camera.getWorldDirection(new Vector3())) + expect(stream.content.surfaceAlong!(sight, 2000)!.y).toBeCloseTo(71, 1) + }) + + it('shows the true ground it has from closer up again, rather than a quick stand-in, while coarser tiles are on their way', async () => { + const neverArrives = new Promise(() => {}) + const slow: FlatLayer = { name: 'slow', height: 90, gate: open, gateAt: (blocksPerPixel) => (blocksPerPixel <= 8 ? open : neverArrives) } + const quick: FlatLayer = { name: 'quick', height: 70, gate: open } + const { stream, camera, moved } = setUp(COARSEST_LEVEL, (layer) => (layer === slow ? quick : null)) + stream.restyle(flatStyle) + stream.showLayer(slow) + await settle() + // Looking far away takes the ground near the origin out of sight, and so out of the drawn tiles. + camera.position.set(500_000, 664, 360) + camera.lookAt(500_000, 64, 0) + moved() + await settle() + camera.position.set(0, 20_000, 12_000) + camera.lookAt(LOOKED_AT) + moved() + await settle() + + const ray = new Ray(new Vector3(10, 30_000, 10), new Vector3(0, -1, 0)) + expect(stream.content.surfaceAlong!(ray, 40_000)!.y).toBeCloseTo(91, 3) + // Three views of up to a few hundred tiles each, every one built as a mesh. + }, 30_000) + + it('draws tiles built away from the frames once they are built', async () => { + const { stream } = setUp() + let builds = 0 + const builtLater: TerrainStyle = { + ...flatStyle, + buildMesh: async (tile, place, base, holes) => { + builds++ + await Promise.resolve() + return buildTerrainMesh(flatStyle.surfaceOf(tile, place), base, holes) + } + } + stream.restyle(builtLater) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(builds).toBeGreaterThan(0) + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) + }) + + it('stops drawing when it is let go', async () => { + const { stream, stopFollowing, requested } = setUp() + stream.restyle(flatStyle) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + stopFollowing() + stream.dispose() + const asked = requested.length + stream.showLayer({ name: 'two', height: 90, gate: open }) + await settle() + expect(requested.length).toBe(asked) + expect(meshesOf(stream)).toHaveLength(0) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainStream.ts b/studio/src/renderer/src/scene/terrainStream.ts new file mode 100644 index 000000000..094797d7f --- /dev/null +++ b/studio/src/renderer/src/scene/terrainStream.ts @@ -0,0 +1,465 @@ +import { Box3, Group, Vector3, type BufferGeometry } from 'three' +import { TileStore, type TileSource } from '../map/TileStore' +import type { TileAddress } from '../map/viewport' +import type { CameraLink, ViewportContent } from '../studio/SceneViewport' +import { CameraSight } from './cameraSight' +import type { ColumnField } from './columnField' +import { groundInView, type GroundInView } from './groundInView' +import { marchOntoSurface } from './surfaceMarch' +import { planCover, type Cover, type DrawnTile, type TileState } from './terrainCover' +import { buildTerrainMesh, type TerrainMesh, type TerrainSurface } from './terrainMesh' +import { addressOf, ancestorAt, childrenOf, isInside, tileAt, tileContaining, tileKey, type ColumnArea, type TerrainTile } from './terrainTiles' + +/** How the tiles of a source look as ground, and how low and high that ground can reach. */ +export interface TerrainStyle { + surfaceOf(tile: Tile, place: TerrainTile): TerrainSurface + floorY: number + topY: number + /** + * Builds a tile's mesh away from the frames, as {@link buildTerrainMesh} does from {@link surfaceOf}; where not given, + * tiles are built on the spot. + */ + buildMesh?(tile: Tile, place: TerrainTile, base: number, holes: ColumnArea[]): Promise +} + +export interface TerrainStreamOptions { + source: TileSource + /** The coarsest level the source samples: tiles of level n have columns 2^n blocks wide. */ + coarsestLevel: number + /** The box the camera frames when the terrain is first shown; ground is looked for between its heights until tiles show where it really stands. */ + focus: Box3 + /** + * A layer whose tiles arrive quickly, drawn where the layer's own have not arrived yet, or null for none; a layer + * whose tiles are slow to sample, such as one with generated blocks, so never leaves ground missing for long. + */ + quickLayerOf?(layer: Layer): Layer | null + /** Told how many tiles are still on their way, whenever that changes. */ + onPending(pending: number): void + onError(message: string): void +} + +/** A layer's tiles that have arrived, and every coarser tile that holds one, as of a version of the store. */ +interface StoredIndex { + version: number + layerKey: string + tiles: Set + holding: Set +} + +/** A tile's mesh on its way from a worker, for the data and holes it was asked for; null until it is built. */ +interface BuildingMesh { + tile: TerrainTile + data: Tile + signature: string + mesh: TerrainMesh | null +} + +interface DrawnMesh { + tile: TerrainTile + data: Tile + signature: string + mesh: TerrainMesh +} + +const MESH_BUILD_BUDGET_MILLISECONDS = 12 +// What a workstation GPU takes in a few milliseconds. +const UPLOAD_BYTES_PER_FRAME = 16 * 1024 * 1024 + +/** The bytes a mesh's geometry hands the GPU when it is first drawn. */ +function bytesOf(mesh: TerrainMesh): number { + let bytes = 0 + mesh.object.traverse((object) => { + const geometry = (object as { geometry?: BufferGeometry }).geometry + if (geometry === undefined) { + return + } + for (const attribute of Object.values(geometry.attributes)) { + bytes += (attribute.array as ArrayLike & { byteLength: number }).byteLength + } + bytes += (geometry.getIndex()?.array as { byteLength: number } | undefined)?.byteLength ?? 0 + }) + return bytes +} +const ABOVE_TOP_BLOCKS = 1 +const FOCUS_HALF_SIDE_BLOCKS = 256 + +/** The box the camera first frames: a square of blocks around the spot, from {@code lowY} to {@code highY}. */ +export function focusAround(centerX: number, centerZ: number, lowY: number, highY: number): Box3 { + return new Box3( + new Vector3(centerX - FOCUS_HALF_SIDE_BLOCKS, lowY, centerZ - FOCUS_HALF_SIDE_BLOCKS), + new Vector3(centerX + FOCUS_HALF_SIDE_BLOCKS, highY, centerZ + FOCUS_HALF_SIDE_BLOCKS) + ) +} + +/** + * Endless terrain drawn where the camera looks: tiles of one layer of a source, coarse ones first and then finer ones + * down to a column per pixel, fetched as the camera moves and kept within a memory budget, so going back is instant. + * Ground that was drawn before the layer changed stands in until its tile is sampled anew, and coarser tiles stand in + * for finer ones that are not there yet, so the view never empties while it catches up. + */ +export class TerrainStream { + readonly content: ViewportContent + private readonly group = new Group() + private readonly store: TileStore + private readonly drawn = new Map>() + private readonly sightListeners = new Set<() => void>() + private standIns = new Map() + private readonly building = new Map>() + private storedIndex: StoredIndex | null = null + private uploadBytesLeft = UPLOAD_BYTES_PER_FRAME + private nextFrame: number | null = null + private layer: Layer | null = null + private style: TerrainStyle | null = null + private styleVersion = 0 + private camera: CameraLink | null = null + private reportedPending = -1 + private continuation: ReturnType | null = null + private disposed = false + // Tiles are looked for where ground stands, not across the world's whole height: under a tall sky most of a tile's + // box is air, which lands in the view where its ground does not. + private lowestGround: number + private highestGround: number + private groundRangeGrew = false + + constructor(private readonly options: TerrainStreamOptions) { + this.lowestGround = options.focus.min.y + this.highestGround = options.focus.max.y + this.store = new TileStore(options.source, () => this.replan(), options.onError) + this.content = { + object: this.group, + bounds: options.focus, + isGround: true, + surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z))), + follow: (camera) => this.follow(camera) + } + } + + /** Draws another layer of the source; what is drawn now stays until the new layer's tiles replace it. */ + showLayer(layer: Layer): void { + if (this.layer !== null && this.options.source.layerKey(this.layer) === this.options.source.layerKey(layer)) { + this.layer = layer + return + } + this.standIns = new Map([...this.drawn].map(([key, drawn]) => [key, drawn.data])) + this.layer = layer + this.replan() + } + + /** Tells the listener whenever what the camera sees may have changed: it moved, or ground arrived; returns how to stop. */ + onSightChanged(listener: () => void): () => void { + this.sightListeners.add(listener) + return () => this.sightListeners.delete(listener) + } + + /** The ground the camera looks at now, or null while none is drawn there. */ + groundInView(): GroundInView | null { + if (this.camera === null || this.style === null) { + return null + } + return groundInView(this.camera.view(), this.style.topY + ABOVE_TOP_BLOCKS, { + surfaceTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z)), + groundTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.groundTopOver(x, z)) + }) + } + + /** Draws the tiles another way, without sampling them again. */ + restyle(style: TerrainStyle): void { + this.style = style + this.styleVersion++ + this.replan() + } + + dispose(): void { + this.disposed = true + this.sightListeners.clear() + if (this.continuation !== null) { + clearTimeout(this.continuation) + } + if (this.nextFrame !== null) { + cancelAnimationFrame(this.nextFrame) + } + this.drawn.forEach((drawn) => drawn.mesh.dispose()) + this.drawn.clear() + this.building.forEach((building) => building.mesh?.dispose()) + this.building.clear() + this.group.clear() + this.store.clear() + } + + private follow(camera: CameraLink): () => void { + this.camera = camera + const stop = camera.onMoved(() => this.replan()) + this.replan() + return () => { + stop() + this.camera = null + } + } + + private replan(): void { + if (this.disposed || this.layer === null || this.style === null || this.camera === null) { + return + } + const sight = new CameraSight(this.camera.view(), this.lowestGround, this.highestGround) + const layer = this.layer + const quick = this.options.quickLayerOf?.(layer) ?? null + const stateOf = (tile: TerrainTile): TileState => this.stateOf(tile, layer, quick) + const knownInside = (tile: TerrainTile): TerrainTile[] => [...this.coarsestStoredInside(tile, layer), ...this.drawnInside(tile)] + const cover = planCover(sight, stateOf, this.options.coarsestLevel, knownInside) + this.store.wantEach(this.wantedOf(cover.wanted, layer, quick)) + this.draw(cover, layer, quick, this.style) + this.reportPending() + this.sightListeners.forEach((listener) => listener()) + } + + // Quick tiles come first, so the view fills at once. The slow ones go finest first: the ground near the camera, whose + // blocks show the most, is not kept waiting behind the horizon's tiles, which each take far longer. + private wantedOf(tiles: TerrainTile[], layer: Layer, quick: Layer | null): { address: TileAddress; layer: Layer }[] { + if (quick === null) { + return tiles.map((tile) => ({ address: addressOf(tile), layer })) + } + const quickOnes = tiles.filter((tile) => !this.store.has(addressOf(tile), quick)).map((tile) => ({ address: addressOf(tile), layer: quick })) + const finestFirst = [...tiles].sort((first, second) => first.level - second.level) + return [...quickOnes, ...finestFirst.map((tile) => ({ address: addressOf(tile), layer }))] + } + + private stateOf(tile: TerrainTile, layer: Layer, quick: Layer | null): TileState { + if (this.store.has(addressOf(tile), layer)) { + return 'fresh' + } + if (this.standIns.has(tileKey(tile))) { + return 'standIn' + } + return quick !== null && this.store.has(addressOf(tile), quick) ? 'quick' : 'none' + } + + private dataOf(tile: TerrainTile, layer: Layer, quick: Layer | null): Tile | null { + const key = tileKey(tile) + const fresh = this.store.get(addressOf(tile), layer) + if (fresh !== null) { + this.standIns.delete(key) + return fresh + } + const quickTile = quick === null ? null : this.store.get(addressOf(tile), quick) + return this.standIns.get(key) ?? quickTile ?? null + } + + // Ground drawn now, such as a stand-in left from the layer before, stays until a tile as true replaces it. + private drawnInside(tile: TerrainTile): TerrainTile[] { + return [...this.drawn.values()].map((drawn) => drawn.tile).filter((finer) => isInside(finer, tile)) + } + + // The layer's tiles that have arrived inside the tile, however much finer, but only the coarsest over each spot: they + // show the ground as well from where it is too coarse for its own tile to have arrived, with the fewest faces. + private coarsestStoredInside(tile: TerrainTile, layer: Layer): TerrainTile[] { + const stored = this.storedIndexOf(layer) + const found: TerrainTile[] = [] + const lookInside = (parent: TerrainTile): void => { + for (const child of childrenOf(parent)) { + const key = tileKey(child) + if (stored.tiles.has(key)) { + found.push(child) + } else if (stored.holding.has(key)) { + lookInside(child) + } + } + } + if (stored.holding.has(tileKey(tile))) { + lookInside(tile) + } + return found + } + + private storedIndexOf(layer: Layer): StoredIndex { + const layerKey = this.options.source.layerKey(layer) + if (this.storedIndex?.version === this.store.version && this.storedIndex.layerKey === layerKey) { + return this.storedIndex + } + const index: StoredIndex = { version: this.store.version, layerKey, tiles: new Set(), holding: new Set() } + for (const address of this.store.addressesOf(layer)) { + const tile = tileAt(address) + index.tiles.add(tileKey(tile)) + for (let level = tile.level + 1; level <= this.options.coarsestLevel; level++) { + index.holding.add(tileKey(ancestorAt(tile, level))) + } + } + this.storedIndex = index + return index + } + + private draw(cover: Cover, layer: Layer, quick: Layer | null, style: TerrainStyle): void { + const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS + const stillDrawn = new Set() + let behind = false + // Finer tiles are built before the coarser ones get their holes, so running out of time leaves ground drawn twice, never a gap. + for (const draw of [...cover.draws].sort((first, second) => first.tile.level - second.tile.level)) { + const key = tileKey(draw.tile) + stillDrawn.add(key) + const data = this.dataOf(draw.tile, layer, quick) + if (data === null || this.isCurrent(this.drawn.get(key), data, draw)) { + continue + } + if (performance.now() > deadline) { + behind = true + continue + } + if (style.buildMesh === undefined) { + this.show(key, draw, this.builtNow(draw, data, style), data) + continue + } + this.showOnceBuilt(key, draw, data, cover, style.buildMesh, style.floorY) + } + for (const [key, building] of [...this.building]) { + if (!stillDrawn.has(key)) { + building.mesh?.dispose() + this.building.delete(key) + } + } + this.camera?.redraw() + if (this.groundRangeGrew) { + this.groundRangeGrew = false + this.continueLater() + } + if (behind) { + this.continueLater() + return + } + for (const [key, drawn] of [...this.drawn]) { + if (!stillDrawn.has(key) && !this.isReplacementBuilding(drawn.tile)) { + this.hide(key, drawn) + } + } + } + + private isCurrent(drawn: DrawnMesh | undefined, data: Tile, draw: DrawnTile): boolean { + return drawn !== undefined && drawn.data === data && drawn.signature === this.signatureOf(draw) + } + + private signatureOf(draw: DrawnTile): string { + const holes = draw.holes.map((hole) => `${hole.fromColumn},${hole.fromRow},${hole.toColumn},${hole.toRow}`).sort() + return `${this.styleVersion}/${holes.join(';')}` + } + + // Ground leaving the plan stays until what takes its place, a coarser tile over it or finer ones in it, is built. + private isReplacementBuilding(tile: TerrainTile): boolean { + for (const building of this.building.values()) { + if (building.mesh === null && (isInside(tile, building.tile) || isInside(building.tile, tile))) { + return true + } + } + return false + } + + private builtNow(draw: DrawnTile, data: Tile, style: TerrainStyle): TerrainMesh { + return buildTerrainMesh(style.surfaceOf(data, draw.tile), style.floorY, draw.holes) + } + + // A tile is built away from the frames, and shown once built. One with holes is shown only once the finer tiles that + // fill them are, so what it drew before stays meanwhile and the ground never shows a gap. + private showOnceBuilt(key: string, draw: DrawnTile, data: Tile, cover: Cover, buildMesh: NonNullable['buildMesh']>, base: number): void { + const signature = this.signatureOf(draw) + const building = this.building.get(key) + if (building !== undefined && building.data === data && building.signature === signature) { + const finer = cover.draws.filter((other) => isInside(other.tile, draw.tile)).map((other) => tileKey(other.tile)) + if (building.mesh === null || !finer.every((finerKey) => this.drawn.has(finerKey))) { + return + } + const bytes = bytesOf(building.mesh) + if (bytes > this.uploadBytesLeft && this.uploadBytesLeft < UPLOAD_BYTES_PER_FRAME) { + this.continueNextFrame() + return + } + this.uploadBytesLeft -= bytes + this.building.delete(key) + this.show(key, draw, building.mesh, data) + return + } + building?.mesh?.dispose() + const started: BuildingMesh = { tile: draw.tile, data, signature, mesh: null } + this.building.set(key, started) + buildMesh(data, draw.tile, base, draw.holes).then( + (mesh) => { + if (this.disposed || this.building.get(key) !== started) { + mesh.dispose() + return + } + started.mesh = mesh + this.continueLater() + }, + (error: Error) => { + if (!this.disposed && this.building.get(key) === started) { + this.building.delete(key) + this.options.onError(error.message) + } + } + ) + } + + private show(key: string, draw: DrawnTile, mesh: TerrainMesh, data: Tile): void { + const previous = this.drawn.get(key) + if (previous !== undefined) { + this.hide(key, previous) + } + this.group.add(mesh.object) + this.drawn.set(key, { tile: draw.tile, data, signature: this.signatureOf(draw), mesh }) + this.growGroundRangeOver(mesh.field) + } + + private growGroundRangeOver(field: ColumnField): void { + const tops = field.topRange + if (tops === null || (tops.lowest >= this.lowestGround && tops.highest <= this.highestGround)) { + return + } + this.lowestGround = Math.min(this.lowestGround, tops.lowest) + this.highestGround = Math.max(this.highestGround, tops.highest) + this.groundRangeGrew = true + } + + private hide(key: string, drawn: DrawnMesh): void { + this.group.remove(drawn.mesh.object) + drawn.mesh.dispose() + this.drawn.delete(key) + } + + // A frame hands the GPU only so many bytes of new meshes; the rest wait for the next, so a burst of tiles never stalls one. + private continueNextFrame(): void { + if (this.nextFrame !== null) { + return + } + this.nextFrame = requestAnimationFrame(() => { + this.nextFrame = null + this.uploadBytesLeft = UPLOAD_BYTES_PER_FRAME + this.replan() + }) + } + + private continueLater(): void { + if (this.continuation !== null) { + return + } + this.continuation = setTimeout(() => { + this.continuation = null + this.replan() + }, 0) + } + + private reportPending(): void { + const pending = this.store.pending() + if (pending !== this.reportedPending) { + this.reportedPending = pending + this.options.onPending(pending) + } + } + + // The finest drawn tile that knows the block answers; coarser ones have holes where finer ones are drawn. + private finestTopOver(worldX: number, worldZ: number, topOf: (field: ColumnField) => number | null): number | null { + for (let level = 0; level <= this.options.coarsestLevel; level++) { + const field = this.drawn.get(tileKey(tileContaining(worldX, worldZ, level)))?.mesh.field + const top = field === undefined ? null : topOf(field) + if (top !== null) { + return top + } + } + return null + } +} diff --git a/studio/src/renderer/src/scene/terrainTiles.test.ts b/studio/src/renderer/src/scene/terrainTiles.test.ts new file mode 100644 index 000000000..01f5d6750 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainTiles.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { addressOf, ancestorAt, childrenOf, columnsUnder, isInside, originXOf, originZOf, tileBlocks, tileContaining, tileKey } from './terrainTiles' + +describe('terrain tiles', () => { + it('lie edge to edge at every level, 128 columns of 2^level blocks across', () => { + expect(tileBlocks(0)).toBe(128) + expect(tileBlocks(3)).toBe(1024) + expect([originXOf({ level: 2, tileX: -1, tileZ: 3 }), originZOf({ level: 2, tileX: -1, tileZ: 3 })]).toEqual([-512, 1536]) + }) + + it('are found by the block they hold, also left and above the origin', () => { + expect(tileContaining(127.9, 128, 0)).toEqual({ level: 0, tileX: 0, tileZ: 1 }) + expect(tileContaining(-0.5, -128.5, 0)).toEqual({ level: 0, tileX: -1, tileZ: -2 }) + expect(tileContaining(1000, -1000, 3)).toEqual({ level: 3, tileX: 0, tileZ: -1 }) + }) + + it('ask the server for the same blocks a column to a pixel', () => { + expect(addressOf({ level: 3, tileX: -2, tileZ: 5 })).toEqual({ tileX: -2, tileZ: 5, blocksPerPixel: 8 }) + }) + + it('split into the four tiles of the level below that cover them', () => { + const tile = { level: 2, tileX: -1, tileZ: 1 } + const children = childrenOf(tile) + expect(children.map(tileKey)).toEqual(['1/-2/2', '1/-1/2', '1/-2/3', '1/-1/3']) + expect(children.every((child) => ancestorAt(child, 2).tileX === -1 && isInside(child, tile))).toBe(true) + }) + + it('belong to the coarser tile that holds them, however many levels up', () => { + expect(ancestorAt({ level: 0, tileX: -1, tileZ: 5 }, 3)).toEqual({ level: 3, tileX: -1, tileZ: 0 }) + expect(isInside({ level: 1, tileX: 3, tileZ: 3 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(true) + expect(isInside({ level: 1, tileX: 4, tileZ: 3 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(false) + expect(isInside({ level: 2, tileX: 1, tileZ: 1 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(false) + }) + + it('cover the columns of a coarser tile that line up with them', () => { + const coarse = { level: 2, tileX: 1, tileZ: -1 } + expect(columnsUnder(coarse, { level: 1, tileX: 3, tileZ: -1 })).toEqual({ fromColumn: 64, fromRow: 64, toColumn: 128, toRow: 128 }) + expect(columnsUnder(coarse, { level: 1, tileX: 2, tileZ: -2 })).toEqual({ fromColumn: 0, fromRow: 0, toColumn: 64, toRow: 64 }) + expect(columnsUnder(coarse, { level: 0, tileX: 7, tileZ: -3 })).toEqual({ fromColumn: 96, fromRow: 32, toColumn: 128, toRow: 64 }) + }) + + it('cover one column of a tile seven levels coarser, and no less', () => { + const coarse = { level: 7, tileX: 0, tileZ: 0 } + expect(columnsUnder(coarse, { level: 0, tileX: 5, tileZ: 9 })).toEqual({ fromColumn: 5, fromRow: 9, toColumn: 6, toRow: 10 }) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainTiles.ts b/studio/src/renderer/src/scene/terrainTiles.ts new file mode 100644 index 000000000..aa8021473 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainTiles.ts @@ -0,0 +1,98 @@ +import type { TileAddress } from '../map/viewport' + +/** Columns along one side of a terrain tile, at every level. */ +export const TILE_COLUMNS = 128 + +/** + * A square of terrain sampled in one go: {@link TILE_COLUMNS} by {@link TILE_COLUMNS} columns, each 2^level blocks wide. + * Tiles of a level lie edge to edge and each covers exactly four of the level below, so finer tiles can stand in for + * parts of a coarser one. + */ +export interface TerrainTile { + level: number + tileX: number + tileZ: number +} + +/** Past this many levels finer, a tile covers less than one column of a coarser one, which cannot be cut a hole. */ +export const MOST_LEVELS_FINER = Math.log2(TILE_COLUMNS) + +/** Columns of a tile, from the first up to but not including the last. */ +export interface ColumnArea { + fromColumn: number + fromRow: number + toColumn: number + toRow: number +} + +export function blocksPerColumn(level: number): number { + return 2 ** level +} + +export function tileBlocks(level: number): number { + return TILE_COLUMNS * blocksPerColumn(level) +} + +export function tileKey(tile: TerrainTile): string { + return `${tile.level}/${tile.tileX}/${tile.tileZ}` +} + +export function sameTile(first: TerrainTile, second: TerrainTile): boolean { + return first.level === second.level && first.tileX === second.tileX && first.tileZ === second.tileZ +} + +export function originXOf(tile: TerrainTile): number { + return tile.tileX * tileBlocks(tile.level) +} + +export function originZOf(tile: TerrainTile): number { + return tile.tileZ * tileBlocks(tile.level) +} + +/** The tile of {@code level} that holds the block. */ +export function tileContaining(worldX: number, worldZ: number, level: number): TerrainTile { + const blocks = tileBlocks(level) + return { level, tileX: Math.floor(worldX / blocks), tileZ: Math.floor(worldZ / blocks) } +} + +/** What to ask the bridge for: tile (x, z) of a layer sampled a column per pixel covers the same blocks. */ +/** The tile at an address, the reverse of {@link addressOf}. */ +export function tileAt(address: TileAddress): TerrainTile { + return { level: Math.round(Math.log2(address.blocksPerPixel)), tileX: address.tileX, tileZ: address.tileZ } +} + +export function addressOf(tile: TerrainTile): TileAddress { + return { tileX: tile.tileX, tileZ: tile.tileZ, blocksPerPixel: blocksPerColumn(tile.level) } +} + +/** The four tiles of the level below that cover this one. */ +export function childrenOf(tile: TerrainTile): TerrainTile[] { + const level = tile.level - 1 + const tileX = tile.tileX * 2 + const tileZ = tile.tileZ * 2 + return [ + { level, tileX, tileZ }, + { level, tileX: tileX + 1, tileZ }, + { level, tileX, tileZ: tileZ + 1 }, + { level, tileX: tileX + 1, tileZ: tileZ + 1 } + ] +} + +/** The tile of a coarser level that this one lies inside. */ +export function ancestorAt(tile: TerrainTile, level: number): TerrainTile { + const levelsUp = level - tile.level + return { level, tileX: tile.tileX >> levelsUp, tileZ: tile.tileZ >> levelsUp } +} + +export function isInside(tile: TerrainTile, coarser: TerrainTile): boolean { + return tile.level < coarser.level && sameTile(ancestorAt(tile, coarser.level), coarser) +} + +/** The columns of {@code coarser} that the finer tile inside it covers. */ +export function columnsUnder(coarser: TerrainTile, finer: TerrainTile): ColumnArea { + const levelsDown = coarser.level - finer.level + const across = TILE_COLUMNS >> levelsDown + const fromColumn = (finer.tileX - coarser.tileX * 2 ** levelsDown) * across + const fromRow = (finer.tileZ - coarser.tileZ * 2 ** levelsDown) * across + return { fromColumn, fromRow, toColumn: fromColumn + across, toRow: fromRow + across } +} diff --git a/studio/src/renderer/src/scene/textureAtlas.ts b/studio/src/renderer/src/scene/textureAtlas.ts new file mode 100644 index 000000000..261febd46 --- /dev/null +++ b/studio/src/renderer/src/scene/textureAtlas.ts @@ -0,0 +1,104 @@ +import { CanvasTexture, NearestFilter } from 'three' + +/** Where block textures come from: the bridge's copy of the client's assets. */ +export interface ImageSource { + /** The PNG at {@code path} below the assets folder, or null when there is none. */ + image(path: string): Promise +} + +/** Where one texture lies in the atlas, as a rectangle of the atlas from 0 to 1. */ +export interface AtlasCell { + u: number + v: number + width: number + height: number + /** Whether every pixel is fully opaque, so a block made of it hides its neighbours' faces. */ + solid: boolean +} + +const CELL_PIXELS = 16 +const CELLS_PER_ROW = 32 +const OPAQUE_ALPHA = 255 +const MISSING_TEXTURE_COLORS = ['#f800f8', '#000000'] + +/** + * The block textures of one scene in one image, each scaled to 16 pixels; an animated texture shows its first frame, + * and a missing one Minecraft's magenta and black checks. + */ +export class TextureAtlas { + readonly texture: CanvasTexture + + private constructor( + private readonly cells: Map, + canvas: HTMLCanvasElement + ) { + this.texture = new CanvasTexture(canvas) + this.texture.magFilter = NearestFilter + this.texture.minFilter = NearestFilter + this.texture.generateMipmaps = false + this.texture.flipY = false + } + + static async of(textureIds: string[], images: ImageSource): Promise { + const unique = [...new Set(textureIds)] + const bitmaps = await Promise.all(unique.map((id) => images.image(texturePath(id)).catch(() => null))) + const rows = Math.max(1, Math.ceil(unique.length / CELLS_PER_ROW)) + const canvas = document.createElement('canvas') + canvas.width = CELLS_PER_ROW * CELL_PIXELS + canvas.height = rows * CELL_PIXELS + const drawing = canvas.getContext('2d', { willReadFrequently: true })! + drawing.imageSmoothingEnabled = false + const cells = new Map() + unique.forEach((id, index) => { + const left = (index % CELLS_PER_ROW) * CELL_PIXELS + const top = Math.floor(index / CELLS_PER_ROW) * CELL_PIXELS + const bitmap = bitmaps[index] + if (bitmap === null) { + drawMissing(drawing, left, top) + } else { + drawing.drawImage(bitmap, 0, 0, bitmap.width, Math.min(bitmap.width, bitmap.height), left, top, CELL_PIXELS, CELL_PIXELS) + } + cells.set(id, { + u: left / canvas.width, + v: top / canvas.height, + width: CELL_PIXELS / canvas.width, + height: CELL_PIXELS / canvas.height, + solid: isSolid(drawing.getImageData(left, top, CELL_PIXELS, CELL_PIXELS).data) + }) + }) + return new TextureAtlas(cells, canvas) + } + + cell(textureId: string): AtlasCell { + return this.cells.get(textureId)! + } + + dispose(): void { + this.texture.dispose() + } +} + +/** {@code minecraft:block/stone} lies at {@code minecraft/textures/block/stone.png}. */ +export function texturePath(textureId: string): string { + const colon = textureId.indexOf(':') + return `${textureId.slice(0, colon)}/textures/${textureId.slice(colon + 1)}.png` +} + +function drawMissing(drawing: CanvasRenderingContext2D, left: number, top: number): void { + const half = CELL_PIXELS / 2 + for (let quarter = 0; quarter < 4; quarter++) { + const column = quarter % 2 + const row = Math.floor(quarter / 2) + drawing.fillStyle = MISSING_TEXTURE_COLORS[(column + row) % 2] + drawing.fillRect(left + column * half, top + row * half, half, half) + } +} + +function isSolid(pixels: Uint8ClampedArray): boolean { + for (let alpha = 3; alpha < pixels.length; alpha += 4) { + if (pixels[alpha] < OPAQUE_ALPHA) { + return false + } + } + return true +} diff --git a/studio/src/renderer/src/scene/texturedTerrain.test.ts b/studio/src/renderer/src/scene/texturedTerrain.test.ts new file mode 100644 index 000000000..bb1e48982 --- /dev/null +++ b/studio/src/renderer/src/scene/texturedTerrain.test.ts @@ -0,0 +1,209 @@ +import { Texture, Vector3, type BufferGeometry, type Mesh, type MeshBasicMaterial } from 'three' +import { describe, expect, it } from 'vitest' +import type { BlockLook, FaceLook } from './blockLooks' +import type { CoverLook } from './coverLooks' +import { cellAt, type TerrainPictures } from './terrainAtlas' +import { buildTerrainMesh, type RaisedBlock, type TerrainSurface } from './terrainMesh' + +const ORIGIN_X = 100 +const ORIGIN_Z = 200 +const PEAK_COLUMN = 1 +const PEAK_GROUND = 12 +const LOW_GROUND = 10 +const HIGH_GROUND = 70 +const FLOOR = 0 +const MOST_TEXTURED_SIDE_BLOCKS = 16 +const GRASS_TINT = 0x91bd59 +const WHITE = 0xffffff + +const plain = cellAt(0, WHITE) +const pictures: TerrainPictures = { texture: new Texture(), cutouts: new Texture(), plain } +const cellWidth = plain.width + +function face(index: number, tint = WHITE): FaceLook { + return { cell: cellAt(index, 0x808080), tint, color: 0x606060 } +} + +function gappyFace(index: number): FaceLook { + return { cell: cellAt(index, 0x808080, true), tint: WHITE, color: 0x606060 } +} + +const grass: BlockLook = { top: face(1, GRASS_TINT), side: face(2), below: face(3) } + +// Three by three columns of one-block ground, the middle one two blocks above the rest. +function surfaceOf(lookAt: TerrainSurface['lookAt'], ground = LOW_GROUND, withPictures = true): TerrainSurface { + return { + columns: 3, + rows: 3, + originX: ORIGIN_X, + originZ: ORIGIN_Z, + blocksPerColumn: 1, + groundAt: (column, row) => (column === PEAK_COLUMN && row === PEAK_COLUMN ? ground + (PEAK_GROUND - LOW_GROUND) : ground), + waterAt: () => null, + colorAt: () => 0x808080, + ...(withPictures ? { pictures, lookAt } : {}) + } +} + +function groundOf(terrain: TerrainSurface): Mesh { + return buildTerrainMesh(terrain, FLOOR).object.children[0] as Mesh +} + +interface Placed { + quad: number + middle: Vector3 + normal: Vector3 +} + +function placed(geometry: BufferGeometry): Placed[] { + const positions = geometry.getAttribute('position') + const found: Placed[] = [] + for (let quad = 0; quad < positions.count / 4; quad++) { + const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, quad * 4 + index) + const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)] + found.push({ + quad, + middle: origin.clone().add(far).multiplyScalar(0.5), + normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize() + }) + } + return found +} + +function uvOf(geometry: BufferGeometry, quad: number, corner: number): [number, number] { + const uvs = geometry.getAttribute('uv') + return [uvs.getX(quad * 4 + corner), uvs.getY(quad * 4 + corner)] +} + +function peakSides(ground: Mesh): Placed[] { + return placed(ground.geometry) + .filter((face) => face.normal.z === -1 && face.middle.x === ORIGIN_X + PEAK_COLUMN + 0.5 && face.middle.z === ORIGIN_Z + PEAK_COLUMN) + .sort((first, second) => second.middle.y - first.middle.y) +} + +describe('textured terrain', () => { + it('draws a top for every column, as tall as it is wide, with the texture of its block', () => { + const ground = groundOf(surfaceOf(() => grass)) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + + expect(tops).toHaveLength(9) + expect((ground.material as MeshBasicMaterial).map).toBe(pictures.texture) + const top = tops.find((candidate) => candidate.middle.x === ORIGIN_X + 0.5 && candidate.middle.z === ORIGIN_Z + 0.5)! + expect(uvOf(ground.geometry, top.quad, 0)).toEqual([grass.top.cell.u, grass.top.cell.v]) + expect(uvOf(ground.geometry, top.quad, 2)).toEqual([grass.top.cell.u + cellWidth, grass.top.cell.v]) + expect(uvOf(ground.geometry, top.quad, 1)).toEqual([grass.top.cell.u, grass.top.cell.v + cellWidth]) + }) + + it('multiplies the picture with the tint of its face, and with nothing on an untinted one', () => { + const ground = groundOf(surfaceOf(() => grass)) + const colors = ground.geometry.getAttribute('color') + const top = placed(ground.geometry).find((face) => face.normal.y === 1)! + const side = peakSides(ground)[0] + + expect(colors.getX(top.quad * 4)).toBeCloseTo(0x91 / 255) + expect(colors.getX(side.quad * 4)).toBeCloseTo(0.8) + }) + + it('shows the side of the top block over the blocks of the side below it, upright seen from outside', () => { + const ground = groundOf(surfaceOf(() => grass)) + const [topBlock, blockBelow] = peakSides(ground) + + expect(topBlock.middle.y).toBe(PEAK_GROUND + 1 - 0.5) + expect(blockBelow.middle.y).toBe(PEAK_GROUND + 1 - 1.5) + expect(uvOf(ground.geometry, topBlock.quad, 3)).toEqual([grass.side.cell.u, grass.side.cell.v]) + expect(uvOf(ground.geometry, topBlock.quad, 0)).toEqual([grass.side.cell.u + cellWidth, grass.side.cell.v + cellWidth]) + expect(uvOf(ground.geometry, blockBelow.quad, 3)).toEqual([grass.below.cell.u, grass.below.cell.v]) + }) + + it('draws deep sides as one flat quad in the average colour below the textured blocks', () => { + const ground = groundOf(surfaceOf(() => grass, HIGH_GROUND)) + const northEdge = placed(ground.geometry) + .filter((face) => face.normal.z === -1 && face.middle.x === ORIGIN_X + 1.5 && face.middle.z === ORIGIN_Z) + .sort((first, second) => second.middle.y - first.middle.y) + const deep = northEdge[northEdge.length - 1] + const texturedFloor = HIGH_GROUND + 1 - MOST_TEXTURED_SIDE_BLOCKS + + expect(northEdge).toHaveLength(MOST_TEXTURED_SIDE_BLOCKS + 1) + expect(deep.middle.y).toBe((FLOOR + texturedFloor) / 2) + expect(uvOf(ground.geometry, deep.quad, 0)).toEqual([plain.u + cellWidth / 2, plain.v + cellWidth / 2]) + expect(ground.geometry.getAttribute('color').getX(deep.quad * 4)).toBeCloseTo((0x60 / 255) * 0.8) + }) + + it('shows columns without a look in their colour on the plain cell, among textured ones', () => { + const ground = groundOf(surfaceOf((column, row) => (column === 0 && row === 0 ? null : grass))) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + const bare = tops.find((face) => face.middle.x === ORIGIN_X + 0.5 && face.middle.z === ORIGIN_Z + 0.5)! + + expect(tops).toHaveLength(9) + expect(uvOf(ground.geometry, bare.quad, 0)).toEqual([plain.u + cellWidth / 2, plain.v + cellWidth / 2]) + expect(ground.geometry.getAttribute('color').getX(bare.quad * 4)).toBeCloseTo(0x80 / 255) + }) + + it('keeps merging columns that show no texture, and draws no uvs for them', () => { + const ground = groundOf(surfaceOf(() => null)) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + + expect(tops).toHaveLength(5) + expect(ground.geometry.getAttribute('uv')).toBeUndefined() + expect((ground.material as MeshBasicMaterial).map).toBeNull() + }) + + it('stands a cover on the top face of its column, cut out along its picture', () => { + const blade: CoverLook = { + faces: [ + { + corners: [[0, 1, 0], [0, 0, 0], [1, 0, 1], [1, 1, 1]], + uvs: [[0, 0], [0, 1], [1, 1], [1, 0]], + cell: cellAt(4, WHITE), + color: [0.5, 0.75, 0.25], + cullFace: null + } + ] + } + const terrain = { ...surfaceOf(() => grass), coverAt: (column: number, row: number) => (column === PEAK_COLUMN && row === PEAK_COLUMN ? blade : null) } + const [, cover, water] = buildTerrainMesh(terrain, FLOOR).object.children as Mesh[] + const positions = cover.geometry.getAttribute('position') + const material = cover.material as MeshBasicMaterial + + expect(water).toBeDefined() + expect(positions.count).toBe(4) + expect([positions.getX(1), positions.getY(1), positions.getZ(1)]).toEqual([ORIGIN_X + PEAK_COLUMN, PEAK_GROUND + 1, ORIGIN_Z + PEAK_COLUMN]) + expect([positions.getX(3), positions.getY(3), positions.getZ(3)]).toEqual([ORIGIN_X + PEAK_COLUMN + 1, PEAK_GROUND + 2, ORIGIN_Z + PEAK_COLUMN + 1]) + expect(uvOf(cover.geometry, 0, 2)).toEqual([blade.faces[0].cell.u + cellWidth, blade.faces[0].cell.v + cellWidth]) + expect(cover.geometry.getAttribute('color').getY(0)).toBeCloseTo(0.75) + expect(material.alphaMap).toBe(pictures.cutouts) + expect(material.alphaTest).toBeGreaterThan(0) + }) + + it('cuts leaves out along their pictures and hides no face behind them, as with fancy graphics', () => { + const leaves: BlockLook = { top: gappyFace(5), side: gappyFace(5), below: gappyFace(5) } + const log: BlockLook = { top: face(6), side: face(7), below: face(7) } + // Two leaves stacked on the peak, a log beside the lower one. + const raisedAt = (column: number, row: number): RaisedBlock[] => { + if (column === PEAK_COLUMN && row === PEAK_COLUMN) { + return [{ y: PEAK_GROUND + 2, color: 0, look: leaves }, { y: PEAK_GROUND + 1, color: 0, look: leaves }] + } + return column === PEAK_COLUMN + 1 && row === PEAK_COLUMN ? [{ y: PEAK_GROUND + 1, color: 0, look: log }] : [] + } + const [ground, seeThrough, water] = buildTerrainMesh({ ...surfaceOf(() => grass), raisedAt }, FLOOR).object.children as Mesh[] + const leafFaces = placed(seeThrough.geometry) + const logBesideLeaf = placed(ground.geometry).filter((face) => face.normal.x === -1 && face.middle.x === ORIGIN_X + PEAK_COLUMN + 1 && face.middle.y === PEAK_GROUND + 1.5) + + expect(water).toBeDefined() + expect((seeThrough.material as MeshBasicMaterial).alphaMap).toBe(pictures.cutouts) + // The lower leaf shows all but its bottom on the ground and its side on the log; the upper one shows every face. + expect(leafFaces).toHaveLength(4 + 6) + expect(leafFaces.filter((face) => face.middle.y === PEAK_GROUND + 2)).toHaveLength(2) + expect(logBesideLeaf).toHaveLength(1) + }) + + it('draws no cover mesh where nothing stands on the ground', () => { + expect(buildTerrainMesh(surfaceOf(() => grass), FLOOR).object.children).toHaveLength(2) + }) + + it('draws a surface without an atlas in its colour alone', () => { + const ground = groundOf(surfaceOf(() => grass, LOW_GROUND, false)) + + expect(ground.geometry.getAttribute('uv')).toBeUndefined() + }) +}) diff --git a/studio/src/renderer/src/scene/voxelMesh.test.ts b/studio/src/renderer/src/scene/voxelMesh.test.ts new file mode 100644 index 000000000..569ca21cc --- /dev/null +++ b/studio/src/renderer/src/scene/voxelMesh.test.ts @@ -0,0 +1,110 @@ +import type { BufferGeometry } from 'three' +import { describe, expect, it } from 'vitest' +import type { TileVoxels } from '../bridge/types' +import type { Direction } from './blockModels' +import type { BlockLook } from './blockLooks' +import { ColumnField } from './columnField' +import type { CoverFace, CoverLook } from './coverLooks' +import { cellAt } from './terrainAtlas' +import type { TerrainSurface } from './terrainMesh' +import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' + +const GROUND = 10 +const DOWN = 1 +const UP = 1 << 1 +const NORTH = 1 << 2 +const STONE = 0 +const LEAVES = 1 +const GRASS = 2 +const WATER = 3 +const plain = cellAt(0, 0xffffff) +const stoneLook: BlockLook = { + top: { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 }, + side: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 }, + below: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 } +} + +function face(cullFace: Direction | null, gappy: boolean): CoverFace { + return { corners: [[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]], uvs: [[0, 0], [0, 1], [1, 1], [1, 0]], cell: cellAt(3, 0x00ff00, gappy), color: [0, 1, 0], cullFace } +} + +const leaves: CoverLook = { faces: (['down', 'up', 'north', 'south', 'west', 'east'] as const).map((side) => face(side, true)) } +const grass: CoverLook = { faces: [face(null, true), face(null, true)] } + +const surface: TerrainSurface = { + columns: 4, + rows: 4, + originX: 100, + originZ: 200, + blocksPerColumn: 1, + groundAt: () => GROUND, + waterAt: () => null, + colorAt: () => 0x808080 +} + +const FULL_LIGHT = 15 + +// Every face lit fully with no corner darkened, unless shades are given. +function voxelsOf(blocks: number[], faces: number[], shades?: number[]): SurfaceVoxels { + const shown = faces.reduce((count, sides) => count + sides.toString(2).split('1').length - 1, 0) + const voxels: TileVoxels = { + x: Uint8Array.from(blocks.map((_, at) => at)), + z: new Uint8Array(blocks.length), + y: new Int16Array(blocks.length).fill(GROUND), + blocks: Int16Array.from(blocks), + faces: Uint8Array.from(faces), + lights: new Uint8Array(blocks.length).fill(FULL_LIGHT), + shades: Uint16Array.from(shades ?? new Array(shown).fill(FULL_LIGHT)) + } + return { voxels, models: [null, leaves, grass, null], looks: [stoneLook, null, null, null], colors: [0x808080, 0, 0, 0], isWater: [false, false, false, true] } +} + +const faceCount = (geometry: BufferGeometry | null): number => (geometry === null ? 0 : geometry.getIndex()!.count / 6) + +describe('voxel mesh', () => { + it('draws a block without a model as a cube of its look, on the sides that face the open air', () => { + const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP]), plain) + + expect(faceCount(opaque)).toBe(1) + expect(faceCount(cutOut)).toBe(0) + expect(opaque!.getAttribute('position').getY(0)).toBe(GROUND + 1) + expect(opaque!.getAttribute('position').getX(0)).toBe(100) + }) + + it('leaves out the faces of a model a neighbour hides, and cuts out the faces of a picture with gaps', () => { + const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([LEAVES], [UP | NORTH]), plain) + + expect(faceCount(opaque)).toBe(0) + expect(faceCount(cutOut)).toBe(2) + }) + + it('draws every face of a model that nothing hides, such as a plant, whatever sides face the air', () => { + const { cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([GRASS], [0]), plain) + + expect(faceCount(cutOut)).toBe(2) + }) + + it('darkens a corner of a face where opaque blocks stand around it, and splits the face away from it', () => { + const cornerHidden = FULL_LIGHT | (3 << 4) + const { opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [cornerHidden]), plain) + const colors = opaque!.getAttribute('color') + + expect(colors.getY(0)).toBeLessThan(colors.getY(2) * 0.5) + expect(colors.getY(1)).toBeCloseTo(colors.getY(2)) + expect(Array.from(opaque!.getIndex()!.array)).toEqual([1, 2, 3, 1, 3, 0]) + }) + + it('darkens a face lit by less of the sky', () => { + const lit = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [FULL_LIGHT]), plain).opaque! + const shaded = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [8]), plain).opaque! + + expect(shaded.getAttribute('color').getY(0)).toBeLessThan(lit.getAttribute('color').getY(0) * 0.7) + }) + + it('draws water as the sides of its sheet that face the air', () => { + const { water, opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([WATER], [UP | DOWN]), plain) + + expect(faceCount(water)).toBe(2) + expect(faceCount(opaque)).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/scene/voxelMesh.ts b/studio/src/renderer/src/scene/voxelMesh.ts new file mode 100644 index 000000000..24f8987e1 --- /dev/null +++ b/studio/src/renderer/src/scene/voxelMesh.ts @@ -0,0 +1,271 @@ +import { BufferAttribute, BufferGeometry } from 'three' +import { VOXEL_SIDES, type TileVoxels } from '../bridge/types' +import type { Direction } from './blockModels' +import type { BlockLook, FaceLook } from './blockLooks' +import type { ColumnField } from './columnField' +import { shaded } from './columnFaces' +import { FACE_LIGHT, type CoverFace, type CoverLook } from './coverLooks' +import { brightnessOfCorner, brightnessOfLight, lightOf, opaqueAround } from './skyLight' +import type { UvCell } from './terrainAtlas' +import { sunk, tintAt } from './waterTint' + +type Corners = CoverFace['corners'] +type Uvs = CoverFace['uvs'] +type Color = readonly [number, number, number] + +/** The blocks of a tile seen from the open air, and how to draw each of the blocks they name. */ +export interface SurfaceVoxels { + voxels: TileVoxels + /** Each named block's model with its pictures placed, or null to draw it as a cube of its look or colour. */ + models: readonly (CoverLook | null)[] + looks: readonly (BlockLook | null)[] + colors: readonly number[] + /** Whether each named block is water, drawn as the water's sheet. */ + isWater: readonly boolean[] +} + +/** The faces of a tile's blocks: opaque ones, ones cut out along their pictures, and the water's. Null where there are none. */ +export interface VoxelGeometries { + opaque: BufferGeometry | null + cutOut: BufferGeometry | null + water: BufferGeometry | null +} + +const SIDE_BITS: Record = Object.fromEntries(VOXEL_SIDES.map((side, bit) => [side, 1 << bit])) as Record +const WHOLE_PICTURE: Uvs = [[0, 0], [0, 1], [1, 1], [1, 0]] +// A whole block's face on each side, top left, bottom left, bottom right and top right as seen from outside. +const CUBE_FACES: Record = { + down: [[0, 0, 1], [0, 0, 0], [1, 0, 0], [1, 0, 1]], + up: [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]], + north: [[1, 1, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0]], + south: [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]], + west: [[0, 1, 0], [0, 0, 0], [0, 0, 1], [0, 1, 1]], + east: [[1, 1, 1], [1, 0, 1], [1, 0, 0], [1, 1, 0]] +} +// The axis a side's faces look along: x, y or z. +const NORMAL_AXIS: Record = { down: 1, up: 1, north: 2, south: 2, west: 0, east: 0 } + +/** + * Each block seen from the open air drawn as Minecraft draws it: the faces of its model, leaving out a face its model + * lets a neighbour hide unless that side faces the open air. A block without a model is a cube of its look, or of its + * colour; water shows the sides that face the air. What lies under water sinks toward its deep colour as the ground does. + */ +export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plain: UvCell): VoxelGeometries { + const opaque = new FaceSoup(true) + const cutOut = new FaceSoup(true) + const water = new FaceSoup(false) + const { voxels } = surface + let firstShade = 0 + for (let at = 0; at < voxels.x.length; at++) { + const column = voxels.x[at] + const row = voxels.z[at] + const corner: Color = [field.originX + column, voxels.y[at], field.originZ + row] + const block = voxels.blocks[at] + const sides = voxels.faces[at] + const shades = new FaceShades(voxels.shades, firstShade, sides, voxels.lights[at]) + firstShade += shades.count + const waterTop = field.waterTopAt(column, row) + if (surface.isWater[block]) { + addCubeFaces(sides, (_side, corners) => water.add(corner, corners, null, null)) + continue + } + const model = surface.models[block] + if (model !== null) { + for (const face of model.faces) { + if (face.cullFace !== null && (sides & SIDE_BITS[face.cullFace]) === 0) { + continue + } + const color = underWater(face.color, corner[1] + middleY(face.corners), waterTop) + const brightness = face.cullFace === null ? shades.inside() : shades.across(face.cullFace, face.corners) + ;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), litCorners(color, brightness)) + } + continue + } + const look = surface.looks[block] + addCubeFaces(sides, (side, corners) => { + const face: FaceLook | null = look === null ? null : side === 'up' || side === 'down' ? look.top : look.side + const light = shaded(face === null ? surface.colors[block] : face.tint, FACE_LIGHT[side]) + const color = underWater(light, corner[1] + middleY(corners), waterTop) + const cell = face === null ? plain : face.cell + ;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), litCorners(color, shades.ofCube(side))) + }) + } + return { opaque: opaque.geometry(), cutOut: cutOut.geometry(), water: water.geometry() } +} + +type CornerBrightness = readonly [number, number, number, number] + +/** One block's face shades, as the server sent them for the sides it shows, read as each corner's brightness. */ +class FaceShades { + readonly count: number + + constructor( + private readonly shades: Uint16Array, + private readonly first: number, + private readonly sides: number, + private readonly ownLight: number + ) { + let count = 0 + for (let rest = sides; rest !== 0; rest &= rest - 1) { + count++ + } + this.count = count + } + + /** A whole face on a side, its corners in {@link CUBE_FACES}' order. */ + ofCube(side: Direction): CornerBrightness { + const shade = this.shadeOf(side) + const light = brightnessOfLight(lightOf(shade)) + return [0, 1, 2, 3].map((corner) => light * brightnessOfCorner(opaqueAround(shade, corner))) as unknown as CornerBrightness + } + + /** A model's face against a side, smaller than the block's, each corner as bright as that place of the whole face. */ + across(side: Direction, corners: Corners): CornerBrightness { + const whole = this.ofCube(side) + const cube = CUBE_FACES[side] + return corners.map((place) => { + let brightness = 0 + for (let corner = 0; corner < CORNERS; corner++) { + brightness += whole[corner] * weightAt(place, cube[corner], side) + } + return brightness + }) as unknown as CornerBrightness + } + + /** A face that stands inside the block, such as a plant's, lit as the block's own cell, with no corner darkened. */ + inside(): CornerBrightness { + const light = brightnessOfLight(this.ownLight) + return [light, light, light, light] + } + + private shadeOf(side: Direction): number { + const bit = SIDE_BITS[side] + let before = 0 + for (let rest = this.sides & (bit - 1); rest !== 0; rest &= rest - 1) { + before++ + } + return this.shades[this.first + before] + } +} + +// How much a corner of a whole face counts at a place on it: the product, along the face's two axes, of how near the +// place lies to the corner's edge. +function weightAt(place: Corners[number], corner: Corners[number], side: Direction): number { + const across = NORMAL_AXIS[side] + let weight = 1 + for (let axis = 0; axis < 3; axis++) { + if (axis !== across) { + weight *= corner[axis] === 1 ? place[axis] : 1 - place[axis] + } + } + return weight +} + +function litCorners(color: Color, brightness: CornerBrightness): Color[] { + return brightness.map((amount) => [color[0] * amount, color[1] * amount, color[2] * amount] as const) +} + +function addCubeFaces(sides: number, add: (side: Direction, corners: Corners) => void): void { + for (const side of VOXEL_SIDES) { + if ((sides & SIDE_BITS[side]) !== 0) { + add(side, CUBE_FACES[side]) + } + } +} + +function middleY(corners: Corners): number { + return (corners[0][1] + corners[2][1]) / 2 +} + +function underWater(color: Color, y: number, waterTop: number | null): Color { + return waterTop === null ? color : sunk(color, tintAt(waterTop - y)) +} + +function pictureUvs(cell: UvCell, uvs: Uvs): Uvs { + return uvs.map(([u, v]) => [cell.u + u * cell.width, cell.v + v * cell.height]) as unknown as Uvs +} + +const CORNERS = 4 +const FIRST_CAPACITY_FACES = 4096 + +/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colours. */ +class FaceSoup { + private positions: Float32Array = new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) + private uvs: Float32Array | null + private colors: Float32Array | null + // Whether each face is split along its other diagonal, as Minecraft splits one whose darker corners lie on the first, + // so the shading runs along the face and not across a crease. + private flipped: Uint8Array = new Uint8Array(FIRST_CAPACITY_FACES) + private faces = 0 + + constructor(textured: boolean) { + this.uvs = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 2) : null + this.colors = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) : null + } + + /** Adds a face, with a colour for each corner, or none. */ + add(origin: Color, corners: Corners, uvs: Uvs | null, colors: readonly Color[] | null): void { + this.reserveOne() + const first = this.faces * CORNERS + for (let corner = 0; corner < CORNERS; corner++) { + const vertex = first + corner + this.positions[vertex * 3] = origin[0] + corners[corner][0] + this.positions[vertex * 3 + 1] = origin[1] + corners[corner][1] + this.positions[vertex * 3 + 2] = origin[2] + corners[corner][2] + if (this.uvs !== null && uvs !== null) { + this.uvs[vertex * 2] = uvs[corner][0] + this.uvs[vertex * 2 + 1] = uvs[corner][1] + } + if (this.colors !== null && colors !== null) { + this.colors.set(colors[corner], vertex * 3) + } + } + this.flipped[this.faces] = colors !== null && sum(colors[0]) + sum(colors[2]) < sum(colors[1]) + sum(colors[3]) ? 1 : 0 + this.faces++ + } + + geometry(): BufferGeometry | null { + if (this.faces === 0) { + return null + } + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(this.positions.slice(0, this.faces * CORNERS * 3), 3)) + if (this.uvs !== null) { + geometry.setAttribute('uv', new BufferAttribute(this.uvs.slice(0, this.faces * CORNERS * 2), 2)) + } + if (this.colors !== null) { + geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, this.faces * CORNERS * 3), 3)) + } + const indices = new Uint32Array(this.faces * 6) + for (let face = 0; face < this.faces; face++) { + const first = face * CORNERS + const split = + this.flipped[face] === 1 ? [first + 1, first + 2, first + 3, first + 1, first + 3, first] : [first, first + 1, first + 2, first, first + 2, first + 3] + indices.set(split, face * 6) + } + geometry.setIndex(new BufferAttribute(indices, 1)) + return geometry + } + + private reserveOne(): void { + if ((this.faces + 1) * CORNERS * 3 <= this.positions.length) { + return + } + this.positions = grown(this.positions) + this.uvs = this.uvs === null ? null : grown(this.uvs) + this.colors = this.colors === null ? null : grown(this.colors) + const flipped = new Uint8Array(this.flipped.length * 2) + flipped.set(this.flipped) + this.flipped = flipped + } +} + +function sum(color: Color): number { + return color[0] + color[1] + color[2] +} + +function grown(values: Float32Array): Float32Array { + const bigger = new Float32Array(values.length * 2) + bigger.set(values) + return bigger +} diff --git a/studio/src/renderer/src/scene/waterTint.ts b/studio/src/renderer/src/scene/waterTint.ts new file mode 100644 index 000000000..d973768db --- /dev/null +++ b/studio/src/renderer/src/scene/waterTint.ts @@ -0,0 +1,34 @@ +import type { Vec3 } from './quadBatch' + +export const WATER_SURFACE_COLOR = 0x5a8ef0 +export const WATER_SURFACE_OPACITY = 0.3 +const DEEP_COLOR: Vec3 = [0x0f / 255, 0x25 / 255, 0x52 / 255] +const SHALLOW_TINT = 0.35 +const DEEPEST_TINT = 0.85 +/** How far down the tint covers about two thirds of the way from shallow to deepest. */ +const TINT_DEPTH_BLOCKS = 24 + +/** + * How much of the deep colour covers ground this many blocks under the water's surface; none for ground at or above + * it, so ground level with the surface stays dry. + */ +export function tintAt(depthBlocks: number): number { + return depthBlocks <= 0 ? 0 : submergedTint(depthBlocks) +} + +/** The same for ground known to lie under the surface, even at its very edge. */ +export function submergedTint(depthBlocks: number): number { + return SHALLOW_TINT + (DEEPEST_TINT - SHALLOW_TINT) * (1 - Math.exp(-depthBlocks / TINT_DEPTH_BLOCKS)) +} + +/** The colour sunk toward the deep colour by {@code tint}, from 0 for none to 1 for all of it. */ +export function sunk(color: Vec3, tint: number): Vec3 { + if (tint === 0) { + return color + } + return [mix(color[0], DEEP_COLOR[0], tint), mix(color[1], DEEP_COLOR[1], tint), mix(color[2], DEEP_COLOR[2], tint)] +} + +function mix(from: number, to: number, share: number): number { + return from + (to - from) * share +} diff --git a/studio/src/renderer/src/studio/BakeMeter.tsx b/studio/src/renderer/src/studio/BakeMeter.tsx new file mode 100644 index 000000000..424837d12 --- /dev/null +++ b/studio/src/renderer/src/studio/BakeMeter.tsx @@ -0,0 +1,87 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useEffect, useState } from 'react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { BakeRun } from '../bridge/types' +import { BAKE_RUN_COUNT, bakeWeightOf, formatMillis, measureBake, meterFill, runMillis, slowestStageIndex, weightScale } from '../scene/bakeTiming' + +const MINIMUM_FILL = '4px' +const MEASURING_LABEL = 'Timing' +const NANOS_PER_MILLI = 1_000_000 +const PERCENT = 100 + +/** + * The chosen entry's bake timed {@link BAKE_RUN_COUNT} times in the background, kept as the median run; null while it is + * timed. Opening another entry, or a pack reload, stops the runs under way. + */ +export function useBakeTiming(client: BridgeClient, viewId: string, key: string | null, baked: boolean, packRevision: number, tell: (message: string) => void): BakeRun | null { + const [timing, setTiming] = useState(null) + + useEffect(() => { + setTiming(null) + if (!baked || key === null) { + return + } + const stop = new AbortController() + measureBake( + () => client.sceneBake(viewId, key, stop.signal), + () => !stop.signal.aborted + ) + .then((median) => median !== null && setTiming(median)) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + return () => stop.abort() + }, [client, viewId, key, baked, packRevision, tell]) + + return timing +} + +interface BakeMeterProps { + /** The median bake of the chosen entry, or null while it is timed. */ + timing: BakeRun | null +} + +/** How heavy the chosen entry's bake is for the chunk that first places it: a rating, a meter and the time, with each step's time in the tooltip. */ +export function BakeMeter({ timing }: BakeMeterProps): React.JSX.Element { + const millis = timing === null ? 0 : runMillis(timing) + const weight = bakeWeightOf(millis) + return ( + + +
+ + + {timing === null ? MEASURING_LABEL : weight.label} + +
+ {timing !== null &&
} +
+ {timing !== null && formatMillis(millis)} +
+ + {timing === null ? `Baking every variant ${BAKE_RUN_COUNT} times over` : } + + ) +} + +function BakeExplanation({ timing }: { timing: BakeRun }): React.JSX.Element { + const slowest = slowestStageIndex(timing) + const variants = timing.variantCount === 1 ? '1 variant' : `${timing.variantCount} variants` + return ( +
+ + {variants} in {formatMillis(runMillis(timing))} · median of {BAKE_RUN_COUNT} runs + +
+ {timing.stages.map((stage, index) => ( +
+ {stage.label} + {formatMillis(stage.nanos / NANOS_PER_MILLI)} +
+ ))} +
+ Paid once per pack load, by the first chunk placing it + {weightScale()} +
+ ) +} diff --git a/studio/src/renderer/src/studio/BlockIcon.tsx b/studio/src/renderer/src/studio/BlockIcon.tsx new file mode 100644 index 000000000..aba3232d9 --- /dev/null +++ b/studio/src/renderer/src/studio/BlockIcon.tsx @@ -0,0 +1,34 @@ +import { useEffect, useRef, useState } from 'react' +import type { BlockColors } from '../scene/blockColors' +import { cn } from '@/lib/utils' + +/** The block's top texture as Minecraft draws it, 16 px and pixel-sharp; an empty square while it loads or when it has none. */ +export function BlockIcon({ block, blocks, className }: { block: string; blocks: BlockColors; className?: string }): React.JSX.Element { + const canvasRef = useRef(null) + const [missing, setMissing] = useState(true) + + useEffect(() => { + let active = true + setMissing(true) + void blocks.topTexture(block).then((texture) => { + const canvas = canvasRef.current + if (!active || texture === null || canvas === null) { + return + } + canvas.width = texture.width + canvas.height = texture.height + canvas.getContext('2d')!.putImageData(texture, 0, 0) + setMissing(false) + }) + return () => { + active = false + } + }, [block, blocks]) + + return ( + + + {missing && } + + ) +} diff --git a/studio/src/renderer/src/studio/ConnectScreen.tsx b/studio/src/renderer/src/studio/ConnectScreen.tsx new file mode 100644 index 000000000..b6fc69fe5 --- /dev/null +++ b/studio/src/renderer/src/studio/ConnectScreen.tsx @@ -0,0 +1,93 @@ +import { useEffect, useRef, useState } from 'react' +import { IdeIcon } from '@/components/IdeIcon' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import type { BridgeConnection } from '../../../shared/bridge' + +const BRIDGE_POLL_MILLIS = 2000 + +interface ConnectScreenProps { + connecting: boolean + error: string | null + onConnect(connection: BridgeConnection): void + onLink(link: string): void +} + +/** + * Lists the worlds servers on this machine opened to the studio, and takes a pasted link for any other. A single + * world is opened right away, once. + */ +export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectScreenProps): React.JSX.Element { + const [bridges, setBridges] = useState([]) + const [link, setLink] = useState('') + const openedOnItsOwn = useRef(false) + + useEffect(() => { + let active = true + const refresh = (): void => { + void window.studio.listBridges().then((found) => { + if (!active) { + return + } + setBridges(found) + if (found.length === 1 && !openedOnItsOwn.current) { + openedOnItsOwn.current = true + onConnect(found[0]) + } + }) + } + refresh() + const timer = window.setInterval(refresh, BRIDGE_POLL_MILLIS) + return () => { + active = false + window.clearInterval(timer) + } + }, [onConnect]) + + return ( +
+
+

Open a world

+

+ Run /iris studio map in game or in the + server console. +

+ +
+ {bridges.length === 0 ? ( +
+ Waiting for a server on this machine +
+ ) : ( + bridges.map((bridge) => ( + + )) + )} +
+ +
{ + event.preventDefault() + onLink(link) + }} + > + setLink(event.target.value)} placeholder="iris-studio://…" className="h-8" /> + +
+ {error !== null &&

{error}

} +
+
+ ) +} diff --git a/studio/src/renderer/src/studio/CurveField.tsx b/studio/src/renderer/src/studio/CurveField.tsx new file mode 100644 index 000000000..a88f6d010 --- /dev/null +++ b/studio/src/renderer/src/studio/CurveField.tsx @@ -0,0 +1,190 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { cn } from '@/lib/utils' +import { + CURVE_SHAPES, + isShape, + keyframesFrom, + samplesOf, + shapeFrom, + shapeNamed, + withAddedKeyframe, + withKeyframe, + withoutKeyframe, + withSetting, + withShape, + type Keyframe +} from '../editor/curves' +import { FieldRow, type SettingFieldProps } from './FieldRow' + +const SPARKLINE_WIDTH = 100 +const SPARKLINE_HEIGHT = 24 +const SPARKLINE_SAMPLES = 40 +const SPARKLINE_MARGIN = 2 + +interface CurveFieldProps extends SettingFieldProps { + open: boolean + onToggle(): void +} + +/** A value written as a curve: a sparkline of it that opens an editor for its keyframes, or for the named shape it follows. */ +export function CurveField(props: CurveFieldProps): React.JSX.Element { + const { value, locked, open, onToggle, onSet } = props + return ( + <> + + + + {open && onSet(JSON.stringify(next))} />} + + ) +} + +function Sparkline({ value }: { value: unknown }): React.JSX.Element { + const samples = samplesOf(value, SPARKLINE_SAMPLES) ?? [] + const low = Math.min(...samples) + const span = Math.max(...samples) - low + const drawable = SPARKLINE_HEIGHT - 2 * SPARKLINE_MARGIN + const points = samples.map((sample, index) => { + const x = (index / (samples.length - 1)) * SPARKLINE_WIDTH + const y = SPARKLINE_MARGIN + (span === 0 ? drawable / 2 : drawable - ((sample - low) / span) * drawable) + return `${x.toFixed(1)},${y.toFixed(1)}` + }) + return ( + + + + ) +} + +function CurveEditor({ value, locked, onWrite }: { value: unknown; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const byShape = isShape(value) + return ( +
+
+ + +
+ {isShape(value) ? : } +
+ ) +} + +function PointsEditor({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { + return ( + <> + {keys.map(([t, value], index) => ( +
+ next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> + next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> + +
+ ))} + + + ) +} + +function ShapeEditor({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const named = shapeNamed(shape.shape)! + const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) + return ( + <> + +
+ onWrite(withSetting(shape, 'from', next))} /> + onWrite(withSetting(shape, 'to', next))} /> +
+ {named.parameters.map((parameter) => ( + onWrite(withSetting(shape, parameter.name, next))} + /> + ))} + + ) +} + +interface NumberBoxProps { + label: string + value: number | undefined + placeholder?: string + disabled: boolean + /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ + onCommit(next: number | undefined): void +} + +function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { + const shown = value === undefined ? '' : String(value) + const [draft, setDraft] = useState(shown) + const [seen, setSeen] = useState(shown) + if (seen !== shown) { + setSeen(shown) + setDraft(shown) + } + const commit = (): void => { + if (draft === shown) { + return + } + const next = draft.trim() === '' ? undefined : Number(draft) + if (next !== undefined && !Number.isFinite(next)) { + setDraft(shown) + return + } + onCommit(next) + } + return ( + + ) +} diff --git a/studio/src/renderer/src/studio/EntryBrowser.tsx b/studio/src/renderer/src/studio/EntryBrowser.tsx new file mode 100644 index 000000000..0d916b35b --- /dev/null +++ b/studio/src/renderer/src/studio/EntryBrowser.tsx @@ -0,0 +1,255 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useEffect, useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' +import { folderPrefixOf } from '../editor/entryKeys' + +const NUMBER = new Intl.NumberFormat('en-US') +const DELETE_KEY = 'Delete' +const FOLDER_SEPARATOR = '/' +const ROW_PADDING_PX = 8 +const TREE_INDENT_PX = 14 +const CHEVRON_SLOT_PX = 18 + +/** An entry of a module view: its key, the name it is listed by, and the heading it is listed under (empty for none). */ +export interface BrowsableEntry { + key: string + name: string + group: string +} + +/** What the browser can do with the files of its entries, for a view whose entries are files of the pack. */ +export interface EntryFileActions { + /** Asks for a new entry, offering `folderPrefix`, such as `trees/`, to name it in. */ + onCreate(folderPrefix: string): void + /** Deletes the entry at `key`, once what still uses it was shown. */ + onDelete(key: string): void +} + +interface EntryBrowserProps { + title: string + entries: BrowsableEntry[] + current: string | null + onSelect(key: string): void + fileActions?: EntryFileActions + className?: string +} + +type MenuTarget = { entry: string } | { folder: string } | null + +/** A view's entries in a tree of their folders, with a search over keys, names and folders that opens every folder holding a match (v3e ObjectBrowser). */ +export function EntryBrowser({ title, entries, current, onSelect, fileActions, className }: EntryBrowserProps): React.JSX.Element { + const [search, setSearch] = useState('') + const [menuTarget, setMenuTarget] = useState(null) + const [openFolders, setOpenFolders] = useState>(new Set()) + const wanted = search.trim().toLowerCase() + const tree = useMemo(() => folderTreeOf(entries, wanted), [entries, wanted]) + const currentGroup = useMemo(() => entries.find((entry) => entry.key === current)?.group ?? '', [entries, current]) + useEffect(() => setOpenFolders((open) => withFolderAndAncestors(open, currentGroup)), [currentGroup]) + const toggleFolder = (path: string): void => setOpenFolders((open) => toggled(open, path)) + const tier: TierContext = { current, isOpen: (path) => wanted !== '' || openFolders.has(path), onToggle: toggleFolder, onSelect, fileActions } + const list = ( +
{ + const target = menuTargetOf(event.target) + setMenuTarget(target) + if (target !== null && 'entry' in target) { + onSelect(target.entry) + } + }} + > + + {tree.size === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} +
+ ) + return ( +
+
+
+

{title}

+ {fileActions !== undefined && ( + + )} +
+

{NUMBER.format(entries.length)} in the pack

+ setSearch(event.target.value)} + onKeyDown={(event) => event.key === 'Escape' && setSearch('')} + /> +
+ + {fileActions === undefined ? ( + list + ) : ( + !open && setMenuTarget(null)}> + {list} + + + )} + +
+ ) +} + +function EntryMenu({ target, actions }: { target: MenuTarget; actions: EntryFileActions }): React.JSX.Element { + if (target !== null && 'entry' in target) { + return ( + + actions.onCreate(folderPrefixOf(target.entry))}>New entry beside it… + actions.onDelete(target.entry)}> + Delete… + + + ) + } + const folder = target === null ? '' : target.folder + return ( + + actions.onCreate(folder === '' ? '' : `${folder}/`)}>{folder === '' ? 'New entry…' : `New entry in ${folder}…`} + + ) +} + +function menuTargetOf(eventTarget: EventTarget): MenuTarget { + if (!(eventTarget instanceof Element)) { + return null + } + const entry = eventTarget.closest('[data-entry-key]')?.dataset.entryKey + if (entry !== undefined) { + return { entry } + } + const folder = eventTarget.closest('[data-entry-folder]')?.dataset.entryFolder + return folder === undefined ? null : { folder } +} + +/** A folder of the tree: its path such as `trees/oak`, its subfolders and entries, and how many entries it holds in all. */ +interface FolderNode { + path: string + name: string + folders: FolderNode[] + entries: BrowsableEntry[] + size: number +} + +interface TierContext { + current: string | null + isOpen(path: string): boolean + onToggle(path: string): void + onSelect(key: string): void + fileActions?: EntryFileActions +} + +function FolderTier({ folder, depth, context }: { folder: FolderNode; depth: number; context: TierContext }): React.JSX.Element { + return ( + <> + {folder.folders.map((child) => ( + + ))} + {folder.entries.map((entry) => ( + + ))} + + ) +} + +function FolderBranch({ folder, depth, context }: { folder: FolderNode; depth: number; context: TierContext }): React.JSX.Element { + const open = context.isOpen(folder.path) + return ( + <> + + {open && } + + ) +} + +function EntryRow({ entry, depth, context }: { entry: BrowsableEntry; depth: number; context: TierContext }): React.JSX.Element { + const { fileActions } = context + return ( + + ) +} + +function indentOf(depth: number): number { + return ROW_PADDING_PX + depth * TREE_INDENT_PX +} + +/** The entries matching `wanted` as a tree of their folders, folders before entries at each tier. */ +function folderTreeOf(entries: BrowsableEntry[], wanted: string): FolderNode { + const root = folderNamed('') + const folders = new Map([['', root]]) + const folderAt = (path: string): FolderNode => { + const known = folders.get(path) + if (known !== undefined) { + return known + } + const folder = folderNamed(path) + folders.set(path, folder) + folderAt(parentOf(path)).folders.push(folder) + return folder + } + for (const entry of entries) { + if (wanted !== '' && ![entry.key, entry.name, entry.group].some((text) => text.toLowerCase().includes(wanted))) { + continue + } + folderAt(entry.group).entries.push(entry) + for (let path = entry.group; ; path = parentOf(path)) { + folderAt(path).size++ + if (path === '') { + break + } + } + } + return root +} + +function folderNamed(path: string): FolderNode { + return { path, name: path.slice(path.lastIndexOf(FOLDER_SEPARATOR) + 1), folders: [], entries: [], size: 0 } +} + +function parentOf(path: string): string { + return path.slice(0, Math.max(path.lastIndexOf(FOLDER_SEPARATOR), 0)) +} + +function withFolderAndAncestors(open: ReadonlySet, path: string): ReadonlySet { + const opened = new Set(open) + for (let folder = path; folder !== ''; folder = parentOf(folder)) { + opened.add(folder) + } + return opened.size === open.size ? open : opened +} + +function toggled(open: ReadonlySet, path: string): ReadonlySet { + const next = new Set(open) + if (!next.delete(path)) { + next.add(path) + } + return next +} diff --git a/studio/src/renderer/src/studio/EntryFileDialogs.tsx b/studio/src/renderer/src/studio/EntryFileDialogs.tsx new file mode 100644 index 000000000..67dbc477b --- /dev/null +++ b/studio/src/renderer/src/studio/EntryFileDialogs.tsx @@ -0,0 +1,150 @@ +import { useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import type { BridgeClient } from '../bridge/BridgeClient' +import { refusalOfNewKey } from '../editor/entryKeys' +import type { EntryFileActions } from './EntryBrowser' + +const MOST_USES_LISTED = 8 + +type Ask = { kind: 'create'; folderPrefix: string } | { kind: 'delete'; key: string; uses: string[] } + +interface EntryFiles { + actions: EntryFileActions + dialogs: React.JSX.Element | null +} + +/** + * Creating and deleting a view's entries: asking for a new key, and listing what still uses an entry before it goes to + * the trash. The new entry is listed once the pack has reloaded, so `onCreated` names it to be chosen then. + */ +export function useEntryFiles( + client: BridgeClient, + viewId: string, + keys: string[], + onCreated: (key: string) => void, + tell: (message: string) => void +): EntryFiles { + const [ask, setAsk] = useState(null) + const close = (): void => setAsk(null) + const actions = useMemo( + () => ({ + onCreate: (folderPrefix) => setAsk({ kind: 'create', folderPrefix }), + onDelete: (key) => { + client + .sceneUses(viewId, key) + .then((uses) => setAsk({ kind: 'delete', key, uses })) + .catch((failure: Error) => tell(failure.message)) + } + }), + [client, viewId, tell] + ) + const create = (key: string): void => { + close() + client + .sceneCreate(viewId, key) + .then(() => { + onCreated(key) + tell(`Created ${key}`) + }) + .catch((failure: Error) => tell(failure.message)) + } + const remove = (key: string): void => { + close() + client + .sceneDelete(viewId, key) + .then((to) => tell(`Moved ${key} to ${to}`)) + .catch((failure: Error) => tell(failure.message)) + } + const dialogs = + ask === null ? null : ask.kind === 'create' ? ( + + ) : ( + remove(ask.key)} onClose={close} /> + ) + return { actions, dialogs } +} + +interface NewEntryDialogProps { + initial: string + existing: string[] + onCreate(key: string): void + onClose(): void +} + +function NewEntryDialog({ initial, existing, onCreate, onClose }: NewEntryDialogProps): React.JSX.Element { + const [typed, setTyped] = useState(initial) + const key = typed.trim() + const refusal = refusalOfNewKey(key, existing) + return ( + !open && onClose()}> + +
{ + event.preventDefault() + if (refusal === null) { + onCreate(key) + } + }} + > + + New entry + Name, with its folders, like trees/oak + + setTyped(event.target.value)} /> +

{typed === initial ? '' : (refusal ?? '')}

+ + + + +
+
+
+ ) +} + +interface DeleteEntryDialogProps { + entryKey: string + uses: string[] + onDelete(): void + onClose(): void +} + +// Used elsewhere, Cancel has the focus; nothing using it, moving it to the trash does. +function DeleteEntryDialog({ entryKey, uses, onDelete, onClose }: DeleteEntryDialogProps): React.JSX.Element { + const unused = uses.length === 0 + return ( + !open && onClose()}> + + + Delete {entryKey}? + {unused ? 'Nothing in the pack uses it.' : 'Still used by these files, which will warn that it is missing:'} + + {!unused && ( +
    + {uses.slice(0, MOST_USES_LISTED).map((file) => ( +
  • + {file} +
  • + ))} + {uses.length > MOST_USES_LISTED &&
  • and {uses.length - MOST_USES_LISTED} more
  • } +
+ )} + + + + +
+
+ ) +} diff --git a/studio/src/renderer/src/studio/FieldRow.tsx b/studio/src/renderer/src/studio/FieldRow.tsx new file mode 100644 index 000000000..08a16163a --- /dev/null +++ b/studio/src/renderer/src/studio/FieldRow.tsx @@ -0,0 +1,41 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import type { SettingOption } from '../bridge/types' + +export interface SettingFieldProps { + option: SettingOption + /** What the file sets it to; undefined when it is not set. */ + value: unknown + locked: boolean + onSet(literal: string): void + onUnset(): void +} + +/** A setting's name on the left and, on the right, what edits it, with the button that unsets it and why the draft is refused. */ +export function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element { + return ( +
+
+ +
+ {children} + +
+
+ {problem !== null &&

{problem}

} +
+ ) +} + +export function defaultLabel(option: SettingOption): string { + if (option.defaultValue === null || option.defaultValue === undefined) { + return option.required ? 'Required' : 'Not set' + } + const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue) + return `Default ${text}` +} diff --git a/studio/src/renderer/src/studio/HelpDialog.tsx b/studio/src/renderer/src/studio/HelpDialog.tsx new file mode 100644 index 000000000..18c215bea --- /dev/null +++ b/studio/src/renderer/src/studio/HelpDialog.tsx @@ -0,0 +1,50 @@ +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Kbd } from '@/components/ui/kbd' +import type { ViewInfo } from '../bridge/types' +import { MOUSE_HINTS, keyTextOf, shortcutRows, type ShortcutGroup } from './shortcuts' +import { useBindings } from './useBindings' + +interface HelpDialogProps { + open: boolean + onOpenChange(open: boolean): void + views: ViewInfo[] +} + +const KEY_GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor'] + +/** Every key and mouse gesture of the map, with the keys as they are set now. */ +export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): React.JSX.Element { + const bindings = useBindings() + const rows = shortcutRows(views) + const groups = [ + ...KEY_GROUPS.map((group) => ({ + title: group, + rows: rows.filter((row) => row.group === group).map((row) => ({ key: keyTextOf(row.id, bindings), label: row.label })).filter((row) => row.key !== '') + })), + { title: 'Mouse', rows: MOUSE_HINTS.map((hint) => ({ key: hint.gesture, label: hint.label })) } + ] + return ( + + + + Shortcuts + +
+ {groups.map((group) => ( +
+

{group.title}

+
    + {group.rows.map((row) => ( +
  • + {row.label} + {row.key} +
  • + ))} +
+
+ ))} +
+
+
+ ) +} diff --git a/studio/src/renderer/src/studio/HoverCard.tsx b/studio/src/renderer/src/studio/HoverCard.tsx new file mode 100644 index 000000000..d8b003e90 --- /dev/null +++ b/studio/src/renderer/src/studio/HoverCard.tsx @@ -0,0 +1,145 @@ +import { useLayoutEffect, useRef, useState } from 'react' +import { Kbd } from '@/components/ui/kbd' +import type { MapHover, MapLabel } from '../bridge/types' +import { hexColor } from './colors' +import type { CanvasPoint } from './MapCanvas' +import { PickRows, replacedParent } from './PickRows' +import { useKeyText } from './useBindings' + +interface HoverCardProps { + hover: MapHover + point: CanvasPoint + viewId: string + /** The region view fills the map with one region's biomes, so the spot is described by its previewed biome. */ + previewing: boolean + detailed: boolean + minY: number +} + +const CURSOR_GAP_PIXELS = 18 +const EDGE_MARGIN_PIXELS = 8 + +interface Row { + label: string + value: string + mono?: boolean +} + +/** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */ +export function HoverCard({ hover, point, viewId, previewing, detailed, minY }: HoverCardProps): React.JSX.Element { + const card = useRef(null) + const highlightKey = useKeyText()('highlight') + const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS }) + + useLayoutEffect(() => { + const element = card.current + const parent = element?.parentElement + if (!element || !parent) { + return + } + const fitsRight = point.x + CURSOR_GAP_PIXELS + element.offsetWidth + EDGE_MARGIN_PIXELS <= parent.clientWidth + const fitsBelow = point.y + CURSOR_GAP_PIXELS + element.offsetHeight + EDGE_MARGIN_PIXELS <= parent.clientHeight + setPosition({ + left: fitsRight ? point.x + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.x - CURSOR_GAP_PIXELS - element.offsetWidth), + top: fitsBelow ? point.y + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.y - CURSOR_GAP_PIXELS - element.offsetHeight) + }) + }, [point, hover, detailed]) + + const labelsRegions = viewId === 'regions' && !previewing + const subject = labelsRegions ? hover.region : hover.biome + const groups = detailed ? detailGroups(hover) : [] + const parent = replacedParent(hover.pickPath) + return ( +
+
+
+ {parent !== null &&

child of {parent}

} +

{ground(hover, minY)}

+ + {groups.map((group) => ( +
+

{group.title}

+
+ {group.rows.map((row) => ( +
+
{row.label}
+
{row.value}
+
+ ))} +
+
+ ))} +
+
+ {!detailed && } + {highlightKey !== '' && } + +
+
+ ) +} + +function Header({ subject, region }: { subject: MapLabel | null; region: MapLabel | null }): React.JSX.Element { + return ( +
+ {subject !== null && } + {subject?.name ?? 'Nothing here'} + {region !== null && {region.name}} +
+ ) +} + +function Hint({ keyText, label }: { keyText: string; label: string }): React.JSX.Element { + return ( + + {keyText} + {label} + + ) +} + +/** Height as the world's Y, how far above or below the water, and how steep. */ +function ground(hover: MapHover, minY: number): string { + const aboveWater = Math.round(hover.height - hover.fluidHeight) + const signed = aboveWater > 0 ? `+${aboveWater}` : String(aboveWater) + return `Y ${Math.round(hover.height + minY)} · ${signed} from water · ${Math.round(hover.slopeDegrees)}°` +} + +function detailGroups(hover: MapHover): { title: string; rows: Row[] }[] { + const groups: { title: string; rows: Row[] }[] = [] + const terrain: Row[] = [] + if (hover.caveBiome !== null && hover.caveBiome.key !== hover.biome?.key) { + terrain.push({ label: 'Cave biome', value: hover.caveBiome.name }) + } + if (hover.vanillaBiome !== null) { + terrain.push({ label: 'Minecraft', value: hover.vanillaBiome.replace('minecraft:', '').replaceAll('_', ' ') }) + } + if (terrain.length > 0) { + groups.push({ title: 'Terrain', rows: terrain }) + } + const blockX = Math.floor(hover.worldX) + const blockZ = Math.floor(hover.worldZ) + groups.push({ + title: 'Location', + rows: [ + { label: 'Block', value: `${blockX}, ${blockZ}` }, + { label: 'Chunk', value: `${blockX >> 4}, ${blockZ >> 4}` }, + { label: 'Region file', value: `r.${blockX >> 9}.${blockZ >> 9}.mca`, mono: true } + ] + }) + const files: Row[] = [] + if (hover.biomeFile !== null) { + files.push({ label: 'Biome', value: hover.biomeFile, mono: true }) + } + if (hover.regionFile !== null) { + files.push({ label: 'Region', value: hover.regionFile, mono: true }) + } + if (files.length > 0) { + groups.push({ title: 'Files', rows: files }) + } + return groups +} diff --git a/studio/src/renderer/src/studio/Legend.tsx b/studio/src/renderer/src/studio/Legend.tsx new file mode 100644 index 000000000..66c525168 --- /dev/null +++ b/studio/src/renderer/src/studio/Legend.tsx @@ -0,0 +1,92 @@ +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' +import type { Share } from '../map/census' +import type { Highlight } from '../map/tileStyle' +import { hexColor } from './colors' + +const ROW = 'flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left' + +/** What highlighting does in a view that can highlight. */ +export interface LegendSelection { + highlight: Highlight | null + onSelect(subject: Highlight): void +} + +interface LegendProps { + title: string + shares: Share[] + /** Absent in a view with nothing to highlight, such as the 3D world, where the legend only lists. */ + selection?: LegendSelection + /** What to say while there is nothing to list. */ + emptyText?: string + className?: string +} + +/** What is on screen and how much of it each covers; clicking one highlights it on the map. */ +export function Legend({ title, shares, selection, emptyText = 'Drawing the map…', className }: LegendProps): React.JSX.Element { + const sharedNames = namesUsedMoreThanOnce(shares) + return ( +
+

{title}

+ +
    + {shares.length === 0 &&
  • {emptyText}
  • } + {shares.map((share) => { + const row = ( + <> + + + {share.subject.name} + {sharedNames.has(share.subject.name) && ( + {fileName(share.subject.key)} + )} + + {percent(share.fraction)} + + ) + const selected = selection?.highlight != null && selection.highlight.kind === share.subject.kind && selection.highlight.key === share.subject.key + return ( +
  • + {selection === undefined ? ( +
    {row}
    + ) : ( + + )} +
  • + ) + })} +
+
+ {selection !== undefined &&

Click to highlight · Esc clears

} +
+ ) +} + +function namesUsedMoreThanOnce(shares: Share[]): Set { + const seen = new Set() + const repeated = new Set() + for (const share of shares) { + if (seen.has(share.subject.name)) { + repeated.add(share.subject.name) + } + seen.add(share.subject.name) + } + return repeated +} + +function fileName(key: string): string { + return key.slice(key.lastIndexOf('/') + 1) +} + +function percent(fraction: number): string { + if (fraction < 0.001) { + return '<0.1%' + } + return fraction < 0.1 ? `${(fraction * 100).toFixed(1)}%` : `${Math.round(fraction * 100)}%` +} diff --git a/studio/src/renderer/src/studio/MapCanvas.tsx b/studio/src/renderer/src/studio/MapCanvas.tsx new file mode 100644 index 000000000..99ad5228c --- /dev/null +++ b/studio/src/renderer/src/studio/MapCanvas.tsx @@ -0,0 +1,204 @@ +import { useEffect, useRef, useState } from 'react' +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuSeparator, + ContextMenuTrigger +} from '@/components/ui/context-menu' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { WorldInfo } from '../bridge/types' +import { MapController, type MapListener, type SpotSubjects } from '../map/MapController' +import type { Highlight } from '../map/tileStyle' + +export interface CanvasPoint { + x: number + y: number +} + +interface MapCanvasProps { + client: BridgeClient + world: WorldInfo + viewId: string + controllerRef: React.RefObject + listener: MapListener + highlight: Highlight | null + onPointer(point: CanvasPoint | null): void + onDragged(): void + onTeleport(point: CanvasPoint): void + onOpenFile(point: CanvasPoint): void + onHighlight(subject: Highlight): void + onCopy(text: string): void +} + +// A press that moves less than this is a click, not a drag. +const CLICK_SLOP_PIXELS = 4 +// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads. +const WHEEL_ZOOM_PER_DELTA = 0.002 + +interface ContextSpot { + point: CanvasPoint + subjects: SpotSubjects + blockX: number + blockZ: number +} + +/** The map canvas and its mouse: drag to move, wheel to zoom, Ctrl+click to teleport, Alt+click to open a file. */ +export function MapCanvas(props: MapCanvasProps): React.JSX.Element { + const { client, world, viewId, controllerRef } = props + const canvasRef = useRef(null) + const latest = useRef(props) + latest.current = props + const [contextSpot, setContextSpot] = useState(null) + + useEffect(() => { + const canvas = canvasRef.current! + const map = new MapController(canvas, client, world, viewId, { + onStatus: (status) => latest.current.listener.onStatus(status), + onShares: (shares) => latest.current.listener.onShares(shares), + onArea: (area) => latest.current.listener.onArea(area), + onError: (message) => latest.current.listener.onError(message) + }) + controllerRef.current = map + const resize = new ResizeObserver(([entry]) => map.resize(entry.contentRect.width, entry.contentRect.height)) + resize.observe(canvas) + return () => { + resize.disconnect() + map.close() + controllerRef.current = null + } + // The controller lives as long as the connection; later view changes go through setView, not a new controller. + }, [client, world, controllerRef]) + + useMouse(canvasRef, controllerRef, latest) + + return ( + { + if (!open) { + setContextSpot(null) + } + }} + > + + { + const map = controllerRef.current + if (map === null) { + return + } + const point = canvasPoint(event) + const spot = map.worldAt(point.x, point.y) + setContextSpot({ point, subjects: map.subjectsAt(point.x, point.y), blockX: Math.floor(spot.x), blockZ: Math.floor(spot.z) }) + }} + /> + + + {contextSpot !== null && } + + + ) +} + +function SpotMenu({ spot, viewId, props }: { spot: ContextSpot; viewId: string; props: MapCanvasProps }): React.JSX.Element { + const { subject, region } = spot.subjects + const coordinates = `${spot.blockX}, ${spot.blockZ}` + return ( + <> + {subject !== null && props.onHighlight(subject)}>{highlightText(subject, props.highlight)}} + {region !== null && subject?.kind !== 'REGION' && ( + props.onHighlight(region)}>{highlightText(region, props.highlight)} + )} + props.onTeleport(spot.point)}>Teleport here + props.onOpenFile(spot.point)}>{viewId === 'regions' ? 'Open region file' : 'Open biome file'} + + props.onCopy(coordinates)}>Copy coordinates ({coordinates}) + + ) +} + +function highlightText(subject: Highlight, current: Highlight | null): string { + const highlighted = current !== null && current.kind === subject.kind && current.key === subject.key + return `${highlighted ? 'Clear highlight of' : 'Highlight'} ${subject.name}` +} + +function canvasPoint(event: { clientX: number; clientY: number; currentTarget: Element }): CanvasPoint { + const bounds = event.currentTarget.getBoundingClientRect() + return { x: event.clientX - bounds.left, y: event.clientY - bounds.top } +} + +function useMouse( + canvasRef: React.RefObject, + controllerRef: React.RefObject, + latest: React.RefObject +): void { + useEffect(() => { + const canvas = canvasRef.current! + let press: { x: number; y: number; lastX: number; lastY: number; dragged: boolean } | null = null + + const down = (event: PointerEvent): void => { + if (event.button !== 0) { + return + } + canvas.setPointerCapture(event.pointerId) + press = { x: event.clientX, y: event.clientY, lastX: event.clientX, lastY: event.clientY, dragged: false } + } + const move = (event: PointerEvent): void => { + const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas }) + controllerRef.current?.setCursor(point) + latest.current.onPointer(point) + if (press === null) { + return + } + if (!press.dragged && Math.hypot(event.clientX - press.x, event.clientY - press.y) >= CLICK_SLOP_PIXELS) { + press.dragged = true + latest.current.onDragged() + } + if (press.dragged) { + controllerRef.current?.panBy(event.clientX - press.lastX, event.clientY - press.lastY) + } + press.lastX = event.clientX + press.lastY = event.clientY + } + const up = (event: PointerEvent): void => { + if (press === null || event.button !== 0) { + return + } + const wasClick = !press.dragged + press = null + if (!wasClick) { + return + } + const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas }) + if (event.ctrlKey || event.metaKey) { + latest.current.onTeleport(point) + } else if (event.altKey) { + latest.current.onOpenFile(point) + } + } + const leave = (): void => { + controllerRef.current?.setCursor(null) + latest.current.onPointer(null) + } + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas }) + controllerRef.current?.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y) + } + + canvas.addEventListener('pointerdown', down) + canvas.addEventListener('pointermove', move) + canvas.addEventListener('pointerup', up) + canvas.addEventListener('pointerleave', leave) + canvas.addEventListener('wheel', wheel, { passive: false }) + return () => { + canvas.removeEventListener('pointerdown', down) + canvas.removeEventListener('pointermove', move) + canvas.removeEventListener('pointerup', up) + canvas.removeEventListener('pointerleave', leave) + canvas.removeEventListener('wheel', wheel) + } + }, [canvasRef, controllerRef, latest]) +} diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx new file mode 100644 index 000000000..ec7682bfd --- /dev/null +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -0,0 +1,525 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import type { ThemeChoice } from '../../../shared/bridge' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' +import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, ServerUsage, ViewInfo, WorldInfo } from '../bridge/types' +import type { Share } from '../map/census' +import type { MapController, MapStatus, MapToggles } from '../map/MapController' +import type { Highlight } from '../map/tileStyle' +import { HelpDialog } from './HelpDialog' +import { HoverCard } from './HoverCard' +import { Legend } from './Legend' +import { MapCanvas, type CanvasPoint } from './MapCanvas' +import { PickInspector } from './PickInspector' +import { RegionPreviewList } from './RegionPreviewList' +import { NoiseStudio } from './NoiseStudio' +import { PatternStudio } from './PatternStudio' +import { SavedWorldStudio } from './SavedWorldStudio' +import { SceneStudio } from './SceneStudio' +import { WorldStudio3D } from './WorldStudio3D' +import { isTypingInto, shortcutRows, viewOfShortcutId, windowShortcutFor, type ShortcutAction } from './shortcuts' +import { ShortcutSettings } from './ShortcutSettings' +import { Panel, ShownViewIcon, SidebarPanel, SidebarSlot, ViewIsland } from './Sidebar' +import { StatusBar } from './StatusBar' +import { MapTools, StudioToolbar } from './StudioToolbar' +import { useBindings } from './useBindings' +import { usePickInspection } from './usePickInspection' +import { ViewList, viewIcon } from './ViewList' + +const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25 +const ENTITY_POLL_MILLIS = 2000 +const NOTICE_MILLIS = 4000 +/** The views whose spots a noise picks, which the pick inspector explains. */ +const PICK_VIEWS = new Set(['biomes', 'regions']) + +interface MapStudioProps { + client: BridgeClient + world: WorldInfo + theme: { choice: ThemeChoice; next: () => void } + onDisconnect(): void +} + +export interface StudioToggles extends MapToggles { + follow: boolean + entities: boolean +} + +/** The map of one world: views on the left, the map in the middle, what is on screen on the right. */ +export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps): React.JSX.Element { + const controller = useRef(null) + const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes') + const [toggles, setToggles] = useState({ shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false }) + const [highlight, setHighlight] = useState(null) + const [status, setStatus] = useState(null) + const [shares, setShares] = useState([]) + const [players, setPlayers] = useState([]) + const [entities, setEntities] = useState([]) + const [usage, setUsage] = useState(null) + const [pointer, setPointer] = useState(null) + const [hover, setHover] = useState(null) + const [detailed, setDetailed] = useState(false) + const [helpOpen, setHelpOpen] = useState(false) + const [settingsOpen, setSettingsOpen] = useState(false) + const [notice, setNotice] = useState(null) + const [connected, setConnected] = useState(true) + const [preview, setPreview] = useState(null) + const [pickDisplay, setPickDisplay] = useState('picks') + const [area, setArea] = useState(null) + const [packRevision, setPackRevision] = useState(0) + const [sceneSummary, setSceneSummary] = useState(null) + const [sceneProgress, setSceneProgress] = useState(null) + const [sidebarSlot, setSidebarSlot] = useState(null) + const loadSceneViews = useCallback(() => client.sceneViews(), [client]) + const loadPatternViews = useCallback(() => client.patternViews(), [client]) + const sceneViews = useModuleViews(loadSceneViews, packRevision) + const patternViews = useModuleViews(loadPatternViews, packRevision) + const views = useMemo( + () => [...withAppViews(world.views), ...patternViews.map(asViewInfo), ...sceneViews.map(asViewInfo), NOISE], + [world.views, patternViews, sceneViews] + ) + const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null + const patternView = patternViews.find((candidate) => candidate.id === viewId) ?? null + const showsMap = sceneView === null && patternView === null && !APP_VIEW_IDS.has(viewId) + const view = views.find((candidate) => candidate.id === viewId) ?? views[0] + const layer = useMemo(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview]) + const regions = usePreviewableRegions(client, packRevision) + const inspectsPicks = PICK_VIEWS.has(viewId) + const inspection = usePickInspection(client, layer, area, inspectsPicks, packRevision) + const previewName = layer.preview === null ? null : (regions.find((region) => region.key === layer.preview)?.name ?? layer.preview) + + const tell = useCallback((message: string) => setNotice(message), []) + + useEffect(() => { + if (notice === null) { + return + } + const timer = window.setTimeout(() => setNotice(null), NOTICE_MILLIS) + return () => window.clearTimeout(timer) + }, [notice]) + + useEffect(() => controller.current?.setView(layer.view, layer.preview), [layer]) + useEffect(() => controller.current?.setPickDisplay(pickDisplay), [pickDisplay]) + useEffect(() => controller.current?.setToggles(toggles), [toggles]) + useEffect(() => controller.current?.setHighlight(highlight), [highlight]) + useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities]) + + useEffect(() => { + if (toggles.follow && players.length > 0) { + controller.current?.centerOn(players[0].worldX, players[0].worldZ) + } + }, [players, toggles.follow]) + + const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), []) + useServerEvents(client, controller, setPlayers, setUsage, tell, setConnected, packReloaded) + useEntities(client, toggles.entities, setEntities) + useHover(client, controller, layer, pointer, setHover) + + const selectView = useCallback((nextViewId: string) => { + setViewId(nextViewId) + setHighlight(null) + }, []) + + const selectPreview = useCallback((regionKey: string | null) => { + setPreview(regionKey) + setHighlight(null) + }, []) + + const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), []) + + const highlightUnderCursor = useCallback(() => { + if (pointer === null || controller.current === null) { + return + } + const { subject } = controller.current.subjectsAt(pointer.x, pointer.y) + setHighlight((current) => (subject === null || sameSubject(current, subject) ? null : subject)) + }, [pointer]) + + const runShortcut = useCallback( + (action: ShortcutAction) => { + const map = controller.current + switch (action) { + case 'nextView': + selectView(views[(views.findIndex((candidate) => candidate.id === viewId) + 1) % views.length].id) + return + case 'refresh': + map?.refresh() + tell('Redrawing with the latest pack files') + return + case 'zoomIn': + map?.zoomAt(KEYBOARD_ZOOM_FACTOR) + return + case 'zoomOut': + map?.zoomAt(1 / KEYBOARD_ZOOM_FACTOR) + return + case 'resetZoom': + map?.resetZoom() + return + case 'dismiss': + setHighlight(null) + return + case 'follow': + toggle('follow') + return + case 'grid': + toggle('grid') + return + case 'entities': + toggle('entities') + return + case 'highlight': + highlightUnderCursor() + return + case 'shading': + toggle('shading') + return + case 'blocks': + toggle('blocks') + return + case 'borders': + toggle('regionBorders') + return + case 'help': + setHelpOpen((open) => !open) + } + }, + [views, viewId, selectView, toggle, highlightUnderCursor, tell] + ) + + useKeyboard(runShortcut, selectView, setDetailed, views) + + const teleport = useCallback( + (point: CanvasPoint) => { + const spot = controller.current?.worldAt(point.x, point.y) + if (spot === undefined) { + return + } + client + .teleport(Math.floor(spot.x), Math.floor(spot.z)) + .then(() => tell(`Teleporting to ${Math.floor(spot.x)}, ${Math.floor(spot.z)}`)) + .catch((failure: Error) => tell(failure.message)) + }, + [client, tell] + ) + + const openFile = useCallback( + (point: CanvasPoint) => { + const spot = controller.current?.worldAt(point.x, point.y) + if (spot === undefined) { + return + } + client + .openInEditor(spot.x, spot.z, viewId) + .then((message) => tell(message ?? 'Opened')) + .catch((failure: Error) => tell(failure.message)) + }, + [client, viewId, tell] + ) + + return ( +
+ setHelpOpen(true)} onSettings={() => setSettingsOpen(true)} onDisconnect={onDisconnect} /> + + +
+ + {viewId === 'regions' && regions.length > 1 && ( + + + + )} + {sceneView !== null ? ( + + ) : patternView !== null ? ( + + ) : viewId === WORLD_3D.id ? ( + + ) : viewId === SAVED_WORLD.id ? ( + + ) : viewId === NOISE.id ? ( + + ) : ( + <> + runShortcut('refresh')} + onResetZoom={() => runShortcut('resetZoom')} + /> + } + > + setArea((current) => (sameRect(current, next) ? current : next)), onError: tell }} + onPointer={setPointer} + onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))} + onTeleport={teleport} + onOpenFile={openFile} + onHighlight={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))} + highlight={highlight} + onCopy={(text) => { + window.studio.copyText(text) + tell(`Copied ${text}`) + }} + /> + {pointer !== null && hover !== null && ( + + )} + {!connected && ( +
+
+

Lost the connection to the server

+ +
+
+ )} +
+
+ {inspectsPicks && ( + + + + )} + + setHighlight((current) => (sameSubject(current, subject) ? null : subject)) }} + /> + +
+ + )} +
+
+
+ + + +
+ ) +} + +const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' } +/** The app draws the 3D world from the server's biome tiles, so the server does not list it among its views. */ +const WORLD_3D: ViewInfo = { + id: 'world3d', + label: '3D world', + description: 'The terrain in 3D, coloured by biome, region or height, or as the blocks the world generates', + group: 'WORLD', + groupLabel: 'World' +} +const SAVED_WORLD: ViewInfo = { + id: 'savedWorld', + label: 'Saved world', + description: 'A world as the server saved it to disk, in 3D', + group: 'WORLD', + groupLabel: 'World' +} +const NOISE: ViewInfo = { + id: 'noise', + label: 'Noise', + description: "The pack's generators and expressions and the built-in noise styles, from above or as terrain", + group: 'PACK', + groupLabel: 'Pack' +} +const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id]) + +function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { + const afterRegions = serverViews.findIndex((candidate) => candidate.id === 'regions') + 1 + return [...serverViews.slice(0, afterRegions), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterRegions)] +} + +function asViewInfo(view: ModuleViewInfo): ViewInfo { + return { ...view, ...SCENE_GROUP } +} + +function statusLabel(viewLabel: string, previewName: string | null, sceneSummary: string | null): string { + const detail = sceneSummary ?? previewName + return detail === null ? viewLabel : `${viewLabel} · ${detail}` +} + +/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */ +function useModuleViews(load: () => Promise, packRevision: number): View[] { + const [views, setViews] = useState([]) + useEffect(() => { + let active = true + load() + .then((found) => active && setViews(found)) + .catch(() => undefined) + return () => { + active = false + } + }, [load, packRevision]) + return views +} + +function sameSubject(first: Highlight | null, second: Highlight | null): boolean { + return first !== null && second !== null && first.kind === second.kind && first.key === second.key +} + +function sameRect(first: WorldRect | null, second: WorldRect): boolean { + return first !== null && first.minX === second.minX && first.minZ === second.minZ && first.maxX === second.maxX && first.maxZ === second.maxZ +} + +function legendTitle(layer: MapLayerQuery): string { + if (layer.view === 'regions' && layer.preview === null) { + return 'Regions on screen' + } + return 'Biomes on screen' +} + +/** The regions the region view can preview, read again after the pack reloads. */ +function usePreviewableRegions(client: BridgeClient, packRevision: number): MapLabel[] { + const [regions, setRegions] = useState([]) + useEffect(() => { + let active = true + client + .regions() + .then((found) => active && setRegions(found)) + .catch(() => undefined) + return () => { + active = false + } + }, [client, packRevision]) + return regions +} + +/** Players, usage and hotloads from the server; the first world event only says the world runs, which is known. */ +function useServerEvents( + client: BridgeClient, + controller: React.RefObject, + setPlayers: (players: Marker[]) => void, + setUsage: (usage: ServerUsage) => void, + tell: (message: string) => void, + setConnected: (connected: boolean) => void, + onPackReloaded: () => void +): void { + useEffect(() => { + const stop = new AbortController() + let firstWorldEvent = true + void client.listen( + { + onWorld: (running) => { + if (firstWorldEvent) { + firstWorldEvent = false + return + } + if (running) { + controller.current?.refresh() + onPackReloaded() + tell('Pack reloaded, redrawing') + } else { + tell('The world stopped') + } + }, + onPlayers: setPlayers, + onUsage: setUsage, + onClosed: () => setConnected(false) + }, + stop.signal + ) + return () => stop.abort() + }, [client, controller, setPlayers, setUsage, tell, setConnected, onPackReloaded]) +} + +function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void { + useEffect(() => { + if (!visible) { + return + } + let active = true + const refresh = (): void => { + client + .entities() + .then((found) => active && setEntities(found)) + .catch(() => undefined) + } + refresh() + const timer = window.setInterval(refresh, ENTITY_POLL_MILLIS) + return () => { + active = false + window.clearInterval(timer) + } + }, [client, visible, setEntities]) +} + +/** Asks the server about the spot under the cursor; a newer spot aborts the question about an older one. */ +function useHover( + client: BridgeClient, + controller: React.RefObject, + layer: MapLayerQuery, + pointer: CanvasPoint | null, + setHover: (hover: MapHover | null) => void +): void { + useEffect(() => { + if (pointer === null || controller.current === null) { + setHover(null) + return + } + const spot = controller.current.worldAt(pointer.x, pointer.y) + const stop = new AbortController() + client + .hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal) + .then(setHover) + .catch(() => undefined) + return () => stop.abort() + }, [client, controller, layer, pointer, setHover]) +} + +function useKeyboard( + runShortcut: (action: ShortcutAction) => void, + selectView: (view: string) => void, + setDetailed: (detailed: boolean) => void, + views: ViewInfo[] +): void { + const bindings = useBindings() + useEffect(() => { + const rows = shortcutRows(views) + const down = (event: KeyboardEvent): void => { + if (event.key === 'Shift') { + setDetailed(true) + } + if (isTypingInto(event.target)) { + return + } + const id = windowShortcutFor(event, rows, bindings) + if (id === null) { + return + } + event.preventDefault() + const viewId = viewOfShortcutId(id) + if (viewId === null) { + runShortcut(id as ShortcutAction) + } else { + selectView(viewId) + } + } + const up = (event: KeyboardEvent): void => { + if (event.key === 'Shift') { + setDetailed(false) + } + } + const blur = (): void => setDetailed(false) + window.addEventListener('keydown', down) + window.addEventListener('keyup', up) + window.addEventListener('blur', blur) + return () => { + window.removeEventListener('keydown', down) + window.removeEventListener('keyup', up) + window.removeEventListener('blur', blur) + } + }, [runShortcut, selectView, setDetailed, views, bindings]) +} diff --git a/studio/src/renderer/src/studio/NodeCanvas.tsx b/studio/src/renderer/src/studio/NodeCanvas.tsx new file mode 100644 index 000000000..8b357bd2f --- /dev/null +++ b/studio/src/renderer/src/studio/NodeCanvas.tsx @@ -0,0 +1,314 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu' +import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' +import { cn } from '@/lib/utils' +import type { GraphEdit, GraphNode, JsonPath } from '../bridge/types' +import { idOf, isWithin, layoutNodes, NODE_HEIGHT, NODE_WIDTH, type NodeLayout, type PlacedNode } from '../editor/nodeLayout' +import { useKeyText } from './useBindings' + +const PART_ICON: IdeIconName = 'views/procedural' +const KIND_ICONS: Record = { + Object: 'views/objects', + Stem: PART_ICON, + Blob: PART_ICON, + Branches: PART_ICON, + Cluster: PART_ICON, + Group: 'groups', + 'Shared part': 'symlink', + Material: 'views/palettes', + Decoration: 'decoration' +} +const FIT_MARGIN = 24 +const LARGEST_FIT_SCALE = 1 +// Below this the node text can't be read; a larger tree is panned instead of shrunk further. +const SMALLEST_FIT_SCALE = 0.8 +const SMALLEST_SCALE = 0.25 +const LARGEST_SCALE = 2 +const WHEEL_ZOOM_PER_PIXEL = 0.0015 +const DRAG_START_PIXELS = 4 +const GRID_SPACING = 16 + +interface Camera { + x: number + y: number + scale: number +} + +interface NodeDrag { + placed: PlacedNode + startX: number + startY: number + pointerX: number + pointerY: number + moved: boolean + target: PlacedNode | null +} + +interface NodeCanvasProps { + roots: GraphNode[] + /** Tells files apart, so a new one is fitted into view. */ + fileKey: string + selectedId: string | null + locked: boolean + /** Filled with the way to fit every node into view, for the keys that live outside the canvas. */ + showAllRef: React.RefObject<(() => void) | null> + onSelect(node: GraphNode | null): void + onEdit(edit: GraphEdit): void +} + +/** The file as a tree of nodes: drag the background to look around, drag a node onto another to grow it from there. */ +export function NodeCanvas({ roots, fileKey, selectedId, locked, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element { + const layout = useMemo(() => layoutNodes(roots), [roots]) + const frame = useRef(null) + const [camera, setCamera] = useCamera(frame, layout, fileKey) + const [drag, setDrag] = useState(null) + const [menuNode, setMenuNode] = useState(null) + const pan = useRef<{ x: number; y: number } | null>(null) + const showAll = useCallback(() => setCamera(fitted(frame.current!, layout)), [setCamera, layout]) + useEffect(() => { + showAllRef.current = showAll + return () => { + showAllRef.current = null + } + }, [showAllRef, showAll]) + + const canvasPoint = (clientX: number, clientY: number): { x: number; y: number } => { + const bounds = frame.current!.getBoundingClientRect() + return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale } + } + + const pointerDown = (event: React.PointerEvent): void => { + if (event.button !== 0) { + return + } + event.currentTarget.setPointerCapture(event.pointerId) + const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY)) + if (placed === null) { + pan.current = { x: event.clientX, y: event.clientY } + return + } + setDrag({ placed, startX: event.clientX, startY: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, target: null }) + } + + const pointerMove = (event: React.PointerEvent): void => { + if (pan.current !== null) { + const [dx, dy] = [event.clientX - pan.current.x, event.clientY - pan.current.y] + pan.current = { x: event.clientX, y: event.clientY } + setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy })) + return + } + if (drag === null) { + return + } + const moved = drag.moved || Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > DRAG_START_PIXELS + const canMove = moved && !locked && drag.placed.node.movable + const target = canMove ? moveTarget(layout, drag.placed, canvasPoint(event.clientX, event.clientY)) : null + setDrag({ ...drag, pointerX: event.clientX, pointerY: event.clientY, moved, target }) + } + + const pointerUp = (): void => { + pan.current = null + if (drag === null) { + return + } + if (!drag.moved) { + onSelect(drag.placed.node) + } else if (drag.target !== null) { + onEdit({ op: 'move', path: drag.placed.node.path, toList: drag.target.node.childList! }) + } + setDrag(null) + } + + const dragging = drag !== null && drag.moved && drag.placed.node.movable && !locked + const dragOffset = dragging ? { x: (drag.pointerX - drag.startX) / camera.scale, y: (drag.pointerY - drag.startY) / camera.scale } : null + + return ( + !open && setMenuNode(null)}> + +
{ + pan.current = null + setDrag(null) + }} + onContextMenu={(event) => { + const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY)) + setMenuNode(placed?.node ?? null) + if (placed === null) { + event.preventDefault() + } else { + onSelect(placed.node) + } + }} + onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && showAll()} + > +
+ + {layout.nodes.map((placed) => ( + + ))} +
+
+
+ {menuNode !== null && } +
+ ) +} + +function NodeBox({ placed, selected, target, offset }: { placed: PlacedNode; selected: boolean; target: boolean; offset: { x: number; y: number } | null }): React.JSX.Element { + const { node } = placed + const icon = KIND_ICONS[node.kind] ?? PART_ICON + const detail = node.roles.length > 0 ? node.roles.join(', ') : node.title === node.kind ? null : node.kind + return ( +
+ +
+
{node.title}
+ {detail !== null &&
{detail}
} +
+
+ ) +} + +function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element { + return ( + + {layout.wires.map(({ from, to, label }) => { + const [startX, startY] = [from.x + NODE_WIDTH, from.y + NODE_HEIGHT / 2] + const [endX, endY] = [to.x, to.y + NODE_HEIGHT / 2] + const bend = (endX - startX) / 2 + return ( + ${to.id}`}> + + {label !== '' && ( + + {label} + + )} + + ) + })} + + ) +} + +function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element { + const keyText = useKeyText() + const removable = node.duplicable + return ( + + {node.additions.length > 0 && ( + + Add + + {node.additions.map((addition) => ( + onEdit({ op: 'append', list: addition.list, literal: addition.literal })}> + {addition.label} + + ))} + + + )} + onEdit({ op: 'duplicate', path: node.path })}> + Duplicate + {keyText('duplicateNode')} + + + onEdit({ op: 'delete', path: node.path })}> + Delete + {keyText('deleteNode')} + + + ) +} + +function nodeAt(layout: NodeLayout, point: { x: number; y: number }): PlacedNode | null { + return layout.nodes.find((placed) => point.x >= placed.x && point.x <= placed.x + NODE_WIDTH && point.y >= placed.y && point.y <= placed.y + NODE_HEIGHT) ?? null +} + +// A node can grow from any other that takes children, except from inside itself or from where it already grows. +function moveTarget(layout: NodeLayout, dragged: PlacedNode, point: { x: number; y: number }): PlacedNode | null { + const over = nodeAt(layout, point) + const toList = over?.node.childList + if (over === null || toList === null || toList === undefined || isWithin(toList, dragged.node.path) || isParentList(dragged.node.path, toList)) { + return null + } + return over +} + +function isParentList(path: JsonPath, list: JsonPath): boolean { + return path.length === list.length + 1 && isWithin(path, list) +} + +function useCamera(frame: React.RefObject, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch>] { + const [camera, setCamera] = useState({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 }) + const fittedFile = useRef(null) + + useEffect(() => { + if (frame.current === null || layout.nodes.length === 0 || fittedFile.current === fileKey) { + return + } + fittedFile.current = fileKey + setCamera(fitted(frame.current, layout)) + }, [frame, layout, fileKey]) + + useEffect(() => { + const element = frame.current + if (element === null) { + return + } + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const bounds = element.getBoundingClientRect() + const [pointerX, pointerY] = [event.clientX - bounds.left, event.clientY - bounds.top] + setCamera((current) => { + const scale = clamp(current.scale * Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL), SMALLEST_SCALE, LARGEST_SCALE) + const ratio = scale / current.scale + return { scale, x: pointerX - (pointerX - current.x) * ratio, y: pointerY - (pointerY - current.y) * ratio } + }) + } + element.addEventListener('wheel', wheel, { passive: false }) + return () => element.removeEventListener('wheel', wheel) + }, [frame]) + + return [camera, setCamera] +} + +function fitted(frame: HTMLDivElement, layout: NodeLayout): Camera { + const [width, height] = [frame.clientWidth - 2 * FIT_MARGIN, frame.clientHeight - 2 * FIT_MARGIN] + const scale = clamp(Math.min(width / Math.max(layout.width, 1), height / Math.max(layout.height, 1)), SMALLEST_FIT_SCALE, LARGEST_FIT_SCALE) + return { scale, x: FIT_MARGIN, y: FIT_MARGIN + Math.max(0, (height - layout.height * scale) / 2) } +} + +function clamp(value: number, lowest: number, highest: number): number { + return Math.min(highest, Math.max(lowest, value)) +} diff --git a/studio/src/renderer/src/studio/NodeInspector.tsx b/studio/src/renderer/src/studio/NodeInspector.tsx new file mode 100644 index 000000000..c3f60c7ae --- /dev/null +++ b/studio/src/renderer/src/studio/NodeInspector.tsx @@ -0,0 +1,295 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' +import type { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types' +import { canBecomeCurve, curveFrom, isCurve } from '../editor/curves' +import { valueAt } from '../editor/jsonValues' +import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from '../editor/settingFolds' +import { NOT_SET, isStringList, isText, literalOf, textOf } from '../editor/settingText' +import type { SuggestionStore } from '../editor/suggestionStore' +import { rolesOf, suggestionSourceOf, type SuggestionSource } from '../editor/suggestions' +import { CurveField } from './CurveField' +import { FieldRow, defaultLabel, type SettingFieldProps } from './FieldRow' +import { SuggestionInput } from './SuggestionInput' + +const FOLD_INDENT_PX = 10 + +interface NodeInspectorProps { + node: GraphNode + state: EditorState + /** The file parsed, to read what each setting is set to. */ + values: unknown + suggestions: SuggestionStore + onEdit(edit: GraphEdit): void +} + +/** What the fields of a section share: the file and the edits made to it, and which folds and curves are open. */ +interface SectionContext { + state: EditorState + values: unknown + locked: boolean + open: ReadonlySet + roles: string[] + suggestions: SuggestionStore + onToggle(id: string): void + onEdit(edit: GraphEdit): void +} + +/** The settings of the chosen node, a field per option of its schema type; an empty field leaves the option unset. */ +export function NodeInspector({ node, state, values, suggestions, onEdit }: NodeInspectorProps): React.JSX.Element { + const [open, setOpen] = useState>(new Set()) + const roles = useMemo(() => rolesOf(state.roots ?? []), [state.roots]) + const context: SectionContext = { + state, + values, + locked: state.locked !== null, + open, + roles, + suggestions, + onToggle: (id) => + setOpen((current) => { + const next = new Set(current) + if (!next.delete(id)) { + next.add(id) + } + return next + }), + onEdit + } + return ( +
+
+

{node.title}

+

{node.roles.length > 0 ? node.roles.join(', ') : node.kind}

+
+ +
+ {node.settings.map((section) => ( + + ))} +
+
+
+ ) +} + +function SettingsSection({ section, context }: { section: NodeSettings; context: SectionContext }): React.JSX.Element { + const { state, values, open } = context + const folds = visibleFolds(foldedSections(section, state.types, values), open) + return ( +
+ {folds.map((fold) => + fold.kind === 'own' ? ( +
+

+ {fold.title} +

+ +
+ ) : ( +
+ + {open.has(idOfFold(fold)) && } +
+ ) + )} +
+ ) +} + +function FoldHeader({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { + const { open, locked, onToggle, onEdit } = context + const id = idOfFold(fold) + const unfolded = open.has(id) + const holder = fold.holder + return ( +
+ + {fold.kind === 'list' && ( + + )} + {holder !== null && ( + + )} + {fold.kind === 'item' && ( + + )} +
+ ) +} + +function FoldFields({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { + const { values, locked, open, roles, suggestions, onToggle, onEdit } = context + return ( +
+ {fold.options.map((option) => { + const value = valueAt(values, [...fold.path, option.name]) + const curveId = JSON.stringify([...fold.path, option.name]) + return ( + onToggle(curveId)} + loadSuggestions={(source) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source))} + onSet={(literal) => onEdit({ op: 'set', object: fold.path, key: option.name, literal })} + onUnset={() => onEdit({ op: 'unset', object: fold.path, key: option.name })} + /> + ) + })} +
+ ) +} + +interface FieldProps extends SettingFieldProps { + /** The schema type of the object the option is in. */ + owner: string + curveOpen: boolean + onToggleCurve(): void + loadSuggestions(source: SuggestionSource): Promise +} + +function SettingField(props: FieldProps): React.JSX.Element { + const kind = props.option.kind.kind + if (kind === 'boolean' || kind === 'enum') { + return + } + if (kind === 'any' && isCurve(props.value)) { + return + } + return +} + +function ChoiceField(props: SettingFieldProps): React.JSX.Element { + const { option, value, locked, onSet, onUnset } = props + const choices = option.kind.kind === 'enum' ? option.kind.constants.map((constant) => constant.name) : ['true', 'false'] + const literalOfChoice = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice) + return ( + + + + ) +} + +// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written. +// A number or range of an option that takes any JSON value can be made a curve, which a curve is an option's to take. +function TypedField(props: FieldProps): React.JSX.Element { + const { option, value, locked, owner, onSet, onUnset, onToggleCurve, loadSuggestions } = props + const shown = textOf(option.kind, value) + const [draft, setDraft] = useState(shown) + const problem = draft.trim() === NOT_SET ? null : problemWith(option, draft) + const source = suggestionSourceOf(owner, option) + const commit = (): void => { + if (draft === shown || problem !== null) { + return + } + if (draft.trim() === NOT_SET) { + onUnset() + return + } + onSet(literalOf(option.kind, draft)) + } + return ( + + loadSuggestions(source)} + disabled={locked} + placeholder={defaultLabel(option)} + aria-invalid={problem !== null} + title={option.description} + inputMode={isNumber(option.kind) ? 'decimal' : undefined} + className={cn('h-7 px-2 text-[12px] md:text-[12px]', isNumber(option.kind) ? 'tabular-nums' : !isText(option.kind) && 'font-mono text-[11.5px] placeholder:font-sans md:text-[11.5px]')} + onBlur={commit} + onKeyDown={(event) => { + if (event.key === 'Enter') { + commit() + } else if (event.key === 'Escape') { + setDraft(shown) + } + }} + /> + {option.kind.kind === 'any' && canBecomeCurve(value) && ( + + )} + + ) +} + +function isNumber(kind: ValueKind): boolean { + return kind.kind === 'integer' || kind.kind === 'decimal' +} + +function problemWith(option: SettingOption, draft: string): string | null { + if (isText(option.kind) || isStringList(option.kind)) { + return isStringList(option.kind) && draft.trim().startsWith('[') && !isJson(draft) ? 'Not JSON' : null + } + if (!isNumber(option.kind)) { + return isJson(draft) ? null : 'Not JSON' + } + const number = Number(draft) + if (draft.trim() === '' || !Number.isFinite(number)) { + return 'Not a number' + } + if (option.kind.kind === 'integer' && !Number.isInteger(number)) { + return 'Not a whole number' + } + if (option.minimum !== null && number < option.minimum) { + return `At least ${option.minimum}` + } + if (option.maximum !== null && number > option.maximum) { + return `At most ${option.maximum}` + } + return null +} + +function isJson(text: string): boolean { + try { + JSON.parse(text) + return true + } catch { + return false + } +} diff --git a/studio/src/renderer/src/studio/NodePane.tsx b/studio/src/renderer/src/studio/NodePane.tsx new file mode 100644 index 000000000..cec2168a0 --- /dev/null +++ b/studio/src/renderer/src/studio/NodePane.tsx @@ -0,0 +1,110 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useEffect, useRef } from 'react' +import { Button } from '@/components/ui/button' +import type { GraphNode } from '../bridge/types' +import type { NodeEditor } from '../editor/useNodeEditor' +import { NodeCanvas } from './NodeCanvas' +import { isInEntryBrowser, isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts' +import { useBindings } from './useBindings' + +interface NodePaneProps { + editor: NodeEditor + /** The entry the file belongs to. */ + entryKey: string + selected: GraphNode | null + onSelect(node: GraphNode | null): void +} + +/** The node editor under the scene: the entry's file as nodes, with undo and redo. */ +export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps): React.JSX.Element { + const { state } = editor + const locked = state === null || state.locked !== null + const showAllRef = useRef<(() => void) | null>(null) + useEditorKeys(editor, selected, locked, showAllRef, onSelect) + + return ( +
+
+

Nodes

+ {state?.file ?? entryKey} + + {state?.locked != null && ( + + + Read only + + )} + {editor.saving && Saving…} + + +
+
+ {state === null &&

Reading the file…

} + {state !== null && state.roots === null && ( +
+

This file can't be shown as nodes

+

{state.problem}

+
+ )} + {state !== null && state.roots !== null && ( + + )} +
+
+ ) +} + +function useEditorKeys( + editor: NodeEditor, + selected: GraphNode | null, + locked: boolean, + showAllRef: React.RefObject<(() => void) | null>, + onSelect: (node: GraphNode | null) => void +): void { + const { undo, redo, edit } = editor + const bindings = useBindings() + useEffect(() => { + const editSelected = (action: NodeEditorAction, event: KeyboardEvent): void => { + if (action === 'undo') { + event.preventDefault() + undo() + } else if (action === 'redo') { + event.preventDefault() + redo() + } else if (selected !== null && selected.duplicable) { + event.preventDefault() + edit({ op: action === 'deleteNode' ? 'delete' : 'duplicate', path: selected.path }) + } + } + // Captured, so the editor's keys come before the window's own: F fits the nodes instead of following the player. + const down = (event: KeyboardEvent): void => { + const action = isTypingInto(event.target) ? null : nodeEditorActionFor(event, bindings) + if (action === 'deleteNode' && isInEntryBrowser(event.target)) { + return + } + if (action === 'dismiss') { + onSelect(null) + } else if (action === 'showAllNodes' && showAllRef.current !== null) { + event.preventDefault() + event.stopImmediatePropagation() + showAllRef.current() + } else if (action !== null && action !== 'showAllNodes' && !locked) { + editSelected(action, event) + } + } + window.addEventListener('keydown', down, true) + return () => window.removeEventListener('keydown', down, true) + }, [undo, redo, edit, selected, locked, bindings, showAllRef, onSelect]) +} diff --git a/studio/src/renderer/src/studio/NoiseChart.tsx b/studio/src/renderer/src/studio/NoiseChart.tsx new file mode 100644 index 000000000..8ab7b37b2 --- /dev/null +++ b/studio/src/renderer/src/studio/NoiseChart.tsx @@ -0,0 +1,131 @@ +import { useState } from 'react' +import { cn } from '@/lib/utils' +import type { PickShare, PickSpread } from '../bridge/types' +import { hexColor } from './colors' + +// A long table keeps the options with the most ground in view until asked for all. +const SHORT_TABLE_ROWS = 6 +// An option getting under half or over twice its share of the noise stands out. +const FAR_FROM_WEIGHT_FACTOR = 2 + +interface NoiseChartProps { + spread: PickSpread + /** What the noise picks, as the table's heading: "Regions" or "Biomes". */ + optionNoun: string +} + +/** + * One noise that picks regions or biomes: how its values in view spread over the bands that pick each option, and a + * table of each option's share of the noise against its share of the ground in view (v3e NoisePickChart). + */ +export function NoiseChart({ spread, optionNoun }: NoiseChartProps): React.JSX.Element { + if (spread.rows.length === 1) { + return ( +
+ {spread.title} +
+ + Picked everywhere +
+
+ ) + } + return ( +
+ {spread.title} + + +
+ ) +} + +function ChartTitle({ children }: { children: React.ReactNode }): React.JSX.Element { + return

{children}

+} + +function Spread({ spread }: { spread: PickSpread }): React.JSX.Element { + const peak = Math.max(1, ...spread.histogram) + return ( +
+
+ {spread.histogram.map((count, bin) => ( + + ))} + {spread.bands.slice(0, -1).map((band, index) => ( + + ))} +
+
+ {spread.bands.map((band, index) => ( + + ))} +
+
+ 0 + 0.5 + 1 +
+
+ ) +} + +function ShareTable({ rows, optionNoun }: { rows: PickShare[]; optionNoun: string }): React.JSX.Element { + const [showsAll, setShowsAll] = useState(false) + const long = rows.length > SHORT_TABLE_ROWS + const shown = showsAll || !long ? rows : largestInView(rows) + return ( +
+ {optionNoun} + Weight + In view + {shown.map((share) => ( + + ))} + {long && ( + + )} +
+ ) +} + +function ShareRow({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element { + const farFromWeight = share.inView * FAR_FROM_WEIGHT_FACTOR < share.weight || share.inView > share.weight * FAR_FROM_WEIGHT_FACTOR + return ( + <> + + {percent(share.weight)} + {percent(share.inView)} + + ) +} + +// Two biomes in different folders can share a name, so their keys tell them apart. +function OptionName({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element { + const shared = rows.some((other) => other !== share && other.option.name === share.option.name) + return ( + + + {shared ? `${share.option.name} (${share.option.key})` : share.option.name} + + ) +} + +/** The rows with the most ground in view, still in the order the noise meets them. */ +export function largestInView(rows: PickShare[]): PickShare[] { + const largest = new Set([...rows].sort((first, second) => second.inView - first.inView).slice(0, SHORT_TABLE_ROWS)) + return rows.filter((row) => largest.has(row)) +} + +export function percent(fraction: number): string { + if (fraction > 0 && fraction < 0.001) { + return '<0.1%' + } + return `${(fraction * 100).toFixed(1)}%` +} diff --git a/studio/src/renderer/src/studio/NoiseStudio.tsx b/studio/src/renderer/src/studio/NoiseStudio.tsx new file mode 100644 index 000000000..641edb1bb --- /dev/null +++ b/studio/src/renderer/src/studio/NoiseStudio.tsx @@ -0,0 +1,338 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { NoiseSource, NoiseTile } from '../bridge/types' +import type { TiledFraming as TerrainFraming } from '../map/TiledView' +import { NOISE_PALETTES, noiseScale, type NoisePaletteId, type NoiseScale } from '../noise/noiseScale' +import { NoiseTerrain } from '../noise/noiseTerrain' +import { createNoiseView, noiseTileSource, type NoiseLayer, type NoiseStatus, type NoiseView } from '../noise/noiseTiles' +import { focusAround, type TerrainStyle } from '../scene/terrainStream' +import { hexColor } from './colors' +import { SceneViewport } from './SceneViewport' +import { TiledCanvas } from './TiledCanvas' +import { Separator } from '@/components/ui/separator' +import { HEADER_CHOICE, Panel, SidebarPanel, ViewIsland } from './Sidebar' +import { useLongPending, useTerrainStream } from './useTerrainStream' + +type NoiseDisplay = 'flat' | 'terrain' + +const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 3 }) +const DEFAULT_SEED = '12345' +// Noise tiles are asked for down to 4096 blocks a value, which is level 12. +const COARSEST_NOISE_LEVEL = 12 +const LOWEST_FOCUS_BLOCKS = -32 +const LOWEST_RELIEF_BLOCKS = 1 +const TALLEST_RELIEF_BLOCKS = 4064 +const DEFAULT_RELIEF_BLOCKS = 64 +const RELIEF_STEPS = 1000 +const SWATCH_STEPS = 24 +const PILL = 'pointer-events-none absolute rounded-md border border-overlay-border bg-card px-3 py-1.5 text-[12px] text-secondary-text' + +interface NoiseStudioProps { + title: string + client: BridgeClient + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** The pack's noise and the built-in styles, from above or as terrain (v3e's noise explorer). */ +export function NoiseStudio({ title, client, packRevision, onSummary, tell }: NoiseStudioProps): React.JSX.Element { + const sources = useNoiseSources(client, packRevision, tell) + const [chosenId, setChosenId] = useState(null) + const source = sources.find((candidate) => candidate.id === chosenId) ?? sources[0] ?? null + const [seed, setSeed] = useState(DEFAULT_SEED) + const [paletteId, setPaletteId] = useState('terrain') + const [display, setDisplay] = useState('flat') + const [reliefBlocks, setReliefBlocks] = useState(DEFAULT_RELIEF_BLOCKS) + const [status, setStatus] = useState(null) + const [terrainFraming, setTerrainFraming] = useState(null) + const controllerRef = useRef(null) + const scale = useMemo(() => noiseScale(paletteId, source), [paletteId, source]) + const latestTell = useRef(tell) + latestTell.current = tell + const createView = useCallback( + (canvas: HTMLCanvasElement) => createNoiseView(canvas, client, { onStatus: setStatus, onError: (message) => latestTell.current(message) }), + [client] + ) + + useEffect(() => { + const layer = source === null ? null : { sourceId: source.id, seed, revision: packRevision } + controllerRef.current?.show(layer, { key: `${paletteId}/${source?.blockRange?.lowest}/${source?.blockRange?.highest}`, scale }) + }, [source, seed, packRevision, paletteId, scale]) + + const showAs = useCallback((next: NoiseDisplay) => { + setDisplay(next) + if (next === 'terrain') { + setTerrainFraming(controllerRef.current?.framing() ?? null) + } + }, []) + + useEffect(() => { + if (source === null) { + onSummary(null) + return + } + const seedText = source.usesSeed ? `seed ${seed}` : "the world's seed" + onSummary(`${source.name} · ${seedText}`) + }, [source, seed, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> + + {display === 'terrain' && source?.blockRange === null && } + {display === 'flat' && ( + + )} + + value !== '' && showAs(value as NoiseDisplay)}> + + 2D + + + 3D + + + + } + > + + {display === 'terrain' && source !== null && terrainFraming !== null && ( + + )} + {display === 'flat' && status !== null && source !== null &&
{readout(status, source)}
} +
+ +
+

Noise

+

{NUMBER.format(sources.length)} sources

+
+ +
+ + + + + + ) +} + +function readout(status: NoiseStatus, source: NoiseSource): string { + const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}` + if (status.value === null) { + return spot + } + const value = NUMBER.format(status.value) + return `${spot} · ${source.blockRange === null ? value : `${value} blocks`}` +} + +function SeedField({ seed, usesSeed, onChange }: { seed: string; usesSeed: boolean; onChange(seed: string): void }): React.JSX.Element { + const [draft, setDraft] = useState(seed) + useEffect(() => setDraft(seed), [seed]) + const commit = (): void => { + const trimmed = draft.trim() + if (/^-?\d{1,19}$/.test(trimmed) && isLong(trimmed)) { + onChange(trimmed) + } else { + setDraft(seed) + } + } + return ( +
+

Seed

+
+ setDraft(event.target.value)} + onBlur={commit} + onKeyDown={(event) => event.key === 'Enter' && commit()} + /> + +
+ {!usesSeed &&

Keeps the world's seed

} +
+ ) +} + +const LONG_LIMIT = 2n ** 63n + +function isLong(text: string): boolean { + const value = BigInt(text) + return value >= -LONG_LIMIT && value < LONG_LIMIT +} + +function randomSeed(): string { + const [high, low] = crypto.getRandomValues(new Uint32Array(2)) + return BigInt.asIntN(64, (BigInt(high) << 32n) | BigInt(low)).toString() +} + +function PaletteList({ + current, + source, + scale, + onSelect +}: { + current: NoisePaletteId + source: NoiseSource | null + scale: NoiseScale + onSelect(palette: NoisePaletteId): void +}): React.JSX.Element { + return ( +
+

Palette

+ {NOISE_PALETTES.map((palette) => ( + + ))} +

+ {NUMBER.format(scale.minimum)} + {source?.blockRange === null ? '' : 'blocks above the fluid'} + {NUMBER.format(scale.maximum)} +

+
+ ) +} + +function gradientOf(scale: NoiseScale): string { + const stops = Array.from({ length: SWATCH_STEPS + 1 }, (_, step) => hexColor(scale.colorAlong(step / SWATCH_STEPS))) + return `linear-gradient(to right, ${stops.join(', ')})` +} + +function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { + const [filter, setFilter] = useState('') + const shown = sources.filter((source) => source.name.toLowerCase().includes(filter.trim().toLowerCase())) + const categories = [...new Set(shown.map((source) => source.category))] + return ( +
+
+ + + + setFilter(event.target.value)} /> +
+ +
+ {categories.map((category) => ( +
+

{category}

+ {shown + .filter((source) => source.category === category) + .map((source) => ( + + ))} +
+ ))} + {shown.length === 0 &&

Nothing to show

} +
+
+
+ ) +} + +/** How many blocks the highest noise rises above the lowest, on a scale that gives low reliefs room. */ +function ReliefControl({ blocks, onChange }: { blocks: number; onChange(blocks: number): void }): React.JSX.Element { + const span = Math.log(TALLEST_RELIEF_BLOCKS) - Math.log(LOWEST_RELIEF_BLOCKS) + const step = Math.round(((Math.log(blocks) - Math.log(LOWEST_RELIEF_BLOCKS)) / span) * RELIEF_STEPS) + return ( + + ) +} + +function NoiseTerrainView({ + client, + source, + seed, + revision, + framing, + scale, + reliefBlocks, + tell +}: { + client: BridgeClient + source: NoiseSource + seed: string + revision: number + framing: TerrainFraming + scale: NoiseScale + reliefBlocks: number + tell(message: string): void +}): React.JSX.Element { + const tileSource = useMemo(() => noiseTileSource(client), [client]) + const focus = useMemo(() => focusAround(framing.centerX, framing.centerZ, LOWEST_FOCUS_BLOCKS, DEFAULT_RELIEF_BLOCKS), [framing]) + const layer = useMemo(() => ({ sourceId: source.id, seed, revision }), [source.id, seed, revision]) + const style = useMemo>( + () => ({ + surfaceOf: (tile, place) => new NoiseTerrain(tile, place, source, scale, reliefBlocks), + floorY: source.blockRange?.lowest ?? 0, + topY: source.blockRange?.highest ?? reliefBlocks + }), + [source, scale, reliefBlocks] + ) + const { content, pending } = useTerrainStream(tileSource, COARSEST_NOISE_LEVEL, focus, layer, style, tell) + const sampling = useLongPending(pending) + return ( +
+ + {sampling &&
Sampling {source.name}
} +
+ ) +} + +function useNoiseSources(client: BridgeClient, packRevision: number, tell: (message: string) => void): NoiseSource[] { + const [sources, setSources] = useState([]) + useEffect(() => { + let active = true + client + .noiseSources() + .then((found) => active && setSources(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, packRevision, tell]) + return sources +} diff --git a/studio/src/renderer/src/studio/PatternStudio.tsx b/studio/src/renderer/src/studio/PatternStudio.tsx new file mode 100644 index 000000000..764fc9fa2 --- /dev/null +++ b/studio/src/renderer/src/studio/PatternStudio.tsx @@ -0,0 +1,206 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useCallback, 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 { ModuleViewInfo, PatternEntry } from '../bridge/types' +import { createPatternView, type PatternBlocks, type PatternLayer, type PatternStatus, type PatternView } from '../pattern/patternTiles' +import { BlockColors } from '../scene/blockColors' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { BlockIcon } from './BlockIcon' +import { EntryBrowser } from './EntryBrowser' +import { Panel, SidebarPanel, Stepper, ViewIsland } from './Sidebar' +import { TiledCanvas } from './TiledCanvas' + +const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' +// A layer thinner than the depth shown, a palette with no block for the spot, or a spot a decorator leaves bare. +const NONE_LABEL = 'nothing placed' + +/** The blocks the shown layer's tiles placed so far by name, each with one state to draw its icon as, and whether some spots got none. */ +interface LegendBlocks { + examples: Map + someNone: boolean +} + +const EMPTY_LEGEND: LegendBlocks = { examples: new Map(), someNone: false } +const PILL = 'pointer-events-none absolute rounded-md border border-overlay-border bg-card px-3 py-1.5 text-[12px] text-secondary-text' + +interface PatternStudioProps { + client: BridgeClient + view: ModuleViewInfo + /** Changes when the pack reloads, so the entries and the tiles are read again. */ + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** A pattern view: its entries on the right, what the chosen one places from above in the middle (v3e palette explorer). */ +export function PatternStudio({ client, view, packRevision, onSummary, tell }: PatternStudioProps): React.JSX.Element { + const entries = usePatternEntries(client, view.id, packRevision, tell) + const [chosen, setChosen] = useState<{ key: string; depth: number } | null>(null) + const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null + const depth = entry !== null && chosen?.key === entry.key ? Math.min(chosen.depth, entry.depths - 1) : 0 + const layer = useMemo( + () => (entry === null ? null : { viewId: view.id, key: entry.key, depth, revision: packRevision }), + [view.id, entry, depth, packRevision] + ) + const [status, setStatus] = useState(null) + const { legend, blockColors, createView } = usePatternView(client, layer, setStatus, tell) + const viewRef = useRef(null) + + useEffect(() => viewRef.current?.show(layer, 'blocks'), [layer]) + useEffect(() => onSummary(entry === null ? null : `${entry.group} · ${entry.name}`), [entry, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + const chooseDepth = (next: number): void => { + if (entry !== null) { + setChosen({ key: entry.key, depth: (next + entry.depths) % entry.depths }) + } + } + + return ( + <> + + {entry !== null && entry.depths > 1 && ( + chooseDepth(depth - 1)} onOn={() => chooseDepth(depth + 1)} /> + )} + + + } + > + + {status !== null && entry !== null &&
{readout(status)}
} +
+ + setChosen({ key, depth: 0 })} /> + + + + + + + ) +} + +function readout(status: PatternStatus): string { + const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}` + switch (status.spot.kind) { + case 'block': + return `${spot} · ${shortName(status.spot.block)}` + case 'none': + return `${spot} · ${NONE_LABEL}` + case 'unknown': + return spot + } +} + +/** The block without its namespace when that is Minecraft's, and without its state, as a builder names it. */ +function shortName(block: string): string { + const material = block.includes('[') ? block.slice(0, block.indexOf('[')) : block + return material.startsWith(DEFAULT_NAMESPACE_PREFIX) ? material.slice(DEFAULT_NAMESPACE_PREFIX.length) : material +} + +function usePatternEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): PatternEntry[] { + const [entries, setEntries] = useState([]) + useEffect(() => { + let active = true + client + .patternEntries(viewId) + .then((found) => active && setEntries(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, viewId, packRevision, tell]) + return entries +} + +/** The view's maker for the canvas, and the blocks the shown layer's tiles placed so far with their colours. */ +function usePatternView( + client: BridgeClient, + layer: PatternLayer | null, + onStatus: (status: PatternStatus) => void, + tell: (message: string) => void +): { legend: LegendBlocks; blockColors: BlockColors; createView(canvas: HTMLCanvasElement): PatternView } { + const blockColors = useMemo(() => { + const images = new BridgeAssets(client, () => {}) + return new BlockColors(new BlockModels(images), images) + }, [client]) + const [legend, setLegend] = useState(EMPTY_LEGEND) + const latest = useRef({ layer, onStatus, tell }) + latest.current = { layer, onStatus, tell } + + useEffect(() => setLegend(EMPTY_LEGEND), [layer]) + + const createView = useCallback( + (canvas: HTMLCanvasElement) => + createPatternView(canvas, client, blockColors, { + onStatus: (status) => latest.current.onStatus(status), + onBlocks: (tileLayer, blocks) => tileLayer === latest.current.layer && setLegend((shown) => withBlocks(shown, blocks)), + onError: (message) => latest.current.tell(message) + }), + [client, blockColors] + ) + return { legend, blockColors, createView } +} + +/** The legend with the tile's blocks added, one row per block whatever its state; unchanged when it had them all. */ +function withBlocks(shown: LegendBlocks, tile: PatternBlocks): LegendBlocks { + const added = [...tile.drawnAs].map(([block, drawnAs]) => [shortName(block), drawnAs] as const).filter(([name]) => !shown.examples.has(name)) + const someNone = shown.someNone || tile.someNone + if (added.length === 0 && someNone === shown.someNone) { + return shown + } + return { examples: new Map([...added, ...shown.examples]), someNone } +} + +function EntryFacts({ entry }: { entry: PatternEntry | null }): React.JSX.Element | null { + if (entry === null) { + return null + } + return ( +
+

+ {entry.group} · {entry.name} +

+ {entry.facts.map((fact) => ( +

+ {fact} +

+ ))} +
+ ) +} + +/** The blocks the shown tiles place, each with its texture. */ +function Legend({ blocks, looks }: { blocks: LegendBlocks; looks: BlockColors }): React.JSX.Element { + const sorted = [...blocks.examples].sort(([first], [second]) => first.localeCompare(second)) + return ( +
+

Blocks

+ +
+ {sorted.map(([block, example]) => ( +
+ + {block} +
+ ))} + {blocks.someNone && ( +
+ + Nothing placed +
+ )} +
+
+
+ ) +} diff --git a/studio/src/renderer/src/studio/PickInspector.tsx b/studio/src/renderer/src/studio/PickInspector.tsx new file mode 100644 index 000000000..569e8f4c0 --- /dev/null +++ b/studio/src/renderer/src/studio/PickInspector.tsx @@ -0,0 +1,120 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useState } from 'react' +import { ScrollArea } from '@/components/ui/scroll-area' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import type { PickDisplay, PickInspection, PickSection } from '../bridge/types' +import { hexColor } from './colors' +import { NoiseChart, percent } from './NoiseChart' + +// The chosen display reads like the toolbar's switched-on toggles. +const DISPLAY_ITEM = 'h-7 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground' + +/** How the map draws the picks, for a view that recolours its tiles. */ +export interface PickDisplayChoice { + /** What the map shows when it draws the picks: "Regions" or "Biomes". */ + picksLabel: string + value: PickDisplay + onChange(display: PickDisplay): void +} + +interface PickInspectorProps { + /** What is inspected: "Regions", "Biomes", or the previewed region's name. */ + title: string + /** The latest measurement of the view; null until the first one arrives. */ + inspection: PickInspection | null + /** Absent in a view that draws no map tiles, such as the 3D world. */ + display?: PickDisplayChoice +} + +/** + * How noise picks the regions or biomes in view, measured against what is in view, with a switch for how the map + * draws the picks (v3e PickInspectorPanel). + */ +export function PickInspector({ title, inspection, display }: PickInspectorProps): React.JSX.Element { + return ( +
+
+

{title}

+

{inspection?.detail ?? 'Measuring what is in view…'}

+ {display !== undefined && ( + value !== '' && display.onChange(value as PickDisplay)} + > + + {display.picksLabel} + + + Noise + + + Both + + + )} +
+ +
{inspection !== null && }
+
+
+ ) +} + +// A single section is the whole view, so its charts stand on their own; several are one region each, folded. +function Sections({ sections }: { sections: PickSection[] }): React.JSX.Element { + const [opened, setOpened] = useState | null>(null) + if (sections.length === 1) { + return + } + const open = opened ?? new Set(sections.slice(0, 1).map(sectionKey)) + const toggle = (key: string): void => { + const next = new Set(open) + if (!next.delete(key)) { + next.add(key) + } + setOpened(next) + } + return ( + <> + {sections.map((section) => ( + toggle(sectionKey(section))} /> + ))} + + ) +} + +function RegionSection({ section, open, onToggle }: { section: PickSection; open: boolean; onToggle(): void }): React.JSX.Element { + const region = section.region + return ( +
+ + {open && } +
+ ) +} + +function Charts({ section }: { section: PickSection }): React.JSX.Element { + const optionNoun = section.region === null ? 'Regions' : 'Biomes' + return ( +
+ {section.spreads.map((spread) => ( + + ))} +
+ ) +} + +function sectionKey(section: PickSection): string { + return section.region?.key ?? '' +} diff --git a/studio/src/renderer/src/studio/PickRows.tsx b/studio/src/renderer/src/studio/PickRows.tsx new file mode 100644 index 000000000..8ce947999 --- /dev/null +++ b/studio/src/renderer/src/studio/PickRows.tsx @@ -0,0 +1,86 @@ +import type { PickBand, PickStep } from '../bridge/types' +import { hexColor } from './colors' + +// Gaps between bands shrink as there are more of them, so many thin bands still read as a bar. +const WIDE_GAP_MOST_BANDS = 18 +const NARROW_GAP_MOST_BANDS = 50 +/** Why a step that nothing picked has its label. */ +const UNPICKED_NOTES: Partial> = { FOCUS: 'Focus', IMAGE_MAP: 'Image map', PREVIEW: 'Preview' } + +/** How the spot got its region and biome: one row per pick, the noise value marked on every option's share of it. */ +export function PickRows({ path }: { path: PickStep[] }): React.JSX.Element | null { + if (path.length === 0) { + return null + } + return ( +
+ {path.map((step, index) => ( + + ))} +
+ ) +} + +function PickRow({ step }: { step: PickStep }): React.JSX.Element { + return ( + <> + {rowLabel(step)} + {step.noise === null ? ( + {UNPICKED_NOTES[step.kind] ?? ''} + ) : ( + + )} + {step.noise === null ? '' : step.noise.toFixed(3)} + + ) +} + +function NoiseBar({ bands, noise }: { bands: PickBand[]; noise: number }): React.JSX.Element { + const picked = pickedBandIndex(bands, noise) + const gap = bands.length <= WIDE_GAP_MOST_BANDS ? 2 : bands.length <= NARROW_GAP_MOST_BANDS ? 1 : 0 + return ( +
+ {bands.map((band, index) => ( + + ))} + +
+ ) +} + +/** The first band the noise does not pass; values beyond 1 pick the last, as the generator does. */ +export function pickedBandIndex(bands: PickBand[], noise: number): number { + const index = bands.findIndex((band) => noise <= band.to) + return index === -1 ? bands.length - 1 : index +} + +function rowLabel(step: PickStep): string { + switch (step.kind) { + case 'REGION': + return 'Region' + case 'BIOME': + return step.list === null ? 'Biome' : step.list.charAt(0).toUpperCase() + step.list.slice(1) + case 'CHILD': + return 'Child' + case 'IMAGE_MAP': + case 'FOCUS': + case 'PREVIEW': + return step.picked.kind === 'REGION' ? 'Region' : 'Biome' + } +} + +/** The parent the spot's biome replaced, when a child step replaced one. */ +export function replacedParent(path: PickStep[]): string | null { + return path.findLast((step) => step.kind === 'CHILD' && step.replaced !== null)?.replaced ?? null +} diff --git a/studio/src/renderer/src/studio/RegionPreviewList.tsx b/studio/src/renderer/src/studio/RegionPreviewList.tsx new file mode 100644 index 000000000..d578fcbee --- /dev/null +++ b/studio/src/renderer/src/studio/RegionPreviewList.tsx @@ -0,0 +1,72 @@ +import { useState } from 'react' +import { Input } from '@/components/ui/input' +import { cn } from '@/lib/utils' +import type { MapLabel } from '../bridge/types' +import { hexColor } from './colors' + +// Short lists are scanned at a glance; longer ones get a search field. +const SEARCHABLE_FROM_REGIONS = 8 + +interface RegionPreviewListProps { + regions: MapLabel[] + /** The previewed region's key, or null for all regions. */ + current: string | null + onSelect(regionKey: string | null): void +} + +/** The region view's regions, any of which can fill the map with its biomes, or all of them as they are (v3e RegionNavigator). */ +export function RegionPreviewList({ regions, current, onSelect }: RegionPreviewListProps): React.JSX.Element { + const [search, setSearch] = useState('') + const wanted = search.trim().toLowerCase() + const shown = wanted === '' ? regions : regions.filter((region) => `${region.name} ${region.key}`.toLowerCase().includes(wanted)) + return ( +
+

Preview a region

+ {regions.length >= SEARCHABLE_FROM_REGIONS && ( + setSearch(event.target.value)} + onKeyDown={(event) => event.key === 'Escape' && setSearch('')} + /> + )} + onSelect(null)} /> + {shown.map((region) => ( + onSelect(region.key)} + /> + ))} + {shown.length === 0 &&

No region matches

} +
+ ) +} + +interface RegionRowProps { + name: string + color: number | null + title?: string + selected: boolean + onSelect(): void +} + +function RegionRow({ name, color, title, selected, onSelect }: RegionRowProps): React.JSX.Element { + return ( + + ) +} diff --git a/studio/src/renderer/src/studio/SavedWorldStudio.tsx b/studio/src/renderer/src/studio/SavedWorldStudio.tsx new file mode 100644 index 000000000..72e23bd09 --- /dev/null +++ b/studio/src/renderer/src/studio/SavedWorldStudio.tsx @@ -0,0 +1,209 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { useEffect, useMemo, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' +import { BridgeError, STATUS_NOT_FOUND, type BridgeClient } from '../bridge/BridgeClient' +import type { SavedStart, SavedWorldInfo, WorldInfo } from '../bridge/types' +import { BlockColors } from '../scene/blockColors' +import { BlockLooks } from '../scene/blockLooks' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { PendingWork } from '../scene/pendingWork' +import { SavedTerrain, type ReadSavedTile, type SavedTerrainColoring } from '../scene/savedTerrain' +import { savedTileSource, type SavedLayer } from '../scene/savedTileSource' +import { TerrainAtlas } from '../scene/terrainAtlas' +import { focusAround, type TerrainStyle } from '../scene/terrainStream' +import { SceneViewport } from './SceneViewport' +import { Separator } from '@/components/ui/separator' +import { HEADER_CHOICE, SidebarPanel, ViewIsland } from './Sidebar' +import { useSpotActions } from './useSpotActions' +import { useTerrainStream } from './useTerrainStream' + +const NUMBER = new Intl.NumberFormat('en-US') +// Saved tiles are read at up to 16 blocks a pixel, which is level 4. +const COARSEST_SAVED_LEVEL = 4 +const PILL = 'pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card px-3 py-1.5 text-[12px] text-secondary-text' + +interface SavedWorldStudioProps { + title: string + client: BridgeClient + /** The studio's own world, whose saved copy is chosen first. */ + world: WorldInfo + onSummary(summary: string | null): void + /** How far the tiles being read have come, 0 to 1, or null when none are. */ + onProgress(progress: number | null): void + tell(message: string): void +} + +/** A world as its region files hold it, in 3D, around the region nearest its origin (v3e's saved world explorer). */ +export function SavedWorldStudio({ title, client, world, onSummary, onProgress, tell }: SavedWorldStudioProps): React.JSX.Element { + const worlds = useSavedWorlds(client, tell) + const [chosenId, setChosenId] = useState(null) + const chosen = worlds.find((candidate) => candidate.id === chosenId) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null + const [coloring, setColoring] = useState('biomes') + const [readings, setReadings] = useState(0) + const { start, looking } = useSavedStart(client, chosen?.id ?? null, readings, tell) + const { tileSource, atlas } = useMemo(() => { + const images = new BridgeAssets(client, () => {}) + const models = new BlockModels(images) + const pictures = new TerrainAtlas(images) + return { tileSource: savedTileSource(client, new BlockColors(models, images), new BlockLooks(models, pictures)), atlas: pictures } + }, [client]) + useEffect(() => () => atlas.dispose(), [atlas]) + const centerX = start?.centerX ?? 0 + const centerZ = start?.centerZ ?? 0 + const lowestGround = start?.lowestGround ?? 0 + const highestGround = start?.highestGround ?? 0 + const focus = useMemo(() => focusAround(centerX, centerZ, lowestGround, highestGround), [centerX, centerZ, lowestGround, highestGround]) + const layer = useMemo(() => (start === null || chosen === null ? null : { worldId: chosen.id, readings }), [start, chosen, readings]) + const seaLevel = start?.seaLevel ?? null + const minY = start?.minY ?? null + const style = useMemo | null>( + () => + minY === null + ? null + : { surfaceOf: (read, place) => new SavedTerrain(read, place, coloring, seaLevel, atlas), floorY: minY, topY: minY + world.height }, + [minY, seaLevel, coloring, world.height, atlas] + ) + const { content, pending } = useTerrainStream(tileSource, COARSEST_SAVED_LEVEL, focus, layer, style, tell) + const reading = looking || pending > 0 + const tileWork = useRef(new PendingWork()) + const showsStudioWorld = chosen !== null && chosen.id === ownWorldAmong(worlds, world)?.id + const spotActions = useSpotActions(client, tell, showsStudioWorld) + + useEffect(() => { + const completion = tileWork.current.completion(pending) + onProgress(pending > 0 ? completion : null) + }, [pending, onProgress]) + useEffect(() => () => onProgress(null), [onProgress]) + + useEffect(() => { + if (chosen === null || start === null) { + onSummary(null) + return + } + onSummary(`${chosen.name} · around ${NUMBER.format(start.centerX)}, ${NUMBER.format(start.centerZ)}`) + }, [chosen, start, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> + + value !== '' && setColoring(value as SavedTerrainColoring)}> + + Biomes + + + Blocks + + + Height + + + + + + } + > + + {reading && chosen !== null &&
Reading {chosen.name}
} + {!reading && chosen !== null && start === null &&
Nothing finished is saved in {chosen.name}
} +
+ +
+

Saved worlds

+

{NUMBER.format(worlds.length)} on the server

+
+ + + +
+ + ) +} + +function WorldList({ worlds, current, onSelect }: { worlds: SavedWorldInfo[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { + const namespaces = [...new Set(worlds.map((world) => world.namespace))] + return ( +
+ {namespaces.map((namespace) => ( +
+

{namespace}

+ {worlds + .filter((world) => world.namespace === namespace) + .map((world) => ( + + ))} +
+ ))} + {worlds.length === 0 &&

Nothing to show

} +
+ ) +} + +// The studio's world folder is named after its dimension, so world_iris_procfix is saved as iris/procfix. +function ownWorldAmong(worlds: SavedWorldInfo[], world: WorldInfo): SavedWorldInfo | undefined { + return worlds.find((candidate) => world.world.endsWith(`_${candidate.name}`) || world.world === candidate.name) +} + +function useSavedWorlds(client: BridgeClient, tell: (message: string) => void): SavedWorldInfo[] { + const [worlds, setWorlds] = useState([]) + useEffect(() => { + let active = true + client + .savedWorlds() + .then((found) => active && setWorlds(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, tell]) + return worlds +} + +/** + * Where the chosen world's view opens, null while it is looked up and where nothing finished is saved. Reading again + * keeps the old start until the new one arrives, so the ground drawn stays. + */ +function useSavedStart(client: BridgeClient, worldId: string | null, readings: number, tell: (message: string) => void): { start: SavedStart | null; looking: boolean } { + const [start, setStart] = useState(null) + const [looking, setLooking] = useState(false) + useEffect(() => setStart(null), [worldId]) + useEffect(() => { + if (worldId === null) { + return + } + const stop = new AbortController() + setLooking(true) + client + .savedStart(worldId, stop.signal) + .then(setStart) + .catch((failure: unknown) => { + if (stop.signal.aborted) { + return + } + if (failure instanceof BridgeError && failure.status === STATUS_NOT_FOUND) { + setStart(null) + return + } + tell(failure instanceof Error ? failure.message : 'The server did not answer') + }) + .finally(() => !stop.signal.aborted && setLooking(false)) + return () => stop.abort() + }, [client, worldId, readings, tell]) + return { start, looking } +} diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx new file mode 100644 index 000000000..0efd569f5 --- /dev/null +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -0,0 +1,406 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import type { BridgeClient } from '../bridge/BridgeClient' +import { NO_PART, type JsonPath, type SceneEntry, type SceneViewInfo } from '../bridge/types' +import { parsedText } from '../editor/jsonValues' +import { nodeDrawingPart, nodeWithPath } from '../editor/nodeLayout' +import { SuggestionStore } from '../editor/suggestionStore' +import { useNodeEditor } from '../editor/useNodeEditor' +import { BlockColors } from '../scene/blockColors' +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 { BlockIcon } from './BlockIcon' +import { EntryBrowser } from './EntryBrowser' +import { useEntryFiles } from './EntryFileDialogs' +import { NodeInspector } from './NodeInspector' +import { NodePane } from './NodePane' +import { Panel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' +import { SceneViewport, type PickedSurface } from './SceneViewport' + +const NUMBER = new Intl.NumberFormat('en-US') +const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' +const FAR_LEAVES_HINT = 'Leaves more than 6 blocks from wood. Vanilla would let them decay, so they are made persistent.' + +interface SceneStudioProps { + client: BridgeClient + view: SceneViewInfo + /** Changes when the pack reloads, so the entries and the scene are read again. */ + packRevision: number + /** What the status bar says about the scene, or null while none is shown. */ + onSummary(summary: string | null): void + tell(message: string): void +} + +/** + * A scene view: its entries on the right, the chosen one in 3D in the middle, with the blocks it is made of. An + * editable view shows the entry's file as nodes under the scene, and the chosen node's settings on the right. + */ +export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element { + const [waiting, setWaiting] = useState(null) + const images = useMemo(() => new BridgeAssets(client, setWaiting), [client]) + const models = useMemo(() => new BlockModels(images), [images]) + const blockLooks = useMemo(() => new BlockColors(models, images), [models, images]) + const entries = useSceneEntries(client, view.id, packRevision, tell) + const [chosen, setChosen] = useState<{ key: string; variant: number } | null>(null) + 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 entryKeys = useMemo(() => entries.map((candidate) => candidate.key), [entries]) + const files = useEntryFiles(client, view.id, entryKeys, (key) => setChosen({ key, variant: 0 }), tell) + const [farLeavesOnly, setFarLeavesOnly] = useState(false) + const [chosenSize, setChosenSize] = useState<{ viewId: string; size: number } | null>(null) + const size = chosenSize?.viewId === view.id ? chosenSize.size : (view.sizes?.opening ?? null) + const chooseVariant = (next: number): void => { + if (entry !== null) { + setChosen({ key: entry.key, variant: (next + entry.variants) % entry.variants }) + } + } + + const bakeTiming = useBakeTiming(client, view.id, entry?.key ?? null, view.baked, packRevision, tell) + + const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell) + const [selectedPath, setSelectedPath] = useState(null) + 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]) + const suggestions = useMemo(() => new SuggestionStore((of) => client.suggestions(of)), [client, packRevision]) + + 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, size, 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) + setPickedPart(NO_PART) + }, [entry?.key]) + + return ( + <> + + setChosen({ key, variant: 0 })} + fileActions={view.creatable ? files.actions : undefined} + /> + {files.dialogs} + +
+ setChosenSize({ viewId: view.id, size: next })} + onPick={view.parts ? pickPart : undefined} + /> + {view.editable && entry !== null && ( + { + setSelectedPath(node?.path ?? null) + setPickedPart(NO_PART) + }} + /> + )} +
+ + {view.baked && entry !== null && } + {selected !== null && editor.state !== null ? ( + + ) : ( + + )} + + + ) +} + +interface SceneAreaProps { + /** What the island is called while no entry is chosen. */ + title: string + entry: SceneEntry | null + variant: number + /** The sizes the scenes can be built at, or null when each entry has its own. */ + sizes: readonly number[] | null + size: number | null + shown: ShownScene | null + /** What is being built, or null when nothing is. */ + status: string | null + onVariant(variant: number): void + onSize(size: number): void + /** Called when a block is clicked; absent when the scene has no parts to pick. */ + onPick?(picked: PickedSurface): void +} + +function SceneArea({ title, entry, variant, sizes, size, shown, status, onVariant, onSize, onPick }: SceneAreaProps): React.JSX.Element { + return ( + + {sizes !== null && size !== null && } + {entry !== null && entry.variants > 1 && ( + onVariant(variant - 1)} + onOn={() => onVariant(variant + 1)} + /> + )} + + } + > + + {status !== null && ( +
+ {status} +
+ )} +
+ ) +} + +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${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[] { + const [entries, setEntries] = useState([]) + useEffect(() => { + let active = true + client + .sceneEntries(viewId) + .then((found) => active && setEntries(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, viewId, packRevision, tell]) + return entries +} + +interface ShownScene { + scene: BlockScene + 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 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, + view: SceneViewInfo, + entry: SceneEntry | null, + variant: number, + size: number | null, + packRevision: number, + models: BlockModels, + images: BridgeAssets, + farLeavesOnly: boolean, + highlightedPart: number, + tell: (message: string) => void +): { scene: BlockScene | null; shown: ShownScene | null; sceneParts: SceneParts | null; building: boolean } { + const [scene, setScene] = useState(null) + const [sceneParts, setSceneParts] = useState(null) + const [shown, setShown] = useState(null) + const [building, setBuilding] = useState(false) + const unknownStatesTold = useRef(null) + const key = entry?.key ?? null + const viewId = view.id + const hasParts = view.parts + + useEffect(() => { + if (key === null) { + return + } + const stop = new AbortController() + const place = { key, variant, size } + setBuilding(true) + client + .scene(viewId, place, stop.signal) + .then((found) => { + if (stop.signal.aborted) { + return + } + setScene(found) + if (hasParts) { + client + .sceneParts(viewId, place, 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 + } + tell(failure.message) + setBuilding(false) + }) + return () => stop.abort() + }, [client, viewId, hasParts, key, variant, size, packRevision, tell]) + + const faint = useMemo(() => { + const parts = partsOf(sceneParts, scene) + return parts === null ? null : blocksOutsidePart(parts, highlightedPart) + }, [sceneParts, scene, highlightedPart]) + + useEffect(() => { + if (scene === null) { + return + } + const stop = new AbortController() + setBuilding(true) + 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 && 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, faint, models, images, tell]) + + useEffect(() => () => disposeMesh(shown?.mesh ?? null), [shown]) + + return { scene, shown, sceneParts, building } +} + +function disposeMesh(mesh: SceneMesh | null): void { + mesh?.dispose() +} + +interface BlockListProps { + scene: BlockScene | null + blocks: BlockColors + farLeavesOnly: boolean + onFarLeavesOnly(only: boolean): void +} + +/** The blocks of the scene, most used first, each with its count (v3e ObjectOverviewPanel), and how many leaves are too far from wood. */ +function BlockList({ scene, blocks, farLeavesOnly, onFarLeavesOnly }: BlockListProps): React.JSX.Element { + const counts = useMemo(() => (scene === null ? [] : blockCounts(scene)), [scene]) + const farLeaves = useMemo(() => (scene === null ? 0 : countFarLeaves(scene)), [scene]) + return ( +
+

Blocks

+ {farLeaves > 0 && ( +
+ + {NUMBER.format(farLeaves)} {farLeaves === 1 ? 'leaf' : 'leaves'} too far from wood + + +
+ )} + +
+ {counts.map(({ material, example, count }) => ( +
+ + {material.replace(DEFAULT_NAMESPACE_PREFIX, '')} + {NUMBER.format(count)} +
+ ))} +
+
+
+ ) +} + +interface BlockUse { + material: string + /** One full state of the block, so its icon has a model to come from. */ + example: string + count: number +} + +// Block states that differ only in how they face count as one block, as a builder reads the list. +function blockCounts(scene: BlockScene): BlockUse[] { + const uses = new Map() + for (let offset = 3; offset < scene.blocks.length; offset += INTS_PER_BLOCK) { + const state = scene.palette[scene.blocks[offset]] + const material = state.includes('[') ? state.slice(0, state.indexOf('[')) : state + const use = uses.get(material) + if (use === undefined) { + uses.set(material, { material, example: state, count: 1 }) + } else { + use.count++ + } + } + return [...uses.values()].sort((first, second) => second.count - first.count) +} diff --git a/studio/src/renderer/src/studio/SceneViewport.tsx b/studio/src/renderer/src/studio/SceneViewport.tsx new file mode 100644 index 000000000..b7c7fc644 --- /dev/null +++ b/studio/src/renderer/src/studio/SceneViewport.tsx @@ -0,0 +1,379 @@ +import { useEffect, useRef, useState } from 'react' +import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/components/ui/context-menu' +import { Box3, ColorManagement, LinearSRGBColorSpace, 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' + +// Colours are worked out as Minecraft and v3e do, on the values a screen shows: a texture times its tint times the light +// on its face. Left to manage colours, three.js would take those values for linear light and encode them again, which +// pales every colour and flattens the shading. +ColorManagement.enabled = false + +const FIELD_OF_VIEW_DEGREES = 45 +// Looking down at the scene from the south east, as v3e's object view opens. +const VIEW_DIRECTION = new Vector3(1, 0.8, 1.2).normalize() +const FRAMING_MARGIN = 1.15 +const NEAREST_CLIP = 0.05 +// The near plane follows the orbit distance: a fixed tiny one leaves too little depth precision far away, so surfaces a block apart flicker. +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 + +// Ground is looked at from above: the camera stops a little over the horizon instead of going under it. +const LOWEST_OVER_GROUND_RADIANS = Math.PI / 2 - 0.05 +const TURNS_ON_DRAG = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN } +const MOVES_ON_DRAG = { LEFT: MOUSE.PAN, MIDDLE: MOUSE.ROTATE, RIGHT: MOUSE.ROTATE } + +const LEFT_BUTTON = 0 +const RIGHT_BUTTON = 2 + +function picks(event: PointerEvent): boolean { + return event.button === LEFT_BUTTON && !event.shiftKey && !event.ctrlKey && !event.metaKey +} + +// As on the map: a right click, or a click while holding Ctrl. +function asksAboutSpot(event: PointerEvent): boolean { + return event.button === RIGHT_BUTTON || (event.button === LEFT_BUTTON && (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. */ + view(): SightView + /** Tells the listener whenever the camera moves or the viewport changes size; returns how to stop. */ + onMoved(listener: () => void): () => void + /** Draws the viewport again, after the content changed by itself. */ + redraw(): void +} + +/** What a viewport shows: one object, and the box the camera frames when it is first shown. */ +export interface ViewportContent { + object: Object3D + bounds: Box3 + /** Ground to travel over: a drag moves it as the map does and a right drag turns the view; anything else turns on a drag. */ + isGround?: boolean + /** Where a ray first meets what is drawn within {@code reach}, or null; without it the viewport casts the ray at the object's meshes. */ + surfaceAlong?(ray: Ray, reach: number): Vector3 | null + /** Called when the content is shown, so it can follow the camera; returns how to stop following when it goes. */ + 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 + /** What a spot on the content offers, as the map does for a spot on it. */ + spotActions?: SpotActions +} + +export interface SpotActions { + /** Called when a spot is clicked while holding Ctrl. */ + onCtrlClick(spot: Vector3): void + /** The items of the menu a right click on a spot opens. */ + menuItems(spot: Vector3): React.ReactNode +} + +/** A spot the user asked about, and where on the screen they did. */ +interface AskedSpot { + spot: Vector3 + gesture: 'ctrlClick' | 'rightClick' + clientX: number + clientY: number +} + +/** + * Something in 3D. An object turns on a drag and moves on a right drag; ground moves on a drag, as the map does, and + * turns on a right drag. Either turns around what is in the middle, and scrolling comes closer to the cursor. The + * camera stops with the mouse, and the view is drawn only when it changes. + */ +export function SceneViewport({ content, framing, onPick, spotActions }: SceneViewportProps): React.JSX.Element { + const host = useRef(null) + const stage = useRef(null) + const [menuSpot, setMenuSpot] = useState(null) + const latestSpotActions = useRef(spotActions) + latestSpotActions.current = spotActions + + useEffect(() => { + const created = new Stage(host.current!) + stage.current = created + return () => { + created.dispose() + stage.current = null + } + }, []) + + useEffect(() => stage.current?.show(content), [content]) + useEffect(() => stage.current?.frameShown(), [framing]) + useEffect(() => stage.current?.onPick(onPick ?? null), [onPick]) + + const offersSpotActions = spotActions !== undefined + useEffect(() => { + if (!offersSpotActions) { + return + } + stage.current?.onSpotAsked((asked) => { + if (asked.gesture === 'ctrlClick') { + latestSpotActions.current?.onCtrlClick(asked.spot) + return + } + setMenuSpot(asked.spot) + openMenuAt(host.current!, asked.clientX, asked.clientY) + }) + return () => stage.current?.onSpotAsked(null) + }, [offersSpotActions]) + useEffect(() => keepPressFromOpeningMenu(host.current!), []) + + return ( + !open && setMenuSpot(null)}> + +
+ + {menuSpot !== null && spotActions?.menuItems(menuSpot)} + + ) +} + +// A right press turns the view, so the menu waits for a right click that did not: the browser's own request for a menu, +// which comes with the press, is kept from the menu, and the viewport asks for it itself. +function keepPressFromOpeningMenu(host: HTMLElement): () => void { + const swallow = (event: MouseEvent): void => { + if (event.isTrusted) { + event.preventDefault() + event.stopPropagation() + } + } + host.addEventListener('contextmenu', swallow, { capture: true }) + return () => host.removeEventListener('contextmenu', swallow, { capture: true }) +} + +function openMenuAt(host: HTMLElement, clientX: number, clientY: number): void { + host.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX, clientY })) +} + +/** The renderer, camera and controls of one viewport. What it shows belongs to whoever built it, who frees it. */ +class Stage { + private readonly renderer = new WebGLRenderer({ antialias: true, alpha: true }) + private readonly camera = new PerspectiveCamera(FIELD_OF_VIEW_DEGREES, 1, NEAREST_CLIP, 10_000) + private readonly scene = new Scene() + private readonly controls: OrbitControls + private readonly resizes: ResizeObserver + private readonly moveListeners = new Set<() => void>() + private shown: ViewportContent | null = null + private stopFollowing: (() => void) | null = null + 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 + private spotListener: ((asked: AskedSpot) => void) | null = null + private spotPressedAt: { x: number; y: number } | null = null + + constructor(private readonly host: HTMLDivElement) { + this.renderer.outputColorSpace = LinearSRGBColorSpace + this.renderer.setPixelRatio(window.devicePixelRatio) + this.renderer.setClearAlpha(0) + host.appendChild(this.renderer.domElement) + this.controls = new OrbitControls(this.camera, this.renderer.domElement) + this.controls.zoomToCursor = true + this.navigateAs(false) + this.renderer.domElement.addEventListener('pointerdown', (event) => { + this.pressedAt = picks(event) ? { x: event.clientX, y: event.clientY } : null + this.spotPressedAt = asksAboutSpot(event) ? { x: event.clientX, y: event.clientY } : null + this.pivotOnSurfaceInMiddle() + }) + this.renderer.domElement.addEventListener('pointerup', (event) => { + this.pickIfClicked(event) + this.askAboutSpotIfClicked(event) + }) + this.controls.addEventListener('change', () => { + this.fitClipToOrbit() + this.notifyMoved() + this.requestFrame() + }) + this.resizes = new ResizeObserver(() => this.fitToHost()) + this.resizes.observe(host) + this.fitToHost() + } + + show(content: ViewportContent | null): void { + this.removeShown() + this.shown = content + if (content !== null) { + this.scene.add(content.object) + this.navigateAs(content.isGround === true) + if (!this.framed) { + this.frameShown() + } + this.stopFollowing = content.follow?.(this.cameraLink()) ?? null + } + this.requestFrame() + } + + private navigateAs(ground: boolean): void { + this.controls.mouseButtons = ground ? MOVES_ON_DRAG : TURNS_ON_DRAG + // Ground moves along itself, so dragging up brings what is further away closer instead of lifting the camera. + this.controls.screenSpacePanning = !ground + this.controls.maxPolarAngle = ground ? LOWEST_OVER_GROUND_RADIANS : Math.PI + } + + private removeShown(): void { + this.stopFollowing?.() + this.stopFollowing = null + if (this.shown !== null) { + this.scene.remove(this.shown.object) + } + } + + private cameraLink(): CameraLink { + return { + view: () => ({ + camera: this.camera, + width: this.host.clientWidth, + height: this.host.clientHeight, + orbitDistance: this.camera.position.distanceTo(this.controls.target) + }), + onMoved: (listener) => { + this.moveListeners.add(listener) + return () => this.moveListeners.delete(listener) + }, + redraw: () => this.requestFrame() + } + } + + private notifyMoved(): void { + this.moveListeners.forEach((listener) => listener()) + } + + frameShown(): void { + if (this.shown === null) { + this.framed = false + return + } + this.framed = true + const bounds = this.shown.bounds + const sphere = bounds.isEmpty() ? new Sphere(new Vector3(), 1) : bounds.getBoundingSphere(new Sphere()) + const halfVertical = (FIELD_OF_VIEW_DEGREES * Math.PI) / 360 + const halfHorizontal = Math.atan(Math.tan(halfVertical) * this.camera.aspect) + const distance = (sphere.radius * FRAMING_MARGIN) / Math.sin(Math.min(halfVertical, halfHorizontal)) + this.controls.target.copy(sphere.center) + this.camera.position.copy(sphere.center).addScaledVector(VIEW_DIRECTION, distance) + this.framedFar = distance * 10 + sphere.radius * 4 + this.controls.update() + this.fitClipToOrbit() + this.notifyMoved() + 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 + } + this.pickListener(this.surfaceUnder(event)) + } + + onSpotAsked(listener: ((asked: AskedSpot) => void) | null): void { + this.spotListener = listener + } + + private askAboutSpotIfClicked(event: PointerEvent): void { + const pressed = this.spotPressedAt + this.spotPressedAt = null + if (pressed === null || this.spotListener === null) { + return + } + if (Math.hypot(event.clientX - pressed.x, event.clientY - pressed.y) > CLICK_SLOP_PIXELS) { + return + } + const surface = this.surfaceUnder(event) + if (surface === null) { + return + } + const gesture = event.button === RIGHT_BUTTON ? 'rightClick' : 'ctrlClick' + this.spotListener({ spot: surface.point, gesture, clientX: event.clientX, clientY: event.clientY }) + } + + private surfaceUnder(event: PointerEvent): PickedSurface { + if (this.shown === null) { + return null + } + 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) + return 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, + // and moving keeps pace with it. + private pivotOnSurfaceInMiddle(): void { + if (this.shown === null) { + return + } + const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3())) + const hit = surfaceAlong(this.shown, ray, this.camera.far) + if (hit === null) { + return + } + this.controls.target.copy(hit) + this.fitClipToOrbit() + this.notifyMoved() + this.requestFrame() + } + + private fitClipToOrbit(): void { + const orbitDistance = this.camera.position.distanceTo(this.controls.target) + this.camera.near = Math.max(NEAREST_CLIP, orbitDistance * NEAR_CLIP_PER_ORBIT_DISTANCE) + this.camera.far = Math.max(this.framedFar, orbitDistance * FAR_CLIP_PER_ORBIT_DISTANCE) + this.camera.updateProjectionMatrix() + } + + dispose(): void { + this.removeShown() + this.resizes.disconnect() + this.controls.dispose() + this.renderer.dispose() + this.renderer.domElement.remove() + } + + private fitToHost(): void { + const width = Math.max(1, this.host.clientWidth) + const height = Math.max(1, this.host.clientHeight) + this.renderer.setSize(width, height) + this.camera.aspect = width / height + this.camera.updateProjectionMatrix() + this.notifyMoved() + this.requestFrame() + } + + private requestFrame(): void { + if (this.frameRequested) { + return + } + this.frameRequested = true + requestAnimationFrame(() => { + this.frameRequested = false + this.renderer.render(this.scene, this.camera) + }) + } +} diff --git a/studio/src/renderer/src/studio/ShortcutSettings.tsx b/studio/src/renderer/src/studio/ShortcutSettings.tsx new file mode 100644 index 000000000..474470daa --- /dev/null +++ b/studio/src/renderer/src/studio/ShortcutSettings.tsx @@ -0,0 +1,167 @@ +import { useEffect, useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { cn } from '@/lib/utils' +import type { GraphicsInfo } from '../../../shared/bridge' +import type { ViewInfo } from '../bridge/types' +import { chordOf, chordText, chordsOf, chordsText, clashesWith, defaultChords, shortcutRows, type ShortcutGroup, type ShortcutRow } from './shortcuts' +import { shortcutStore, useBindings } from './useBindings' + +interface ShortcutSettingsProps { + open: boolean + onOpenChange(open: boolean): void + views: ViewInfo[] +} + +interface Note { + text: string + warning: boolean +} + +const GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor'] +const RECORDING_TEXT = 'Press a key…' +const NO_KEYS_TEXT = 'None' + +/** Every shortcut with its keys, rebound by clicking its keys and pressing the new one. Changes are saved at once. */ +export function ShortcutSettings({ open, onOpenChange, views }: ShortcutSettingsProps): React.JSX.Element { + const bindings = useBindings() + const rows = useMemo(() => shortcutRows(views), [views]) + const [recording, setRecording] = useState(null) + const [note, setNote] = useState(null) + + useEffect(() => { + if (!open) { + setRecording(null) + } + }, [open]) + + useEffect(() => { + if (recording === null) { + return + } + const record = (event: KeyboardEvent): void => { + event.preventDefault() + event.stopPropagation() + const chord = chordOf(event) + if (chord === null) { + return + } + const clashes = clashesWith(recording, chord, rows, shortcutStore.snapshot()) + shortcutStore.rebind(recording.id, [chord]) + setRecording(null) + setNote( + clashes.length === 0 + ? { text: `${recording.label} is now ${chordText(chord)}`, warning: false } + : { text: `${chordText(chord)} is also ${clashes.map((clash) => clash.label).join(', ')}`, warning: true } + ) + } + window.addEventListener('keydown', record, true) + return () => window.removeEventListener('keydown', record, true) + }, [recording, rows]) + + return ( + + + + Settings + Click a shortcut's keys, then press the new key. Esc can be chosen too; click the keys again to cancel. + +
+ + {GROUPS.map((group) => ( +
+

{group}

+ {rows + .filter((row) => row.group === group) + .map((row) => ( + setRecording((current) => (current?.id === row.id ? null : row))} + onReset={() => { + setRecording(null) + shortcutStore.reset(row.id) + }} + /> + ))} +
+ ))} +
+ + {note?.text} + + +
+
+ ) +} + +/** The GPU choice, shown only where there is an NVIDIA GPU to choose. Changing it restarts the studio. */ +function GraphicsSection(): React.JSX.Element | null { + const [graphics, setGraphics] = useState(null) + + useEffect(() => { + void window.studio.graphics().then(setGraphics) + }, []) + + if (graphics === null || !graphics.canUseDedicatedGpu) { + return null + } + const dedicated = graphics.usesDedicatedGpu + return ( +
+

Graphics

+
+ Draw with the NVIDIA GPU (restarts) + + +
+
+ ) +} + +interface ShortcutRowViewProps { + row: ShortcutRow + keys: string[] + changed: boolean + recording: boolean + onRecord(): void + onReset(): void +} + +function ShortcutRowView({ row, keys, changed, recording, onRecord, onReset }: ShortcutRowViewProps): React.JSX.Element { + return ( +
+ + {row.label} + + + +
+ ) +} diff --git a/studio/src/renderer/src/studio/Sidebar.tsx b/studio/src/renderer/src/studio/Sidebar.tsx new file mode 100644 index 000000000..25295a39e --- /dev/null +++ b/studio/src/renderer/src/studio/Sidebar.tsx @@ -0,0 +1,98 @@ +import { createContext, useContext } from 'react' +import { createPortal } from 'react-dom' +import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' +import { Button } from '@/components/ui/button' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' + +/** Where a view puts its own lists: under the views in the left island, as in v3e. */ +export const SidebarSlot = createContext(null) + +/** A section of the left island under the views, filled by the view that is shown. */ +export function SidebarPanel({ className, children }: { className?: string; children: React.ReactNode }): React.JSX.Element | null { + const slot = useContext(SidebarSlot) + if (slot === null) { + return null + } + return createPortal(
{children}
, slot) +} + +/** One choice of a switch in an island's header: plain until chosen and outlined then, as IntelliJ's tabs are. */ +export const HEADER_CHOICE = + 'h-7 flex-none rounded-md! border border-transparent px-2.5 text-[12.5px] font-normal hover:bg-accent hover:text-foreground data-[state=on]:border-input data-[state=on]:bg-transparent data-[state=on]:text-foreground' + +interface StepperProps { + /** Where the steps are now: "Variant 2 of 5". */ + label: string + backHint: string + onHint: string + onBack(): void + onOn(): void +} + +/** Steps through numbered things from an island's header. */ +export function Stepper({ label, backHint, onHint, onBack, onOn }: StepperProps): React.JSX.Element { + return ( + + + {label} + + + ) +} + +interface SizeChoiceProps { + /** Each size, as blocks across, smallest first. */ + sizes: readonly number[] + size: number + onSize(size: number): void +} + +/** Chooses how many blocks across an area is, from an island's header. */ +export function SizeChoice({ sizes, size, onSize }: SizeChoiceProps): React.JSX.Element { + return ( + value !== '' && onSize(Number(value))}> + {sizes.map((choice) => ( + + {choice} + + ))} + + ) +} + +interface ViewIslandProps { + title: string + /** The view's own buttons, at the right of its header. */ + tools?: React.ReactNode + className?: string + children: React.ReactNode +} + +/** The shown view's icon in the stripe, which its island repeats beside its name so the two are learned together. */ +export const ShownViewIcon = createContext(null) + +/** The island a view draws in, under a header with the view's icon, its name and its tools, as an IntelliJ tool window has. */ +export function ViewIsland({ title, tools, className, children }: ViewIslandProps): React.JSX.Element { + const icon = useContext(ShownViewIcon) + return ( +
+
+ {icon !== null && } +

{title}

+ + {tools} +
+
{children}
+
+ ) +} + +/** A card in the shell: the panels sit apart on the window background instead of sharing borders. */ +export function Panel({ className, children }: { className?: string; children: React.ReactNode }): React.JSX.Element { + return +} diff --git a/studio/src/renderer/src/studio/StatusBar.tsx b/studio/src/renderer/src/studio/StatusBar.tsx new file mode 100644 index 000000000..ba2c7f191 --- /dev/null +++ b/studio/src/renderer/src/studio/StatusBar.tsx @@ -0,0 +1,104 @@ +import { IdeIcon } from '@/components/IdeIcon' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { ServerUsage } from '../bridge/types' +import type { MapStatus } from '../map/MapController' +import { cpuIsHigh, formatCpu, formatHeap, heapIsHigh } from './serverUsage' + +interface StatusBarProps { + viewLabel: string + status: MapStatus | null + notice: string | null + usage: ServerUsage | null + /** How far a scene view's reading has come, 0 to 1, or null when it is not reading. */ + progress: number | null +} + +const NUMBER = new Intl.NumberFormat('en-US') + +/** What the map shows, what it is busy with, and where the cursor is (v3e StudioStatusBar). */ +export function StatusBar({ viewLabel, status, notice, usage, progress }: StatusBarProps): React.JSX.Element { + const drawing = status !== null && status.tilesReady < status.tilesTotal + return ( +
+ + {viewLabel} + {status !== null && ( + <> + + {formatScale(status.blocksPerPixel)} blocks/px + + {NUMBER.format(status.widthBlocks)} × {NUMBER.format(status.heightBlocks)} blocks + + )} + + + {notice ?? (drawing ? `Drawing ${status.tilesReady} of ${status.tilesTotal} tiles` : progress !== null ? 'Reading' : '')} + {notice === null && drawing && } + {notice === null && !drawing && progress !== null && } + + {usage !== null && } + {status !== null && ( + + X {NUMBER.format(status.cursorX)} + Z {NUMBER.format(status.cursorZ)} + + )} +
+ ) +} + +function ProgressBar({ fraction }: { fraction: number }): React.JSX.Element { + return ( + + + + ) +} + +/** The server's CPU, 100% per busy thread, and Java heap; each turns warning-coloured at 80%. */ +function UsageReadout({ usage }: { usage: ServerUsage }): React.JSX.Element { + return ( + + } + value={formatCpu(usage)} + high={cpuIsHigh(usage)} + hint={`Server CPU, 100% per busy thread, ${usage.threads} threads in all`} + /> + } value={formatHeap(usage)} high={heapIsHigh(usage)} hint="Java memory the server uses, of its maximum" /> + + ) +} + +interface ReadingProps { + icon: React.ReactNode + value: string + high: boolean + hint: string +} + +function Reading({ icon, value, high, hint }: ReadingProps): React.JSX.Element { + return ( + + + + {icon} + {value} + + + {hint} + + ) +} + +function Gap(): React.JSX.Element { + return +} + +function formatScale(blocksPerPixel: number): string { + if (blocksPerPixel >= 10) { + return String(Math.round(blocksPerPixel)) + } + return blocksPerPixel >= 1 ? blocksPerPixel.toFixed(1) : blocksPerPixel.toFixed(2) +} diff --git a/studio/src/renderer/src/studio/StudioToolbar.tsx b/studio/src/renderer/src/studio/StudioToolbar.tsx new file mode 100644 index 000000000..3d4f41a4d --- /dev/null +++ b/studio/src/renderer/src/studio/StudioToolbar.tsx @@ -0,0 +1,147 @@ +import type { ReactNode } from 'react' +import { IdeIcon } from '@/components/IdeIcon' +import { Button } from '@/components/ui/button' +import { Kbd } from '@/components/ui/kbd' +import { Separator } from '@/components/ui/separator' +import { Toggle } from '@/components/ui/toggle' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import type { ThemeChoice } from '../../../shared/bridge' +import type { WorldInfo } from '../bridge/types' +import type { StudioToggles } from './MapStudio' +import type { ShortcutAction } from './shortcuts' +import { useKeyText } from './useBindings' + +interface StudioToolbarProps { + world: WorldInfo + theme: { choice: ThemeChoice; next: () => void } + onHelp(): void + onSettings(): void + onDisconnect(): void +} + +const THEME_NAMES: Record = { system: 'Theme: system', light: 'Theme: light', dark: 'Theme: dark' } + +/** The window's bar: the world the studio is connected to, which leads back to the world list, and the studio's own buttons. */ +export function StudioToolbar({ world, theme, onHelp, onSettings, onDisconnect }: StudioToolbarProps): React.JSX.Element { + return ( +
+ + + +
+ + + + + + + + + +
+ ) +} + +interface MapToolsProps { + toggles: StudioToggles + hasPlayers: boolean + onToggle(name: keyof StudioToggles): void + onRefresh(): void + onResetZoom(): void +} + +/** The map's own buttons, for the header of its island. */ +export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom }: MapToolsProps): React.JSX.Element { + return ( + <> + onToggle('grid')}> + + + onToggle('regionBorders')}> + + + onToggle('shading')}> + + + onToggle('blocks')}> + + + + onToggle('entities')}> + + + onToggle('follow')}> + + + + + + + + + + + ) +} + +function IconHint({ hint, keyText, children }: { hint: string; keyText?: string; children: ReactNode }): React.JSX.Element { + return ( + + {children} + + {hint} + {keyText !== undefined && keyText !== '' && {keyText}} + + + ) +} + +function ToolButton({ action, hint, onClick, children }: { action: ShortcutAction; hint: string; onClick(): void; children: ReactNode }): React.JSX.Element { + const keyText = useKeyText() + return ( + + + + ) +} + +interface ToolToggleProps { + action: ShortcutAction + hint: string + pressed: boolean + disabled?: boolean + onPressed(): void + children: ReactNode +} + +function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: ToolToggleProps): React.JSX.Element { + const keyText = useKeyText() + return ( + + + + {children} + + + + ) +} diff --git a/studio/src/renderer/src/studio/SuggestionInput.tsx b/studio/src/renderer/src/studio/SuggestionInput.tsx new file mode 100644 index 000000000..1fe7b5624 --- /dev/null +++ b/studio/src/renderer/src/studio/SuggestionInput.tsx @@ -0,0 +1,91 @@ +import { useState } from 'react' +import { Input } from '@/components/ui/input' +import { cn } from '@/lib/utils' +import { completed, matching, wordBeingTyped } from '../editor/suggestions' + +const NO_CHOICE = -1 + +type InputProps = Omit, 'value' | 'onChange'> + +interface SuggestionInputProps extends InputProps { + value: string + onValue(value: string): void + /** Whether the text is a list typed as {@code a, b}, which completes the item being typed. */ + isList: boolean + /** Reads what the text may be completed with, when the field is first used; null for a field typed freely. */ + load: (() => Promise) | null +} + +/** A text field that offers what it may be typed as while it is typed; Arrow keys and Enter or Tab choose, a click chooses too. */ +export function SuggestionInput({ value, onValue, isList, load, onKeyDown, onFocus, onBlur, className, ...props }: SuggestionInputProps): React.JSX.Element { + const [choices, setChoices] = useState(null) + const [focused, setFocused] = useState(false) + const [highlighted, setHighlighted] = useState(NO_CHOICE) + const offered = focused && choices !== null ? matching(choices, wordBeingTyped(value, isList).typed) : [] + + const pick = (choice: string): void => { + onValue(completed(value, choice, isList)) + setHighlighted(NO_CHOICE) + } + + return ( +
+ { + onValue(event.target.value) + setHighlighted(NO_CHOICE) + }} + onFocus={(event) => { + setFocused(true) + if (load !== null && choices === null) { + load() + .then(setChoices) + .catch(() => setChoices([])) + } + onFocus?.(event) + }} + onBlur={(event) => { + setFocused(false) + setHighlighted(NO_CHOICE) + onBlur?.(event) + }} + onKeyDown={(event) => { + if (offered.length > 0 && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + event.preventDefault() + const step = event.key === 'ArrowDown' ? 1 : -1 + setHighlighted((current) => ((current + step + offered.length + 2) % (offered.length + 1)) - 1) + return + } + if (highlighted >= 0 && highlighted < offered.length && (event.key === 'Enter' || event.key === 'Tab')) { + event.preventDefault() + pick(offered[highlighted]) + return + } + onKeyDown?.(event) + }} + /> + {offered.length > 0 && ( +
    + {offered.map((choice, index) => ( +
  • + +
  • + ))} +
+ )} +
+ ) +} diff --git a/studio/src/renderer/src/studio/TiledCanvas.tsx b/studio/src/renderer/src/studio/TiledCanvas.tsx new file mode 100644 index 000000000..79a291f1f --- /dev/null +++ b/studio/src/renderer/src/studio/TiledCanvas.tsx @@ -0,0 +1,78 @@ +import { useEffect, useRef } from 'react' +import type { TiledView } from '../map/TiledView' + +type AnyTiledView = TiledView + +interface TiledCanvasProps { + /** Makes the view on the canvas; called again only when it changes, so keep it stable. */ + create(canvas: HTMLCanvasElement): View + viewRef: React.RefObject + className?: string +} + +// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads. +const WHEEL_ZOOM_PER_DELTA = 0.002 + +/** A tiled view from above: drag to move, wheel to zoom. */ +export function TiledCanvas({ create, viewRef, className }: TiledCanvasProps): React.JSX.Element { + const canvasRef = useRef(null) + + useEffect(() => { + const canvas = canvasRef.current! + const view = create(canvas) + viewRef.current = view + const resize = new ResizeObserver(([entry]) => view.resize(entry.contentRect.width, entry.contentRect.height)) + resize.observe(canvas) + const stopMouse = followMouse(canvas, view) + return () => { + stopMouse() + resize.disconnect() + view.close() + viewRef.current = null + } + }, [create, viewRef]) + + return +} + +function followMouse(canvas: HTMLCanvasElement, view: AnyTiledView): () => void { + let last: { x: number; y: number } | null = null + const pointOf = (event: MouseEvent): { x: number; y: number } => { + const bounds = canvas.getBoundingClientRect() + return { x: event.clientX - bounds.left, y: event.clientY - bounds.top } + } + const down = (event: PointerEvent): void => { + if (event.button === 0) { + canvas.setPointerCapture(event.pointerId) + last = { x: event.clientX, y: event.clientY } + } + } + const move = (event: PointerEvent): void => { + view.setCursor(pointOf(event)) + if (last !== null) { + view.panBy(event.clientX - last.x, event.clientY - last.y) + last = { x: event.clientX, y: event.clientY } + } + } + const up = (): void => { + last = null + } + const leave = (): void => view.setCursor(null) + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const point = pointOf(event) + view.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y) + } + canvas.addEventListener('pointerdown', down) + canvas.addEventListener('pointermove', move) + canvas.addEventListener('pointerup', up) + canvas.addEventListener('pointerleave', leave) + canvas.addEventListener('wheel', wheel, { passive: false }) + return () => { + canvas.removeEventListener('pointerdown', down) + canvas.removeEventListener('pointermove', move) + canvas.removeEventListener('pointerup', up) + canvas.removeEventListener('pointerleave', leave) + canvas.removeEventListener('wheel', wheel) + } +} diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx new file mode 100644 index 000000000..6b7f3becc --- /dev/null +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -0,0 +1,145 @@ +import { DropdownMenu } from 'radix-ui' +import { Fragment } from 'react' +import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' +import { Kbd } from '@/components/ui/kbd' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { ViewInfo } from '../bridge/types' +import { viewShortcutId } from './shortcuts' +import { useKeyText } from './useBindings' + +const VIEW_ICONS: Record = { + biomes: 'views/biomes', + regions: 'views/regions', + world3d: 'views/world-3d', + savedWorld: 'views/saved-world', + 'iris:terrain/palettes': 'views/palettes', + 'iris:decorant/decorators': 'decoration', + 'iris:objects': 'views/objects', + 'iris:objects/procedural': 'views/procedural', + noise: 'views/noise' +} +const FALLBACK_ICON: IdeIconName = 'blocks' +/** Inset, because the stripe scrolls and so clips anything drawn outside its buttons. */ +const STRIPE_BUTTON = 'flex size-8 shrink-0 items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset' + +/** The icon a view has in the stripe, which its island's header repeats beside its name. */ +export function viewIcon(viewId: string): IdeIconName { + return VIEW_ICONS[viewId] ?? FALLBACK_ICON +} + +interface ViewListProps { + views: ViewInfo[] + current: string + onSelect(view: string): void + /** Receives the element the shown view fills with its own lists, beside the views. */ + slotRef(element: HTMLElement | null): void +} + +/** + * The views the server offers, as a stripe of buttons on the window's edge in their groups with a list of their names + * under them, and beside it the island the shown view fills with its own lists, which is not there for a view without + * any (IntelliJ's tool window stripe). + */ +export function ViewList({ views, current, onSelect, slotRef }: ViewListProps): React.JSX.Element { + const groups = groupsOf(views) + return ( + <> + +
+ + ) +} + +interface ViewGroup { + label: string + views: ViewInfo[] +} + +function groupsOf(views: ViewInfo[]): ViewGroup[] { + const labels = [...new Set(views.map((view) => view.groupLabel))] + return labels.map((label) => ({ label, views: views.filter((view) => view.groupLabel === label) })) +} + +function StripeLine(): React.JSX.Element { + return +} + +function ViewButton({ view, selected, onSelect }: { view: ViewInfo; selected: boolean; onSelect(): void }): React.JSX.Element { + const keyText = useKeyText()(viewShortcutId(view.id)) + return ( + + + + + + + {view.label} + {keyText !== '' && {keyText}} + + {view.description} + + + ) +} + +/** Every view by name, for when its icon alone does not say which it is (IntelliJ's "more tool windows"). */ +function NamedViews({ groups, current, onSelect }: { groups: ViewGroup[]; current: string; onSelect(view: string): void }): React.JSX.Element { + const keyText = useKeyText() + return ( + + + + + + + {groups.map((group) => ( + + {group.label} + {group.views.map((view) => ( + onSelect(view.id)} + className={cn( + 'flex h-[26px] cursor-default items-center gap-2 rounded-md px-2 outline-none data-[highlighted]:bg-accent', + view.id === current && 'bg-selection' + )} + > + + {view.label} + {keyText(viewShortcutId(view.id)) !== '' && ( + {keyText(viewShortcutId(view.id))} + )} + + ))} + + ))} + + + + ) +} diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx new file mode 100644 index 000000000..b9a1d6743 --- /dev/null +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -0,0 +1,189 @@ +import { useEffect, useMemo, useState } from 'react' +import { Toggle } from '@/components/ui/toggle' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' +import type { MapTile, WorldInfo } from '../bridge/types' +import { heightBandShares } from '../map/census' +import { mapTileSource, type TileLayer } from '../map/mapTileSource' +import type { GroundInView } from '../scene/groundInView' +import { blockArt } from '../scene/blockArt' +import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain' +import { meshOfGeometry } from '../scene/terrainMesh' +import { TerrainMeshWorkers } from '../scene/terrainMeshWorkers' +import { focusAround, type TerrainStyle } from '../scene/terrainStream' +import { TILE_COLUMNS } from '../scene/terrainTiles' +import { Legend } from './Legend' +import { PickInspector } from './PickInspector' +import { SceneViewport } from './SceneViewport' +import { usePickInspection } from './usePickInspection' +import { useSpotActions } from './useSpotActions' +import { HEADER_CHOICE, Panel, SizeChoice, ViewIsland } from './Sidebar' +import { useGroundInView, useLongPending, useTerrainStream } from './useTerrainStream' +import { caveBandShares, useWorldCaves, type CaveArea } from './useWorldCaves' + +const NUMBER = new Intl.NumberFormat('en-US') +// The map's coarsest tiles are 4096 blocks a pixel, which is level 12. +const COARSEST_LEVEL = 12 +const BLOCKS_ABOVE_FLUID_IN_FOCUS = 96 +const BLOCKS_BELOW_FLUID_IN_FOCUS = 32 +// Every level carries blocks, out to the horizon: a coarse tile generates a chunk for each of its columns, a minute or +// so of the server's time, and the ground already sampled stays in sight meanwhile. +const MOST_BLOCKS_PER_COLUMN = 2 ** COARSEST_LEVEL +// Every chunk of the square is generated: 256 blocks across is 256 chunks, seconds of the server's time. +const CAVE_SIZES = [128, 256, 512] +const OPENING_CAVE_SIZE = 256 + +// Tiles with generated blocks take seconds to minutes each. The same tiles without them stand in, but only on ground +// where no tile with blocks of any level is known yet. +function withoutBlocks(layer: TileLayer): TileLayer | null { + return layer.blocks === null ? null : { ...layer, blocks: null, shape: false } +} + +interface WorldStudio3DProps { + title: string + client: BridgeClient + world: WorldInfo + /** Where the map last looked; the terrain opens around its middle, or around the world's centre. */ + mapArea: WorldRect | null + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** + * The terrain around where the map looked, in 3D and without an edge, coloured by biome, region or height, beside how + * the noise picks the biomes or regions the camera sees, or how much of that ground lies at each height (v3e's 3D world view). + */ +export function WorldStudio3D({ title, client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element { + const [coloring, setColoring] = useState('biomes') + const centre = useMemo(() => centreOf(mapArea), [mapArea]) + const art = useMemo(() => blockArt(client, true), [client]) + useEffect(() => () => art.dispose(), [art]) + const source = useMemo(() => mapTileSource(client, TILE_COLUMNS, art, MOST_BLOCKS_PER_COLUMN), [client, art]) + const focus = useMemo( + () => focusAround(centre.x, centre.z, world.fluidHeight - BLOCKS_BELOW_FLUID_IN_FOCUS, world.fluidHeight + BLOCKS_ABOVE_FLUID_IN_FOCUS), + [centre, world.fluidHeight] + ) + const showsBlocks = coloring === 'blocks' + const layer = useMemo( + () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, shape: showsBlocks, revision: packRevision }), + [packRevision, showsBlocks] + ) + const meshWorkers = useMemo(() => new TerrainMeshWorkers(), []) + useEffect(() => () => meshWorkers.dispose(), [meshWorkers]) + const style = useMemo>( + () => ({ + surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight, art.atlas ?? undefined), + floorY: world.minY, + topY: world.minY + world.height, + buildMesh: (tile, place, base, holes) => + meshWorkers + .build({ tile, place, coloring, fluidHeight: world.fluidHeight, plain: art.atlas?.plain ?? null, base, holes }) + .then((geometry) => meshOfGeometry(geometry, art.atlas)) + }), + [coloring, world.fluidHeight, world.minY, world.height, art, meshWorkers] + ) + const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell, withoutBlocks) + const sampling = useLongPending(pending) + const ground = useGroundInView(stream) + const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight]) + const inspectsPicks = coloring !== 'height' + const pickView = coloring === 'regions' ? 'regions' : 'biomes' + const pickLayer = useMemo(() => ({ view: pickView, preview: null }), [pickView]) + const area = useAreaOf(ground) + const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision) + const spotActions = useSpotActions(client, tell, true) + const [showsCaves, setShowsCaves] = useState(false) + const [caveArea, setCaveArea] = useState(null) + const caves = useWorldCaves(client, caveArea, packRevision, tell) + const caveShares = useMemo(() => (caves.scene === null ? [] : caveBandShares(caves.scene)), [caves.scene]) + // The caves are generated around the middle of the ground in view when they are shown, or at another size there. + const showCavesAt = (size: number): void => { + const middle = area === null ? centre : { x: Math.round((area.minX + area.maxX) / 2), z: Math.round((area.minZ + area.maxZ) / 2) } + setCaveArea((known) => (known !== null && known.centerX === middle.x && known.centerZ === middle.z && known.size === size ? known : { centerX: middle.x, centerZ: middle.z, size })) + setShowsCaves(true) + } + + const notice = showsCaves ? caves.status : sampling ? 'Sampling the terrain' : null + + useEffect(() => { + const around = showsCaves && caveArea !== null ? { x: caveArea.centerX, z: caveArea.centerZ } : centre + onSummary(`${showsCaves ? 'Caves around' : 'Around'} ${NUMBER.format(around.x)}, ${NUMBER.format(around.z)}`) + return () => onSummary(null) + }, [centre, showsCaves, caveArea, onSummary]) + + return ( + <> + + {showsCaves ? ( + + ) : ( + value !== '' && setColoring(value as MapTerrainColoring)}> + + Biomes + + + Regions + + + Height + + + Blocks + + + )} + (pressed ? showCavesAt(caveArea?.size ?? OPENING_CAVE_SIZE) : setShowsCaves(false))} + > + Caves + + + } + > + {showsCaves ? ( + + ) : ( + + )} + {notice !== null && ( +
+ {notice} +
+ )} +
+ + {showsCaves ? ( + + ) : inspectsPicks ? ( + + ) : ( + + )} + + + ) +} + +// The same box is the same area, so the measurement is not asked for again while only the heights in it change. +function useAreaOf(ground: GroundInView | null): WorldRect | null { + const minX = ground?.area.minX + const minZ = ground?.area.minZ + const maxX = ground?.area.maxX + const maxZ = ground?.area.maxZ + return useMemo(() => (minX === undefined || minZ === undefined || maxX === undefined || maxZ === undefined ? null : { minX, minZ, maxX, maxZ }), [minX, minZ, maxX, maxZ]) +} + +function centreOf(area: WorldRect | null): { x: number; z: number } { + if (area === null) { + return { x: 0, z: 0 } + } + return { x: Math.round((area.minX + area.maxX) / 2), z: Math.round((area.minZ + area.maxZ) / 2) } +} diff --git a/studio/src/renderer/src/studio/colors.ts b/studio/src/renderer/src/studio/colors.ts new file mode 100644 index 000000000..79e9ca266 --- /dev/null +++ b/studio/src/renderer/src/studio/colors.ts @@ -0,0 +1,4 @@ +/** A 0xRRGGBB colour as CSS. */ +export function hexColor(color: number): string { + return `#${color.toString(16).padStart(6, '0')}` +} diff --git a/studio/src/renderer/src/studio/serverUsage.test.ts b/studio/src/renderer/src/studio/serverUsage.test.ts new file mode 100644 index 000000000..4a27f27cb --- /dev/null +++ b/studio/src/renderer/src/studio/serverUsage.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import type { ServerUsage } from '../bridge/types' +import { cpuIsHigh, formatCpu, formatHeap, heapIsHigh } from './serverUsage' + +const GIGABYTE = 1024 ** 3 + +function usageOf(cpuPercent: number | null, heapGigabytes: number): ServerUsage { + return { cpuPercent, threads: 8, heapUsedBytes: heapGigabytes * GIGABYTE, heapMaxBytes: 10 * GIGABYTE } +} + +describe('server usage', () => { + it('shows the CPU in percent per busy thread, and a dash when the server cannot tell', () => { + expect(formatCpu(usageOf(312.4, 1))).toBe('312%') + expect(formatCpu(usageOf(null, 1))).toBe('–') + }) + + it('shows the heap in use of its maximum in gigabytes', () => { + expect(formatHeap(usageOf(0, 3.25))).toBe('3.3 / 10.0 GB') + }) + + it('warns once four fifths of the threads are busy, not before', () => { + expect(cpuIsHigh(usageOf(639, 1))).toBe(false) + expect(cpuIsHigh(usageOf(640, 1))).toBe(true) + expect(cpuIsHigh(usageOf(null, 1))).toBe(false) + }) + + it('warns once four fifths of the heap is in use, not before', () => { + expect(heapIsHigh(usageOf(0, 7.9))).toBe(false) + expect(heapIsHigh(usageOf(0, 8))).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/studio/serverUsage.ts b/studio/src/renderer/src/studio/serverUsage.ts new file mode 100644 index 000000000..6a6b40e07 --- /dev/null +++ b/studio/src/renderer/src/studio/serverUsage.ts @@ -0,0 +1,27 @@ +import type { ServerUsage } from '../bridge/types' + +const HIGH_USAGE = 0.8 +const PERCENT_PER_THREAD = 100 +const BYTES_PER_GIGABYTE = 1024 ** 3 + +export function formatCpu(usage: ServerUsage): string { + return usage.cpuPercent === null ? '–' : `${Math.round(usage.cpuPercent)}%` +} + +export function formatHeap(usage: ServerUsage): string { + return `${gigabytes(usage.heapUsedBytes)} / ${gigabytes(usage.heapMaxBytes)} GB` +} + +/** Whether four fifths of the CPU's threads are busy. */ +export function cpuIsHigh(usage: ServerUsage): boolean { + return usage.cpuPercent !== null && usage.cpuPercent >= usage.threads * PERCENT_PER_THREAD * HIGH_USAGE +} + +/** Whether four fifths of the heap is in use. */ +export function heapIsHigh(usage: ServerUsage): boolean { + return usage.heapUsedBytes >= usage.heapMaxBytes * HIGH_USAGE +} + +function gigabytes(bytes: number): string { + return (bytes / BYTES_PER_GIGABYTE).toFixed(1) +} diff --git a/studio/src/renderer/src/studio/shortcutStore.test.ts b/studio/src/renderer/src/studio/shortcutStore.test.ts new file mode 100644 index 000000000..565325d24 --- /dev/null +++ b/studio/src/renderer/src/studio/shortcutStore.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { createShortcutStore, type ShortcutStorage } from './shortcutStore' +import type { Bindings } from './shortcuts' + +function storageHolding(stored: unknown): ShortcutStorage & { saved: Bindings[] } { + const saved: Bindings[] = [] + return { saved, load: () => Promise.resolve(stored), save: (bindings) => void saved.push(bindings) } +} + +describe('createShortcutStore', () => { + it('starts with the defaults and reads the saved keys on load', async () => { + const store = createShortcutStore(storageHolding({ grid: ['x'], help: 'nonsense' })) + expect(store.snapshot()).toEqual({}) + + await store.load() + + expect(store.snapshot()).toEqual({ grid: ['x'] }) + }) + + it('keeps the defaults when the saved keys cannot be read', async () => { + const store = createShortcutStore({ load: () => Promise.reject(new Error('unreadable')), save: () => undefined }) + await store.load() + expect(store.snapshot()).toEqual({}) + }) + + it('saves and announces every change', () => { + const storage = storageHolding({}) + const store = createShortcutStore(storage) + let announced = 0 + store.subscribe(() => announced++) + + store.rebind('grid', ['x']) + store.rebind('redo', []) + + expect(store.snapshot()).toEqual({ grid: ['x'], redo: [] }) + expect(storage.saved).toEqual([{ grid: ['x'] }, { grid: ['x'], redo: [] }]) + expect(announced).toBe(2) + }) + + it('drops a binding that is the default again, and resets one or all', () => { + const storage = storageHolding({}) + const store = createShortcutStore(storage) + store.rebind('grid', ['x']) + store.rebind('zoomIn', ['z']) + + store.rebind('grid', ['g']) + expect(store.snapshot()).toEqual({ zoomIn: ['z'] }) + + store.reset('zoomIn') + store.reset('zoomIn') + expect(store.snapshot()).toEqual({}) + expect(storage.saved).toHaveLength(4) + + store.rebind('grid', ['x']) + store.resetAll() + expect(store.snapshot()).toEqual({}) + }) + + it('stops announcing to a listener that unsubscribed', () => { + const store = createShortcutStore(storageHolding({})) + let announced = 0 + const unsubscribe = store.subscribe(() => announced++) + unsubscribe() + store.rebind('grid', ['x']) + expect(announced).toBe(0) + }) +}) diff --git a/studio/src/renderer/src/studio/shortcutStore.ts b/studio/src/renderer/src/studio/shortcutStore.ts new file mode 100644 index 000000000..51d3b3ff4 --- /dev/null +++ b/studio/src/renderer/src/studio/shortcutStore.ts @@ -0,0 +1,69 @@ +import { defaultChords, sanitizeBindings, type Bindings, type Chord } from './shortcuts' + +/** Where the rebound keys are kept between runs. */ +export interface ShortcutStorage { + load(): Promise + save(bindings: Bindings): void +} + +export interface ShortcutStore { + snapshot(): Bindings + subscribe(listener: () => void): () => void + /** Reads the saved keys; the defaults stay when there are none or they cannot be read. */ + load(): Promise + rebind(id: string, chords: Chord[]): void + reset(id: string): void + resetAll(): void +} + +/** The keys the user rebound, saved at each change and shared with every component that shows or reads a key. */ +export function createShortcutStore(storage: ShortcutStorage): ShortcutStore { + let bindings: Bindings = {} + const listeners = new Set<() => void>() + + const publish = (next: Bindings): void => { + bindings = next + listeners.forEach((listener) => listener()) + } + const change = (next: Bindings): void => { + publish(next) + storage.save(next) + } + const rebind = (id: string, chords: Chord[]): void => { + if (sameChords(chords, defaultChords(id))) { + reset(id) + return + } + change({ ...bindings, [id]: chords }) + } + const reset = (id: string): void => { + if (bindings[id] === undefined) { + return + } + const rest = { ...bindings } + delete rest[id] + change(rest) + } + + return { + snapshot: () => bindings, + subscribe(listener) { + listeners.add(listener) + return () => listeners.delete(listener) + }, + async load() { + try { + publish(sanitizeBindings(await storage.load())) + } catch { + publish({}) + } + }, + rebind, + reset, + resetAll: () => change({}) + } +} + +function sameChords(first: Chord[], second: Chord[]): boolean { + return first.length === second.length && first.every((chord, index) => chord === second[index]) +} diff --git a/studio/src/renderer/src/studio/shortcuts.test.ts b/studio/src/renderer/src/studio/shortcuts.test.ts new file mode 100644 index 000000000..886158276 --- /dev/null +++ b/studio/src/renderer/src/studio/shortcuts.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest' +import { + SHORTCUTS, + chordOf, + chordText, + clashesWith, + defaultChords, + isChord, + keyTextOf, + matches, + nodeEditorActionFor, + sanitizeBindings, + shortcutRows, + viewShortcutId, + windowShortcutFor, + type KeyPress +} from './shortcuts' + +const DEFAULT_VIEWS = ['biomes', 'regions', 'world3d', 'savedWorld', 'noise'].map((id) => ({ id, label: id })) +const ROWS = shortcutRows(DEFAULT_VIEWS) + +function press(key: string, modifiers: Partial> = {}): KeyPress { + return { key, ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...modifiers } +} + +describe('shortcuts', () => { + it('never gives two shortcuts that work together the same default key', () => { + for (const row of ROWS) { + for (const chord of defaultChords(row.id)) { + expect(clashesWith(row, chord, ROWS, {}).map((clash) => clash.id), `${row.id} ${chord}`).toEqual([]) + } + } + }) + + it('writes every default key as a chord that reads back as itself', () => { + for (const row of ROWS) { + for (const chord of defaultChords(row.id)) { + expect(isChord(chord), `${row.id} ${chord}`).toBe(true) + } + } + }) + + it('makes a chord of a key press, folding Cmd into Ctrl and keeping shift for letters only', () => { + expect(chordOf(press('Z', { ctrlKey: true, shiftKey: true }))).toBe('ctrl+shift+z') + expect(chordOf(press('z', { metaKey: true }))).toBe('ctrl+z') + expect(chordOf(press('M'))).toBe('m') + expect(chordOf(press('?', { shiftKey: true }))).toBe('?') + expect(chordOf(press('ArrowLeft', { shiftKey: true, altKey: true }))).toBe('alt+shift+ArrowLeft') + expect(chordOf(press('Shift', { shiftKey: true }))).toBeNull() + }) + + it('shows chords as people write them', () => { + expect(chordText('ctrl+shift+z')).toBe('Ctrl+Shift+Z') + expect(chordText('Escape')).toBe('Esc') + expect(chordText('=')).toBe('=') + expect(chordText('ctrl++')).toBe('Ctrl++') + expect(chordText('ArrowUp')).toBe('Up') + expect(chordText(' ')).toBe('Space') + }) + + it('finds the window shortcut a key press triggers, by default and once rebound', () => { + expect(windowShortcutFor(press('g'), ROWS, {})).toBe('grid') + expect(windowShortcutFor(press('1'), ROWS, {})).toBe(viewShortcutId('biomes')) + expect(windowShortcutFor(press('z', { ctrlKey: true }), ROWS, {})).toBeNull() + expect(windowShortcutFor(press('g'), ROWS, { grid: ['x'] })).toBeNull() + expect(windowShortcutFor(press('x'), ROWS, { grid: ['x'] })).toBe('grid') + expect(windowShortcutFor(press('4'), ROWS, { [viewShortcutId('biomes')]: ['4'] })).toBe(viewShortcutId('biomes')) + }) + + it('leaves a shortcut with no keys unreachable', () => { + expect(windowShortcutFor(press('g'), ROWS, { grid: [] })).toBeNull() + expect(keyTextOf('grid', { grid: [] })).toBe('') + }) + + it('shows the first key of a shortcut', () => { + expect(keyTextOf('redo', {})).toBe('Ctrl+Y') + expect(keyTextOf('redo', { redo: ['ctrl+shift+z'] })).toBe('Ctrl+Shift+Z') + expect(keyTextOf(viewShortcutId('noise'), {})).toBe('N') + expect(keyTextOf(viewShortcutId('some:module/view'), {})).toBe('') + }) + + it('matches the node editor keys by the live bindings', () => { + expect(matches(press('z', { ctrlKey: true }), 'undo', {})).toBe(true) + expect(matches(press('z', { ctrlKey: true, shiftKey: true }), 'redo', {})).toBe(true) + expect(matches(press('z', { ctrlKey: true }), 'undo', { undo: ['ctrl+u'] })).toBe(false) + expect(matches(press('Control', { ctrlKey: true }), 'undo', {})).toBe(false) + }) + + it('finds the node editor action of a key press, by default and once rebound', () => { + expect(nodeEditorActionFor(press('d', { ctrlKey: true }), {})).toBe('duplicateNode') + expect(nodeEditorActionFor(press('F'), {})).toBe('showAllNodes') + expect(nodeEditorActionFor(press('Home'), {})).toBe('showAllNodes') + expect(nodeEditorActionFor(press('Escape'), {})).toBe('dismiss') + expect(nodeEditorActionFor(press('Delete'), {})).toBe('deleteNode') + expect(nodeEditorActionFor(press('Backspace'), {})).toBe('deleteNode') + expect(nodeEditorActionFor(press('d'), {})).toBeNull() + expect(nodeEditorActionFor(press('f'), { showAllNodes: ['a'] })).toBeNull() + expect(nodeEditorActionFor(press('a'), { showAllNodes: ['a'] })).toBe('showAllNodes') + }) + + it('keeps the node editor keys out of the map shortcuts, which share F', () => { + expect(windowShortcutFor(press('f'), ROWS, {})).toBe('follow') + expect(ROWS.find((row) => row.id === 'showAllNodes')!.group).toBe('Node editor') + expect(clashesWith(ROWS.find((row) => row.id === 'showAllNodes')!, 'f', ROWS, {})).toEqual([]) + }) + + it('reports the shortcuts a new key would clash with, only where both work together', () => { + const grid = ROWS.find((row) => row.id === 'grid')! + const undo = ROWS.find((row) => row.id === 'undo')! + expect(clashesWith(grid, 'h', ROWS, {}).map((clash) => clash.id)).toEqual(['highlight']) + expect(clashesWith(grid, 'ctrl+z', ROWS, {})).toEqual([]) + expect(clashesWith(undo, 'Escape', ROWS, {}).map((clash) => clash.id)).toEqual(['dismiss']) + expect(clashesWith(undo, 'g', ROWS, {})).toEqual([]) + }) + + it('keeps only lists of chords from a settings file', () => { + expect(sanitizeBindings({ grid: ['x', 'ctrl+x'], zoomIn: 'x', help: ['ctrl+Z'], undo: [], redo: ['a', 'a'] })).toEqual({ + grid: ['x', 'ctrl+x'], + undo: [], + redo: ['a'] + }) + expect(sanitizeBindings(null)).toEqual({}) + expect(sanitizeBindings(['grid'])).toEqual({}) + }) + + it('gives every shortcut a label and a default key', () => { + expect(SHORTCUTS.every((shortcut) => shortcut.label !== '' && shortcut.chords.length > 0)).toBe(true) + }) +}) diff --git a/studio/src/renderer/src/studio/shortcuts.ts b/studio/src/renderer/src/studio/shortcuts.ts new file mode 100644 index 000000000..29c6e3f32 --- /dev/null +++ b/studio/src/renderer/src/studio/shortcuts.ts @@ -0,0 +1,261 @@ +/** The studio's keys, as v3e's studio had them (StudioShortcut). */ +export type ShortcutAction = + | 'nextView' + | 'refresh' + | 'zoomIn' + | 'zoomOut' + | 'resetZoom' + | 'dismiss' + | 'follow' + | 'grid' + | 'entities' + | 'highlight' + | 'shading' + | 'blocks' + | 'borders' + | 'help' + | 'undo' + | 'redo' + | 'deleteNode' + | 'duplicateNode' + | 'showAllNodes' + +export type ShortcutGroup = 'Views' | 'Everywhere' | 'Map' | 'Node editor' + +/** + * A key press as text: the modifiers in the order ctrl, alt, shift, then the key as {@code KeyboardEvent.key} names it, + * lowercase when it is a letter. Ctrl stands for Cmd too, and shift is only kept for letters and named keys, as a + * symbol such as ? already says it. + */ +export type Chord = string + +/** The keys a user set, by shortcut id; a shortcut missing here keeps its default keys. */ +export type Bindings = Record + +/** What the settings and help dialogs list: a studio shortcut, or the key that opens one view. */ +export interface ShortcutRow { + id: string + label: string + group: ShortcutGroup +} + +interface ShortcutDefinition extends ShortcutRow { + id: ShortcutAction + chords: Chord[] +} + +export const SHORTCUTS: ShortcutDefinition[] = [ + { id: 'nextView', label: 'Next view', group: 'Views', chords: ['m'] }, + { id: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', chords: ['r'] }, + { id: 'zoomIn', label: 'Zoom in', group: 'Everywhere', chords: ['=', '+'] }, + { id: 'zoomOut', label: 'Zoom out', group: 'Everywhere', chords: ['-'] }, + { id: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', chords: ['\\'] }, + { id: 'dismiss', label: 'Clear the highlight or the chosen node', group: 'Everywhere', chords: ['Escape'] }, + { id: 'follow', label: 'Follow your player', group: 'Map', chords: ['f'] }, + { id: 'grid', label: 'Chunk and region grid', group: 'Map', chords: ['g'] }, + { id: 'entities', label: 'Show entities', group: 'Map', chords: ['e'] }, + { id: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', chords: ['h'] }, + { id: 'shading', label: 'Terrain shading', group: 'Map', chords: ['s'] }, + { id: 'blocks', label: 'Generated blocks', group: 'Map', chords: ['k'] }, + { id: 'borders', label: 'Region borders', group: 'Map', chords: ['b'] }, + { id: 'help', label: 'Show the shortcuts', group: 'Map', chords: ['/', '?'] }, + { id: 'undo', label: 'Undo', group: 'Node editor', chords: ['ctrl+z'] }, + { id: 'redo', label: 'Redo', group: 'Node editor', chords: ['ctrl+y', 'ctrl+shift+z'] }, + { id: 'deleteNode', label: 'Delete the chosen node', group: 'Node editor', chords: ['Delete', 'Backspace'] }, + { id: 'duplicateNode', label: 'Duplicate the chosen node', group: 'Node editor', chords: ['ctrl+d'] }, + { id: 'showAllNodes', label: 'Show every node', group: 'Node editor', chords: ['f', 'Home'] } +] + +/** The key of each view, as in v3e. */ +const VIEW_KEYS: Record = { + biomes: '1', + regions: '2', + world3d: '4', + 'iris:terrain/palettes': 'p', + 'iris:objects': 'o', + 'iris:objects/procedural': 't', + noise: 'n', + savedWorld: 'w' +} + +export const MOUSE_HINTS: { gesture: string; label: string }[] = [ + { gesture: 'Drag', label: 'Move the map' }, + { gesture: 'Wheel', label: 'Zoom around the cursor' }, + { gesture: 'Shift', label: 'More about the spot under the cursor' }, + { gesture: 'Ctrl+Click', label: 'Teleport there' }, + { gesture: 'Alt+Click', label: 'Open the biome or region file' }, + { gesture: 'Right click', label: 'Highlight, teleport, open or copy' } +] + +/** + * The window's own keys work anywhere in it, while the node editor takes its keys first while it is shown, so two + * shortcuts only clash when both are window keys or both are node editor keys. + */ +const GROUP_SCOPES: Record = { + Views: { windowWide: true, nodeEditor: false }, + Everywhere: { windowWide: true, nodeEditor: true }, + Map: { windowWide: true, nodeEditor: false }, + 'Node editor': { windowWide: false, nodeEditor: true } +} + +const NODE_EDITOR_ACTIONS = ['undo', 'redo', 'deleteNode', 'duplicateNode', 'showAllNodes', 'dismiss'] as const +export type NodeEditorAction = (typeof NODE_EDITOR_ACTIONS)[number] + +const VIEW_ID_PREFIX ='view:' +const MODIFIER_PREFIXES = ['ctrl+', 'alt+', 'shift+'] as const +const MODIFIER_KEYS = new Set(['Control', 'Shift', 'Alt', 'Meta', 'AltGraph', 'CapsLock', 'Dead', 'Unidentified']) +const KEY_NAMES: Record = { Escape: 'Esc', ' ': 'Space' } +const ARROW_PREFIX = 'Arrow' + +export interface KeyPress { + key: string + ctrlKey: boolean + metaKey: boolean + altKey: boolean + shiftKey: boolean +} + +export function viewShortcutId(viewId: string): string { + return VIEW_ID_PREFIX + viewId +} + +export function viewOfShortcutId(id: string): string | null { + return id.startsWith(VIEW_ID_PREFIX) ? id.slice(VIEW_ID_PREFIX.length) : null +} + +/** Every shortcut to list, the views first as they head the Views group. */ +export function shortcutRows(views: { id: string; label: string }[]): ShortcutRow[] { + return [...views.map((view) => ({ id: viewShortcutId(view.id), label: view.label, group: 'Views' as const })), ...SHORTCUTS] +} + +export function defaultChords(id: string): Chord[] { + const viewId = viewOfShortcutId(id) + if (viewId !== null) { + return VIEW_KEYS[viewId] === undefined ? [] : [VIEW_KEYS[viewId]] + } + return SHORTCUTS.find((shortcut) => shortcut.id === id)?.chords ?? [] +} + +export function chordsOf(id: string, bindings: Bindings): Chord[] { + return bindings[id] ?? defaultChords(id) +} + +/** The chord of a key press; null for a modifier alone, which names no key yet. */ +export function chordOf(press: KeyPress): Chord | null { + if (MODIFIER_KEYS.has(press.key) || press.key === '') { + return null + } + const key = press.key.length === 1 ? press.key.toLowerCase() : press.key + const keepsShift = press.shiftKey && (key.length > 1 || key !== key.toUpperCase()) + const modifiers = [press.ctrlKey || press.metaKey ? 'ctrl+' : '', press.altKey ? 'alt+' : '', keepsShift ? 'shift+' : ''] + return modifiers.join('') + key +} + +/** Whether a text is a chord in the form {@link chordOf} makes. */ +export function isChord(text: unknown): text is Chord { + if (typeof text !== 'string') { + return false + } + const parsed = splitChord(text) + if (parsed === null) { + return false + } + return chordOf({ key: parsed.key, ctrlKey: parsed.modifiers.includes('ctrl+'), metaKey: false, altKey: parsed.modifiers.includes('alt+'), shiftKey: parsed.modifiers.includes('shift+') }) === text +} + +/** A chord as people write it, like Ctrl+Shift+Z or Esc. */ +export function chordText(chord: Chord): string { + const parsed = splitChord(chord) + if (parsed === null) { + return chord + } + const modifiers = parsed.modifiers.map((prefix) => prefix[0].toUpperCase() + prefix.slice(1)) + return modifiers.join('') + keyName(parsed.key) +} + +export function chordsText(chords: Chord[]): string { + return chords.map(chordText).join(', ') +} + +/** The first key of a shortcut as shown beside it, empty when it has none. */ +export function keyTextOf(id: string, bindings: Bindings): string { + const chords = chordsOf(id, bindings) + return chords.length === 0 ? '' : chordText(chords[0]) +} + +/** Whether the key press is one of the keys of the shortcut. */ +export function matches(press: KeyPress, id: string, bindings: Bindings): boolean { + const chord = chordOf(press) + return chord !== null && chordsOf(id, bindings).includes(chord) +} + +/** The window shortcut a key press triggers, if any. */ +export function windowShortcutFor(press: KeyPress, rows: ShortcutRow[], bindings: Bindings): string | null { + const chord = chordOf(press) + if (chord === null) { + return null + } + return rows.filter((row) => GROUP_SCOPES[row.group].windowWide).find((row) => chordsOf(row.id, bindings).includes(chord))?.id ?? null +} + +/** The node editor shortcut a key press triggers, if any. */ +export function nodeEditorActionFor(press: KeyPress, bindings: Bindings): NodeEditorAction | null { + return NODE_EDITOR_ACTIONS.find((action) => matches(press, action, bindings)) ?? null +} + +/** The other shortcuts the chord already triggers where {@code row} works too. */ +export function clashesWith(row: ShortcutRow, chord: Chord, rows: ShortcutRow[], bindings: Bindings): ShortcutRow[] { + return rows.filter((other) => other.id !== row.id && sharesKeys(row.group, other.group) && chordsOf(other.id, bindings).includes(chord)) +} + +/** The bindings a settings file holds, without what is not a list of chords. */ +export function sanitizeBindings(stored: unknown): Bindings { + if (typeof stored !== 'object' || stored === null || Array.isArray(stored)) { + return {} + } + const bindings: Bindings = {} + for (const [id, chords] of Object.entries(stored)) { + if (Array.isArray(chords) && chords.every(isChord)) { + bindings[id] = [...new Set(chords)] + } + } + return bindings +} + +/** Whether a key press goes to a field being typed into, so the studio's keys leave it alone. */ +export function isTypingInto(target: EventTarget | null): boolean { + return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement +} + +/** Whether a key press goes to the list of a view's entries, where Delete is for the entry and not the chosen node. */ +export function isInEntryBrowser(target: EventTarget | null): boolean { + return target instanceof Element && target.closest('[data-entry-browser]') !== null +} + +function sharesKeys(first: ShortcutGroup, second: ShortcutGroup): boolean { + const a = GROUP_SCOPES[first] + const b = GROUP_SCOPES[second] + return (a.windowWide && b.windowWide) || (a.nodeEditor && b.nodeEditor) +} + +function splitChord(chord: Chord): { modifiers: string[]; key: string } | null { + let key = chord + const modifiers: string[] = [] + for (const prefix of MODIFIER_PREFIXES) { + if (key.startsWith(prefix) && key.length > prefix.length) { + modifiers.push(prefix) + key = key.slice(prefix.length) + } + } + return key === '' ? null : { modifiers, key } +} + +function keyName(key: string): string { + if (KEY_NAMES[key] !== undefined) { + return KEY_NAMES[key] + } + if (key.length === 1) { + return key.toUpperCase() + } + return key.startsWith(ARROW_PREFIX) ? key.slice(ARROW_PREFIX.length) : key +} diff --git a/studio/src/renderer/src/studio/theme.ts b/studio/src/renderer/src/studio/theme.ts new file mode 100644 index 000000000..2302a2cca --- /dev/null +++ b/studio/src/renderer/src/studio/theme.ts @@ -0,0 +1,33 @@ +import { useEffect, useState } from 'react' +import type { ThemeChoice } from '../../../shared/bridge' + +const STORAGE_KEY = 'iris-studio.theme' +const DARK_QUERY = '(prefers-color-scheme: dark)' +const ORDER: ThemeChoice[] = ['system', 'light', 'dark'] + +function storedChoice(): ThemeChoice { + const stored = localStorage.getItem(STORAGE_KEY) + return stored === 'light' || stored === 'dark' ? stored : 'system' +} + +function apply(choice: ThemeChoice): void { + const dark = choice === 'dark' || (choice === 'system' && matchMedia(DARK_QUERY).matches) + document.documentElement.classList.toggle('dark', dark) +} + +/** The light or dark look, following the system unless chosen; the choice outlives the window. */ +export function useTheme(): { choice: ThemeChoice; next: () => void } { + const [choice, setChoice] = useState(storedChoice) + + useEffect(() => { + apply(choice) + window.studio.setTheme(choice) + localStorage.setItem(STORAGE_KEY, choice) + const media = matchMedia(DARK_QUERY) + const follow = (): void => apply(choice) + media.addEventListener('change', follow) + return () => media.removeEventListener('change', follow) + }, [choice]) + + return { choice, next: () => setChoice(ORDER[(ORDER.indexOf(choice) + 1) % ORDER.length]) } +} diff --git a/studio/src/renderer/src/studio/useBindings.ts b/studio/src/renderer/src/studio/useBindings.ts new file mode 100644 index 000000000..4d9a6d6d6 --- /dev/null +++ b/studio/src/renderer/src/studio/useBindings.ts @@ -0,0 +1,19 @@ +import { useCallback, useSyncExternalStore } from 'react' +import { createShortcutStore } from './shortcutStore' +import { keyTextOf, type Bindings } from './shortcuts' + +export const shortcutStore = createShortcutStore({ + load: () => window.studio.loadShortcuts(), + save: (bindings) => window.studio.saveShortcuts(bindings) +}) + +/** The keys the user rebound; components read them through here so a rebound key shows and works at once. */ +export function useBindings(): Bindings { + return useSyncExternalStore(shortcutStore.subscribe, shortcutStore.snapshot) +} + +/** The first key of a shortcut as shown beside it, empty when it has none. */ +export function useKeyText(): (id: string) => string { + const bindings = useBindings() + return useCallback((id) => keyTextOf(id, bindings), [bindings]) +} diff --git a/studio/src/renderer/src/studio/usePickInspection.ts b/studio/src/renderer/src/studio/usePickInspection.ts new file mode 100644 index 000000000..b9a4b5744 --- /dev/null +++ b/studio/src/renderer/src/studio/usePickInspection.ts @@ -0,0 +1,38 @@ +import { useEffect, useState } from 'react' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' +import type { PickInspection } from '../bridge/types' + +// Measuring the picks in view samples thousands of spots, so it waits for the view to rest. +const INSPECTION_REST_MILLIS = 350 + +/** + * Measures how the noise picks what the view shows, once the view has rested on an area for a moment; the last + * measurement stays up until the next one arrives, so panning does not blank the panel. + */ +export function usePickInspection( + client: BridgeClient, + layer: MapLayerQuery, + area: WorldRect | null, + enabled: boolean, + packRevision: number +): PickInspection | null { + const [inspection, setInspection] = useState(null) + useEffect(() => setInspection(null), [layer, packRevision]) + useEffect(() => { + if (!enabled || area === null) { + return + } + const stop = new AbortController() + const timer = window.setTimeout(() => { + client + .picks(layer, area, stop.signal) + .then(setInspection) + .catch(() => undefined) + }, INSPECTION_REST_MILLIS) + return () => { + window.clearTimeout(timer) + stop.abort() + } + }, [client, layer, area, enabled, packRevision]) + return inspection +} diff --git a/studio/src/renderer/src/studio/useSpotActions.tsx b/studio/src/renderer/src/studio/useSpotActions.tsx new file mode 100644 index 000000000..f51105d6a --- /dev/null +++ b/studio/src/renderer/src/studio/useSpotActions.tsx @@ -0,0 +1,46 @@ +import { useMemo } from 'react' +import type { Vector3 } from 'three' +import { ContextMenuItem, ContextMenuSeparator } from '@/components/ui/context-menu' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { SpotActions } from './SceneViewport' + +/** + * What a spot of terrain in 3D offers, as a spot on the map does: teleporting there and copying where it is. + * + * @param inStudioWorld whether the terrain is the studio's own world, the only one the server teleports into + */ +export function useSpotActions(client: BridgeClient, tell: (message: string) => void, inStudioWorld: boolean): SpotActions { + return useMemo(() => { + const teleportTo = (spot: Vector3): void => { + const [blockX, blockZ] = [Math.floor(spot.x), Math.floor(spot.z)] + client + .teleport(blockX, blockZ) + .then(() => tell(`Teleporting to ${blockX}, ${blockZ}`)) + .catch((failure: Error) => tell(failure.message)) + } + const copy = (spot: Vector3): void => { + const coordinates = coordinatesOf(spot) + window.studio.copyText(coordinates) + tell(`Copied ${coordinates}`) + } + return { + onCtrlClick: (spot) => inStudioWorld && teleportTo(spot), + menuItems: (spot) => ( + <> + {inStudioWorld && ( + <> + teleportTo(spot)}>Teleport here + + + )} + copy(spot)}>Copy coordinates ({coordinatesOf(spot)}) + + ) + } + }, [client, tell, inStudioWorld]) +} + +// A top face stands where a player's feet do, so its height is the Y to stand at. +function coordinatesOf(spot: Vector3): string { + return `${Math.floor(spot.x)}, ${Math.round(spot.y)}, ${Math.floor(spot.z)}` +} diff --git a/studio/src/renderer/src/studio/useTerrainStream.ts b/studio/src/renderer/src/studio/useTerrainStream.ts new file mode 100644 index 000000000..6a33911d8 --- /dev/null +++ b/studio/src/renderer/src/studio/useTerrainStream.ts @@ -0,0 +1,91 @@ +import { useEffect, useRef, useState } from 'react' +import type { Box3 } from 'three' +import type { TileSource } from '../map/TileStore' +import type { GroundInView } from '../scene/groundInView' +import { TerrainStream, type TerrainStyle } from '../scene/terrainStream' +import type { ViewportContent } from './SceneViewport' + +/** + * Endless terrain around {@code focus} for a viewport: the tiles of {@code layer} drawn in {@code style}, where the + * camera looks. A new layer keeps the ground drawn until its tiles arrive; a new source or focus starts again. Where + * {@code quickLayerOf} gives a quicker layer, its tiles stand in until the layer's own arrive. + * + * @return what to show, or null before there is any, and how many tiles are still on their way + */ +export function useTerrainStream( + source: TileSource, + coarsestLevel: number, + focus: Box3, + layer: Layer | null, + style: TerrainStyle | null, + tell: (message: string) => void, + quickLayerOf?: (layer: Layer) => Layer | null +): { content: ViewportContent | null; pending: number; stream: TerrainStream | null } { + const [stream, setStream] = useState | null>(null) + const [pending, setPending] = useState(0) + const latestTell = useRef(tell) + latestTell.current = tell + + useEffect(() => { + const created = new TerrainStream({ source, coarsestLevel, focus, quickLayerOf, onPending: setPending, onError: (message) => latestTell.current(message) }) + setStream(created) + return () => { + created.dispose() + setStream(null) + setPending(0) + } + }, [source, coarsestLevel, focus, quickLayerOf]) + useEffect(() => { + if (layer !== null) { + stream?.showLayer(layer) + } + }, [stream, layer]) + useEffect(() => { + if (style !== null) { + stream?.restyle(style) + } + }, [stream, style]) + + return { content: stream?.content ?? null, pending, stream } +} + +// Moving the camera a little samples a tile or two, which is over before it is worth a word. +const WORTH_TELLING_MILLIS = 700 + +/** Whether tiles have been on their way for long enough to say so. */ +export function useLongPending(pending: number): boolean { + const waiting = pending > 0 + const [long, setLong] = useState(false) + useEffect(() => { + if (!waiting) { + setLong(false) + return + } + const timer = window.setTimeout(() => setLong(true), WORTH_TELLING_MILLIS) + return () => window.clearTimeout(timer) + }, [waiting]) + return long +} + +// The camera drifts and tiles arrive in bursts; the ground it sees is read once they have rested this long. +const GROUND_REST_MILLIS = 250 + +/** The ground the camera of a stream looks at, read once the view has rested; the last reading stays until the next one. */ +export function useGroundInView(stream: TerrainStream | null): GroundInView | null { + const [ground, setGround] = useState(null) + useEffect(() => { + if (stream === null) { + return + } + let timer: number | undefined + const stopWatching = stream.onSightChanged(() => { + window.clearTimeout(timer) + timer = window.setTimeout(() => setGround(stream.groundInView()), GROUND_REST_MILLIS) + }) + return () => { + stopWatching() + window.clearTimeout(timer) + } + }, [stream]) + return ground +} diff --git a/studio/src/renderer/src/studio/useWorldCaves.ts b/studio/src/renderer/src/studio/useWorldCaves.ts new file mode 100644 index 000000000..bb7833e5b --- /dev/null +++ b/studio/src/renderer/src/studio/useWorldCaves.ts @@ -0,0 +1,92 @@ +import { useEffect, useMemo, useState } from 'react' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { Share } from '../map/census' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' +import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' + +/** Where the caves of the world are shown: a square of blocks around a spot. */ +export interface CaveArea { + centerX: number + centerZ: number + size: number +} + +export interface WorldCaves { + scene: BlockScene | null + mesh: SceneMesh | null + /** What the server is doing while the caves are on their way, or null once they are in. */ + status: string | null +} + +/** + * The colour of each band of heights the caves are drawn in, from the highest down, as the server colours them + * (Iris core CaveSpace). + */ +const CAVE_BANDS: readonly { block: string; name: string; color: number }[] = [ + { block: 'minecraft:yellow_concrete', name: 'Y 64 and up', color: 0xf1af15 }, + { block: 'minecraft:orange_concrete', name: 'Y 32 to 63', color: 0xe06101 }, + { block: 'minecraft:red_concrete', name: 'Y 0 to 31', color: 0x8e2121 }, + { block: 'minecraft:magenta_concrete', name: 'Y −32 to −1', color: 0xa9309f }, + { block: 'minecraft:purple_concrete', name: 'Y −64 to −33', color: 0x64209c }, + { block: 'minecraft:blue_concrete', name: 'Below Y −64', color: 0x2c2e8f } +] + +/** How much of the caves' outside lies in each band of heights, highest first; bands without caves are left out. */ +export function caveBandShares(scene: BlockScene): Share[] { + const counts = new Map() + for (let offset = 3; offset < scene.blocks.length; offset += INTS_PER_BLOCK) { + const paletteIndex = scene.blocks[offset] + counts.set(paletteIndex, (counts.get(paletteIndex) ?? 0) + 1) + } + const blocks = scene.blocks.length / INTS_PER_BLOCK + return CAVE_BANDS.flatMap((band) => { + const count = counts.get(scene.palette.indexOf(band.block)) ?? 0 + return count === 0 ? [] : [{ subject: { kind: 'HEIGHT' as const, key: band.block, name: band.name }, color: band.color, fraction: count / blocks }] + }) +} + +/** + * The caves of the world's generated chunks in {@code area}, asked for again when it or the pack changes; null asks + * for none. A newer area abandons an older one, on the server too, and a replaced mesh is freed. + */ +export function useWorldCaves(client: BridgeClient, area: CaveArea | null, packRevision: number, tell: (message: string) => void): WorldCaves { + const [waiting, setWaiting] = useState(null) + const images = useMemo(() => new BridgeAssets(client, setWaiting), [client]) + const models = useMemo(() => new BlockModels(images), [images]) + const [shown, setShown] = useState<{ scene: BlockScene; mesh: SceneMesh } | null>(null) + const [building, setBuilding] = useState(false) + const centerX = area?.centerX + const centerZ = area?.centerZ + const size = area?.size + + useEffect(() => { + if (centerX === undefined || centerZ === undefined || size === undefined) { + return + } + const stop = new AbortController() + setBuilding(true) + client + .caves(centerX, centerZ, size, stop.signal) + .then((scene) => buildSceneMesh(scene, models, images).then((mesh) => ({ scene, mesh }))) + .then((built) => { + if (stop.signal.aborted) { + built.mesh.dispose() + return + } + setShown(built) + }) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + .finally(() => !stop.signal.aborted && setBuilding(false)) + return () => stop.abort() + }, [client, centerX, centerZ, size, packRevision, models, images, tell]) + + useEffect(() => () => shown?.mesh.dispose(), [shown]) + + return { + scene: shown?.scene ?? null, + mesh: shown?.mesh ?? null, + status: building ? (waiting ?? `Generating the caves of ${size} × ${size} blocks`) : null + } +} diff --git a/studio/src/renderer/src/styles.css b/studio/src/renderer/src/styles.css new file mode 100644 index 000000000..219763905 --- /dev/null +++ b/studio/src/renderer/src/styles.css @@ -0,0 +1,118 @@ +@import "tailwindcss"; + +@custom-variant dark (&:is(.dark *)); + +/* The studio's colours, taken from the Swing studio (StudioTheme) so both look alike. */ +:root { + --background: #dfe2e8; + --foreground: #000000; + --card: #f7f8fa; + --card-foreground: #000000; + --popover: #ffffff; + --popover-foreground: #000000; + --primary: #3574f0; + --primary-foreground: #ffffff; + --secondary: #dfe1e5; + --secondary-foreground: #000000; + --muted: #f7f8fa; + --muted-foreground: #818594; + --secondary-text: #6c707e; + --accent: #dfe1e5; + --accent-foreground: #000000; + --selection: #d3d5db; + --destructive: #db3b4b; + --warning: #c27d04; + --success: #208a3c; + --link: #315fbd; + --border: #ebecf0; + --input: #c9ccd6; + --ring: #3574f0; + --overlay-border: #dfe1e5; + --map-background: #eceef2; + --radius: 10px; +} + +.dark { + --background: #1e1f22; + --foreground: #dfe1e5; + --card: #2b2d30; + --card-foreground: #dfe1e5; + --popover: #2b2d30; + --popover-foreground: #dfe1e5; + --primary: #3574f0; + --primary-foreground: #ffffff; + --secondary: #393b40; + --secondary-foreground: #dfe1e5; + --muted: #2b2d30; + --muted-foreground: #868a91; + --secondary-text: #9da0a8; + --accent: #393b40; + --accent-foreground: #dfe1e5; + --selection: #43454a; + --destructive: #f75464; + --warning: #f2c55c; + --success: #5fb865; + --link: #548af7; + --border: #393b40; + --input: #4e5157; + --ring: #3574f0; + --overlay-border: #43454a; + --map-background: #25272a; +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-secondary-text: var(--secondary-text); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-selection: var(--selection); + --color-destructive: var(--destructive); + --color-warning: var(--warning); + --color-success: var(--success); + --color-link: var(--link); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-overlay-border: var(--overlay-border); + --color-map-background: var(--map-background); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); + --font-sans: "Inter", "Segoe UI", system-ui, sans-serif; + --font-mono: "JetBrains Mono", ui-monospace, monospace; +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + + html, + body, + #root { + @apply h-full overflow-hidden; + } + + body { + @apply bg-background text-foreground text-[13px] antialiased select-none; + } +} + +/* The window around the islands: its colour, tinted with the accent from the top left corner as IntelliJ's islands theme does. */ +.window-frame { + background: + radial-gradient(ellipse 55% 45% at 0% 0%, color-mix(in srgb, var(--primary) 16%, transparent), transparent), + var(--background); +} diff --git a/studio/src/shared/bridge.ts b/studio/src/shared/bridge.ts new file mode 100644 index 000000000..31448d371 --- /dev/null +++ b/studio/src/shared/bridge.ts @@ -0,0 +1,52 @@ +/** A bridge a running Iris server opened, as its connection file or a studio link describes it. */ +export interface BridgeConnection { + world: string + port: number + token: string + startedMillis?: number +} + +/** The keys the user rebound, by shortcut id, each a list of key chords. */ +export type StoredShortcuts = Record + +export type ThemeChoice = 'system' | 'light' | 'dark' + +export interface GraphicsInfo { + /** Whether this machine has an NVIDIA GPU the studio can be asked to draw on. */ + canUseDedicatedGpu: boolean + usesDedicatedGpu: boolean +} + +/** What the preload script hands the renderer. */ +export interface StudioHost { + listBridges(): Promise + /** The studio link the app was started with, if any. */ + initialLink(): Promise + onLink(listener: (link: string) => void): () => void + setTheme(theme: ThemeChoice): void + copyText(text: string): void + /** The rebound shortcuts from the studio settings, as the file holds them, for the caller to check. */ + loadShortcuts(): Promise + saveShortcuts(shortcuts: StoredShortcuts): void + graphics(): Promise + /** Saves the choice and restarts the studio, which only picks its GPU when it starts. */ + useDedicatedGpu(dedicated: boolean): void +} + +const LINK_PROTOCOL = 'iris-studio:' + +/** The bridge a link such as {@code iris-studio://127.0.0.1:44503/?token=...} names; null for anything else. */ +export function parseStudioLink(text: string): BridgeConnection | null { + let url: URL + try { + url = new URL(text.trim()) + } catch { + return null + } + const port = Number(url.port) + const token = url.searchParams.get('token') + if (url.protocol !== LINK_PROTOCOL || !Number.isInteger(port) || port <= 0 || !token) { + return null + } + return { world: url.searchParams.get('world') ?? '', port, token } +} diff --git a/studio/tsconfig.json b/studio/tsconfig.json new file mode 100644 index 000000000..434c40bb5 --- /dev/null +++ b/studio/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "isolatedModules": true, + "resolveJsonModule": true, + "types": ["node"], + "paths": { "@/*": ["./src/renderer/src/*"] } + }, + "include": ["src", "electron.vite.config.ts"] +}