From 7f218e77f354c2f817b1f096949629dddc507040 Mon Sep 17 00:00:00 2001 From: Mark7625 <72366279+Mark7625@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:20:34 +0000 Subject: [PATCH 1/5] RLHD Editor RLHD Editor --- .gitmodules | 3 +- AGENTS.md | 39 + Tools/Dev/build.gradle | 45 + Tools/Dev/java/rs117/hd/DeveloperConfig.java | 12 + Tools/Dev/java/rs117/hd/DeveloperPlugin.java | 39 +- .../hd/dev/definitions/DefinitionsScreen.java | 1359 +++++++++++ .../hd/dev/definitions/WaterPreview.java | 141 ++ .../hd/dev/editor/BeforeAfterSwatch.java | 72 + .../java/rs117/hd/dev/editor/CacheModels.java | 238 ++ .../java/rs117/hd/dev/editor/ColorPicker.java | 329 +++ .../rs117/hd/dev/editor/DashedAddButton.java | 26 + .../rs117/hd/dev/editor/EditorButton.java | 105 + .../hd/dev/editor/EditorButtonGroup.java | 84 + .../java/rs117/hd/dev/editor/EditorModal.java | 141 ++ .../rs117/hd/dev/editor/EditorPanels.java | 26 + .../java/rs117/hd/dev/editor/EditorPopup.java | 102 + .../rs117/hd/dev/editor/EditorScrollPane.java | 75 + .../rs117/hd/dev/editor/EditorSearch.java | 79 + .../rs117/hd/dev/editor/EditorSection.java | 106 + .../rs117/hd/dev/editor/EditorSelect.java | 92 + .../rs117/hd/dev/editor/EditorSession.java | 165 ++ .../java/rs117/hd/dev/editor/EditorShell.java | 141 ++ .../rs117/hd/dev/editor/EditorSplash.java | 266 +++ .../java/rs117/hd/dev/editor/EditorText.java | 41 + .../rs117/hd/dev/editor/EditorToolRail.java | 43 + .../rs117/hd/dev/editor/EditorWindow.java | 80 + .../hd/dev/editor/FloatingDockWindow.java | 428 ++++ .../rs117/hd/dev/editor/HdContextMenu.java | 236 ++ .../java/rs117/hd/dev/editor/NumberField.java | 327 +++ .../java/rs117/hd/dev/editor/PopupLayer.java | 221 ++ .../rs117/hd/dev/editor/PreviewDropdown.java | 447 ++++ .../java/rs117/hd/dev/editor/PropertyRow.java | 78 + .../rs117/hd/dev/editor/PropertySection.java | 226 ++ .../hd/dev/editor/SearchableIdDropdown.java | 167 ++ .../rs117/hd/dev/editor/SegmentedControl.java | 168 ++ .../rs117/hd/dev/editor/SelectionModal.java | 371 +++ .../rs117/hd/dev/editor/SwatchDropdown.java | 417 ++++ .../java/rs117/hd/dev/editor/SwatchStrip.java | 24 + .../java/rs117/hd/dev/editor/ToggleList.java | 198 ++ .../rs117/hd/dev/editor/ToggleSwitch.java | 150 ++ .../rs117/hd/dev/editor/UvTypeDropdown.java | 158 ++ .../rs117/hd/dev/editor/WorkspaceActions.java | 562 +++++ .../rs117/hd/dev/editor/WorkspaceDocks.java | 342 +++ .../rs117/hd/dev/editor/WorkspaceHistory.java | 58 + .../rs117/hd/dev/editor/WorkspaceMenu.java | 87 + .../rs117/hd/dev/editor/WorkspaceStyle.java | 319 +++ .../rs117/hd/dev/overrides/AreaListField.java | 241 ++ .../hd/dev/overrides/ColorExpression.java | 88 + .../dev/overrides/ColorExpressionPanel.java | 313 +++ .../hd/dev/overrides/MaterialThumbnails.java | 198 ++ .../hd/dev/overrides/ModelColorPalette.java | 48 + .../dev/overrides/ModelOverrideDocument.java | 463 ++++ .../hd/dev/overrides/ModelOverrideFields.java | 79 + .../dev/overrides/ModelOverridesScreen.java | 2024 +++++++++++++++++ .../dev/overrides/OverridePreviewSurface.java | 218 ++ .../hd/dev/overrides/OverrideProperties.java | 1986 ++++++++++++++++ .../hd/dev/overrides/PreviewDiagnostics.java | 63 + .../hd/dev/overrides/PreviewFacePicker.java | 131 ++ .../rs117/hd/dev/overrides/PreviewGrid.java | 102 + .../hd/dev/overrides/WindModeDropdown.java | 201 ++ .../rs117/hd/dev/overrides/WindPreview.java | 87 + .../rs117/hd/dev/overrides/WindStrength.java | 146 ++ .../rs117/hd/dev/sceneloader/FreeCamera.java | 445 ++++ .../hd/dev/sceneloader/ModelPreview.java | 236 ++ .../rs117/hd/dev/sceneloader/SceneLoader.java | 874 +++++++ .../hd/dev/sceneloader/SceneLoaderPanel.java | 863 +++++++ .../sceneloader/devtools/CameraOverlay.java | 92 + .../sceneloader/devtools/DevToolBridge.java | 236 ++ .../sceneloader/devtools/LocationOverlay.java | 114 + .../devtools/SceneToolsOverlay.java | 284 +++ .../devtools/SelectionHighlight.java | 120 + .../hd/dev/sceneloader/map/MapControls.java | 218 ++ .../rs117/hd/dev/sceneloader/map/MapHost.java | 248 ++ .../hd/dev/sceneloader/map/MapProjection.java | 72 + .../hd/dev/sceneloader/map/MapTileCache.java | 240 ++ .../dev/sceneloader/map/RegionMapPanel.java | 487 ++++ .../dev/sceneloader/scene/BuiltAnimation.java | 86 + .../scene/BuiltDecorativeObject.java | 69 + .../sceneloader/scene/BuiltDynamicObject.java | 225 ++ .../sceneloader/scene/BuiltGameObject.java | 66 + .../sceneloader/scene/BuiltGroundObject.java | 24 + .../hd/dev/sceneloader/scene/BuiltModel.java | 465 ++++ .../hd/dev/sceneloader/scene/BuiltScene.java | 359 +++ .../hd/dev/sceneloader/scene/BuiltTile.java | 186 ++ .../dev/sceneloader/scene/BuiltTileModel.java | 370 +++ .../sceneloader/scene/BuiltTileObject.java | 158 ++ .../dev/sceneloader/scene/BuiltTilePaint.java | 112 + .../sceneloader/scene/BuiltWallObject.java | 48 + .../hd/dev/sceneloader/scene/Definitions.java | 445 ++++ .../hd/dev/sceneloader/scene/HslPalette.java | 70 + .../hd/dev/sceneloader/scene/ModelBounds.java | 45 + .../dev/sceneloader/scene/ModelFactory.java | 874 +++++++ .../dev/sceneloader/scene/NormalMerger.java | 322 +++ .../dev/sceneloader/scene/ObjectPlacer.java | 656 ++++++ .../dev/sceneloader/scene/SceneBuilder.java | 974 ++++++++ .../dev/sceneloader/scene/VariantObject.java | 77 + .../dev/sceneloader/scene/VariantOptions.java | 106 + .../dev/sceneloader/standalone/FlyCamera.java | 236 ++ .../dev/sceneloader/standalone/HdRuntime.java | 639 ++++++ .../sceneloader/standalone/HdSettings.java | 104 + .../standalone/InlineClientThread.java | 106 + .../standalone/PreviewZoneAccess.java | 72 + .../dev/sceneloader/standalone/Textures.java | 95 + .../client/CacheTextureProvider.java | 97 + .../sceneloader/standalone/client/Fake.java | 137 ++ .../standalone/client/FakeClient.java | 301 +++ .../standalone/client/FakeObjects.java | 83 + .../standalone/client/FakeWorldView.java | 60 + .../standalone/headless/HdBenchmark.java | 457 ++++ .../standalone/ui/HdConfigPanel.java | 370 +++ .../sceneloader/standalone/ui/HdPreview.java | 640 ++++++ .../java/rs117/hd/model/ModelExporter.java | 41 +- .../java/rs117/hd/model/ModelImporter.java | 27 +- .../rs117/hd/model/SceneTerrainExporter.java | 26 +- .../rs117/hd/dev/editor/117hd-wordmark.png | Bin 0 -> 83488 bytes .../dev/editor/cursors/cursor-box-select.png | Bin 0 -> 1007 bytes .../dev/editor/cursors/cursor-box-select.svg | 1 + .../hd/dev/editor/cursors/cursor-grab.png | Bin 0 -> 1097 bytes .../hd/dev/editor/cursors/cursor-grab.svg | 1 + .../hd/dev/editor/cursors/cursor-orbit.png | Bin 0 -> 926 bytes .../hd/dev/editor/cursors/cursor-orbit.svg | 1 + .../hd/dev/editor/cursors/cursor-pan.png | Bin 0 -> 1162 bytes .../hd/dev/editor/cursors/cursor-pan.svg | 1 + .../dev/editor/cursors/cursor-pick-face.png | Bin 0 -> 884 bytes .../dev/editor/cursors/cursor-pick-face.svg | 1 + .../dev/editor/cursors/cursor-pick-vertex.png | Bin 0 -> 702 bytes .../dev/editor/cursors/cursor-pick-vertex.svg | 1 + .../dev/editor/cursors/cursor-place-light.png | Bin 0 -> 1031 bytes .../dev/editor/cursors/cursor-place-light.svg | 1 + .../editor/cursors/cursor-remove-light.png | Bin 0 -> 1060 bytes .../editor/cursors/cursor-remove-light.svg | 1 + .../hd/dev/editor/cursors/cursor-scrub.png | Bin 0 -> 739 bytes .../hd/dev/editor/cursors/cursor-scrub.svg | 1 + .../rs117/hd/dev/editor/cursors/hotspots.json | 38 + .../hd/dev/editor/fonts/ibmplexsans-400.ttf | Bin 0 -> 218056 bytes .../hd/dev/editor/fonts/ibmplexsans-500.ttf | Bin 0 -> 218256 bytes .../hd/dev/editor/fonts/ibmplexsans-600.ttf | Bin 0 -> 218192 bytes .../hd/dev/editor/fonts/ibmplexsans-OFL.txt | 93 + .../rs117/hd/dev/editor/fonts/ibmplexsans.ttf | Bin 0 -> 537244 bytes .../hd/dev/editor/fonts/jetbrainsmono-400.ttf | Bin 0 -> 115152 bytes .../hd/dev/editor/fonts/jetbrainsmono-600.ttf | Bin 0 -> 115060 bytes .../hd/dev/editor/fonts/jetbrainsmono-OFL.txt | 93 + .../hd/dev/editor/fonts/jetbrainsmono.ttf | Bin 0 -> 187208 bytes .../rs117/hd/dev/editor/icons/117hd-logo.png | Bin 0 -> 32447 bytes .../hd/dev/editor/icons/LICENSE-lucide.txt | 43 + .../rs117/hd/dev/editor/icons/box.png | Bin 0 -> 573 bytes .../rs117/hd/dev/editor/icons/check.svg | 1 + .../hd/dev/editor/icons/chevron-down.svg | 1 + .../hd/dev/editor/icons/chevron-left.svg | 1 + .../hd/dev/editor/icons/chevron-right.svg | 1 + .../rs117/hd/dev/editor/icons/chevron-up.svg | 1 + .../rs117/hd/dev/editor/icons/close.svg | 1 + .../hd/dev/editor/icons/context/copy.svg | 1 + .../hd/dev/editor/icons/context/duplicate.svg | 1 + .../dev/editor/icons/context/eyedropper.svg | 1 + .../hd/dev/editor/icons/context/faces.svg | 1 + .../hd/dev/editor/icons/context/find.svg | 1 + .../hd/dev/editor/icons/context/json.svg | 1 + .../rs117/hd/dev/editor/icons/context/key.svg | 1 + .../hd/dev/editor/icons/context/layers.svg | 1 + .../hd/dev/editor/icons/context/light.svg | 1 + .../hd/dev/editor/icons/context/load.svg | 1 + .../hd/dev/editor/icons/context/material.svg | 1 + .../dev/editor/icons/context/place-centre.svg | 1 + .../hd/dev/editor/icons/context/plus.svg | 1 + .../hd/dev/editor/icons/context/rename.svg | 1 + .../hd/dev/editor/icons/context/reset.svg | 1 + .../rs117/hd/dev/editor/icons/context/tag.svg | 1 + .../hd/dev/editor/icons/context/trash.svg | 1 + .../rs117/hd/dev/editor/icons/copy.svg | 1 + .../dev/editor/icons/dock-menu-floating.svg | 1 + .../rs117/hd/dev/editor/icons/dock-menu.svg | 1 + .../hd/dev/editor/icons/dock-swap-panel.svg | 1 + .../rs117/hd/dev/editor/icons/dot.png | Bin 0 -> 153 bytes .../rs117/hd/dev/editor/icons/draft-save.svg | 1 + .../rs117/hd/dev/editor/icons/duplicate.svg | 1 + .../hd/dev/editor/icons/editor-icon-128.png | Bin 0 -> 14910 bytes .../hd/dev/editor/icons/editor-icon-16.png | Bin 0 -> 755 bytes .../hd/dev/editor/icons/editor-icon-24.png | Bin 0 -> 1568 bytes .../hd/dev/editor/icons/editor-icon-256.png | Bin 0 -> 39259 bytes .../hd/dev/editor/icons/editor-icon-32.png | Bin 0 -> 2247 bytes .../hd/dev/editor/icons/editor-icon-48.png | Bin 0 -> 4020 bytes .../hd/dev/editor/icons/editor-icon-512.png | Bin 0 -> 115371 bytes .../hd/dev/editor/icons/editor-icon-64.png | Bin 0 -> 5730 bytes .../rs117/hd/dev/editor/icons/editor-icon.ico | Bin 0 -> 68607 bytes .../rs117/hd/dev/editor/icons/entity.svg | 1 + .../rs117/hd/dev/editor/icons/eraser.png | Bin 0 -> 405 bytes .../hd/dev/editor/icons/expand-single.svg | 1 + .../rs117/hd/dev/editor/icons/eye-off.svg | 1 + .../rs117/hd/dev/editor/icons/eye.svg | 1 + .../rs117/hd/dev/editor/icons/eyedropper.svg | 3 + .../hd/dev/editor/icons/find-in-world.svg | 1 + .../hd/dev/editor/icons/float-window.svg | 1 + .../rs117/hd/dev/editor/icons/frame-all.svg | 1 + .../rs117/hd/dev/editor/icons/grid.png | Bin 0 -> 410 bytes .../rs117/hd/dev/editor/icons/grip.png | Bin 0 -> 496 bytes .../rs117/hd/dev/editor/icons/grip.svg | 1 + .../hd/dev/editor/icons/ground-layers.svg | 3 + .../dev/editor/icons/handoff-chevron-down.png | Bin 0 -> 150 bytes .../dev/editor/icons/handoff-chevron-left.png | Bin 0 -> 142 bytes .../editor/icons/handoff-chevron-right.png | Bin 0 -> 142 bytes .../hd/dev/editor/icons/handoff-close.png | Bin 0 -> 171 bytes .../hd/dev/editor/icons/handoff-copy.png | Bin 0 -> 205 bytes .../hd/dev/editor/icons/handoff-entity.png | Bin 0 -> 431 bytes .../hd/dev/editor/icons/handoff-eye-off.png | Bin 0 -> 318 bytes .../rs117/hd/dev/editor/icons/handoff-eye.png | Bin 0 -> 249 bytes .../hd/dev/editor/icons/handoff-frame-all.png | Bin 0 -> 388 bytes .../hd/dev/editor/icons/handoff-grip.png | Bin 0 -> 153 bytes .../editor/icons/handoff-layout-single.png | Bin 0 -> 197 bytes .../dev/editor/icons/handoff-layout-split.png | Bin 0 -> 215 bytes .../editor/icons/handoff-layout-together.png | Bin 0 -> 301 bytes .../hd/dev/editor/icons/handoff-light.png | Bin 0 -> 431 bytes .../hd/dev/editor/icons/handoff-model.png | Bin 0 -> 362 bytes .../editor/icons/handoff-open-external.png | Bin 0 -> 179 bytes .../editor/icons/handoff-panel-browser.png | Bin 0 -> 227 bytes .../hd/dev/editor/icons/handoff-particles.png | Bin 0 -> 214 bytes .../hd/dev/editor/icons/handoff-pick-face.png | Bin 0 -> 267 bytes .../dev/editor/icons/handoff-pick-vertex.png | Bin 0 -> 380 bytes .../hd/dev/editor/icons/handoff-plus.png | Bin 0 -> 161 bytes .../hd/dev/editor/icons/handoff-refresh.png | Bin 0 -> 405 bytes .../hd/dev/editor/icons/handoff-save.png | Bin 0 -> 389 bytes .../hd/dev/editor/icons/handoff-search.png | Bin 0 -> 329 bytes .../hd/dev/editor/icons/handoff-shading.png | Bin 0 -> 388 bytes .../editor/icons/handoff-tool-place-light.png | Bin 0 -> 428 bytes .../icons/handoff-tool-remove-light.png | Bin 0 -> 446 bytes .../dev/editor/icons/handoff-tool-select.png | Bin 0 -> 377 bytes .../hd/dev/editor/icons/handoff-trash.png | Bin 0 -> 224 bytes .../dev/editor/icons/handoff-view-camera.png | Bin 0 -> 263 bytes .../rs117/hd/dev/editor/icons/history.svg | 1 + .../hd/dev/editor/icons/in-game-toggle.svg | 1 + .../rs117/hd/dev/editor/icons/isolate.svg | 1 + .../rs117/hd/dev/editor/icons/keyboard.svg | 1 + .../rs117/hd/dev/editor/icons/layers.png | Bin 0 -> 635 bytes .../hd/dev/editor/icons/layout-single.svg | 1 + .../hd/dev/editor/icons/layout-split.svg | 1 + .../hd/dev/editor/icons/layout-together.svg | 1 + .../rs117/hd/dev/editor/icons/light.svg | 1 + .../rs117/hd/dev/editor/icons/lightbulb.png | Bin 0 -> 452 bytes .../rs117/hd/dev/editor/icons/list-tree.png | Bin 0 -> 317 bytes .../rs117/hd/dev/editor/icons/minus.svg | 3 + .../rs117/hd/dev/editor/icons/mirror.svg | 1 + .../rs117/hd/dev/editor/icons/model.svg | 1 + .../hd/dev/editor/icons/mouse-pointer-2.png | Bin 0 -> 462 bytes .../hd/dev/editor/icons/open-external.svg | 1 + .../hd/dev/editor/icons/override-cube.svg | 3 + .../rs117/hd/dev/editor/icons/palette.png | Bin 0 -> 643 bytes .../hd/dev/editor/icons/panel-browser.svg | 1 + .../rs117/hd/dev/editor/icons/particles.svg | 1 + .../hd/dev/editor/icons/person-standing.png | Bin 0 -> 367 bytes .../rs117/hd/dev/editor/icons/pick-face.svg | 1 + .../rs117/hd/dev/editor/icons/pick-vertex.svg | 1 + .../rs117/hd/dev/editor/icons/plus.svg | 1 + .../rs117/hd/dev/editor/icons/redo.svg | 1 + .../rs117/hd/dev/editor/icons/refresh-cw.png | Bin 0 -> 544 bytes .../rs117/hd/dev/editor/icons/refresh.svg | 1 + .../rs117/hd/dev/editor/icons/resize-grip.svg | 1 + .../rs117/hd/dev/editor/icons/save.png | Bin 0 -> 409 bytes .../rs117/hd/dev/editor/icons/save.svg | 1 + .../hd/dev/editor/icons/scene-isolated.svg | 1 + .../hd/dev/editor/icons/scene-layers.svg | 1 + .../rs117/hd/dev/editor/icons/search.svg | 1 + .../rs117/hd/dev/editor/icons/shading.svg | 1 + .../dev/editor/icons/sliders-horizontal.png | Bin 0 -> 404 bytes .../rs117/hd/dev/editor/icons/snap.svg | 1 + .../rs117/hd/dev/editor/icons/sparkles.png | Bin 0 -> 535 bytes .../rs117/hd/dev/editor/icons/spinner.svg | 1 + .../hd/dev/editor/icons/tool-place-light.svg | 1 + .../hd/dev/editor/icons/tool-remove-light.svg | 1 + .../rs117/hd/dev/editor/icons/tool-select.svg | 1 + .../rs117/hd/dev/editor/icons/trash.svg | 1 + .../rs117/hd/dev/editor/icons/triangle.png | Bin 0 -> 448 bytes .../rs117/hd/dev/editor/icons/undo.svg | 1 + .../rs117/hd/dev/editor/icons/uv/BOX.svg | 1 + .../rs117/hd/dev/editor/icons/uv/GEOMETRY.svg | 1 + .../rs117/hd/dev/editor/icons/uv/MODEL_XY.svg | 1 + .../dev/editor/icons/uv/MODEL_XY_MIRROR_A.svg | 1 + .../dev/editor/icons/uv/MODEL_XY_MIRROR_B.svg | 1 + .../rs117/hd/dev/editor/icons/uv/MODEL_XZ.svg | 1 + .../dev/editor/icons/uv/MODEL_XZ_MIRROR_A.svg | 1 + .../dev/editor/icons/uv/MODEL_XZ_MIRROR_B.svg | 1 + .../rs117/hd/dev/editor/icons/uv/MODEL_YZ.svg | 1 + .../dev/editor/icons/uv/MODEL_YZ_MIRROR_A.svg | 1 + .../dev/editor/icons/uv/MODEL_YZ_MIRROR_B.svg | 1 + .../rs117/hd/dev/editor/icons/uv/VANILLA.svg | 1 + .../rs117/hd/dev/editor/icons/uv/WORLD_XY.svg | 1 + .../rs117/hd/dev/editor/icons/uv/WORLD_XZ.svg | 1 + .../rs117/hd/dev/editor/icons/uv/WORLD_YZ.svg | 1 + .../rs117/hd/dev/editor/icons/view-camera.svg | 1 + .../rs117/hd/dev/editor/icons/water-drop.svg | 3 + .../hd/dev/editor/icons/wind-disabled.svg | 1 + .../editor/icons/wind-object-no-ground.svg | 1 + .../rs117/hd/dev/editor/icons/wind-object.svg | 1 + .../editor/icons/wind-vertex-hemisphere.svg | 1 + .../dev/editor/icons/wind-vertex-jiggle.svg | 1 + .../rs117/hd/dev/editor/icons/wind-vertex.svg | 1 + build.gradle | 21 + 296 files changed, 29344 insertions(+), 36 deletions(-) create mode 100644 AGENTS.md create mode 100644 Tools/Dev/java/rs117/hd/dev/definitions/DefinitionsScreen.java create mode 100644 Tools/Dev/java/rs117/hd/dev/definitions/WaterPreview.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/BeforeAfterSwatch.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/CacheModels.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/ColorPicker.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/DashedAddButton.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorButton.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorButtonGroup.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorModal.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorPanels.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorPopup.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorScrollPane.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorSearch.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorSection.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorSelect.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorSession.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorShell.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorSplash.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorText.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorToolRail.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/EditorWindow.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/FloatingDockWindow.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/HdContextMenu.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/NumberField.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/PopupLayer.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/PreviewDropdown.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/PropertyRow.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/PropertySection.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/SearchableIdDropdown.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/SegmentedControl.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/SelectionModal.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/SwatchDropdown.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/SwatchStrip.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/ToggleList.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/ToggleSwitch.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/UvTypeDropdown.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/WorkspaceActions.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/WorkspaceDocks.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/WorkspaceHistory.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/WorkspaceMenu.java create mode 100644 Tools/Dev/java/rs117/hd/dev/editor/WorkspaceStyle.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/AreaListField.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ColorExpression.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ColorExpressionPanel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/MaterialThumbnails.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ModelColorPalette.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideDocument.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideFields.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/ModelOverridesScreen.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/OverridePreviewSurface.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/OverrideProperties.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/PreviewDiagnostics.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/PreviewFacePicker.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/PreviewGrid.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/WindModeDropdown.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/WindPreview.java create mode 100644 Tools/Dev/java/rs117/hd/dev/overrides/WindStrength.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/PreviewZoneAccess.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/ui/HdConfigPanel.java create mode 100644 Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/ui/HdPreview.java create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/117hd-wordmark.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-box-select.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-box-select.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-grab.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-grab.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-orbit.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-orbit.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pan.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pan.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pick-face.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pick-face.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pick-vertex.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-pick-vertex.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-place-light.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-place-light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-remove-light.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-remove-light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-scrub.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/cursor-scrub.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/cursors/hotspots.json create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/ibmplexsans-400.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/ibmplexsans-500.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/ibmplexsans-600.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/ibmplexsans-OFL.txt create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/ibmplexsans.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/jetbrainsmono-400.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/jetbrainsmono-600.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/jetbrainsmono-OFL.txt create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/fonts/jetbrainsmono.ttf create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/117hd-logo.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/LICENSE-lucide.txt create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/box.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/check.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/chevron-down.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/chevron-left.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/chevron-right.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/chevron-up.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/close.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/copy.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/duplicate.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/eyedropper.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/faces.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/find.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/json.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/key.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/layers.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/load.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/material.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/place-centre.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/plus.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/rename.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/reset.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/tag.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/context/trash.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/copy.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/dock-menu-floating.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/dock-menu.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/dock-swap-panel.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/dot.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/draft-save.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/duplicate.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-128.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-16.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-24.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-256.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-32.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-48.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-512.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon-64.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/editor-icon.ico create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/entity.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/eraser.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/expand-single.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/eye-off.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/eye.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/eyedropper.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/find-in-world.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/float-window.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/frame-all.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/grid.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/grip.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/grip.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/ground-layers.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-chevron-down.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-chevron-left.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-chevron-right.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-close.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-copy.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-entity.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-eye-off.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-eye.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-frame-all.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-grip.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-layout-single.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-layout-split.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-layout-together.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-light.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-model.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-open-external.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-panel-browser.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-particles.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-pick-face.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-pick-vertex.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-plus.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-refresh.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-save.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-search.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-shading.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-tool-place-light.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-tool-remove-light.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-tool-select.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-trash.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/handoff-view-camera.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/history.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/in-game-toggle.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/isolate.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/keyboard.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/layers.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/layout-single.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/layout-split.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/layout-together.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/lightbulb.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/list-tree.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/minus.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/mirror.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/model.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/mouse-pointer-2.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/open-external.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/override-cube.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/palette.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/panel-browser.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/particles.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/person-standing.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/pick-face.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/pick-vertex.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/plus.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/redo.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/refresh-cw.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/refresh.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/resize-grip.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/save.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/save.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/scene-isolated.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/scene-layers.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/search.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/shading.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/sliders-horizontal.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/snap.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/sparkles.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/spinner.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/tool-place-light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/tool-remove-light.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/tool-select.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/trash.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/triangle.png create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/undo.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/BOX.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/GEOMETRY.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XY.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XY_MIRROR_A.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XY_MIRROR_B.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XZ.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XZ_MIRROR_A.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_XZ_MIRROR_B.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_YZ.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_YZ_MIRROR_A.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/MODEL_YZ_MIRROR_B.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/VANILLA.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/WORLD_XY.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/WORLD_XZ.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/uv/WORLD_YZ.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/view-camera.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/water-drop.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-disabled.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-object-no-ground.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-object.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-vertex-hemisphere.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-vertex-jiggle.svg create mode 100644 Tools/Dev/resources/rs117/hd/dev/editor/icons/wind-vertex.svg diff --git a/.gitmodules b/.gitmodules index 8602a53..60dd874 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,7 +1,6 @@ [submodule "RLHD"] path = RLHD - url = https://github.com/117HD/RLHD.git - branch = master + url = https://github.com/Mark7625/RLHD.git [submodule "Tools/rlawt"] path = Tools/rlawt url = https://github.com/aHooder/rlawt diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..68df461 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,39 @@ +# 117HD Editor design rules + +These rules apply to the editor in `Tools/Dev`. + +## Typography + +- Use IBM Plex Sans for labels, buttons, menus, headings, help text, and body copy. Use `WorkspaceStyle.UI` for 400, `MEDIUM` for 500, and `SEMIBOLD` for 600. +- Use JetBrains Mono for values, IDs, gamevals, enum names, coordinates, shortcuts, and expressions such as `h == 63 && s > 0`. Use `WorkspaceStyle.MONO` for 400 and `MONO_SEMIBOLD` for 600. +- Use the bundled font faces through `WorkspaceStyle` and derive only the size. Give mixed labels and technical values separate components when practical. Avoid Swing's default fonts and synthetic bold or italic. +- Segmented controls use UI typography by default. Use `.values()` for segments that show values or enum names. + +## Reusable UI + +- Use the existing editor builders for buttons, text, selects, segmented controls, toggles, and modals. Start with `EditorButton`, `EditorText`, `EditorSelect`, `SegmentedControl`, `ToggleSwitch`, and `EditorModal`. +- Put reusable variants, icons, state styling, and interaction behavior in the shared editor components. Keep screen-specific data and action callbacks in the screen. Use `WorkspaceStyle` for palette tokens, SVG icons, and custom cursors. +- Use `PropertyRow` for aligned property fields, `PropertySection` for collapsible groups, `PopupLayer` for dropdowns, `HdContextMenu` for context menus, and `EditorScrollPane` where content needs scrolling. +- Check narrow docks and open menus against the handoff. Preserve control heights, align field edges, and keep labels and buttons clear of clipping. Verify hover, focus, selected, and disabled states when changing a shared component. +- Keep editor changes in this repository's developer tools. Use the existing reflection adapters when accessing RLHD internals. + +### Adding editor controls + +- Use `EditorButton.builder()` for actions and toggles. Omit a fixed size for text buttons so the label can fit. +- Use `EditorSearch.builder()` for search panels. Set the placeholder and `onChange` callback, and use `field()` to focus, clear, or read the search. +- Use `EditorButtonGroup.builder()` for content-width mode switches. Add `track()` for the viewport toolbar style. Use `SegmentedControl.builder()` for equal-width property options. +- Use `EditorPanels.stack()` for a transparent column and `EditorPanels.centered(component)` to preserve a control's preferred size inside a stretching panel. + +Example for a filter and a viewport mode switch + +```java +var filter = EditorSearch.builder("Filter by name") + .onChange(this::filterByName) + .build(); + +var modes = EditorButtonGroup.builder(List.of("Vanilla", "Override", "Split")) + .selected("Override") + .track() + .onChange(this::setPreviewMode) + .build(); +``` diff --git a/Tools/Dev/build.gradle b/Tools/Dev/build.gradle index 9ffeac8..f3eb08a 100644 --- a/Tools/Dev/build.gradle +++ b/Tools/Dev/build.gradle @@ -24,6 +24,12 @@ sourceSets.test.runtimeClasspath += sourceSets.developer.output def lwjglVersion = '3.3.2' dependencies { + add('developerImplementation', 'net.runelite:cache:1.13.+') { + exclude group: 'org.slf4j', module: 'slf4j-simple' + } + + add('developerImplementation', 'org.mockito:mockito-core:5.14.2') + add('developerImplementation', platform("org.lwjgl:lwjgl-bom:$lwjglVersion")) add('developerImplementation', "org.lwjgl:lwjgl") add('developerImplementation', "org.lwjgl:lwjgl-assimp") @@ -41,6 +47,30 @@ tasks.named('processDeveloperResources') { } } +tasks.register('simulatedRender', JavaExec) { + group = 'application' + description = 'Draws a cache scene with the real 117 HD renderer, without RuneLite' + dependsOn tasks.named('classes'), tasks.named('developerClasses') + classpath = sourceSets.developer.runtimeClasspath + mainClass = 'rs117.hd.dev.sceneloader.standalone.ui.HdPreview' + workingDir = project.rootProject.projectDir + jvmArgs '-ea', '-Xmx2G' + if (project.hasProperty('simArgs')) + args project.property('simArgs').toString().split('\\s+') +} + +tasks.register('benchmark', JavaExec) { + group = 'verification' + description = 'Times 117 HD drawing a cache scene, and writes the frame timers to a CSV' + dependsOn tasks.named('classes'), tasks.named('developerClasses') + classpath = sourceSets.developer.runtimeClasspath + mainClass = 'rs117.hd.dev.sceneloader.standalone.headless.HdBenchmark' + workingDir = project.rootProject.projectDir + jvmArgs '-ea', '-Xmx2G' + if (project.hasProperty('simArgs')) + args project.property('simArgs').toString().split('\\s+') +} + tasks.register('developerJar', Jar) { dependsOn tasks.named('classes'), tasks.named('developerClasses'), tasks.named('processDeveloperResources') from sourceSets.developer.output @@ -48,3 +78,18 @@ tasks.register('developerJar', Jar) { archiveFileName.set("${rootProject.name}-${project.version}-developer.jar") duplicatesStrategy = DuplicatesStrategy.EXCLUDE } + +tasks.register('devToolsEditor', JavaExec) { + group = 'application' + description = 'Opens the standalone 117HD Editor (Model Overrides, plus stub workspaces)' + dependsOn tasks.named('developerClasses') + classpath = sourceSets.developer.runtimeClasspath + mainClass = 'rs117.hd.dev.editor.EditorShell' + workingDir = project.rootProject.projectDir + jvmArgs '-ea', '-Xmx2G' + systemProperty 'rlhd.resource-path', project.file('src/main/resources').absolutePath + if (project.hasProperty('editorCache')) + systemProperty 'rlhd.editor-cache', project.property('editorCache') + if (project.hasProperty('editorModel')) + systemProperty 'rlhd.editor-model', project.property('editorModel') +} \ No newline at end of file diff --git a/Tools/Dev/java/rs117/hd/DeveloperConfig.java b/Tools/Dev/java/rs117/hd/DeveloperConfig.java index 60213ba..b83bddd 100644 --- a/Tools/Dev/java/rs117/hd/DeveloperConfig.java +++ b/Tools/Dev/java/rs117/hd/DeveloperConfig.java @@ -2,8 +2,20 @@ import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; +import net.runelite.client.config.ConfigItem; @ConfigGroup("117hd-developer") public interface DeveloperConfig extends Config { String CONFIG_GROUP = "117hd-developer"; + + String KEY_CACHE_SCENE = "cacheScene"; + @ConfigItem( + keyName = KEY_CACHE_SCENE, + name = "Cache Scene", + description = "Add the 117 HD Cache Scene sidebar, for loading any region straight from the cache without travelling there", + position = 1 + ) + default boolean cacheScene() { + return true; + } } diff --git a/Tools/Dev/java/rs117/hd/DeveloperPlugin.java b/Tools/Dev/java/rs117/hd/DeveloperPlugin.java index c784576..4f026a4 100644 --- a/Tools/Dev/java/rs117/hd/DeveloperPlugin.java +++ b/Tools/Dev/java/rs117/hd/DeveloperPlugin.java @@ -1,15 +1,18 @@ package rs117.hd; import com.google.inject.Provides; +import javax.annotation.Nullable; import javax.inject.Inject; -import javax.inject.Provider; import javax.inject.Singleton; import lombok.extern.slf4j.Slf4j; import net.runelite.client.callback.ClientThread; import net.runelite.client.config.ConfigManager; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.events.ConfigChanged; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginManager; +import rs117.hd.dev.sceneloader.SceneLoader; import rs117.hd.model.ModelExporter; import rs117.hd.model.ModelImporter; import rs117.hd.utils.Props; @@ -34,9 +37,16 @@ public class DeveloperPlugin extends Plugin { @Inject private PluginManager pluginManager; + @Inject + private DeveloperConfig config; + private ModelExporter modelExporter; private ModelImporter modelImporter; + // From 117 HD's injector, so it works with the running 117 HD's renderer, scene & managers + @Nullable + private volatile SceneLoader sceneLoader; + @Provides DeveloperConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(DeveloperConfig.class); @@ -57,12 +67,22 @@ protected void startUp() { modelExporter = injector.getInstance(ModelExporter.class); modelImporter = injector.getInstance(ModelImporter.class); + var loader = injector.getInstance(SceneLoader.class); + sceneLoader = loader; + if (config.cacheScene()) + loader.startUp(); + return true; }); } @Override protected void shutDown() { + var loader = sceneLoader; + sceneLoader = null; + if (loader != null) + loader.shutDown(); + clientThread.invoke(() -> { if (modelImporter != null) modelImporter.close(); @@ -72,4 +92,21 @@ protected void shutDown() { modelExporter = null; }); } + + @Subscribe + public void onConfigChanged(ConfigChanged event) { + if (!event.getGroup().equals(DeveloperConfig.CONFIG_GROUP)) + return; + + if (event.getKey().equals(DeveloperConfig.KEY_CACHE_SCENE)) { + var loader = sceneLoader; + if (loader == null) + return; + if (config.cacheScene()) { + loader.startUp(); + } else { + loader.shutDown(); + } + } + } } diff --git a/Tools/Dev/java/rs117/hd/dev/definitions/DefinitionsScreen.java b/Tools/Dev/java/rs117/hd/dev/definitions/DefinitionsScreen.java new file mode 100644 index 0000000..894bd2a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/definitions/DefinitionsScreen.java @@ -0,0 +1,1359 @@ +package rs117.hd.dev.definitions; + +import com.google.gson.*; +import java.awt.*; +import java.io.IOException; +import java.nio.file.*; +import java.util.*; +import java.util.List; +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import rs117.hd.dev.editor.*; +import rs117.hd.scene.MaterialManager; +import rs117.hd.scene.materials.Material; +import rs117.hd.scene.water_types.WaterType; +import rs117.hd.utils.ColorUtils; +import rs117.hd.utils.Props; +import rs117.hd.utils.ResourcePath; + +public final class DefinitionsScreen extends JPanel { + private static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + private enum Type { + WATER("Water types", "water_types.json", "rlhd.water-types-path"), + GROUND("Ground materials", "ground_materials.json", "rlhd.ground-materials-path"); + + final String label, file, property; + Type(String label, String file, String property) { + this.label = label; + this.file = file; + this.property = property; + } + } + + private static final class Document { + final ResourcePath resource; + final List entries = new ArrayList<>(); + final Map originalNames = new IdentityHashMap<>(); + final Map resetBaselines = new IdentityHashMap<>(); + final Set dirty = Collections.newSetFromMap(new IdentityHashMap<>()); + JsonObject selected; + String source; + boolean changed; + + Document(Type type) throws IOException { + resource = Props.getFile(type.property, () -> ResourcePath.path(rs117.hd.scene.WaterTypeManager.class, type.file)); + try (var reader = resource.toReader()) { + var text = new StringBuilder(); + char[] buffer = new char[4096]; + for (int count; (count = reader.read(buffer)) != -1;) + text.append(buffer, 0, count); + source = text.toString(); + } + for (var element : new JsonParser().parse(source).getAsJsonArray()) { + var entry = element.getAsJsonObject(); + entries.add(entry); + originalNames.put(entry, name(entry)); + resetBaselines.put(entry, copyEntry(entry)); + } + selected = entries.isEmpty() ? null : entries.get(0); + } + } + + private final Map documents = new EnumMap<>(Type.class); + private final DefaultListModel rows = new DefaultListModel<>(); + private final JList list = new JList<>(rows); + private final JPanel filters = new JPanel(new BorderLayout()); + private final JPanel properties = EditorPanels.stack(); + private final JPanel selectionHeader = new JPanel(new BorderLayout(10, 0)); + private final JLabel selectionName = EditorText.builder("").font(WorkspaceStyle.MONO_SEMIBOLD).build(); + private final JLabel selectionMeta = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(10f)).color(WorkspaceStyle.DIM).build(); + private final JLabel selectionChip = new JLabel(); + private final Map groupHeaders = new IdentityHashMap<>(); + private static final List OCEAN_FAMILIES = List.of("STORMY", "SUNBAKED", "PROFANE", "CURSED", + "SCALDING", "ICY", "ENDLESS", "CRYSTAL", "FETID", "TANGLED", "JAGGED"); + private final List fieldUpdates = new ArrayList<>(); + private final JLabel count = EditorText.builder("").font(WorkspaceStyle.MONO).build(); + private final JLabel status = EditorText.builder("").build(); + private final javax.swing.Timer filterRefresh = new javax.swing.Timer(150, event -> refreshRows()); + private JsonObject displayedGround; + private String displayedGroundMaterials; + private boolean displayedGroundSingle; + private JLabel groundHeading; + private final JPanel groundFieldsHost = new JPanel(new BorderLayout()); + + private void scheduleFilterRefresh() { + filterRefresh.setRepeats(false); + filterRefresh.restart(); + } + + private final JPanel groundPreview = EditorPanels.stack(); + private final CardLayout previewLayout = new CardLayout(); + private final JPanel previewCards = new JPanel(previewLayout); + private final JLabel groundName = EditorText.builder("").font(WorkspaceStyle.MONO).color(WorkspaceStyle.DIM).build(); + private final JLabel previewTitle = EditorText.builder("").font(WorkspaceStyle.MONO_SEMIBOLD).build(); + private final JTextArea json = new JTextArea(); + private PropertySection jsonSection; + private final JButton create = EditorButton.builder().text("New").icon("plus", 12).onClick(this::create).build(); + private final JButton save = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY).icon("save", 12).onClick(this::saveCurrent).build(); + private final JPanel preview = new JPanel() { + @Override protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + paintSwatch((Graphics2D) graphics); + } + }; + private volatile WaterRequest waterPreview; + private volatile boolean showWaterObjects, isolateWater; + private final JLabel waterLocation = EditorText.builder("").font(WorkspaceStyle.MONO).color(WorkspaceStyle.DIM).build(); + + static final class WaterRequest { + final String json, originalName; + WaterRequest(String json, String originalName) { + this.json = json; + this.originalName = originalName; + } + } + + boolean showWaterObjects() { return showWaterObjects; } + boolean isolateWater() { return isolateWater; } + + void showWaterLocation(WaterRequest request, String location) { + if (waterPreviewRequest() == request) + waterLocation.setText(location); + } + private volatile boolean waterPreviewVisible; + static final class WaterCamera { + final float east, north, zoom; + WaterCamera(float east, float north, float zoom) { + this.east = east; + this.north = north; + this.zoom = zoom; + } + } + + private volatile WaterCamera waterCamera = new WaterCamera(0, 0, 1); + + WaterCamera waterCamera() { return waterCamera; } + + private void installWaterCameraControls(JComponent... surfaces) { + var mouse = new java.awt.event.MouseAdapter() { + private Point prior; + + @Override public void mousePressed(java.awt.event.MouseEvent event) { + if (waterPreview == null || !SwingUtilities.isLeftMouseButton(event)) + return; + prior = event.getLocationOnScreen(); + preview.setCursor(WorkspaceStyle.cursor("orbit")); + } + + @Override public void mouseReleased(java.awt.event.MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) { + prior = null; + updateWaterCursor(); + } + } + + @Override public void mouseDragged(java.awt.event.MouseEvent event) { + if (prior == null || waterPreview == null) + return; + var camera = waterCamera; + Point current = event.getLocationOnScreen(); + float scale = 4f / camera.zoom; + waterCamera = new WaterCamera( + clampPan(camera.east - (current.x - prior.x) * scale), + clampPan(camera.north + (current.y - prior.y) * scale), camera.zoom); + prior = current; + } + + @Override public void mouseWheelMoved(java.awt.event.MouseWheelEvent event) { + if (waterPreview == null) + return; + var camera = waterCamera; + float zoom = (float) (camera.zoom * Math.pow(1.16, -event.getPreciseWheelRotation())); + waterCamera = new WaterCamera(camera.east, camera.north, Math.max(.4f, Math.min(5f, zoom))); + event.consume(); + } + }; + for (var surface : surfaces) { + surface.addMouseListener(mouse); + surface.addMouseMotionListener(mouse); + surface.addMouseWheelListener(mouse); + } + } + + private static float clampPan(float offset) { return Math.max(-4096, Math.min(4096, offset)); } + + private void updateWaterCursor() { + preview.setCursor(waterPreview == null ? Cursor.getDefaultCursor() : WorkspaceStyle.cursor("grab")); + } + + private Image waterFrame; + private String waterPreviewMessage; + + WaterRequest waterPreviewRequest() { return waterPreviewVisible ? waterPreview : null; } + + public void setPreviewActive(boolean active) { + if (waterPreviewVisible == active) + return; + if (active && waterPreview != null) + waterPreview = new WaterRequest(waterPreview.json, waterPreview.originalName); + waterPreviewVisible = active; + if (!active) { + waterFrame = null; + waterPreviewMessage = null; + refreshGroundPreview(null); + } else if (type == Type.GROUND && document() != null) { + refreshGroundPreview(document().selected); + } + preview.repaint(); + } + + public void showWaterFrame(WaterRequest request, Image image, String message) { + if (!Objects.equals(request, waterPreviewRequest())) + return; + waterFrame = image; + waterPreviewMessage = message; + preview.repaint(); + } + + private Type type = Type.WATER; + private String query = ""; + private boolean refreshing; + + public DefinitionsScreen() { + super(new BorderLayout()); + setBackground(WorkspaceStyle.GAP); + var head = new JPanel(new BorderLayout(8, 0)); + head.setBackground(WorkspaceStyle.HEADER); + head.setBorder(new EmptyBorder(0, 10, 0, 8)); + head.setPreferredSize(new Dimension(0, 30)); + var title = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 7)); + title.setOpaque(false); + title.add(EditorText.builder("Definitions").font(WorkspaceStyle.SEMIBOLD).build()); + title.add(count); + head.add(title); + head.add(EditorPanels.centered(create), BorderLayout.EAST); + var left = new JPanel(new BorderLayout()); + left.setBackground(WorkspaceStyle.PANEL); + var controls = new JPanel(new BorderLayout()); + controls.setOpaque(false); + controls.add(head, BorderLayout.NORTH); + var modes = EditorButtonGroup.builder(List.of(Type.values())).label(value -> value.label) + .onChange(this::selectType).track().build(); + modes.button(Type.WATER).setIcon(WorkspaceStyle.icon("water-drop", 12)); + modes.button(Type.GROUND).setIcon(WorkspaceStyle.icon("ground-layers", 12)); + modes.setLayout(new GridLayout(1, 2)); + modes.setBorder(new EmptyBorder(3, 2, 3, 2)); + var toolbar = new JPanel(new BorderLayout()); + toolbar.setOpaque(false); + toolbar.setBorder(new EmptyBorder(6, 5, 3, 5)); + toolbar.add(modes); + controls.add(toolbar, BorderLayout.CENTER); + filters.setBorder(new EmptyBorder(0, 5, 8, 8)); + filters.setOpaque(false); + controls.add(filters, BorderLayout.SOUTH); + left.add(controls, BorderLayout.NORTH); + left.add(scroll(list)); + left.setMinimumSize(new Dimension(275, 0)); + left.setPreferredSize(new Dimension(310, 0)); + list.setBackground(WorkspaceStyle.PANEL); + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.setCellRenderer(new DefinitionRowRenderer()); + list.addListSelectionListener(event -> { + if (!refreshing && !event.getValueIsAdjusting() && list.getSelectedValue() != null) { + document().selected = list.getSelectedValue(); + showProperties(); + } + }); + + var center = new JPanel(new BorderLayout()); + center.setBackground(WorkspaceStyle.PANEL); + center.setMinimumSize(new Dimension(280, 0)); + var previewControls = EditorPanels.stack(); + previewControls.add(header("Preview")); + var previewBar = new JPanel(new BorderLayout()); + previewBar.setAlignmentX(Component.LEFT_ALIGNMENT); + previewBar.setBackground(WorkspaceStyle.BAR); + previewBar.setBorder(new EmptyBorder(5, 8, 5, 8)); + previewBar.add(waterLocation, BorderLayout.WEST); + addPropertyChangeListener("waterPreview", event -> waterLocation.setText(Boolean.TRUE.equals(event.getNewValue()) + ? "Finding water…" : "Material swatch")); + previewControls.add(previewBar); + var resetCamera = EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("frame-all", 12) + .tooltip("Reset view · Drag to pan, scroll to zoom").onClick(() -> waterCamera = new WaterCamera(0, 0, 1)).build(); + var objects = EditorButton.builder().style(WorkspaceStyle.Button.SCENE_TOGGLE) + .icon("scene-layers", 12).text("Show objects").buildToggle(false); + objects.addActionListener(event -> showWaterObjects = objects.isSelected()); + var isolate = EditorButton.builder().style(WorkspaceStyle.Button.SCENE_TOGGLE) + .icon("scene-isolated", 12).text("Isolate").tooltip("Only show tiles that use this water type").buildToggle(false); + isolate.addActionListener(event -> isolateWater = isolate.isSelected()); + var actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0)); + actions.setOpaque(false); + actions.add(objects); + actions.add(isolate); + actions.add(resetCamera); + previewBar.add(actions, BorderLayout.EAST); + addPropertyChangeListener("waterPreview", event -> actions.setVisible(Boolean.TRUE.equals(event.getNewValue()))); + var waterPanel = new JPanel(new BorderLayout()); + waterPanel.add(previewControls, BorderLayout.NORTH); + preview.setBackground(new Color(0x2A2A2A)); + preview.setLayout(new BorderLayout()); + previewTitle.setBorder(new EmptyBorder(5, 8, 5, 8)); + var caption = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)); + caption.setOpaque(false); + previewTitle.setBackground(new Color(28, 31, 22, 220)); + previewTitle.setOpaque(true); + caption.add(previewTitle); + preview.add(caption, BorderLayout.SOUTH); + installWaterCameraControls(preview, caption, previewTitle); + waterPanel.add(preview); + previewCards.add(waterPanel, Type.WATER.name()); + var groundPanel = new JPanel(new BorderLayout()); + groundPanel.setBackground(new Color(0x1F1F1F)); + var groundHeader = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 6)); + groundHeader.setBackground(WorkspaceStyle.HEADER); + var materialsTitle = EditorText.builder("Materials").font(WorkspaceStyle.SEMIBOLD).build(); + materialsTitle.setIcon(WorkspaceStyle.badge("", new Color(0x78AD54))); + groundHeader.add(materialsTitle); + groundHeader.add(groundName); + groundPanel.add(groundHeader, BorderLayout.NORTH); + var groundScroll = scroll(new PropertiesView(groundPreview)); + groundScroll.getViewport().setBackground(groundPanel.getBackground()); + groundPreview.setBorder(new EmptyBorder(15, 16, 12, 16)); + groundPanel.add(groundScroll); + previewCards.add(groundPanel, Type.GROUND.name()); + center.add(previewCards); + + var right = new JPanel(new BorderLayout()); + right.setBackground(WorkspaceStyle.INPUT); + right.setMinimumSize(new Dimension(320, 0)); + right.setPreferredSize(new Dimension(385, 0)); + selectionHeader.setBackground(WorkspaceStyle.HEADER); + selectionHeader.setBorder(new EmptyBorder(6, 14, 6, 6)); + selectionHeader.setPreferredSize(new Dimension(0, 46)); + right.add(selectionHeader, BorderLayout.NORTH); + properties.setBorder(new EmptyBorder(0, 15, 0, 15)); + properties.setBackground(new Color(0x1F1F1F)); + properties.setOpaque(true); + var propertyScroll = scroll(new PropertiesView(properties)); + propertyScroll.getViewport().setBackground(properties.getBackground()); + right.add(propertyScroll); + var footer = new JPanel(new BorderLayout(6, 6)); + footer.setBackground(WorkspaceStyle.BAR); + footer.setBorder(new EmptyBorder(8, 14, 10, 14)); + save.setPreferredSize(new Dimension(0, 30)); + footer.add(status); + footer.add(save, BorderLayout.SOUTH); + right.add(footer, BorderLayout.SOUTH); + var centerRight = split(center, right, 1); + add(split(left, centerRight, 0)); + selectType(type); + } + + private static final class PropertiesView extends JPanel implements Scrollable { + PropertiesView(JComponent content) { + super(new BorderLayout()); + setOpaque(false); + add(content, BorderLayout.NORTH); + } + + @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } + @Override public boolean getScrollableTracksViewportWidth() { return true; } + @Override public boolean getScrollableTracksViewportHeight() { return false; } + @Override public int getScrollableUnitIncrement(Rectangle visible, int orientation, int direction) { return 24; } + @Override public int getScrollableBlockIncrement(Rectangle visible, int orientation, int direction) { + return Math.max(24, visible.height - 24); + } + } + + private static JSplitPane split(Component left, Component right, double weight) { + var split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right); + split.setBorder(null); + split.setDividerSize(2); + if (split.getUI() instanceof javax.swing.plaf.basic.BasicSplitPaneUI) + ((javax.swing.plaf.basic.BasicSplitPaneUI) split.getUI()).getDivider().setBackground(WorkspaceStyle.GAP); + split.setContinuousLayout(true); + split.setResizeWeight(weight); + split.resetToPreferredSizes(); + return split; + } + + private static JComponent header(String text) { + var header = EditorText.builder(text).font(WorkspaceStyle.SEMIBOLD).border(new EmptyBorder(0, 12, 0, 12)).build(); + header.setBackground(WorkspaceStyle.HEADER); + header.setOpaque(true); + header.setHorizontalAlignment(SwingConstants.LEFT); + header.setAlignmentX(Component.LEFT_ALIGNMENT); + header.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30)); + header.setPreferredSize(new Dimension(0, 30)); + return header; + } + + private static JScrollPane scroll(Component content) { + var scroll = new EditorScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(null); + return scroll; + } + + private Document document() { return documents.get(type); } + + private static String name(JsonObject item) { return item.get("name").getAsString(); } + + private void selectType(Type selected) { + type = selected; + query = ""; + filters.removeAll(); + var search = new JPanel(new BorderLayout()); + search.setOpaque(false); + search.add(EditorSearch.builder(type == Type.WATER ? "Search water types" : "Search by name or material") + .height(26).onChange(text -> { query = text.toLowerCase(Locale.ROOT).strip(); scheduleFilterRefresh(); }).build()); + filters.add(search); + filters.revalidate(); + if (document() == null) { + try { + documents.put(type, new Document(type)); + } catch (IOException | RuntimeException e) { + status.setText(e.getMessage()); + } + } + create.setEnabled(document() != null); + save.setText("Save " + type.label.toLowerCase(Locale.ROOT)); + save.setEnabled(document() != null && document().resource.isFileSystemResource()); + refreshRows(); + showProperties(); + } + + private void refreshRows() { + filterRefresh.stop(); + var doc = document(); + refreshing = true; + try { + rows.clear(); + groupHeaders.clear(); + if (doc != null) { + var groups = new LinkedHashMap>(); + for (var item : doc.entries) { + String text = name(item); + if (type == Type.GROUND && item.has("materials")) + text += " " + item.get("materials"); + if (text.toLowerCase(Locale.ROOT).contains(query)) + groups.computeIfAbsent(group(item), key -> new ArrayList<>()).add(item); + } + groups.forEach((group, items) -> { + groupHeaders.put(items.get(0), group + " " + items.size()); + items.forEach(rows::addElement); + }); + list.setSelectedValue(doc.selected, false); + } + count.setText(Integer.toString(rows.size())); + } finally { + refreshing = false; + } + } + + private String group(JsonObject item) { + if (type == Type.GROUND) + return materials(item).size() <= 1 ? "SINGLE MATERIAL" : "MIXED"; + String name = name(item); + for (String family : OCEAN_FAMILIES) + if (name.startsWith("WATER_" + family)) + return "OCEAN · " + family; + return Set.of("WATER_OPEN", "WATER_SHELF", "WATER_DROPOFF", "WATER_DEEP", + "WATER_TRENCH", "WATER_OUT_OF_BOUNDS").contains(name) ? "OCEAN · DEFAULT" : "SPECIAL"; + } + + private Icon chip(JsonObject item) { + var colors = new ArrayList(); + var textures = new ArrayList(); + if (type == Type.WATER) { + var surface = color(item.get("surfaceColor"), waterColorDefault("surfaceColor")); + colors.add(surface); + colors.add(color(item.get("depthColor"), surface)); + } else { + var names = new LinkedHashSet(); + for (var material : materials(item)) { + String name = material.getAsString(); + if (names.add(name)) { + textures.add(materialTexture(name, 32, list)); + colors.add(groundColor(name)); + } + if (names.size() == 4) + break; + } + if (colors.isEmpty()) + colors.add(WorkspaceStyle.DIM); + } + return new Icon() { + @Override public int getIconWidth() { return 28; } + @Override public int getIconHeight() { return 14; } + @Override public void paintIcon(Component component, Graphics graphics, int x, int y) { + var g = (Graphics2D) graphics.create(); + try { + g.clip(new java.awt.geom.RoundRectangle2D.Float(x, y, getIconWidth(), getIconHeight(), 4, 4)); + for (int i = 0; i < colors.size(); i++) { + int start = i * getIconWidth() / colors.size(); + g.setColor(colors.get(i)); + int width = (i + 1) * getIconWidth() / colors.size() - start; + g.fillRect(x + start, y, width, getIconHeight()); + if (i < textures.size() && textures.get(i) != null) + g.drawImage(textures.get(i), x + start, y, width, getIconHeight(), component); + } + } finally { + g.dispose(); + } + } + }; + } + + private static final Color ROW_SELECTED_BACKGROUND = new Color(0x334D73); + private static final Color ROW_DIRTY_COLOR = new Color(0xE8A33D); + + /** Swing calls this for every visible row on every list repaint; reusing one instance and updating + * its fields avoids rebuilding a whole component per row on every scroll/resize/repaint. */ + private final class DefinitionRowRenderer extends JComponent implements ListCellRenderer { + private String group; + private int headingHeight; + private String tag; + private boolean dirty; + private boolean selected; + private Icon swatch; + private String name; + + @Override public Dimension getPreferredSize() { return new Dimension(245, 28 + headingHeight); } + + @Override + public Component getListCellRendererComponent( + JList list, JsonObject item, int index, boolean selected, boolean cellHasFocus + ) { + group = groupHeaders.get(item); + headingHeight = group == null ? 0 : 20; + tag = type == Type.GROUND ? materials(item).size() + "x" + : (item.has("flat") && item.get("flat").getAsBoolean() ? "FLAT " : "") + (item.has("material") ? "MAT" : ""); + dirty = document().dirty.contains(item); + this.selected = selected; + swatch = chip(item); + name = name(item); + return this; + } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + try { + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.PANEL); + g.fillRect(0, 0, getWidth(), getHeight()); + if (group != null) { + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.setColor(WorkspaceStyle.DIM); + g.drawString(group, 6, 15); + } + if (selected) { + g.setColor(ROW_SELECTED_BACKGROUND); + g.fillRect(0, headingHeight, getWidth(), 28); + } + swatch.paintIcon(this, g, 6, headingHeight + 7); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + String meta = tag + (dirty ? " *" : ""); + int metaX = getWidth() - 8 - g.getFontMetrics().stringWidth(meta); + g.setColor(dirty ? ROW_DIRTY_COLOR : WorkspaceStyle.DIM); + g.drawString(meta, metaX, headingHeight + 18); + g.clipRect(42, headingHeight, Math.max(0, metaX - 48), 28); + g.setColor(WorkspaceStyle.TEXT); + g.drawString(name, 42, headingHeight + 18); + } finally { + g.dispose(); + } + } + } + + private static JsonObject copyEntry(JsonObject item) { + return new JsonParser().parse(item.toString()).getAsJsonObject(); + } + + private void create() { + var doc = document(); + var item = new JsonObject(); + item.addProperty("name", unique(type == Type.WATER ? "NEW_WATER" : "NEW_GROUND")); + if (type == Type.WATER) { + item.addProperty("surfaceColor", "#69809C"); + item.addProperty("fresnelAmount", .85); + } else { + var materials = new JsonArray(); + materials.add(new JsonPrimitive("DIRT_1")); + item.add("materials", materials); + } + doc.entries.add(0, item); + doc.resetBaselines.put(item, copyEntry(item)); + doc.selected = item; + changed(item); + showProperties(); + } + + private String unique(String prefix) { + var names = new HashSet(); + document().entries.forEach(item -> names.add(name(item))); + if (!names.contains(prefix) && prefix.endsWith("_COPY")) + return prefix; + int suffix = 1; + while (names.contains(prefix + "_" + suffix)) + suffix++; + return prefix + "_" + suffix; + } + + private void showProperties() { + properties.removeAll(); + jsonSection = null; + selectionHeader.removeAll(); + fieldUpdates.clear(); + var doc = document(); + if (doc == null || doc.selected == null) { + updateStatus(); + properties.revalidate(); + properties.repaint(); + return; + } + var item = doc.selected; + var general = EditorPanels.stack(); + var actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); + actions.setOpaque(false); + actions.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).tooltip("Duplicate").size(28, 26).icon("copy", 12).onClick(() -> { + var copy = copyEntry(item); + copy.addProperty("name", unique(name(item) + "_COPY")); + doc.entries.add(doc.entries.indexOf(item) + 1, copy); + doc.resetBaselines.put(copy, copyEntry(copy)); + doc.selected = copy; + changed(copy); + showProperties(); + }).build()); + actions.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).tooltip("Delete").size(28, 26).icon("trash", 12).onClick(() -> { + doc.entries.remove(item); + doc.resetBaselines.remove(item); + doc.dirty.remove(item); + doc.selected = doc.entries.isEmpty() ? null : doc.entries.get(0); + changed(null); + showProperties(); + }).build()); + var heading = EditorPanels.stack(); + heading.add(selectionName); + heading.add(selectionMeta); + selectionHeader.add(selectionChip, BorderLayout.WEST); + selectionHeader.add(heading); + selectionHeader.add(EditorPanels.centered(actions), BorderLayout.EAST); + var name = new JTextField(name(item)); + style(name); + var nameRow = new PropertyRow("Name", name, PropertyRow.Layout.WIDE); + EditorSearch.onChange(name, value -> { + item.addProperty("name", value.strip()); + changed(item, false); + if (!query.isEmpty()) + scheduleFilterRefresh(); + }); + general.add(nameRow); + if (type == Type.WATER) { + general.add(field(item, "material", "Material", materialPicker(item, "material", false))); + for (String key : List.of("flat", "hasFoam", "skipUnderwaterTerrain")) { + boolean baseline = Boolean.TRUE.equals(waterDefault(key)); + var toggle = ToggleSwitch.builder().selected(item.has(key) ? item.get(key).getAsBoolean() : baseline) + .onChange(value -> { + set(item, key, value == baseline ? null : new JsonPrimitive(value)); + }).build(); + var toggleRow = new JPanel(new BorderLayout()); + toggleRow.setOpaque(false); + toggleRow.setAlignmentX(Component.LEFT_ALIGNMENT); + toggleRow.setBorder(new EmptyBorder(5, 0, 5, 0)); + toggleRow.add(EditorText.builder(label(key)).color(WorkspaceStyle.DIM).build()); + toggleRow.add(toggle, BorderLayout.EAST); + toggleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34)); + general.add(toggleRow); + } + } + section("General", general, item, type == Type.WATER ? List.of("name", "material", "flat", "hasFoam", "skipUnderwaterTerrain") : List.of("name")); + if (type == Type.WATER) { + var colors = EditorPanels.stack(); + for (String key : List.of("surfaceColor", "depthColor", "foamColor")) + colors.add(field(item, key, label(key), colorButton(item, key))); + section("Colors", colors, item, List.of("surfaceColor", "depthColor", "foamColor")); + var surface = EditorPanels.stack(); + for (String key : List.of("baseOpacity", "fresnelAmount", "specularStrength", "specularGloss", "normalStrength")) + surface.add(number(item, key, 0, key.equals("specularGloss") ? 500 : 1)); + surface.add(field(item, "normalMap", "Normal map", materialPicker(item, "normalMap", true))); + section("Surface", surface, item, List.of("baseOpacity", "fresnelAmount", "specularStrength", "specularGloss", "normalStrength", "normalMap")); + section("Animation", number(item, "duration", 0, Double.MAX_VALUE), item, List.of("duration")); + section("Other", fishingSpotColor(item), item, List.of("fishingSpotRecolor")); + } else { + groundFieldsHost.setOpaque(false); + refreshGroundFields(item); + section("Materials", groundFieldsHost, item, List.of("materials")); + } + json.setEditable(false); + style(json); + json.setRows(10); + jsonSection = new PropertySection("JSON", scroll(json), expanded -> { + if (expanded) + refreshJson(); + else + json.setText(""); + }); + jsonSection.setExpanded(false); + properties.add(jsonSection); + updateStatus(); + properties.revalidate(); + properties.repaint(); + } + + private void section(String title, JComponent content, JsonObject item, List keys) { + var section = new PropertySection(title, content); + boolean materialList = keys.contains("materials"); + if (materialList) + section.setInactiveNote("Picked at random per tile"); + var doc = document(); + section.onReset(() -> { + var baseline = doc.resetBaselines.get(item); + var restored = copyEntry(baseline); + for (String key : keys) { + if (restored.has(key)) + item.add(key, restored.get(key)); + else + item.remove(key); + } + changed(item); + showProperties(); + }); + Runnable refresh = () -> { + var baseline = doc.resetBaselines.get(item); + int configured = (int) keys.stream().filter(key -> { + if (key.equals("name") || !item.has(key)) + return false; + if (!key.equals("materials")) + return true; + var values = materials(item); + return values.size() != 1 || !values.get(0).getAsString().equals("NONE"); + }).count(); + boolean edited = keys.stream().anyMatch(key -> !Objects.equals(item.get(key), baseline.get(key))); + section.setChangedCount(materialList ? materials(item).size() : configured, edited); + }; + refresh.run(); + fieldUpdates.add(refresh); + properties.add(section); + } + + private static void style(javax.swing.text.JTextComponent field) { + field.setFont(WorkspaceStyle.MONO); + field.setBackground(new Color(0x141414)); + field.setForeground(WorkspaceStyle.TEXT); + field.setCaretColor(WorkspaceStyle.TEXT); + } + + private JComponent number(JsonObject item, String key, double min, double max) { + var builder = NumberField.builder().nullable(true).emptyText("Default").min(min).max(max) + .step(key.equals("specularGloss") ? 1 : .01) + .value(item.has(key) ? item.get(key).getAsDouble() : null) + .onChange(value -> set(item, key, value == null ? null : new JsonPrimitive(value))); + if (waterDefault(key) instanceof Number) + builder.defaultValue(((Number) waterDefault(key)).doubleValue()); + var field = builder.build(); + return field(item, key, label(key), field); + } + + private JComponent field(JsonObject item, String key, String label, JComponent control) { + var content = new JPanel(new BorderLayout(4, 0)); + content.setOpaque(false); + content.add(control); + var clear = EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("close", 10).size(18, 18) + .tooltip("Use default").onClick(() -> { set(item, key, null); showProperties(); }).build(); + clear.setVisible(item.has(key)); + content.add(clear, BorderLayout.EAST); + var row = new PropertyRow(label, content, PropertyRow.Layout.WIDE); + row.setChanged(item.has(key)); + fieldUpdates.add(() -> { + clear.setVisible(item.has(key)); + row.setChanged(item.has(key)); + }); + return row; + } + + private JComponent materialPicker(JsonObject item, String key, boolean normal) { + return materialPicker(item.has(key) ? item.get(key).getAsString() : null, normal, value -> { + set(item, key, new JsonPrimitive(value)); + }); + } + + private PreviewDropdown materialPicker(String initial, boolean normal, java.util.function.Consumer change) { + var picker = PreviewDropdown.builder(new PreviewDropdown.Provider() { + @Override public List items() { + updateMaterialIndex(); + if (!normal) + return materialNames; + return materialNames.stream().filter(name -> name.startsWith("WATER_NORMAL_MAP")) + .collect(java.util.stream.Collectors.toList()); + } + @Override public String label(String value) { return value; } + @Override public Image preview(String value, int size) { return preview(value, size, DefinitionsScreen.this); } + @Override public Image preview(String value, int size, JComponent observer) { + return materialTexture(value, size, observer); + } + }).search(normal ? "Search normal maps" : "Search materials").compact(true).emptyText(normal ? "Default" : "None set").build(); + picker.setValue(initial); + picker.onChange(change); + return picker; + } + + private JComponent fishingSpotColor(JsonObject item) { + String key = "fishingSpotRecolor"; + return field(item, key, "Fishing spot recolor", colorButton(item, key)); + } + + private static Color hslColor(int value) { + float[] rgb = ColorUtils.packedHslToSrgb(value); + return new Color(channel(rgb[0]), channel(rgb[1]), channel(rgb[2])); + } + + private JComponent colorButton(JsonObject item, String key) { + boolean packed = key.equals("fishingSpotRecolor"); + java.util.function.Supplier current = () -> { + if (!packed) + return color(item.get(key), waterColorDefault(key)); + int hsl = item.has(key) ? item.get(key).getAsInt() : -1; + return hsl < 0 ? Color.WHITE : hslColor(hsl); + }; + var button = EditorButton.builder().style(WorkspaceStyle.Button.TAB) + .tooltip("Choose " + label(key).toLowerCase(Locale.ROOT)).build(); + Runnable update = () -> { + button.setText(item.has(key) ? hex(current.get()) : "Default"); + button.setFont(item.has(key) ? WorkspaceStyle.MONO_SEMIBOLD.deriveFont(11f) : WorkspaceStyle.UI); + button.setIcon(ColorPicker.swatch(current.get(), 24)); + }; + update.run(); + fieldUpdates.add(update); + ColorPicker.builder(button, current).palette("FROM OTHER WATER", () -> waterPalette(item)).onApply(picked -> { + JsonPrimitive next = packed ? new JsonPrimitive(ColorUtils.hsl(picked.getRGB() & 0xffffff)) + : new JsonPrimitive(hex(picked)); + if (!next.equals(item.get(key))) + set(item, key, next); + }).bind(); + button.setBorder(new EmptyBorder(0, 0, 0, 0)); + button.setHorizontalAlignment(SwingConstants.LEFT); + button.setIconTextGap(4); + return button; + } + + private List waterPalette(JsonObject current) { + var palette = new LinkedHashSet(); + for (var item : document().entries) { + if (item == current) + continue; + for (String key : List.of("surfaceColor", "depthColor", "foamColor")) + if (item.has(key)) + palette.add(color(item.get(key), waterColorDefault(key))); + } + return List.copyOf(palette); + } + + private static JsonArray materials(JsonObject item) { + return item.has("materials") ? item.getAsJsonArray("materials") : new JsonArray(); + } + + private Material[] materialSource; + private Map materialsByName = Map.of(); + private List materialNames = List.of(); + + private void updateMaterialIndex() { + var source = MaterialManager.MATERIALS; + if (source == materialSource) + return; + materialSource = source; + var byName = new TreeMap(); + if (source != null) + for (Material material : source) + byName.putIfAbsent(material.name, material); + materialsByName = byName; + materialNames = List.copyOf(byName.keySet()); + } + + private Image materialTexture(String name, int size, Component observer) { + updateMaterialIndex(); + return rs117.hd.dev.overrides.MaterialThumbnails.preview(materialsByName.get(name), size, observer); + } + + private void refreshGroundFields(JsonObject item) { + groundFieldsHost.removeAll(); + groundFieldsHost.add(groundFields(item)); + groundFieldsHost.revalidate(); + groundFieldsHost.repaint(); + } + + private JComponent groundFields(JsonObject item) { + var content = EditorPanels.stack(); + var values = materials(item); + var mix = new JComponent() { + @Override protected void paintComponent(Graphics graphics) { + if (values.size() == 0) + return; + var g = (Graphics2D) graphics.create(); + try { + g.clip(new java.awt.geom.RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 6, 6)); + for (int i = 0; i < values.size(); i++) { + String name = values.get(i).getAsString(); + int x = i * getWidth() / values.size(); + int width = (i + 1) * getWidth() / values.size() - x; + g.setColor(groundColor(name)); + g.fillRect(x, 0, width, getHeight()); + var texture = materialTexture(name, 32, this); + if (texture != null) + g.drawImage(texture, x, 0, width, getHeight(), this); + } + } finally { + g.dispose(); + } + } + }; + mix.setPreferredSize(new Dimension(0, 10)); + mix.setMaximumSize(new Dimension(Integer.MAX_VALUE, 10)); + mix.setAlignmentX(LEFT_ALIGNMENT); + content.add(mix); + content.add(Box.createVerticalStrut(8)); + for (int i = 0; i < values.size(); i++) { + int index = i; + var row = new JPanel(new BorderLayout(5, 0)); + row.setOpaque(false); + row.setAlignmentX(LEFT_ALIGNMENT); + row.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true), + new EmptyBorder(1, 7, 1, 2))); + var number = EditorText.builder(Integer.toString(i + 1)).font(WorkspaceStyle.MONO.deriveFont(10f)) + .color(WorkspaceStyle.DIM).build(); + number.setPreferredSize(new Dimension(20, 0)); + row.add(number, BorderLayout.WEST); + row.add(materialPicker(values.get(i).getAsString(), false, value -> { + values.set(index, new JsonPrimitive(value)); + groundMaterialsChanged(item, values); + mix.repaint(); + })); + var buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); + buttons.setOpaque(false); + buttons.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("chevron-up", 10).size(22, 22).enabled(i > 0).tooltip("Move up").onClick(() -> { + var prior = values.get(index - 1); + values.set(index - 1, values.get(index)); + values.set(index, prior); + groundMaterialsChanged(item, values); + refreshGroundFields(item); + }).build()); + buttons.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("close", 10).size(22, 22).enabled(values.size() > 1).tooltip("Remove material").onClick(() -> { + values.remove(index); + groundMaterialsChanged(item, values); + refreshGroundFields(item); + }).build()); + row.add(buttons, BorderLayout.EAST); + content.add(row); + content.add(Box.createVerticalStrut(4)); + } + var footer = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 4)); + footer.setOpaque(false); + footer.setAlignmentX(LEFT_ALIGNMENT); + var add = DashedAddButton.create("Add material"); + var picker = materialPicker(null, false, material -> changeGroundCount(item, material, 1)); + add.addActionListener(event -> picker.togglePopup(add)); + footer.add(add); + footer.add(EditorText.builder("Repeat a material to make it more common").color(WorkspaceStyle.DIM) + .font(WorkspaceStyle.UI.deriveFont(10f)).border(new EmptyBorder(0, 8, 0, 0)).build()); + content.add(footer); + return content; + } + + private static String label(String key) { + String text = key.replaceAll("([a-z])([A-Z])", "$1 $2").toLowerCase(Locale.ROOT); + return Character.toUpperCase(text.charAt(0)) + text.substring(1); + } + + private static Object waterDefault(String key) { + try { + var field = WaterType.class.getDeclaredField(key); + field.setAccessible(true); + return field.get(WaterType.NONE); + } catch (ReflectiveOperationException e) { + return null; + } + } + + private static Color waterColorDefault(String key) { + Object value = waterDefault(key); + return value instanceof float[] ? linear((float[]) value) : Color.GRAY; + } + + private static Color linear(float[] value) { + var rgb = ColorUtils.linearToSrgb(value.clone()); + return new Color(channel(rgb[0]), channel(rgb[1]), channel(rgb[2])); + } + + private static float channel(float value) { return Math.max(0, Math.min(1, value)); } + + private static Color color(JsonElement value, Color fallback) { + if (value == null || value.isJsonNull()) + return fallback; + if (value.isJsonArray()) { + var array = value.getAsJsonArray(); + return linear(new float[] { array.get(0).getAsFloat() / 255, array.get(1).getAsFloat() / 255, array.get(2).getAsFloat() / 255 }); + } + try { return Color.decode(value.getAsString()); } + catch (NumberFormatException e) { return fallback; } + } + + private static String hex(Color color) { return String.format("#%06X", color.getRGB() & 0xffffff); } + + private static Color groundColor(String name) { + return name == null ? WorkspaceStyle.DIM : Color.getHSBColor(Math.floorMod(name.hashCode(), 360) / 360f, .28f, .64f); + } + + private void paintSwatch(Graphics2D graphics) { + var doc = document(); + if (doc == null || doc.selected == null) + return; + if (type == Type.WATER) { + if (waterFrame != null) { + int imageWidth = waterFrame.getWidth(null); + int imageHeight = waterFrame.getHeight(null); + if (imageWidth > 0 && imageHeight > 0) { + double scale = Math.max(preview.getWidth() / (double) imageWidth, preview.getHeight() / (double) imageHeight); + int width = (int) Math.ceil(imageWidth * scale), height = (int) Math.ceil(imageHeight * scale); + graphics.drawImage(waterFrame, (preview.getWidth() - width) / 2, (preview.getHeight() - height) / 2, + width, height, null); + } + } else { + String message = waterPreviewMessage == null ? "Loading water preview…" : waterPreviewMessage; + graphics.setFont(WorkspaceStyle.UI); + graphics.setColor(WorkspaceStyle.DIM); + graphics.drawString(message, Math.max(8, (preview.getWidth() - graphics.getFontMetrics().stringWidth(message)) / 2), + preview.getHeight() / 2); + } + } + } + + private void refreshGroundPreview(JsonObject item) { + String materialList = item == null ? "" : materials(item).toString(); + groundName.setText(item == null ? "" : name(item)); + if (displayedGround == item && Objects.equals(displayedGroundMaterials, materialList)) { + if (groundHeading != null) + groundHeading.setText("Materials in " + name(item)); + return; + } + displayedGround = item; + displayedGroundMaterials = materialList; + displayedGroundSingle = item != null && materials(item).size() <= 1; + groundPreview.removeAll(); + groundHeading = null; + if (item != null) { + var counts = new LinkedHashMap(); + var entries = materials(item); + for (var entry : entries) + counts.merge(entry.getAsString(), 1, Integer::sum); + var heading = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0)); + heading.setOpaque(false); + heading.setAlignmentX(LEFT_ALIGNMENT); + groundHeading = EditorText.builder("Materials in " + name(item)).font(WorkspaceStyle.SEMIBOLD).build(); + heading.add(groundHeading); + heading.add(EditorText.builder(entries.size() + " entries · " + counts.size() + " materials") + .color(WorkspaceStyle.DIM).build()); + groundPreview.add(heading); + groundPreview.add(Box.createVerticalStrut(12)); + + var layout = new GridLayout(0, 5, 10, 10); + var cards = new JPanel(layout) { + @Override public Dimension getMaximumSize() { + return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); + } + }; + cards.setOpaque(false); + cards.setAlignmentX(LEFT_ALIGNMENT); + cards.addComponentListener(new java.awt.event.ComponentAdapter() { + @Override public void componentResized(java.awt.event.ComponentEvent event) { + int columns = Math.max(1, Math.min(5, (cards.getWidth() + 10) / 145)); + if (columns != layout.getColumns()) { + layout.setColumns(columns); + cards.revalidate(); + } + } + }); + counts.forEach((material, count) -> cards.add(groundCard(item, material, count, entries.size()))); + var add = DashedAddButton.create("Add material"); + add.setVerticalTextPosition(SwingConstants.BOTTOM); + add.setHorizontalTextPosition(SwingConstants.CENTER); + add.setIcon(WorkspaceStyle.icon("plus", 16)); + var picker = materialPicker(null, false, material -> changeGroundCount(item, material, 1)); + add.addActionListener(event -> picker.togglePopup(add)); + cards.add(add); + groundPreview.add(cards); + groundPreview.add(Box.createVerticalStrut(10)); + var note = new JTextArea("Each tile picks one entry at random. Add more entries to make a material more common. Swap or reorder entries in the panel on the right."); + note.setFont(WorkspaceStyle.UI.deriveFont(11f)); + note.setForeground(WorkspaceStyle.DIM); + note.setOpaque(false); + note.setEditable(false); + note.setFocusable(false); + note.setLineWrap(true); + note.setWrapStyleWord(true); + note.setAlignmentX(LEFT_ALIGNMENT); + groundPreview.add(note); + } + groundPreview.revalidate(); + groundPreview.repaint(); + } + + private JPanel groundCard(JsonObject item, String material, int count, int total) { + float share = count / (float) total; + var card = new JPanel(new BorderLayout()); + card.setBackground(new Color(0x252525)); + card.setBorder(BorderFactory.createLineBorder(new Color(0x353535), 1, true)); + var texture = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 6)) { + @Override protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + graphics.setColor(material.startsWith("GRASS") ? new Color(0x617F43) + : material.startsWith("DIRT") ? new Color(0x785E43) : groundColor(material)); + graphics.fillRect(0, 0, getWidth(), getHeight()); + Image thumbnail = materialTexture(material, 192, this); + if (thumbnail != null) { + graphics.drawImage(thumbnail, 0, 0, getWidth(), getHeight(), this); + return; + } + graphics.setColor(new Color(255, 255, 255, 24)); + for (int x = -getHeight(); x < getWidth(); x += 8) + graphics.drawLine(x, 0, x + getHeight(), getHeight()); + } + }; + texture.setPreferredSize(new Dimension(120, 124)); + var percent = EditorText.builder(Math.round(share * 100) + "%").font(WorkspaceStyle.MONO_SEMIBOLD.deriveFont(10f)) + .border(new EmptyBorder(1, 4, 1, 4)).build(); + percent.setOpaque(true); + percent.setBackground(new Color(0, 0, 0, 175)); + texture.add(percent); + card.add(texture, BorderLayout.NORTH); + + var details = EditorPanels.stack(); + details.setBorder(new EmptyBorder(7, 9, 8, 9)); + details.add(EditorText.builder(material).font(WorkspaceStyle.MONO_SEMIBOLD.deriveFont(11f)).build()); + var bar = new JComponent() { + @Override protected void paintComponent(Graphics graphics) { + graphics.setColor(WorkspaceStyle.INPUT); + graphics.fillRect(0, 0, getWidth(), getHeight()); + graphics.setColor(WorkspaceStyle.ACCENT); + graphics.fillRect(0, 0, Math.round(share * getWidth()), getHeight()); + } + }; + bar.setPreferredSize(new Dimension(0, 4)); + bar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 4)); + bar.setAlignmentX(LEFT_ALIGNMENT); + details.add(bar); + var footer = new JPanel(new BorderLayout()); + footer.setOpaque(false); + footer.setAlignmentX(LEFT_ALIGNMENT); + footer.add(EditorText.builder(count + (count == 1 ? " entry" : " entries")) + .font(WorkspaceStyle.MONO.deriveFont(10f)).color(WorkspaceStyle.DIM).build()); + var controls = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 3)); + controls.setOpaque(false); + var remove = EditorButton.builder().icon("minus", 10).size(22, 22).tooltip("Remove one entry").enabled(total > 1) + .onClick(() -> changeGroundCount(item, material, -1)).build(); + var increment = EditorButton.builder().icon("plus", 10).size(22, 22).tooltip("Add one entry") + .onClick(() -> changeGroundCount(item, material, 1)).build(); + for (var button : List.of(remove, increment)) { + button.setBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true)); + button.setBorderPainted(true); + controls.add(button); + } + footer.add(controls, BorderLayout.EAST); + details.add(footer); + card.add(details); + card.setPreferredSize(new Dimension(130, 190)); + return card; + } + + private void changeGroundCount(JsonObject item, String material, int delta) { + var entries = materials(item); + if (delta > 0) { + entries.add(new JsonPrimitive(material)); + } else { + for (int i = entries.size() - 1; i >= 0; i--) { + if (material.equals(entries.get(i).getAsString())) { + entries.remove(i); + break; + } + } + } + groundMaterialsChanged(item, entries); + refreshGroundFields(item); + } + + private void groundMaterialsChanged(JsonObject item, JsonArray entries) { + item.add("materials", entries); + // A count change only moves the row when it crosses the single-material boundary. + boolean regroup = displayedGround != item || displayedGroundMaterials == null + || (entries.size() <= 1) != displayedGroundSingle; + changed(item, regroup); + if (!regroup && !query.isEmpty()) + scheduleFilterRefresh(); + } + + private void set(JsonObject item, String key, JsonElement value) { + if (value == null) + item.remove(key); + else + item.add(key, value); + changed(item, false); + } + + private void changed(JsonObject item) { + changed(item, true); + } + + private void changed(JsonObject item, boolean rebuildRows) { + var doc = document(); + doc.changed = true; + if (item != null) + doc.dirty.add(item); + if (rebuildRows) + refreshRows(); + else + list.repaint(); + updateStatus(); + fieldUpdates.forEach(Runnable::run); + } + + private void refreshJson() { + var selected = document().selected; + json.setText(selected == null ? "" : JSON.toJson(selected)); + json.setCaretPosition(0); + } + + private void updateStatus() { + previewLayout.show(previewCards, type.name()); + if (type == Type.GROUND) + refreshGroundPreview(document() == null ? null : document().selected); + var doc = document(); + if (doc == null) { + waterPreview = null; + return; + } + if (jsonSection != null && jsonSection.isExpanded()) + refreshJson(); + var selected = doc.selected; + String nextJson = type == Type.WATER && selected != null ? selected.toString() : null; + String originalName = doc.originalNames.get(selected); + if (!Objects.equals(nextJson, waterPreview == null ? null : waterPreview.json) + || !Objects.equals(originalName, waterPreview == null ? null : waterPreview.originalName)) { + if (waterPreview == null || nextJson == null || !Objects.equals(originalName, waterPreview.originalName)) { + waterCamera = new WaterCamera(0, 0, 1); + waterFrame = null; + } + waterPreviewMessage = null; + waterPreview = nextJson == null ? null : new WaterRequest(nextJson, originalName); + updateWaterCursor(); + } + firePropertyChange("waterPreview", type != Type.WATER, type == Type.WATER); + previewTitle.setVisible(selected != null); + if (selected != null) { + selectionChip.setIcon(chip(selected)); + selectionName.setText(name(selected)); + boolean flat = selected.has("flat") && selected.get("flat").getAsBoolean(); + selectionMeta.setText((type == Type.GROUND ? materials(selected).size() + " materials" : flat ? "flat" : "animated") + + " · " + (selected.entrySet().size() - 1) + " fields set"); + previewTitle.setText(name(selected)); + } + selectionHeader.revalidate(); + selectionHeader.repaint(); + preview.repaint(); + status.setText(doc.changed ? Math.max(1, doc.dirty.size()) + " unsaved changes" : "All changes saved"); + status.setForeground(new Color(doc.changed ? 0xE8A33D : 0x6CB348)); + } + + public boolean confirmClose() { + if (documents.values().stream().noneMatch(doc -> doc.changed)) + return true; + int answer = JOptionPane.showOptionDialog(this, "Save changes to definitions before closing?", "Definitions", + JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { "Save", "Discard", "Cancel" }, "Save"); + if (answer == 1) + return true; + if (answer != 0) + return false; + for (var entry : documents.entrySet()) + if (entry.getValue().changed && !save(entry.getKey(), entry.getValue())) + return false; + return true; + } + + public void saveCurrent() { + if (document() != null && save(type, document())) { + updateStatus(); + fieldUpdates.forEach(Runnable::run); + } + } + + // Consume quoted strings as tokens so bracket text inside a string is never treated as an array. + private static final String JSON_STRING = "\"(?:[^\"\\\\]|\\\\.)*\""; + private static final java.util.regex.Pattern ARRAY_FIELDS = java.util.regex.Pattern.compile( + "(" + JSON_STRING + "\\s*:\\s*)(\\[(?:" + JSON_STRING + "|[^\\[\\]{}\"])*\\])|" + JSON_STRING); + + private static String retainInlineArrays(String source, String output) { + var inline = new HashMap(); + var matcher = ARRAY_FIELDS.matcher(source); + while (matcher.find()) { + String array = matcher.group(2); + if (array != null && !array.contains("\n") && !array.contains("\r")) { + String key = matcher.group(1).substring(0, matcher.group(1).lastIndexOf(':')).stripTrailing(); + inline.putIfAbsent(key + new JsonParser().parse(array), array); + } + } + matcher = ARRAY_FIELDS.matcher(output); + var result = new StringBuffer(); + while (matcher.find()) { + String array = matcher.group(2); + if (array == null || !array.contains("\n")) + continue; + String prefix = matcher.group(1); + String previous = inline.get(prefix.substring(0, prefix.lastIndexOf(':')).stripTrailing() + new JsonParser().parse(array)); + if (previous != null) + matcher.appendReplacement(result, java.util.regex.Matcher.quoteReplacement(prefix + previous)); + } + matcher.appendTail(result); + return result.toString(); + } + + private boolean save(Type type, Document doc) { + try { + if (!doc.resource.isFileSystemResource()) + throw new IOException("Configure a writable path for " + type.file); + Path path = doc.resource.toPath().toAbsolutePath(); + if (!Files.readString(path).equals(doc.source)) + throw new IOException(type.file + " changed on disk"); + var savedCounts = new HashMap(); + for (var entry : new JsonParser().parse(doc.source).getAsJsonArray()) + savedCounts.merge(name(entry.getAsJsonObject()), 1, Integer::sum); + var counts = new HashMap(); + for (var entry : doc.entries) { + String name = name(entry); + if (name.isBlank()) + throw new IOException("Each definition needs a name"); + if (counts.merge(name, 1, Integer::sum) > Math.max(1, savedCounts.getOrDefault(name, 0))) + throw new IOException("Duplicate definition name: " + name); + } + var output = new JsonArray(); + doc.entries.forEach(output::add); + String newline = doc.source.contains("\r\n") ? "\r\n" : "\n"; + String result = retainInlineArrays(doc.source, JSON.toJson(output)).replace("\n", newline) + newline; + Path temporary = Files.createTempFile(path.getParent(), ".definitions-", ".tmp"); + try { + Files.writeString(temporary, result); + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(temporary); + } + doc.source = result; + doc.changed = false; + doc.dirty.clear(); + doc.entries.forEach(entry -> doc.resetBaselines.put(entry, copyEntry(entry))); + list.repaint(); + return true; + } catch (IOException e) { + status.setText(e.getMessage()); + status.setForeground(new Color(0xE06060)); + return false; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/definitions/WaterPreview.java b/Tools/Dev/java/rs117/hd/dev/definitions/WaterPreview.java new file mode 100644 index 0000000..e8f1802 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/definitions/WaterPreview.java @@ -0,0 +1,141 @@ +package rs117.hd.dev.definitions; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.dev.editor.EditorSession; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.standalone.HdRuntime; + +@Slf4j +public final class WaterPreview { + private static final int WORLD_X = 1569; + private static final int WORLD_Y = 2799; + private static final float PITCH = .8f; + + private final EditorSession session; + private final DefinitionsScreen screen; + private final AtomicBoolean queuedFrame = new AtomicBoolean(); + private BuiltScene scene; + private float focusX, focusY, focusZ; + private DefinitionsScreen.WaterRequest applied, failed; + private final java.util.Map> locations = new java.util.HashMap<>(); + private net.runelite.cache.region.Position position; + private boolean objects, isolated; + private DefinitionsScreen.WaterCamera lastView; + private long lastCapture; + private boolean needsFrame; + + public WaterPreview(EditorSession session, DefinitionsScreen screen) { + this.session = session; + this.screen = screen; + } + + public boolean render(HdRuntime runtime) { + var request = screen.waterPreviewRequest(); + if (request == null) + return false; + if (request == failed) + return true; + + try { + boolean isolate = screen.isolateWater(); + boolean showObjects = screen.showWaterObjects() && !isolate; + String source = request.originalName; + net.runelite.cache.region.Position next; + if (source == null) { + next = new net.runelite.cache.region.Position(WORLD_X, WORLD_Y, 0); + } else { + if (!locations.containsKey(source)) { + runtime.setPreviewWater(null, null); + SwingUtilities.invokeLater(() -> screen.showWaterLocation(request, "Finding water…")); + next = session.findWaterPlacement(source, runtime, () -> { + var current = screen.waterPreviewRequest(); + return current != null && source.equals(current.originalName); + }); + var current = screen.waterPreviewRequest(); + if (current == null || !source.equals(current.originalName)) + return true; + locations.put(source, java.util.Optional.ofNullable(next)); + } + next = locations.get(source).orElse(null); + } + boolean fallback = next == null; + if (fallback) + next = new net.runelite.cache.region.Position(WORLD_X, WORLD_Y, 0); + String waterFilter = fallback ? null : source; + boolean locationChanged = position == null || next.getX() != position.getX() + || next.getY() != position.getY() || next.getZ() != position.getZ(); + boolean installScene = locationChanged || showObjects != objects || isolate != isolated + || (applied != null && !java.util.Objects.equals(source, applied.originalName)); + if (installScene) { + runtime.setPreviewWater(null, null); + scene = session.buildTerrainPreview(next.getX(), next.getY(), showObjects); + int x = next.getX() - scene.getBaseX(), y = next.getY() - scene.getBaseY(); + focusX = x * 128 + 64; + focusY = scene.getTileHeights()[next.getZ()][x + BuiltScene.SCENE_OFFSET][y + BuiltScene.SCENE_OFFSET]; + focusZ = y * 128 + 64; + if (isolate) + runtime.isolatePreviewWater(scene, waterFilter); + position = next; + objects = showObjects; + isolated = isolate; + } + if (installScene || request != applied || runtime.previewWaterNeedsRefresh()) { + needsFrame = true; + runtime.setPreviewModel(null, null, null); + runtime.setPreviewOverride(null, null); + boolean attachScene = installScene || applied == null || runtime.previewWaterNeedsRefresh(); + applied = request; + runtime.setPreviewWater(request.json, waterFilter); + if (attachScene) + runtime.setScene(scene); + runtime.setLevels(next.getZ(), true, false); + runtime.setPreviewPass(true, false); + String label = next.getX() + ", " + next.getY() + (next.getZ() > 0 ? " · Plane " + next.getZ() : ""); + String locationLabel = fallback ? label + " · Test site" : label; + SwingUtilities.invokeLater(() -> screen.showWaterLocation(request, locationLabel)); + } + var view = screen.waterCamera(); + long now = System.nanoTime(); + // Keep camera movement responsive and lower the capture rate for stationary water. + if (queuedFrame.get() || (!needsFrame && view == lastView && now - lastCapture < 66_000_000L)) + return true; + runtime.nextFrameTo(image -> { + if (image == null || !queuedFrame.compareAndSet(false, true)) + return; + lastCapture = now; + lastView = view; + needsFrame = false; + SwingUtilities.invokeLater(() -> { + try { + screen.showWaterFrame(request, image, null); + } finally { + queuedFrame.set(false); + } + }); + }); + float[] camera = {focusX + view.east, focusY - 1450 / view.zoom, focusZ + view.north - 1400 / view.zoom}; + runtime.frame(camera, 0, PITCH); + } catch (IOException | RuntimeException e) { + log.warn("Could not render the Definitions water preview", e); + failed = request; + SwingUtilities.invokeLater(() -> screen.showWaterFrame(request, null, "Could not render water preview")); + } + return true; + } + + public boolean detach(HdRuntime runtime) { + failed = null; + scene = null; + position = null; + lastView = null; + if (applied == null) + return false; + runtime.nextFrameTo(null); + runtime.setPreviewWater(null, null); + applied = null; + return true; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/BeforeAfterSwatch.java b/Tools/Dev/java/rs117/hd/dev/editor/BeforeAfterSwatch.java new file mode 100644 index 0000000..d50ee94 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/BeforeAfterSwatch.java @@ -0,0 +1,72 @@ +package rs117.hd.dev.editor; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Shape; +import java.awt.geom.RoundRectangle2D; +import javax.swing.JComponent; + +public final class BeforeAfterSwatch extends JComponent { + public enum Split { HORIZONTAL, VERTICAL } + + private final Split split; + private Color before; + private Color after; + + public BeforeAfterSwatch(int size, Split split, Color before, Color after) { + this.split = split; + this.before = before; + this.after = after; + setOpaque(false); + var dimension = new Dimension(size, size); + setPreferredSize(dimension); + setMinimumSize(dimension); + setMaximumSize(dimension); + } + + public void setColors(Color before, Color after) { + this.before = before; + this.after = after; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + int width = getWidth(); + int height = getHeight(); + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + Shape clip = new RoundRectangle2D.Float(0, 0, width, height, 3, 3); + Shape previousClip = g.getClip(); + g.clip(clip); + if (before.getAlpha() < 255 || after.getAlpha() < 255) { + int cell = 5; + for (int y = 0; y < height; y += cell) { + for (int x = 0; x < width; x += cell) { + g.setColor((x / cell + y / cell) % 2 == 0 ? new Color(0x777777) : new Color(0x444444)); + g.fillRect(x, y, cell, cell); + } + } + } + if (split == Split.HORIZONTAL) { + int half = width / 2; + g.setColor(before); + g.fillRect(0, 0, half, height); + g.setColor(after); + g.fillRect(half, 0, width - half, height); + } else { + int half = height / 2; + g.setColor(before); + g.fillRect(0, 0, width, half); + g.setColor(after); + g.fillRect(0, half, width, height - half); + } + g.setClip(previousClip); + g.setColor(WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, width - 1, height - 1, 3, 3); + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/CacheModels.java b/Tools/Dev/java/rs117/hd/dev/editor/CacheModels.java new file mode 100644 index 0000000..281de23 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/CacheModels.java @@ -0,0 +1,238 @@ +package rs117.hd.dev.editor; + +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import net.runelite.cache.ConfigType; +import net.runelite.cache.IndexType; +import net.runelite.cache.NpcManager; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.loaders.SpotAnimLoader; +import rs117.hd.dev.sceneloader.scene.BuiltModel; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.ModelFactory; +import rs117.hd.scene.GamevalManager; + +public final class CacheModels { + public enum Category { NPCs, Objects, Graphics } + + public interface ModelSource { BuiltModel load() throws IOException; } + + public static final class Entry { + public final Category category; + public final int id; + public final String label; + public final String name; + public final String displayName; + private final List gamevals; + public final String searchLabel; + public final ModelSource source; + + public String gamevalName() { return gamevals.isEmpty() ? null : gamevals.get(0); } + + Entry(Category category, int id, String name, List gamevals, ModelSource source) { + this.category = category; + this.id = id; + this.name = name == null || name.isBlank() || name.equals("null") ? category == Category.Graphics ? "Spot animation" : "Unnamed" : name; + this.gamevals = gamevals == null ? List.of() : gamevals; + displayName = this.gamevals.isEmpty() ? this.name : this.gamevals.get(0); + label = displayName + " (" + id + ")"; + searchLabel = (this.name + " " + id + " " + String.join(" ", this.gamevals)).toLowerCase(Locale.ROOT); + this.source = source; + } + + @Override public String toString() { return label; } + } + + public static final class Group { + public final Entry root; + public final List variants; + + Group(Entry root, List variants) { + this.root = root; + this.variants = variants; + } + @Override public String toString() { + return variants.size() > 1 ? root.label + " · " + variants.size() + " variants" : root.label; + } + } + + public static final class Index { + public final List entries; + public final List groups; + + Index(List entries, List groups) { + this.entries = entries; + this.groups = groups; + } + } + + static Index index(Definitions defs, GamevalManager.Handle gamevals) throws IOException { + var groups = new ArrayList(); + var definitions = new TreeMap(); + var transforms = new TreeMap(); + var entries = new ArrayList(); + var npcGamevals = byId(gamevals.getNpcs()); + var objectGamevals = byId(gamevals.getObjects()); + var spotanimGamevals = byId(gamevals.getSpotanims()); + var npcs = new NpcManager(defs.getStore()); + npcs.load(); + for (var npc : npcs.getNpcs()) { + boolean hasModel = npc.models != null && npc.models.length != 0; + if (npc.configs != null) + transforms.put(npc.id, npc.configs); + if (!hasModel && npc.configs == null) + continue; + var entry = new Entry(Category.NPCs, npc.id, npc.name, npcGamevals.get(npc.id), !hasModel ? null : () -> { + ModelDefinition model = loadParts(defs, npc.models); + if (model == null) + return null; + applyMaterials(model, npc.recolorToFind, npc.recolorToReplace, npc.retextureToFind, npc.retextureToReplace); + model.resize(npc.widthScale, npc.heightScale, npc.widthScale); + return ModelFactory.light(model, 64 + npc.ambient, 850 + npc.contrast); + }); + definitions.put(entry.id, entry); + } + groupTransforms(definitions, transforms, groups, entries); + definitions.clear(); + transforms.clear(); + + var factory = new ModelFactory(defs); + for (var object : defs.objects()) { + int id = object.getId(); + int[] destinations = object.getConfigChangeDest(); + if (destinations != null) + transforms.put(id, destinations); + int[] models = object.getObjectModels(); + boolean hasModel = models != null && models.length != 0; + if (!hasModel && destinations == null) + continue; + int[] types = object.getObjectTypes(); + int shape = types == null || types.length == 0 ? 10 : types[0]; + definitions.put(id, new Entry(Category.Objects, id, object.getName(), objectGamevals.get(id), + hasModel ? () -> factory.model(object, shape, 0) : null)); + } + groupTransforms(definitions, transforms, groups, entries); + + var store = defs.getStore(); + var archive = store.getIndex(IndexType.CONFIGS).getArchive(ConfigType.SPOTANIM.getId()); + if (archive != null) { + var files = archive.getFiles(store.getStorage().loadArchive(archive)); + var loader = new SpotAnimLoader(); + for (var file : files.getFiles()) { + var spot = loader.load(file.getFileId(), file.getContents()); + var entry = new Entry(Category.Graphics, spot.id, spot.debugName, spotanimGamevals.get(spot.id), () -> { + var model = defs.model(spot.modelId); + if (model == null) + return null; + applyMaterials(model, spot.recolorToFind, spot.recolorToReplace, spot.textureToFind, spot.textureToReplace); + model.resize(spot.resizeX, spot.resizeY, spot.resizeX); + for (int turns = Math.floorMod(spot.rotaton / 90, 4); turns > 0; turns--) + model.rotate1(); + return ModelFactory.light(model, 64 + spot.ambient, 850 + spot.contrast); + }); + entries.add(entry); + groups.add(new Group(entry, List.of(entry))); + } + } + entries.sort(Comparator.comparingInt(entry -> entry.id)); + groups.sort(Comparator.comparingInt(group -> group.root.id)); + return new Index(List.copyOf(entries), List.copyOf(groups)); + } + + private static Map> byId(Map gamevals) { + var names = new HashMap>(); + gamevals.forEach((name, id) -> names.computeIfAbsent(id, ignored -> new ArrayList<>()).add(name)); + return names; + } + + private static void groupTransforms(Map definitions, Map transforms, + List groups, List entries) { + var children = new HashSet(); + transforms.forEach((id, destinations) -> { + for (int destination : destinations) + if (destination >= 0 && destination != id) + children.add(destination); + }); + var covered = new HashSet(); + var selectable = new TreeMap(); + for (int id : transforms.keySet()) + if (!children.contains(id)) + addTransformGroup(id, definitions, transforms, covered, selectable, groups); + // A cycle can leave every transforming definition with an incoming edge. + for (int id : transforms.keySet()) + if (!covered.contains(id)) + addTransformGroup(id, definitions, transforms, covered, selectable, groups); + for (var entry : definitions.values()) { + if (entry.source != null) { + selectable.putIfAbsent(entry.id, entry); + if (!covered.contains(entry.id)) + groups.add(new Group(entry, List.of(entry))); + } + } + entries.addAll(selectable.values()); + } + + private static void addTransformGroup(int rootId, Map definitions, Map transforms, + Set covered, Map selectable, List groups) { + var seen = new LinkedHashSet(); + var pending = new ArrayDeque(); + pending.add(rootId); + while (!pending.isEmpty()) { + int id = pending.removeFirst(); + if (!seen.add(id)) + continue; + int[] destinations = transforms.get(id); + if (destinations != null) + for (int destination : destinations) + if (destination >= 0 && definitions.containsKey(destination)) + pending.addLast(destination); + } + covered.addAll(seen); + var variants = new ArrayList(); + for (int id : seen) { + var entry = definitions.get(id); + if (entry != null && entry.source != null) + variants.add(entry); + } + if (variants.isEmpty()) + return; + + var root = definitions.get(rootId); + if (root.source == null) { + var first = variants.get(0); + root = new Entry(root.category, root.id, root.name.equals("Unnamed") ? first.name : root.name, root.gamevals, first.source); + variants.add(0, root); + } + selectable.put(root.id, root); + groups.add(new Group(root, List.copyOf(variants))); + } + + private static ModelDefinition loadParts(Definitions defs, int[] ids) throws IOException { + var parts = new ModelDefinition[ids.length]; + for (int i = 0; i < ids.length; i++) { + parts[i] = defs.model(ids[i]); + if (parts[i] == null) + return null; + } + return parts.length == 1 ? parts[0] : ModelFactory.merge(parts); + } + + private static void applyMaterials(ModelDefinition model, short[] colors, short[] recolors, short[] textures, short[] retextures) { + if (colors != null && recolors != null) + for (int i = 0; i < Math.min(colors.length, recolors.length); i++) + model.recolor(colors[i], recolors[i]); + if (textures != null && retextures != null) + for (int i = 0; i < Math.min(textures.length, retextures.length); i++) + model.retexture(textures[i], retextures[i]); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/ColorPicker.java b/Tools/Dev/java/rs117/hd/dev/editor/ColorPicker.java new file mode 100644 index 0000000..780fd91 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/ColorPicker.java @@ -0,0 +1,329 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.function.Consumer; +import javax.swing.*; + +public final class ColorPicker extends JPanel { + private final float[] hsv = new float[3]; + private final JTextField[] inputs = new JTextField[4]; + private final Consumer apply; + private final Timer debounce; + private Color committed; + private boolean syncing; + private final JPanel sample = new JPanel(); + private final Gradient saturation = new Gradient(false); + private final Gradient hue = new Gradient(true); + + private ColorPicker(String paletteLabel, List palette, Color initial, Consumer apply, boolean manual) { + super(new BorderLayout(0, 8)); + this.apply = apply; + committed = new Color(initial.getRGB()); + debounce = manual ? null : new Timer(150, event -> commit()); + if (debounce != null) + debounce.setRepeats(false); + setOpaque(false); + setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + var controls = new JPanel(new BorderLayout(0, 8)); + controls.setOpaque(false); + controls.add(saturation); + hue.setPreferredSize(new Dimension(0, 16)); + controls.add(hue, BorderLayout.SOUTH); + add(controls); + + var footer = EditorPanels.stack(); + var fields = new JPanel(new BorderLayout(5, 0)); + fields.setOpaque(false); + sample.setPreferredSize(new Dimension(34, 0)); + sample.setBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true)); + fields.add(sample, BorderLayout.WEST); + var values = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gap 4, fillx", "[grow,fill][38!][38!][38!]")); + values.setOpaque(false); + String[] labels = {"HEX", "R", "G", "B"}; + for (int i = 0; i < inputs.length; i++) { + var column = new JPanel(new BorderLayout(0, 2)); + column.setOpaque(false); + var field = inputs[i] = new JTextField(); + field.setFont(WorkspaceStyle.MONO.deriveFont(11f)); + field.setForeground(WorkspaceStyle.TEXT); + field.setCaretColor(WorkspaceStyle.TEXT); + field.setBackground(WorkspaceStyle.INPUT); + field.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true), + BorderFactory.createEmptyBorder(3, 3, 3, 3))); + field.getAccessibleContext().setAccessibleName(labels[i]); + var caption = EditorText.builder(labels[i]).color(WorkspaceStyle.DIM).font(WorkspaceStyle.UI.deriveFont(10f)).build(); + caption.setLabelFor(field); + column.add(caption, BorderLayout.NORTH); + column.add(field); + int channel = i; + field.addActionListener(event -> { + if (readInput(channel, true).isPresent() && debounce != null) + commit(); + }); + EditorSearch.onChange(field, text -> { + if (!syncing && debounce != null) { + debounce.stop(); + if (parseInput(channel).isPresent()) + debounce.restart(); + } + }); + field.addFocusListener(new java.awt.event.FocusAdapter() { + @Override public void focusLost(java.awt.event.FocusEvent event) { + if (!event.isTemporary()) + readInput(channel, false); + } + }); + values.add(column); + } + fields.add(values); + footer.add(fields); + if (!palette.isEmpty()) { + footer.add(Box.createVerticalStrut(10)); + footer.add(EditorText.builder(paletteLabel).color(WorkspaceStyle.DIM).font(WorkspaceStyle.SEMIBOLD.deriveFont(10f)).build()); + var chips = new JPanel(new GridLayout(0, 10, 3, 3)); + chips.setOpaque(false); + for (Color color : palette) { + var chip = EditorButton.builder().style(WorkspaceStyle.Button.TAB).size(19, 19) + .icon(swatch(color, 19)).tooltip(hex(color)).onClick(() -> setColor(color)).build(); + chips.add(chip); + } + footer.add(chips); + } + if (manual) { + footer.add(Box.createVerticalStrut(6)); + footer.add(EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY).text("Apply") + .onClick(() -> apply.accept(currentInput())).build()); + } + add(footer, BorderLayout.SOUTH); + setColor(new Color(initial.getRGB())); + } + + private Color currentInput() { + var focus = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + for (int i = 0; i < inputs.length; i++) + if (focus == inputs[i]) + return parseInput(i).orElseGet(this::color); + return color(); + } + + private void commit() { + debounce.stop(); + Color next = currentInput(); + if (!next.equals(committed)) { + committed = next; + if (!next.equals(color())) + setColor(next); + apply.accept(next); + } + } + + public static Builder builder(AbstractButton trigger, java.util.function.Supplier initial) { + return new Builder(trigger, initial); + } + + public static final class Builder { + private final AbstractButton trigger; + private final java.util.function.Supplier initial; + private String paletteLabel = ""; + private java.util.function.Supplier> palette = List::of; + private Consumer action; + private boolean manual; + + private Builder(AbstractButton trigger, java.util.function.Supplier initial) { + this.trigger = trigger; + this.initial = initial; + } + + public Builder palette(String label, java.util.function.Supplier> colors) { + paletteLabel = label; + palette = colors; + return this; + } + + public Builder showApplyButton(boolean enabled) { manual = enabled; return this; } + public Builder onApply(Consumer action) { this.action = action; return this; } + + public void bind() { + Consumer callback = java.util.Objects.requireNonNull(action, "Provide a color apply action"); + boolean explicitApply = manual; + String label = paletteLabel; + var colors = palette; + PopupLayer.Handle[] popup = {null}; + trigger.addHierarchyListener(event -> { + if ((event.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0 + && !trigger.isShowing() && popup[0] != null) + popup[0].close(); + }); + trigger.addActionListener(event -> { + if (popup[0] != null) { + popup[0].close(); + return; + } + var picker = new ColorPicker(label, colors.get().stream().distinct().limit(20) + .collect(java.util.stream.Collectors.toList()), initial.get(), color -> { + if (explicitApply) + PopupLayer.select(popup[0], () -> callback.accept(color)); + else + callback.accept(color); + }, explicitApply); + var scroll = new EditorScrollPane(picker, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(null); + scroll.setOpaque(false); + scroll.getViewport().setOpaque(false); + popup[0] = PopupLayer.show(trigger, scroll, 248, 0, Integer.MAX_VALUE); + popup[0].onClose(() -> { + popup[0] = null; + if (picker.debounce != null && picker.debounce.isRunning()) { + if (trigger.isShowing()) + picker.commit(); + else + picker.debounce.stop(); + } + }); + }); + } + } + + public static String hex(Color color) { return String.format("#%06X", color.getRGB() & 0xffffff); } + + public static Icon swatch(Color color, int size) { + return new Icon() { + @Override public int getIconWidth() { return size; } + @Override public int getIconHeight() { return size; } + @Override public void paintIcon(Component component, Graphics graphics, int x, int y) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(color); + g.fillRoundRect(x, y, size, size, 7, 7); + g.setColor(new Color(255, 255, 255, 28)); + g.drawRoundRect(x, y, size - 1, size - 1, 7, 7); + g.dispose(); + } + }; + } + + private Color color() { return Color.getHSBColor(hsv[0], hsv[1], hsv[2]); } + + private void setColor(Color color) { + Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsv); + refresh(); + } + + private void refresh() { + Color color = color(); + sample.setBackground(color); + syncing = true; + inputs[0].setText(hex(color)); + inputs[1].setText(Integer.toString(color.getRed())); + inputs[2].setText(Integer.toString(color.getGreen())); + inputs[3].setText(Integer.toString(color.getBlue())); + syncing = false; + if (debounce != null && !color.equals(committed)) + debounce.restart(); + saturation.repaint(); + hue.repaint(); + } + + private java.util.Optional parseInput(int channel) { + String text = inputs[channel].getText().strip(); + Color current = color(); + try { + Color next; + if (channel == 0) { + if (!text.matches("#?[0-9a-fA-F]{6}")) + throw new IllegalArgumentException(); + next = new Color(Integer.parseInt(text.replace("#", ""), 16)); + } else { + int[] rgb = {current.getRed(), current.getGreen(), current.getBlue()}; + rgb[channel - 1] = Integer.parseInt(text); + next = new Color(rgb[0], rgb[1], rgb[2]); + } + return java.util.Optional.of(next); + } catch (IllegalArgumentException invalid) { + return java.util.Optional.empty(); + } + } + + private java.util.Optional readInput(int channel, boolean report) { + var result = parseInput(channel); + if (result.isPresent()) + setColor(result.get()); + else if (report) { + Toolkit.getDefaultToolkit().beep(); + inputs[channel].selectAll(); + } else + refresh(); + return result; + } + + private final class Gradient extends JComponent { + private final boolean hueOnly; + + Gradient(boolean hueOnly) { + this.hueOnly = hueOnly; + setPreferredSize(new Dimension(226, 140)); + setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); + var mouse = new MouseAdapter() { + @Override public void mousePressed(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) + move(event); + } + @Override public void mouseDragged(MouseEvent event) { + if ((event.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) + move(event); + } + }; + addMouseListener(mouse); + addMouseMotionListener(mouse); + } + + private void move(MouseEvent event) { + float x = Math.max(0, Math.min(1, (event.getX() - (hueOnly ? 3 : 6)) / (float) Math.max(1, getWidth() - (hueOnly ? 7 : 12)))); + if (hueOnly) { + hsv[0] = x; + } else { + hsv[1] = x; + hsv[2] = 1 - Math.max(0, Math.min(1, (event.getY() - 6) / (float) Math.max(1, getHeight() - 12))); + } + refresh(); + } + + @Override protected void paintComponent(Graphics graphics) { + int w = getWidth(), h = getHeight(); + if (w < 2 || h < 2) + return; + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + if (hueOnly) { + g.setPaint(new LinearGradientPaint(0, 0, w - 1, 0, + new float[]{0, 1f/6, 2f/6, 3f/6, 4f/6, 5f/6, 1}, + new Color[]{Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA, Color.RED})); + g.fillRoundRect(0, 3, w, h - 6, 10, 10); + int x = Math.round(hsv[0] * (w - 7)); + g.setColor(Color.WHITE); + g.fillRoundRect(x, 0, 7, h, 5, 5); + g.setColor(WorkspaceStyle.BORDER); + g.drawRoundRect(x, 0, 6, h - 1, 5, 5); + } else { + var plane = new java.awt.geom.RoundRectangle2D.Float(0, 0, w, h, 8, 8); + g.setPaint(new GradientPaint(0, 0, Color.WHITE, w - 1, 0, Color.getHSBColor(hsv[0], 1, 1))); + g.fill(plane); + g.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0), 0, h - 1, Color.BLACK)); + g.fill(plane); + int x = 6 + Math.round(hsv[1] * (w - 12)); + int y = 6 + Math.round((1 - hsv[2]) * (h - 12)); + g.setColor(Color.BLACK); + g.drawOval(x - 6, y - 6, 12, 12); + g.setColor(Color.WHITE); + g.setStroke(new BasicStroke(2)); + g.drawOval(x - 5, y - 5, 10, 10); + } + g.dispose(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/DashedAddButton.java b/Tools/Dev/java/rs117/hd/dev/editor/DashedAddButton.java new file mode 100644 index 0000000..cdf74e4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/DashedAddButton.java @@ -0,0 +1,26 @@ +package rs117.hd.dev.editor; + +import java.awt.Color; +import javax.swing.BorderFactory; +import javax.swing.JButton; + +public final class DashedAddButton { + private DashedAddButton() {} + + public static JButton create(String label, Runnable action) { + var button = create(label); + button.addActionListener(e -> action.run()); + return button; + } + + public static JButton create(String label) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.DASHED_ADD) + .icon("plus", 10).text(label).build(); + var padding = BorderFactory.createEmptyBorder(3, 9, 3, 9); + var border = BorderFactory.createCompoundBorder( + BorderFactory.createDashedBorder(new Color(0x4A4A4A), 3, 3), padding); + button.setBorderPainted(true); + button.setBorder(border); + return button; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorButton.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorButton.java new file mode 100644 index 0000000..29e4fc6 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorButton.java @@ -0,0 +1,105 @@ +package rs117.hd.dev.editor; + +import java.awt.Dimension; +import java.util.Objects; +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JToggleButton; + +/** Builds ordinary Swing buttons with the editor's shared appearance. */ +public final class EditorButton { + private EditorButton() {} + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private WorkspaceStyle.Button style = WorkspaceStyle.Button.SECONDARY; + private String text; + private Icon icon; + private String tooltip; + private boolean enabled = true; + private Dimension size; + private Runnable action; + private java.util.function.Consumer toggleAction; + + private Builder() {} + + public Builder style(WorkspaceStyle.Button style) { + this.style = Objects.requireNonNull(style); + return this; + } + + public Builder text(String text) { + this.text = text; + return this; + } + + public Builder icon(Icon icon) { + this.icon = icon; + return this; + } + + public Builder icon(String name, int size) { + return icon(WorkspaceStyle.icon(name, size)); + } + + public Builder tooltip(String tooltip) { + this.tooltip = tooltip; + return this; + } + + public Builder enabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + public Builder size(int width, int height) { + this.size = new Dimension(width, height); + return this; + } + + public Builder onClick(Runnable action) { + this.action = Objects.requireNonNull(action); + return this; + } + + /** Called after a user activates a toggle with its new selected state. */ + public Builder onToggle(java.util.function.Consumer action) { + this.toggleAction = Objects.requireNonNull(action); + return this; + } + + public JButton build() { + if (toggleAction != null) + throw new IllegalStateException("Use buildToggle() with onToggle()"); + return configure(new JButton()); + } + + public JToggleButton buildToggle(boolean selected) { + var button = configure(new JToggleButton()); + button.setSelected(selected); + var listener = toggleAction; + if (listener != null) + button.addActionListener(event -> listener.accept(button.isSelected())); + return button; + } + + private T configure(T button) { + WorkspaceStyle.button(button, style); + button.setText(text); + button.setIcon(icon); + button.setEnabled(enabled); + button.setToolTipText(tooltip); + if ((text == null || text.isEmpty()) && tooltip != null) + button.getAccessibleContext().setAccessibleName(tooltip); + if (size != null) + button.setPreferredSize(new Dimension(size)); + if (action != null) + button.addActionListener(event -> action.run()); + return button; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorButtonGroup.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorButtonGroup.java new file mode 100644 index 0000000..d0e9065 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorButtonGroup.java @@ -0,0 +1,84 @@ +package rs117.hd.dev.editor; + +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JPanel; +import javax.swing.JToggleButton; + +/** Content-width segmented buttons for toolbars and inline mode switches. */ +public final class EditorButtonGroup extends JPanel { + private final Map buttons = new LinkedHashMap<>(); + private final boolean track; + + private EditorButtonGroup(Builder builder) { + super(new FlowLayout(builder.track ? FlowLayout.LEFT : FlowLayout.RIGHT, builder.track ? 0 : 2, builder.track ? 3 : 0)); + track = builder.track; + setOpaque(false); + if (track) + setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); + + var group = new ButtonGroup(); + var onChange = builder.change; + for (T option : builder.options) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.SEGMENT) + .text(builder.label.apply(option)).onClick(() -> onChange.accept(option)) + .buildToggle(java.util.Objects.equals(option, builder.selected)); + if (track) + button.setForeground(WorkspaceStyle.DIM); + buttons.put(option, button); + group.add(button); + add(button); + } + } + + public JToggleButton button(T option) { return buttons.get(option); } + + public void setSelected(T option) { button(option).setSelected(true); } + + @Override protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + if (!track) + return; + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.MENU); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10); + g.dispose(); + } + + public static Builder builder(List options) { return new Builder<>(options); } + + public static final class Builder { + private final List options; + private T selected; + private java.util.function.Function label = String::valueOf; + private Consumer change = option -> {}; + private boolean track; + + private Builder(List options) { + this.options = List.copyOf(options); + if (options.isEmpty() || new java.util.HashSet<>(options).size() != options.size()) + throw new IllegalArgumentException("Provide distinct button options"); + selected = this.options.get(0); + } + + public Builder label(java.util.function.Function value) { label = value; return this; } + public Builder selected(T value) { selected = value; return this; } + public Builder onChange(Consumer action) { change = action; return this; } + public Builder track() { track = true; return this; } + + public EditorButtonGroup build() { + if (!options.contains(selected)) + throw new IllegalArgumentException("Select one of the button options"); + return new EditorButtonGroup<>(this); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorModal.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorModal.java new file mode 100644 index 0000000..882273c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorModal.java @@ -0,0 +1,141 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import javax.swing.*; + +/** Builds an editor dialog with an owner backdrop and Escape-to-close behavior. */ +public final class EditorModal { + private static final Color BACKDROP_TINT = new Color(10, 10, 10, 128); + private static final Color SHADOW_COLOR = new Color(0, 0, 0, 9); + + private EditorModal() {} + + public static Builder builder(JFrame owner, String title) { return new Builder(owner, title); } + + public static final class Builder { + private final JFrame owner; + private final String title; + private JComponent content; + private Dimension size; + private Integer topOffsetPercent; + private JComponent initialFocus; + + private Builder(JFrame owner, String title) { this.owner = owner; this.title = title; } + public Builder content(JComponent content) { this.content = content; return this; } + public Builder size(int width, int height) { size = new Dimension(width, height); return this; } + + public Builder topOffsetPercent(int percent) { topOffsetPercent = percent; return this; } + public Builder initialFocus(JComponent component) { initialFocus = component; return this; } + + public JDialog open() { + var dialog = build(); + dialog.setVisible(true); + if (initialFocus != null) + initialFocus.requestFocusInWindow(); + return dialog; + } + + public JDialog build() { + var dialog = create(owner, title); + if (content != null) + dialog.setContentPane(content); + if (size == null) + dialog.pack(); + else + dialog.setSize(size); + dialog.setLocationRelativeTo(owner); + if (topOffsetPercent != null) { + int x = owner.getX() + (owner.getWidth() - dialog.getWidth()) / 2; + int y = owner.getY() + owner.getHeight() * topOffsetPercent / 100; + dialog.setLocation(x, y); + } + return dialog; + } + } + + public static JDialog create(JFrame owner, String title) { + class BackdropDialog extends JDialog { + private JComponent backdrop; + private Component previousGlass; + private boolean previouslyVisible; + + BackdropDialog() { super(owner, title, Dialog.ModalityType.MODELESS); } + + @Override public void setVisible(boolean visible) { + if (visible && !isVisible() && backdrop != null && previousGlass == null) { + previousGlass = owner.getGlassPane(); + previouslyVisible = previousGlass.isVisible(); + owner.setGlassPane(backdrop); + backdrop.setVisible(true); + } + try { + super.setVisible(visible); + } finally { + if (!isVisible()) + restoreGlassPane(); + else if (backdrop != null) + backdrop.repaint(); + } + } + + @Override public void dispose() { + try { + super.dispose(); + } finally { + restoreGlassPane(); + } + } + + private void restoreGlassPane() { + if (previousGlass == null) + return; + backdrop.setVisible(false); + if (owner.getGlassPane() == backdrop) { + owner.setGlassPane(previousGlass); + previousGlass.setVisible(previouslyVisible); + owner.getRootPane().repaint(); + } + previousGlass = null; + } + } + var dialog = new BackdropDialog(); + dialog.setUndecorated(true); + dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + var backdrop = new JComponent() { + @Override protected void paintComponent(Graphics g) { + g.setColor(BACKDROP_TINT); + g.fillRect(0, 0, getWidth(), getHeight()); + if (!dialog.isVisible() || !isShowing()) + return; + var shadow = (Graphics2D) g.create(); + shadow.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + shadow.setColor(SHADOW_COLOR); + Point origin = getLocationOnScreen(); + int x = dialog.getX() - origin.x; + int y = dialog.getY() - origin.y + 12; + for (int spread = 28; spread > 0; spread -= 2) { + shadow.fillRoundRect(x - spread, y - spread, dialog.getWidth() + spread * 2, + dialog.getHeight() + spread * 2, 16 + spread * 2, 16 + spread * 2); + } + shadow.dispose(); + } + }; + backdrop.addMouseListener(new java.awt.event.MouseAdapter() { + @Override public void mousePressed(java.awt.event.MouseEvent e) { dialog.dispose(); } + }); + dialog.backdrop = backdrop; + dialog.getRootPane().setBorder(new javax.swing.border.LineBorder(WorkspaceStyle.BORDER, 1, true)); + dialog.addComponentListener(new java.awt.event.ComponentAdapter() { + @Override public void componentResized(java.awt.event.ComponentEvent e) { + if (dialog.getGraphicsConfiguration().getDevice().isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + dialog.setShape(new java.awt.geom.RoundRectangle2D.Float(0, 0, dialog.getWidth(), dialog.getHeight(), 16, 16)); + backdrop.repaint(); + } + }); + dialog.getContentPane().setBackground(WorkspaceStyle.MENU); + dialog.getRootPane().registerKeyboardAction(e -> dialog.dispose(), KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_IN_FOCUSED_WINDOW); + return dialog; + } + +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorPanels.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorPanels.java new file mode 100644 index 0000000..ed64c0a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorPanels.java @@ -0,0 +1,26 @@ +package rs117.hd.dev.editor; + +import java.awt.Component; +import java.awt.GridBagLayout; +import javax.swing.BoxLayout; +import javax.swing.JPanel; + +/** Layout containers for the editor's common transparent groups. */ +public final class EditorPanels { + private EditorPanels() {} + + public static JPanel centered(Component content) { + var panel = new JPanel(new GridBagLayout()); + panel.setOpaque(false); + panel.add(content); + return panel; + } + + public static JPanel stack() { + var panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.setOpaque(false); + return panel; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorPopup.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorPopup.java new file mode 100644 index 0000000..0487115 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorPopup.java @@ -0,0 +1,102 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.*; + +/** Floating utility window. Docked panels use WorkspaceDocks instead. */ +public final class EditorPopup { + private EditorPopup() {} + + public enum Anchor { CENTER, LEFT, RIGHT } + + public static Builder builder(Window owner, String title) { return new Builder(owner, title); } + + public static final class Builder { + private final Window owner; + private final String title; + private JComponent content = new JPanel(); + private Anchor anchor = Anchor.CENTER; + private Dimension size = new Dimension(420, 300); + private Dimension minimum = new Dimension(180, 100); + private boolean movable = true; + private boolean resizable = true; + + private Builder(Window owner, String title) { this.owner = owner; this.title = title; } + public Builder content(JComponent content) { this.content = content; return this; } + public Builder anchor(Anchor anchor) { this.anchor = anchor; return this; } + public Builder size(int width, int height) { size = new Dimension(width, height); return this; } + public Builder minimumSize(int width, int height) { minimum = new Dimension(width, height); return this; } + public Builder movable(boolean value) { movable = value; return this; } + public Builder resizable(boolean value) { resizable = value; return this; } + + public JDialog build() { + var dialog = new JDialog(owner, title); + dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + dialog.setIconImages(EditorSplash.appIcons()); + dialog.setUndecorated(!movable); + dialog.setResizable(resizable); + dialog.setMinimumSize(minimum); + if (movable) { + dialog.setContentPane(content); + } else { + var root = new JPanel(new BorderLayout()); + root.setBackground(WorkspaceStyle.PANEL); + root.setBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER)); + var header = new JPanel(new BorderLayout()); + header.setBackground(WorkspaceStyle.HEADER); + header.add(EditorText.builder(title).font(WorkspaceStyle.SEMIBOLD) + .border(BorderFactory.createEmptyBorder(0, 8, 0, 0)).build()); + header.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB) + .icon("close", 12).tooltip("Close").size(24, 24).onClick(dialog::dispose).build(), BorderLayout.EAST); + root.add(header, BorderLayout.NORTH); + root.add(content); + if (resizable) + root.add(resizeHandle(dialog), BorderLayout.SOUTH); + dialog.setContentPane(root); + } + dialog.setSize(Math.max(size.width, minimum.width), Math.max(size.height, minimum.height)); + dialog.setLocationRelativeTo(owner); + if (owner != null && anchor != Anchor.CENTER) { + Rectangle bounds = owner.getBounds(); + dialog.setLocation(anchor == Anchor.LEFT ? bounds.x : bounds.x + bounds.width - dialog.getWidth(), dialog.getY()); + } + return dialog; + } + } + + private static JComponent resizeHandle(JDialog dialog) { + var handle = new JLabel(WorkspaceStyle.icon("grip", 10), SwingConstants.RIGHT); + handle.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); + var drag = new MouseAdapter() { + private Point origin; + private Dimension size; + + @Override public void mousePressed(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) { + origin = event.getLocationOnScreen(); + size = dialog.getSize(); + } + } + + @Override public void mouseDragged(MouseEvent event) { + if (origin == null) + return; + var min = dialog.getMinimumSize(); + dialog.setSize(Math.max(min.width, size.width + event.getXOnScreen() - origin.x), + Math.max(min.height, size.height + event.getYOnScreen() - origin.y)); + } + + @Override public void mouseReleased(MouseEvent event) { origin = null; } + }; + handle.addMouseListener(drag); + handle.addMouseMotionListener(drag); + return handle; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorScrollPane.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorScrollPane.java new file mode 100644 index 0000000..1c26b63 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorScrollPane.java @@ -0,0 +1,75 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import javax.swing.*; +import javax.swing.plaf.basic.BasicScrollBarUI; + +/** Scroll panes with the editor's arrow buttons and rounded thumb. */ +public class EditorScrollPane extends JScrollPane { + public EditorScrollPane(Component view) { + this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); + } + + public EditorScrollPane(Component view, int verticalPolicy, int horizontalPolicy) { + super(view, verticalPolicy, horizontalPolicy); + getVerticalScrollBar().setUI(new ScrollBarStyle()); + getHorizontalScrollBar().setUI(new ScrollBarStyle()); + } + + private static final class ScrollBarStyle extends BasicScrollBarUI { + private static final int WIDTH = 15; + private static final Color TRACK = new Color(0x292929); + private static final Color THUMB = new Color(0xA0A0A0); + + @Override public Dimension getPreferredSize(JComponent component) { + return new Dimension(WIDTH, WIDTH); + } + + @Override protected Dimension getMinimumThumbSize() { + return scrollbar.getOrientation() == JScrollBar.VERTICAL ? new Dimension(WIDTH, 20) : new Dimension(20, WIDTH); + } + + @Override protected JButton createDecreaseButton(int direction) { return arrow(direction); } + @Override protected JButton createIncreaseButton(int direction) { return arrow(direction); } + + @Override protected void paintTrack(Graphics graphics, JComponent component, Rectangle bounds) { + graphics.setColor(TRACK); + graphics.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); + } + + @Override protected void paintThumb(Graphics graphics, JComponent component, Rectangle bounds) { + if (bounds.isEmpty() || !scrollbar.isEnabled()) + return; + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(isDragging || isThumbRollover() ? new Color(0xB8B8B8) : THUMB); + int xInset = scrollbar.getOrientation() == JScrollBar.VERTICAL ? 3 : 0; + int yInset = xInset == 0 ? 3 : 0; + g.fillRoundRect(bounds.x + xInset, bounds.y + yInset, bounds.width - 2 * xInset, bounds.height - 2 * yInset, 9, 9); + g.dispose(); + } + + private static JButton arrow(int direction) { + var button = new JButton() { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(getModel().isRollover() ? new Color(0x353535) : TRACK); + g.fillRect(0, 0, getWidth(), getHeight()); + g.translate(getWidth() / 2.0, getHeight() / 2.0); + int quarterTurns = direction == SwingConstants.NORTH ? 0 : direction == SwingConstants.EAST ? 1 + : direction == SwingConstants.SOUTH ? 2 : 3; + g.rotate(quarterTurns * Math.PI / 2); + g.setColor(THUMB); + g.fillPolygon(new int[] {-4, 0, 4}, new int[] {3, -3, 3}, 3); + g.dispose(); + } + }; + button.setPreferredSize(new Dimension(WIDTH, WIDTH)); + button.setBorderPainted(false); + button.setFocusable(false); + button.setRolloverEnabled(true); + return button; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorSearch.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorSearch.java new file mode 100644 index 0000000..b5da06d --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorSearch.java @@ -0,0 +1,79 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.util.function.Consumer; +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +/** A search box with the shared icon, placeholder, and editor typography. */ +public final class EditorSearch extends JPanel { + private final JTextField field; + + private EditorSearch(Builder builder) { + super(new BorderLayout(builder.gap, 0)); + setBackground(builder.background); + setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(builder.outline, 1, true), + BorderFactory.createEmptyBorder(0, builder.left, 0, builder.right))); + if (builder.height > 0) + setPreferredSize(new Dimension(0, builder.height)); + field = WorkspaceStyle.search(builder.placeholder); + field.setOpaque(false); + field.setForeground(builder.foreground); + field.setCaretColor(WorkspaceStyle.TEXT); + field.setFont(WorkspaceStyle.UI.deriveFont(builder.fontSize)); + field.setBorder(BorderFactory.createEmptyBorder(0, builder.textInset, 0, builder.textInset)); + if (builder.fieldHeight > 0) + field.setPreferredSize(new Dimension(10, builder.fieldHeight)); + field.getAccessibleContext().setAccessibleName(builder.placeholder); + add(new JLabel(WorkspaceStyle.icon("search", 12)), BorderLayout.WEST); + add(field); + } + + public JTextField field() { return field; } + + public static Builder builder(String placeholder) { return new Builder(placeholder); } + + public static void onChange(JTextField field, Consumer listener) { + field.getDocument().addDocumentListener(new DocumentListener() { + @Override public void insertUpdate(DocumentEvent event) { listener.accept(field.getText()); } + @Override public void removeUpdate(DocumentEvent event) { listener.accept(field.getText()); } + @Override public void changedUpdate(DocumentEvent event) { listener.accept(field.getText()); } + }); + } + + public static final class Builder { + private final String placeholder; + private Color background = WorkspaceStyle.INPUT; + private Color outline = WorkspaceStyle.BORDER; + private Color foreground = WorkspaceStyle.TEXT; + private int gap = 6, left = 6, right = 6, height, fieldHeight, textInset; + private float fontSize = 12f; + private Consumer listener; + + private Builder(String placeholder) { this.placeholder = placeholder; } + + public Builder background(Color value) { background = value; return this; } + public Builder outline(Color value) { outline = value; return this; } + public Builder foreground(Color value) { foreground = value; return this; } + public Builder gap(int value) { gap = value; return this; } + public Builder padding(int start, int end) { left = start; right = end; return this; } + public Builder height(int value) { height = value; return this; } + public Builder fieldHeight(int value) { fieldHeight = value; return this; } + public Builder textInset(int value) { textInset = value; return this; } + public Builder fontSize(float value) { fontSize = value; return this; } + public Builder onChange(Consumer action) { listener = action; return this; } + + public EditorSearch build() { + var search = new EditorSearch(this); + if (listener != null) + EditorSearch.onChange(search.field, listener); + return search; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorSection.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorSection.java new file mode 100644 index 0000000..fef7983 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorSection.java @@ -0,0 +1,106 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.function.Consumer; +import javax.swing.*; +import javax.swing.border.Border; + +public final class EditorSection extends JPanel { + private final JPanel body; + private final JPanel header; + private final JLabel chevron; + private final Consumer onToggle; + private final boolean collapsible; + + private EditorSection(Builder builder) { + super(); + body = builder.body; + onToggle = builder.onToggle; + collapsible = builder.collapsible; + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setOpaque(false); + setAlignmentX(Component.LEFT_ALIGNMENT); + var title = EditorText.builder(builder.title).font(WorkspaceStyle.SEMIBOLD).color(builder.titleColor).build(); + header = new JPanel(new BorderLayout(6, 0)); + header.setBackground(WorkspaceStyle.HEADER); + header.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, builder.dividerColor), + BorderFactory.createEmptyBorder(4, 10, 4, 10))); + header.setMaximumSize(new Dimension(Integer.MAX_VALUE, 28)); + header.setAlignmentX(Component.LEFT_ALIGNMENT); + header.add(title); + chevron = new JLabel("", SwingConstants.CENTER); + chevron.setPreferredSize(new Dimension(16, 20)); + if (collapsible) { + header.add(chevron, BorderLayout.WEST); + header.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + var toggle = new MouseAdapter() { + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) + setExpanded(!body.isVisible()); + } + }; + header.addMouseListener(toggle); + title.addMouseListener(toggle); + chevron.addMouseListener(toggle); + } + body.setBorder(builder.bodyBorder); + add(header); + add(body); + updateExpanded(!collapsible || builder.expanded); + } + + public JPanel content() { return body; } + public JPanel header() { return header; } + public boolean isExpanded() { return body.isVisible(); } + + public void setExpanded(boolean expanded) { + if (!collapsible || isExpanded() == expanded) + return; + updateExpanded(expanded); + if (onToggle != null) + onToggle.accept(expanded); + } + + private void updateExpanded(boolean expanded) { + body.setVisible(expanded); + chevron.setIcon(WorkspaceStyle.icon(expanded ? "chevron-down" : "chevron-right", 9)); + revalidate(); + repaint(); + } + + public static Builder builder(String title) { return new Builder(title); } + + public static final class Builder { + private final String title; + private JPanel body = new JPanel(); + private Border bodyBorder = BorderFactory.createEmptyBorder(2, 4, 6, 0); + private Color titleColor = new Color(0x9A9A9A); + private Color dividerColor = WorkspaceStyle.BORDER; + private Consumer onToggle; + private boolean collapsible = true; + private boolean expanded = true; + + private Builder(String title) { + this.title = title; + body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); + body.setOpaque(false); + } + + public Builder content(JPanel body) { this.body = body; return this; } + public Builder add(JComponent child) { body.add(child); return this; } + public Builder bodyBorder(Border border) { bodyBorder = border; return this; } + public Builder titleColor(Color color) { titleColor = color; return this; } + public Builder dividerColor(Color color) { dividerColor = color; return this; } + public Builder collapsible(boolean value) { collapsible = value; return this; } + public Builder expanded(boolean value) { expanded = value; return this; } + public Builder onToggle(Consumer action) { onToggle = action; return this; } + public EditorSection build() { return new EditorSection(this); } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorSelect.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorSelect.java new file mode 100644 index 0000000..6e4d7aa --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorSelect.java @@ -0,0 +1,92 @@ +package rs117.hd.dev.editor; + +import java.awt.Dimension; +import javax.swing.*; + +/** Shared dropdown chrome. The caller supplies the model and row renderer. */ +public final class EditorSelect { + private EditorSelect() {} + + public static Builder builder() { return new Builder<>(); } + + public static final class Builder { + private ComboBoxModel model = new DefaultComboBoxModel<>(); + private ListCellRenderer renderer; + private java.util.function.Consumer onChange; + private Dimension size; + private boolean enabled = true; + private String tooltip; + private T selection; + private boolean hasSelection; + + private Builder() {} + public Builder model(ComboBoxModel model) { this.model = model; return this; } + + public Builder options(java.util.Collection options) { + var values = new DefaultComboBoxModel(); + options.forEach(values::addElement); + return model(values); + } + + public Builder renderer(ListCellRenderer renderer) { this.renderer = renderer; return this; } + public Builder selected(T value) { selection = value; hasSelection = true; return this; } + public Builder enabled(boolean enabled) { this.enabled = enabled; return this; } + public Builder size(int width, int height) { size = new Dimension(width, height); return this; } + public Builder tooltip(String tooltip) { this.tooltip = tooltip; return this; } + public Builder onChange(java.util.function.Consumer action) { onChange = action; return this; } + + public JComboBox build() { + var selector = new JComboBox<>(model); + style(selector); + if (renderer != null) + selector.setRenderer(renderer); + if (hasSelection) + selector.setSelectedItem(selection); + if (size != null) + selector.setPreferredSize(new Dimension(size)); + selector.setToolTipText(tooltip); + selector.setEnabled(enabled); + if (onChange != null) + selector.addItemListener(event -> { + if (event.getStateChange() == java.awt.event.ItemEvent.SELECTED) + onChange.accept(selector.getItemAt(selector.getSelectedIndex())); + }); + return selector; + } + } + + public static void style(JComboBox selector) { + selector.setUI(new javax.swing.plaf.basic.BasicComboBoxUI() { + @Override protected JButton createArrowButton() { + var button = new JButton(WorkspaceStyle.icon("chevron-down", 10)); + button.setOpaque(false); + button.setContentAreaFilled(false); + button.setBorderPainted(false); + button.setFocusable(false); + button.setPreferredSize(new Dimension(24, 24)); + return button; + } + + @Override public void paintCurrentValueBackground(java.awt.Graphics graphics, java.awt.Rectangle bounds, boolean focus) { + // The field paints its background across the value and arrow. + } + + @Override public void paint(java.awt.Graphics graphics, JComponent component) { + var g = (java.awt.Graphics2D) graphics.create(); + g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON); + int width = component.getWidth() - 1; + int height = component.getHeight() - 1; + g.setColor(WorkspaceStyle.INPUT); + g.fillRoundRect(0, 0, width, height, 8, 8); + g.setColor(selector.isPopupVisible() ? WorkspaceStyle.ACCENT : WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, width, height, 8, 8); + g.dispose(); + super.paint(graphics, component); + } + }); + selector.setOpaque(false); + selector.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); + selector.setMinimumSize(new Dimension(0, 24)); + selector.setPreferredSize(new Dimension(150, 24)); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorSession.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorSession.java new file mode 100644 index 0000000..0db23c3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorSession.java @@ -0,0 +1,165 @@ +package rs117.hd.dev.editor; + +import java.awt.Canvas; +import java.io.IOException; +import java.nio.file.Path; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import javax.swing.JWindow; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.WorldView; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.standalone.HdRuntime; +import rs117.hd.dev.sceneloader.standalone.HdSettings; +import rs117.hd.dev.sceneloader.standalone.Textures; + +/** Owns the standalone editor's cache and OpenGL context for the lifetime of its window. */ +@Slf4j +public final class EditorSession implements AutoCloseable { + private final Canvas canvas = new Canvas(); + private final JWindow renderHost = new JWindow(); + private final CompletableFuture preview = new CompletableFuture<>(); + private final Thread worker; + private Definitions definitions; + private Textures textures; + private volatile CacheModels.Index modelCatalog; + + @FunctionalInterface + public interface Preview { + void run(HdRuntime runtime, BuiltScene scene) throws InterruptedException; + } + + EditorSession(Consumer progress, Consumer onReady, Consumer onFailure) { + canvas.setIgnoreRepaint(true); + renderHost.setFocusableWindowState(false); + renderHost.add(canvas); + renderHost.setBounds(-4096, -4096, 640, 560); + renderHost.setVisible(true); + worker = new Thread(() -> run(progress, onReady, onFailure), "117HD editor renderer"); + worker.start(); + } + + public int[] vanillaTexturePixels(int textureId) { + return textures.get(textureId, 1.0); + } + + public CacheModels.Index modelCatalog() { + return modelCatalog; + } + + /** Rebuilds the shared catalog on the thread that owns the cache. */ + public CacheModels.Index refreshModelCatalog(HdRuntime runtime) throws IOException { + if (Thread.currentThread() != worker) + throw new IllegalStateException("Cache refresh must run on the editor renderer thread"); + try (var gamevals = runtime.openGamevals()) { + modelCatalog = CacheModels.index(definitions, gamevals); + return modelCatalog; + } + } + + public net.runelite.cache.region.Location findObjectPlacement(int id, java.util.function.BooleanSupplier active) { + return definitions.findObjectPlacement(id, active); + } + + public BuiltScene buildPreviewScene(int x, int y, int id, net.runelite.cache.region.Location focus, boolean showOthers, boolean showAll) throws IOException { + return new SceneBuilder(definitions).buildPreview(x, y, WorldView.TOPLEVEL, location -> { + if (focus != null && location.getId() == id && location.getPosition().equals(focus.getPosition()) + && location.getType() == focus.getType() && location.getOrientation() == focus.getOrientation()) + return false; + return location.getId() == id ? showAll : showOthers; + }); + } + + public net.runelite.cache.region.Position findWaterPlacement(String name, HdRuntime runtime, + java.util.function.BooleanSupplier active) { + return definitions.findWaterPlacement(name, runtime.tileOverrides(), runtime.terrain(), active); + } + + public BuiltScene buildTerrainPreview(int x, int y, boolean showObjects) throws IOException { + return new SceneBuilder(definitions).buildPreview(x, y, WorldView.TOPLEVEL, location -> showObjects); + } + + public void clearPreviewCaches() { + definitions.clearPreviewCaches(); + } + + void attachPreview(Preview task) { + preview.complete(task); + } + + @Override public void close() { + worker.interrupt(); + } + + private void run(Consumer progress, Consumer onReady, Consumer onFailure) { + try { + step(progress, "Opening the game cache"); + String cache = System.getProperty("rlhd.editor-cache"); + try (var opened = new Definitions(cache == null ? Definitions.findDefaultCache() : Path.of(cache), true)) { + definitions = opened; + var settings = new HdSettings(); + settings.set("daylightCycle", "DAY"); + settings.set("shadowMode", "OFF"); + settings.set("hideUnrelatedAreas", "false"); + textures = new Textures(opened); + var runtime = new HdRuntime(canvas, opened, textures, settings); + try { + step(progress, "Starting the 117 HD renderer"); + runtime.setPreviewSky(0x2C2C2C); + runtime.start(); + var scene = new BuiltScene(3200, 3200, WorldView.TOPLEVEL, new int[0]); + runtime.setScene(scene); + + step(progress, "Warming up the preview"); + warmUp(runtime); + + step(progress, "Indexing NPCs, objects and graphics"); + refreshModelCatalog(runtime); + step(progress, "Opening the editor"); + SwingUtilities.invokeLater(() -> { + try { + onReady.accept(this); + } catch (RuntimeException e) { + close(); + onFailure.accept(e); + } + }); + preview.get().run(runtime, scene); + } finally { + Thread.interrupted(); + runtime.stop(); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + log.error("Could not start the standalone editor", e); + SwingUtilities.invokeLater(() -> onFailure.accept(e)); + } finally { + SwingUtilities.invokeLater(renderHost::dispose); + } + } + + private static void warmUp(HdRuntime runtime) throws IOException, InterruptedException { + long deadline = System.nanoTime() + 30_000_000_000L; + float[] camera = {52 * 128f + 200, -140, 52 * 128f - 200}; + int readyFrames = 0; + while (readyFrames < 2) { + runtime.frameModelPreview(camera, .55f, .30f); + if (runtime.getPlugin().isPluginStopPending()) + throw new IOException("The 117 HD renderer stopped during startup"); + if (runtime.isReady()) + readyFrames++; + else if (System.nanoTime() >= deadline) + throw new IOException("Timed out waiting for the 117 HD renderer"); + Thread.sleep(8); + } + } + + private static void step(Consumer progress, String message) { + SwingUtilities.invokeLater(() -> progress.accept(message)); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorShell.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorShell.java new file mode 100644 index 0000000..a28241d --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorShell.java @@ -0,0 +1,141 @@ +package rs117.hd.dev.editor; + +import com.google.gson.JsonObject; +import java.awt.CardLayout; +import java.util.concurrent.atomic.AtomicReference; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; +import rs117.hd.dev.overrides.ModelOverridesScreen; + +/** The 117 HD Editor's top-level window: tab switching, undo/redo, autosave and command search, shared across workspaces. */ +public final class EditorShell extends EditorWindow { + private static final String[] TAB_KEYS = { "overrides", "lights", "defs" }; + private static final String[] TAB_LABELS = { "Model Overrides", "Lights", "Definitions" }; + + private final CardLayout cards = new CardLayout(); + private final JPanel body = new JPanel(cards); + private String activeTab = "overrides"; + private ModelOverridesScreen overrides; + private rs117.hd.dev.definitions.DefinitionsScreen definitions; + + public static void main(String[] args) { + SwingUtilities.invokeLater(EditorShell::launch); + } + + private static void launch() { + net.runelite.client.ui.laf.RuneLiteLAF.setup(); + var window = new AtomicReference(); + var splash = new EditorSplash(() -> window.get().setVisible(true), EditorShell::launch, () -> System.exit(0)); + splash.setVisible(true); + new EditorSession(splash::step, session -> { + var shell = new EditorShell(session); + shell.addNotify(); + shell.validate(); + window.set(shell); + shell.overrides.whenInitialPreviewReady(splash::finish); + session.attachPreview((runtime, scene) -> shell.overrides.render(runtime, scene, shell.definitions)); + }, error -> { + splash.step("Could not open the editor · " + error.getMessage()); + splash.fail(); + }); + } + + private EditorShell(EditorSession session) { + setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + + overrides = new ModelOverridesScreen(this, session); + body.add(overrides, "overrides"); + body.add(stub("Lights"), "lights"); + definitions = new rs117.hd.dev.definitions.DefinitionsScreen(); + body.add(definitions, "defs"); + + var status = EditorText.builder("").color(WorkspaceStyle.DIM).build(); + status.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 10, 4, 10)); + status.setOpaque(true); + status.setBackground(WorkspaceStyle.BAR); + + var actions = new WorkspaceActions(this, this::captureState, this::restoreState, status); + actions.addCommandSource(() -> java.util.List.of( + new WorkspaceActions.Command("Window", "Go to Model Overrides", "", () -> showTab("overrides")), + new WorkspaceActions.Command("File", "Save model overrides", "", this::saveOverrides))); + actions.reset("Model overrides"); + overrides.onSelectionChanged(() -> { + String label = overrides.selectedOverrideLabel(); + if (label != null) + actions.reset(label); + }); + + var tabButtons = new java.util.ArrayList(); + for (int i = 0; i < TAB_KEYS.length; i++) { + String key = TAB_KEYS[i]; + boolean ready = !key.equals("lights"); + var button = EditorButton.builder().style(WorkspaceStyle.Button.TAB).text(TAB_LABELS[i]).enabled(ready) + .onClick(() -> selectTab(key, tabButtons)).build(); + button.setSelected(key.equals("overrides")); + if (!ready) + WorkspaceStyle.soon(button); + tabButtons.add(button); + } + + var saves = new JPanel(); + saves.setOpaque(false); + + var sidebarToggle = EditorButton.builder().icon("panel-browser", 16).tooltip("Show/hide the left column") + .size(28, 24).buildToggle(true); + sidebarToggle.addActionListener(e -> overrides.setSidebarVisible(sidebarToggle.isSelected())); + + var toolbar = editorToolbar(sidebarToggle, actions.toolbar(), saves, compact -> {}, + tabButtons.toArray(new javax.swing.JButton[0])); + toolbar.setPreferredSize(new java.awt.Dimension(0, 40)); + toolbar.setBorder(javax.swing.BorderFactory.createEmptyBorder(8, 10, 8, 10)); + toolbar.setBackground(WorkspaceStyle.MENU); + installEditorContent(toolbar, body, status); + + addWindowListener(new java.awt.event.WindowAdapter() { + @Override public void windowOpened(java.awt.event.WindowEvent e) { actions.start(); } + @Override public void windowIconified(java.awt.event.WindowEvent e) { updatePreviewVisibility(false); } + @Override public void windowDeiconified(java.awt.event.WindowEvent e) { updatePreviewVisibility(true); } + @Override public void windowClosing(java.awt.event.WindowEvent e) { + if (definitions.confirmClose()) + dispose(); + } + @Override public void windowClosed(java.awt.event.WindowEvent e) { + actions.stop(); + session.close(); + } + }); + } + + private void showTab(String key) { + activeTab = key; + cards.show(body, key); + updatePreviewVisibility((getExtendedState() & ICONIFIED) == 0); + } + + private void updatePreviewVisibility(boolean visible) { + overrides.setPreviewActive(visible && "overrides".equals(activeTab)); + definitions.setPreviewActive(visible && "defs".equals(activeTab)); + } + + private void selectTab(String key, java.util.List tabButtons) { + for (int i = 0; i < TAB_KEYS.length; i++) + tabButtons.get(i).setSelected(TAB_KEYS[i].equals(key)); + showTab(key); + } + + private JsonObject captureState() { return ModelOverridesScreen.capture(overrides); } + + private void restoreState(JsonObject state) { ModelOverridesScreen.restore(overrides, state); } + + private void saveOverrides() { ModelOverridesScreen.saveSelected(overrides); } + + private static JPanel stub(String name) { + var panel = new JPanel(new java.awt.BorderLayout()); + panel.setBackground(WorkspaceStyle.GAP); + var label = EditorText.builder(name + " isn't built yet").color(WorkspaceStyle.DIM).build(); + label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); + panel.add(label); + return panel; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorSplash.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorSplash.java new file mode 100644 index 0000000..9a78b46 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorSplash.java @@ -0,0 +1,266 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.font.TextAttribute; +import java.awt.geom.RoundRectangle2D; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import javax.swing.*; + +public final class EditorSplash extends JWindow { + private static final int WIDTH = 640; + private static final int HEIGHT = 400; + private static final int STEP_COUNT = 6; + // These are repainted at 60Hz for the duration of startup, so the fixed parts of the look are cached once. + private static final Font TITLE_FONT = WorkspaceStyle.SEMIBOLD.deriveFont(11f).deriveFont(Map.of(TextAttribute.TRACKING, .32f)); + private static final Color GLOW_BLUE = new Color(79, 182, 255, 26); + private static final Color GLOW_ORANGE = new Color(255, 165, 61, 26); + private static final Color DIVIDER_COLOR = new Color(0x222222); + private static final Color VERSION_COLOR = new Color(0x6A6A6A); + private static final Color STATUS_OK_COLOR = new Color(0x6CB348); + private static final Color STATUS_ERROR_COLOR = new Color(0xE06060); + private static final Color STATUS_TEXT_COLOR = new Color(0xD6D6D6); + private static final Color STEP_COUNT_COLOR = new Color(0x7D7D7D); + private static final Color STEP_HISTORY_COLOR = new Color(0x5F5F5F); + private static final Color ERROR_BORDER_COLOR = new Color(0x3A2626); + private static final Color[] PROGRESS_FILL_COLORS = { new Color(0x4FB6FF), new Color(0xECE7DF), new Color(0xFFA53D) }; + private static final Color[] SHIMMER_COLORS = { new Color(255, 255, 255, 0), new Color(255, 255, 255, 89), new Color(255, 255, 255, 0) }; + private static final RoundRectangle2D PROGRESS_TRACK = new RoundRectangle2D.Double(32, 323, 576, 4, 4, 4); + private final Image logo = image("icons/editor-icon-256.png"); + private final Image wordmark = image("117hd-wordmark.png"); + private final String version = buildVersion(); + private final List completed = new ArrayList<>(); + private final long started = System.nanoTime(); + private final Timer animation = new Timer(16, e -> tick()); + private final Runnable openEditor; + private final Runnable retry; + private final Runnable closeEditor; + private final JPanel card = new JPanel(null) { + @Override protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + paintCard(graphics); + } + }; + + private String status = ""; + private int step; + private boolean failed; + private long transition; + private long readyAt; + private boolean editorShown; + private double from; + private double progress; + + public EditorSplash(Runnable openEditor, Runnable retry, Runnable closeEditor) { + this.openEditor = openEditor; + this.retry = retry; + this.closeEditor = closeEditor; + setIconImages(appIcons()); + setSize(WIDTH, HEIGHT); + setLocationRelativeTo(null); + setAlwaysOnTop(true); + if (supports(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) + setShape(new RoundRectangle2D.Double(0, 0, WIDTH, HEIGHT, 20, 20)); + card.setBackground(new Color(0x161616)); + setContentPane(card); + var drag = new java.awt.event.MouseAdapter() { + private Point pressed; + @Override public void mousePressed(java.awt.event.MouseEvent e) { pressed = e.getPoint(); } + @Override public void mouseDragged(java.awt.event.MouseEvent e) { + if (pressed != null) + setLocation(e.getXOnScreen() - pressed.x, e.getYOnScreen() - pressed.y); + } + }; + card.setCursor(WorkspaceStyle.cursor("grab")); + card.addMouseListener(drag); + card.addMouseMotionListener(drag); + animation.start(); + } + + public static List appIcons() { + var images = new ArrayList(); + for (int size : new int[] {16, 24, 32, 48, 64, 128, 256, 512}) + images.add(image("icons/editor-icon-" + size + ".png")); + return images; + } + + private static Image image(String name) { + return new ImageIcon(EditorSplash.class.getResource("/rs117/hd/dev/editor/" + name)).getImage(); + } + + private static String buildVersion() { + var properties = new Properties(); + try (var stream = EditorSplash.class.getResourceAsStream("/rs117/hd/dev/editor/editor-build.properties")) { + if (stream != null) + properties.load(stream); + } catch (IOException ignored) { + } + String value = properties.getProperty("version"); + return value == null ? "dev build" : "v" + value + " · dev build"; + } + + public void step(String message) { + if (!status.isEmpty()) + completed.add(status); + status = message; + step = Math.min(step + 1, STEP_COUNT); + from = progress; + transition = System.nanoTime(); + } + + public void finish() { + step("Ready"); + readyAt = Math.max(started + 600_000_000L, System.nanoTime() + 800_000_000L); + } + + public void fail() { + failed = true; + var retryButton = new JButton("Retry"); + WorkspaceStyle.button(retryButton, WorkspaceStyle.Button.PRIMARY); + retryButton.setBounds(542, 312, 58, 24); + retryButton.addActionListener(e -> { + dispose(); + retry.run(); + }); + card.add(retryButton); + var close = new JButton("Close"); + WorkspaceStyle.button(close, WorkspaceStyle.Button.SECONDARY); + close.setBounds(474, 312, 62, 24); + close.addActionListener(e -> { + dispose(); + closeEditor.run(); + }); + card.add(close); + card.repaint(); + } + + private void tick() { + long now = System.nanoTime(); + double t = Math.min(1, (now - transition) / 500_000_000.0); + progress = from + (step / (double) STEP_COUNT - from) * (1 - Math.pow(1 - t, 3)); + if (readyAt != 0 && now >= readyAt) { + if (!editorShown) { + editorShown = true; + openEditor.run(); + } + float fade = (now - readyAt) / 150_000_000f; + if (fade >= 1 || !supports(GraphicsDevice.WindowTranslucency.TRANSLUCENT)) { + dispose(); + return; + } + setOpacity(1 - fade); + } + card.repaint(); + } + + private boolean supports(GraphicsDevice.WindowTranslucency mode) { + return getGraphicsConfiguration().getDevice().isWindowTranslucencySupported(mode); + } + + @Override public void dispose() { + animation.stop(); + super.dispose(); + } + + private void paintCard(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + double seconds = (System.nanoTime() - started) / 1e9; + glow(g, -120, 40, 420, 320, GLOW_BLUE); + glow(g, 340, 40, 420, 320, GLOW_ORANGE); + double pulse = failed ? 0 : (1 - Math.cos(seconds * Math.PI * 2 / 2.4)) / 2; + double glowScale = .92 + .13 * pulse; + glow(g, 320 - 80 * glowScale, 72 - 70 * glowScale, 160 * glowScale, 140 * glowScale, + new Color(255, 190, 110, (int) (45 + pulse * 37))); + g.drawImage(logo, 276, 47, 88, 88, null); + g.drawImage(wordmark, 190, 149, 260, 92, null); + g.setFont(TITLE_FONT); + g.setColor(WorkspaceStyle.DIM); + String title = "HD EDITOR"; + g.drawString(title, (WIDTH - g.getFontMetrics().stringWidth(title)) / 2, 260); + + if (failed) + paintError(g); + else + paintProgress(g, seconds); + g.setColor(DIVIDER_COLOR); + g.drawLine(0, 372, WIDTH, 372); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.setColor(VERSION_COLOR); + g.drawString(version, 14, 390); + String mode = failed ? "Standalone · startup error" : "Standalone · dev build"; + int modeX = WIDTH - 14 - g.getFontMetrics().stringWidth(mode); + g.drawString(mode, modeX, 390); + g.setColor(failed ? STATUS_ERROR_COLOR : STATUS_OK_COLOR); + g.fillOval(modeX - 12, 383, 6, 6); + g.setColor(WorkspaceStyle.HEADER); + g.drawRoundRect(0, 0, WIDTH - 1, HEIGHT - 1, 20, 20); + g.dispose(); + } + + private void paintProgress(Graphics2D g, double seconds) { + g.setFont(WorkspaceStyle.UI); + g.setColor(STATUS_TEXT_COLOR); + g.drawString(status + (readyAt == 0 ? "…" : ""), 32, 311); + g.setFont(WorkspaceStyle.MONO); + g.setColor(STEP_COUNT_COLOR); + String count = step + " / " + STEP_COUNT; + g.drawString(count, WIDTH - 32 - g.getFontMetrics().stringWidth(count), 311); + var track = PROGRESS_TRACK; + g.setColor(WorkspaceStyle.PANEL); + g.fill(track); + int fill = (int) (576 * progress); + if (fill > 0) { + g.setPaint(new LinearGradientPaint(32, 323, 32 + fill, 323, new float[] {0, .55f, 1}, PROGRESS_FILL_COLORS)); + g.fillRoundRect(32, 323, fill, 4, 4, 4); + } + var oldClip = g.getClip(); + g.clip(track); + float x = (float) (32 - 230 + (seconds % 1.6) / 1.6 * 806); + g.setPaint(new LinearGradientPaint(x, 323, x + 230, 323, new float[] {0, .5f, 1}, SHIMMER_COLORS)); + g.fillRect((int) x, 323, 230, 4); + g.setClip(oldClip); + g.clipRect(32, 332, 576, 20); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.setColor(STEP_HISTORY_COLOR); + int doneX = 32; + for (int i = Math.max(0, completed.size() - 3); i < completed.size(); i++) { + g.drawLine(doneX + 1, 342, doneX + 3, 344); + g.drawLine(doneX + 3, 344, doneX + 7, 339); + String label = completed.get(i); + g.drawString(label, doneX + 12, 346); + doneX += 28 + g.getFontMetrics().stringWidth(label); + } + g.setClip(oldClip); + } + + private void paintError(Graphics2D g) { + g.setColor(WorkspaceStyle.MENU); + g.fillRoundRect(32, 300, 576, 48, 12, 12); + g.setColor(ERROR_BORDER_COLOR); + g.drawRoundRect(32, 300, 575, 47, 12, 12); + g.setColor(STATUS_ERROR_COLOR); + g.fillOval(44, 320, 8, 8); + g.setFont(WorkspaceStyle.SEMIBOLD); + g.setColor(WorkspaceStyle.TEXT); + g.drawString("Couldn't start the 117HD Editor", 64, 320); + g.setFont(WorkspaceStyle.UI.deriveFont(11f)); + g.setColor(WorkspaceStyle.DIM); + g.drawString("Make sure 117 HD is enabled, then retry.", 64, 335); + } + + private static void glow(Graphics2D graphics, double x, double y, double width, double height, Color color) { + var g = (Graphics2D) graphics.create(); + g.translate(x, y); + g.scale(width, height); + g.setPaint(new RadialGradientPaint(.5f, .5f, .5f, new float[] {0, 1}, + new Color[] {color, new Color(color.getRed(), color.getGreen(), color.getBlue(), 0)})); + g.fill(new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1)); + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorText.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorText.java new file mode 100644 index 0000000..5bb9026 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorText.java @@ -0,0 +1,41 @@ +package rs117.hd.dev.editor; + +import java.awt.Color; +import java.awt.Font; +import javax.swing.Icon; +import javax.swing.JLabel; +import javax.swing.SwingConstants; +import javax.swing.border.Border; + +public final class EditorText { + private EditorText() {} + + public static Builder builder(String text) { return new Builder(text); } + + public static final class Builder { + private final String text; + private Font font = WorkspaceStyle.UI; + private Color color = WorkspaceStyle.TEXT; + private Icon icon; + private Border border; + private String tooltip; + private int alignment = SwingConstants.LEADING; + + private Builder(String text) { this.text = text; } + public Builder font(Font font) { this.font = font; return this; } + public Builder color(Color color) { this.color = color; return this; } + public Builder icon(Icon icon) { this.icon = icon; return this; } + public Builder border(Border border) { this.border = border; return this; } + public Builder tooltip(String tooltip) { this.tooltip = tooltip; return this; } + public Builder alignment(int alignment) { this.alignment = alignment; return this; } + + public JLabel build() { + var label = new JLabel(text, icon, alignment); + label.setFont(font); + label.setForeground(color); + label.setBorder(border); + label.setToolTipText(tooltip); + return label; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorToolRail.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorToolRail.java new file mode 100644 index 0000000..941bf18 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorToolRail.java @@ -0,0 +1,43 @@ +package rs117.hd.dev.editor; + +import java.awt.Component; +import java.awt.Dimension; +import java.util.List; +import javax.swing.*; + +/** Vertical rail whose tool groups are supplied by the active workspace. */ +public final class EditorToolRail extends JPanel { + public EditorToolRail() { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBackground(WorkspaceStyle.BAR); + setBorder(BorderFactory.createEmptyBorder(8, 6, 0, 6)); + setPreferredSize(new Dimension(44, 0)); + } + + public void setGroups(List> groups) { + removeAll(); + boolean previousGroup = false; + for (List group : groups) { + if (group.isEmpty()) + continue; + if (previousGroup) { + var divider = new JPanel(); + divider.setBackground(WorkspaceStyle.BORDER); + divider.setMaximumSize(new Dimension(22, 1)); + add(divider); + add(Box.createVerticalStrut(4)); + } + for (AbstractButton tool : group) { + if (!WorkspaceStyle.hasButtonStyle(tool)) + WorkspaceStyle.button(tool, WorkspaceStyle.Button.TOOL); + tool.setAlignmentX(Component.CENTER_ALIGNMENT); + tool.setMaximumSize(new Dimension(32, 32)); + add(tool); + add(Box.createVerticalStrut(4)); + } + previousGroup = true; + } + revalidate(); + repaint(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/EditorWindow.java b/Tools/Dev/java/rs117/hd/dev/editor/EditorWindow.java new file mode 100644 index 0000000..22b39f1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/EditorWindow.java @@ -0,0 +1,80 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Image; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.util.function.Consumer; +import javax.swing.*; +import net.miginfocom.swing.MigLayout; + +/** Window chrome shared by content editors. Content supplies its tabs, actions and body. */ +public class EditorWindow extends JFrame { + public EditorWindow() { + super("117HD Editor"); + setIconImages(EditorSplash.appIcons()); + setMinimumSize(new Dimension(1100, 700)); + setSize(1456, 939); + } + + protected final JPanel editorToolbar(JComponent leading, JComponent actions, JComponent saves, + Consumer compactChanged, JButton... workspaceTabs) { + var top = new JPanel(new BorderLayout(14, 0)); + top.setBackground(WorkspaceStyle.BAR); + top.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10)); + top.setPreferredSize(new Dimension(0, 32)); + + var brand = new JPanel(new MigLayout("insets 0, gap 8 0, aligny center", "[][][]14[]", "[24!]")); + brand.setOpaque(false); + var logo = new ImageIcon(EditorWindow.class.getResource("/rs117/hd/dev/editor/icons/editor-icon-48.png")); + brand.add(new JLabel(new ImageIcon(logo.getImage().getScaledInstance(22, 22, Image.SCALE_SMOOTH)))); + var product = new JLabel("117HD"); + product.setFont(WorkspaceStyle.SEMIBOLD); + product.setForeground(new Color(0xE6E6E6)); + brand.add(product); + var editorName = new JLabel("Editor"); + editorName.setFont(WorkspaceStyle.UI); + editorName.setForeground(new Color(0x7D7D7D)); + brand.add(editorName); + brand.add(leading); + top.add(brand, BorderLayout.WEST); + + var tabs = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 0)); + tabs.setOpaque(false); + for (JButton tab : workspaceTabs) + tabs.add(tab); + top.add(tabs, BorderLayout.CENTER); + + var right = new JPanel(new BorderLayout(6, 0)); + right.setOpaque(false); + right.add(actions, BorderLayout.CENTER); + right.add(saves, BorderLayout.EAST); + top.add(right, BorderLayout.EAST); + top.addComponentListener(new ComponentAdapter() { + @Override public void componentResized(ComponentEvent event) { + boolean compact = top.getWidth() < 1250; + ((BorderLayout) top.getLayout()).setHgap(compact ? 8 : 14); + for (JButton tab : workspaceTabs) { + int padding = compact ? 9 : 12; + tab.setBorder(BorderFactory.createEmptyBorder(0, padding, 0, padding)); + } + editorName.setVisible(!compact); + compactChanged.accept(compact); + } + }); + return top; + } + + protected final void installEditorContent(JComponent toolbar, JComponent body, JComponent footer) { + var root = new JPanel(new BorderLayout(0, 1)); + root.setBackground(WorkspaceStyle.GAP); + root.add(toolbar, BorderLayout.NORTH); + root.add(body, BorderLayout.CENTER); + root.add(footer, BorderLayout.SOUTH); + setContentPane(root); + setLocationRelativeTo(null); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/FloatingDockWindow.java b/Tools/Dev/java/rs117/hd/dev/editor/FloatingDockWindow.java new file mode 100644 index 0000000..3253a3e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/FloatingDockWindow.java @@ -0,0 +1,428 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.function.Consumer; +import javax.swing.*; + +/** A dockable panel that can also snap to, or float over, the workspace viewport. */ +public final class FloatingDockWindow extends JPanel { + public enum Dock { PANEL, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, LEFT_SIDE, RIGHT_SIDE, FLOATING } + + private static final int MIN_WIDTH = 200; + private static final int MIN_HEIGHT = 130; + private static final int VIEWER_MARGIN = 8; + private static final int SNAP_DISTANCE = 56; + private static final int RESIZE_HIT_SIZE = 8; + + private final JFrame frame; + private final JComponent viewer; + private final JPanel header = new JPanel(new net.miginfocom.swing.MigLayout( + "insets 0, fill, gap 0, hidemode 3", "[]6[]6[grow,fill][]2[]2[]2[]", "[grow,center]")); + private final JLabel statusDot = new JLabel(WorkspaceStyle.badge("", new Color(0x6CB348))); + private final JLabel title; + private final JLabel subtitle = new JLabel(); + private final JPanel body = new JPanel(new BorderLayout()); + private final JPanel headerArea = new JPanel(new BorderLayout()); + private final JPanel resizeBar = resizeHandle(Cursor.N_RESIZE_CURSOR); + private final JPanel widthBar = resizeHandle(Cursor.E_RESIZE_CURSOR); + + private final JButton swapButton, floatButton, menuButton, closeButton; + private Dock dock = Dock.PANEL; + private WorkspaceDocks.Side panelSide = WorkspaceDocks.Side.RIGHT; + private Point floatLocation; + private int overlayTopInset; + private int floatWidth = 280, floatHeight = 200; + private int panelBodyHeight = 200; + private Consumer dockListener = d -> {}; + private Runnable hideListener = () -> {}; + private PopupLayer.Handle dockMenu; + private Dock snapTarget = Dock.FLOATING; + private final JComponent snapPreview = new JComponent() { + @Override public boolean contains(int x, int y) { return false; } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(71, 114, 179, 46)); + g.fillRoundRect(1, 1, getWidth() - 3, getHeight() - 3, 6, 6); + g.setColor(WorkspaceStyle.ACCENT); + g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1, new float[] {5, 4}, 0)); + g.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, 6, 6); + g.setFont(WorkspaceStyle.UI.deriveFont(11f)); + String label = snapTarget.name().toLowerCase(java.util.Locale.ROOT).replace('_', ' '); + int w = g.getFontMetrics().stringWidth(label) + 16; + int x = (getWidth() - w) / 2, y = (getHeight() - 22) / 2; + g.fillRoundRect(x, y, w, 22, 6, 6); + g.setColor(Color.WHITE); + g.drawString(label, x + 8, y + 15); + g.dispose(); + } + }; + + public FloatingDockWindow(JFrame frame, JComponent viewer, String titleText) { + super(new BorderLayout()); + this.frame = frame; + this.viewer = viewer; + setBackground(WorkspaceStyle.PANEL); + setBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1)); + + title = new JLabel(titleText); + title.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(12f)); + title.setForeground(WorkspaceStyle.TEXT); + subtitle.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + subtitle.setForeground(new Color(0x6F6F6F)); + + var move = swapButton = headerButton("dock-swap-panel", "Move to the other panel"); + move.addActionListener(e -> setPanelDock(panelSide == WorkspaceDocks.Side.LEFT ? WorkspaceDocks.Side.RIGHT : WorkspaceDocks.Side.LEFT)); + var dockButton = menuButton = headerButton("dock-menu", "Choose where this docks"); + dockButton.addActionListener(e -> showDockMenu(dockButton)); + floatButton = headerButton("float-window", "Float"); + floatButton.addActionListener(e -> setDock(Dock.FLOATING)); + var hide = closeButton = headerButton("close", "Hide"); + hide.addActionListener(e -> hideListener.run()); + header.setOpaque(true); + header.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 4)); + header.add(statusDot, "cell 0 0, aligny center"); + header.add(title, "cell 1 0, aligny center"); + header.add(subtitle, "cell 2 0, width 0:pref, aligny center"); + header.add(move, "cell 3 0, aligny center"); + header.add(dockButton, "cell 4 0, aligny center"); + header.add(floatButton, "cell 5 0, aligny center"); + header.add(hide, "cell 6 0, aligny center"); + installDrag(header); + installDrag(title); + installDrag(subtitle); + installDrag(statusDot); + updateHeader(); + + body.setOpaque(false); + body.setPreferredSize(new Dimension(0, panelBodyHeight)); + + resizeBar.setPreferredSize(new Dimension(0, RESIZE_HIT_SIZE)); + widthBar.setPreferredSize(new Dimension(RESIZE_HIT_SIZE, 0)); + installPanelResize(); + installWidthResize(); + + headerArea.add(header); + add(headerArea, BorderLayout.NORTH); + add(body); + updateResizeHandles(); + + viewer.addComponentListener(new ComponentAdapter() { + @Override public void componentResized(ComponentEvent e) { layoutOverlay(); } + }); + } + + public JComponent content() { return body; } + + public void setStatus(boolean live, String subtitleText) { + statusDot.setIcon(WorkspaceStyle.badge("", live ? new Color(0x6CB348) : new Color(0x8A8A8A))); + subtitle.setText(subtitleText); + subtitle.setToolTipText(subtitleText.isEmpty() ? null : subtitleText); + } + + public Dock getDock() { return dock; } + public WorkspaceDocks.Side getPanelSide() { return panelSide; } + + private void setPanelDock(WorkspaceDocks.Side side) { + panelSide = side; + setDock(Dock.PANEL); + } + + public void setDock(Dock next) { + dock = next; + updateHeader(); + updateResizeHandles(); + if (dockMenu != null) + dockMenu.close(); + dockListener.accept(next); + layoutOverlay(); + } + + public void onDockChanged(Consumer listener) { dockListener = listener; } + public void onHide(Runnable listener) { hideListener = listener; } + + public void setOverlayTopInset(int inset) { + overlayTopInset = inset; + } + + public void layoutOverlay() { + if (dock == Dock.PANEL || getParent() != viewer) + return; + setBounds(overlayBounds(dock)); + if (viewer instanceof JLayeredPane) + ((JLayeredPane) viewer).moveToFront(this); + revalidate(); + repaint(); + } + + private Rectangle overlayBounds(Dock position) { + Rectangle area = new Rectangle(0, overlayTopInset, viewer.getWidth(), Math.max(0, viewer.getHeight() - overlayTopInset)); + int width = Math.max(MIN_WIDTH, Math.min(floatWidth, area.width - VIEWER_MARGIN * 2)); + int height = Math.max(MIN_HEIGHT, Math.min(floatHeight, area.height - VIEWER_MARGIN * 2)); + int x, y; + switch (position) { + case TOP_LEFT: x = area.x + VIEWER_MARGIN; y = area.y + VIEWER_MARGIN; break; + case TOP_RIGHT: x = area.x + area.width - width - VIEWER_MARGIN; y = area.y + VIEWER_MARGIN; break; + case BOTTOM_LEFT: x = area.x + VIEWER_MARGIN; y = area.y + area.height - height - VIEWER_MARGIN; break; + case BOTTOM_RIGHT: x = area.x + area.width - width - VIEWER_MARGIN; y = area.y + area.height - height - VIEWER_MARGIN; break; + case LEFT_SIDE: x = area.x + VIEWER_MARGIN; y = area.y + VIEWER_MARGIN; height = area.height - VIEWER_MARGIN * 2; break; + case RIGHT_SIDE: x = area.x + area.width - width - VIEWER_MARGIN; y = area.y + VIEWER_MARGIN; height = area.height - VIEWER_MARGIN * 2; break; + default: + x = floatLocation == null ? (area.width - width) / 2 : floatLocation.x; + y = floatLocation == null ? area.y + (area.height - height) / 2 : floatLocation.y; + x = Math.max(VIEWER_MARGIN, Math.min(x, area.width - width - VIEWER_MARGIN)); + y = Math.max(area.y + VIEWER_MARGIN, Math.min(y, area.y + area.height - height - VIEWER_MARGIN)); + } + return new Rectangle(x, y, width, height); + } + + private void showSnapPreview(Dock target) { + snapTarget = target; + if (!(viewer instanceof JLayeredPane)) + return; + if (target == Dock.FLOATING) { + viewer.remove(snapPreview); + viewer.repaint(); + } else { + if (snapPreview.getParent() != viewer) + ((JLayeredPane) viewer).add(snapPreview, Integer.valueOf(JLayeredPane.MODAL_LAYER + 1)); + snapPreview.setBounds(overlayBounds(target)); + viewer.repaint(); + } + } + + private void updateHeader() { + boolean panel = dock == Dock.PANEL; + header.setPreferredSize(new Dimension(0, panel ? 30 : 24)); + header.setBackground(panel ? WorkspaceStyle.HEADER : WorkspaceStyle.PANEL); + title.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(panel ? 12f : 11f)); + swapButton.setVisible(panel); + floatButton.setVisible(panel); + menuButton.setVisible(!panel); + menuButton.setIcon(WorkspaceStyle.icon(dock == Dock.FLOATING ? "dock-menu-floating" : "dock-menu", 13)); + closeButton.setPreferredSize(new Dimension(panel ? 22 : 20, panel ? 22 : 20)); + menuButton.setPreferredSize(new Dimension(20, 20)); + setBorder(panel ? BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1A1A1A)) + : BorderFactory.createLineBorder(dock == Dock.FLOATING ? new Color(0x4A4A4A) : WorkspaceStyle.BORDER, 1, true)); + } + + private JButton headerButton(String icon, String tooltip) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.SEGMENT).icon(icon, 13).tooltip(tooltip).size(22, 22).build(); + return button; + } + + private void installDrag(JComponent handle) { + handle.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + var drag = new MouseAdapter() { + private Point pressed; + private Point grabOffset; + private boolean dragging; + + @Override public void mousePressed(MouseEvent e) { + if (!SwingUtilities.isLeftMouseButton(e)) + return; + pressed = e.getLocationOnScreen(); + grabOffset = SwingUtilities.convertPoint(handle, e.getPoint(), FloatingDockWindow.this); + } + + @Override public void mouseDragged(MouseEvent e) { + if (pressed == null || !dragging && pressed.distance(e.getLocationOnScreen()) < 5) + return; + dragging = true; + var point = e.getLocationOnScreen(); + SwingUtilities.convertPointFromScreen(point, viewer); + floatLocation = new Point(point.x - grabOffset.x, point.y - grabOffset.y); + if (dock == Dock.FLOATING) + layoutOverlay(); + else + setDock(Dock.FLOATING); + showSnapPreview(viewer.contains(point) ? spotFor(point) : Dock.FLOATING); + } + + @Override public void mouseReleased(MouseEvent e) { + if (dragging) { + showSnapPreview(Dock.FLOATING); + var point = e.getLocationOnScreen(); + SwingUtilities.convertPointFromScreen(point, viewer); + if (point.x < 0) + setPanelDock(WorkspaceDocks.Side.LEFT); + else if (point.x >= viewer.getWidth()) + setPanelDock(WorkspaceDocks.Side.RIGHT); + else + setDock(spotFor(point)); + } + pressed = null; + dragging = false; + } + }; + handle.addMouseListener(drag); + handle.addMouseMotionListener(drag); + } + + private Dock spotFor(Point point) { + boolean left = point.x < SNAP_DISTANCE; + if (!left && point.x < viewer.getWidth() - SNAP_DISTANCE) + return Dock.FLOATING; + if (point.y < viewer.getHeight() / 3) + return left ? Dock.TOP_LEFT : Dock.TOP_RIGHT; + if (point.y >= viewer.getHeight() * 2 / 3) + return left ? Dock.BOTTOM_LEFT : Dock.BOTTOM_RIGHT; + return left ? Dock.LEFT_SIDE : Dock.RIGHT_SIDE; + } + + private static JPanel resizeHandle(int cursorType) { + var bar = new JPanel(); + bar.setBackground(WorkspaceStyle.MENU); + bar.setCursor(Cursor.getPredefinedCursor(cursorType)); + bar.addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent e) { bar.setBackground(WorkspaceStyle.ACCENT); } + @Override public void mouseExited(MouseEvent e) { bar.setBackground(WorkspaceStyle.MENU); } + }); + return bar; + } + + private boolean rightAnchored() { + return dock == Dock.TOP_RIGHT || dock == Dock.BOTTOM_RIGHT || dock == Dock.RIGHT_SIDE; + } + + private boolean bottomAnchored() { + return dock == Dock.BOTTOM_LEFT || dock == Dock.BOTTOM_RIGHT; + } + + private void updateResizeHandles() { + if (resizeBar.getParent() != null) + resizeBar.getParent().remove(resizeBar); + if (widthBar.getParent() != null) + widthBar.getParent().remove(widthBar); + + if (bottomAnchored()) + headerArea.add(resizeBar, BorderLayout.NORTH); + else if (dock != Dock.LEFT_SIDE && dock != Dock.RIGHT_SIDE) + add(resizeBar, BorderLayout.SOUTH); + if (dock != Dock.PANEL) + add(widthBar, rightAnchored() ? BorderLayout.WEST : BorderLayout.EAST); + revalidate(); + repaint(); + } + + private void installPanelResize() { + var drag = new MouseAdapter() { + private int startY, startHeight; + + @Override public void mousePressed(MouseEvent e) { + startY = e.getYOnScreen(); + startHeight = dock == Dock.PANEL ? body.getHeight() : getHeight(); + } + + @Override public void mouseDragged(MouseEvent e) { + int delta = e.getYOnScreen() - startY; + if (dock != Dock.PANEL) { + floatHeight = Math.max(MIN_HEIGHT, startHeight + (bottomAnchored() ? -delta : delta)); + layoutOverlay(); + return; + } + int next = Math.max(110, Math.min(startHeight + delta, frame.getHeight() * 60 / 100)); + panelBodyHeight = next; + body.setPreferredSize(new Dimension(0, next)); + if (getParent() instanceof JSplitPane && ((JSplitPane) getParent()).getTopComponent() == FloatingDockWindow.this) + ((JSplitPane) getParent()).setDividerLocation(getPreferredSize().height); + revalidate(); + } + }; + resizeBar.addMouseListener(drag); + resizeBar.addMouseMotionListener(drag); + } + + private void installWidthResize() { + var drag = new MouseAdapter() { + private int startX, startWidth; + + @Override public void mousePressed(MouseEvent e) { + startX = e.getXOnScreen(); + startWidth = getWidth(); + } + + @Override public void mouseDragged(MouseEvent e) { + int delta = e.getXOnScreen() - startX; + floatWidth = Math.max(MIN_WIDTH, startWidth + (rightAnchored() ? -delta : delta)); + layoutOverlay(); + } + }; + widthBar.addMouseListener(drag); + widthBar.addMouseMotionListener(drag); + } + + private void showDockMenu(JComponent trigger) { + var content = new JPanel(new BorderLayout(0, 6)); + content.setBackground(WorkspaceStyle.MENU); + content.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + var caption = new JLabel("DOCK TO"); + caption.setFont(WorkspaceStyle.UI.deriveFont(10f)); + caption.setForeground(WorkspaceStyle.DIM); + content.add(caption, BorderLayout.NORTH); + + var map = new JPanel(new BorderLayout(4, 0)); + map.setOpaque(false); + map.setPreferredSize(new Dimension(150, 84)); + map.add(mapBar("Left panel", WorkspaceDocks.Side.LEFT), BorderLayout.WEST); + map.add(mapInner(), BorderLayout.CENTER); + map.add(mapBar("Right panel", WorkspaceDocks.Side.RIGHT), BorderLayout.EAST); + content.add(map); + + var floatRow = EditorButton.builder().text("Float").icon("open-external", 13).onClick(() -> setDock(Dock.FLOATING)).build(); + var hint = new JLabel("
Outer bars dock into the Browser / Properties panels. You can also drag the title bar there.
"); + hint.setFont(WorkspaceStyle.UI.deriveFont(10f)); + hint.setForeground(new Color(0x6F6F6F)); + var south = new JPanel(new BorderLayout(0, 6)); + south.setOpaque(false); + south.add(floatRow, BorderLayout.NORTH); + south.add(hint, BorderLayout.SOUTH); + content.add(south, BorderLayout.SOUTH); + + dockMenu = PopupLayer.show(trigger, content, 168); + } + + private JComponent mapBar(String tooltip, WorkspaceDocks.Side side) { + var bar = dockTarget(tooltip, dock == Dock.PANEL && panelSide == side, () -> setPanelDock(side)); + bar.setPreferredSize(new Dimension(14, 84)); + return bar; + } + + private JComponent mapInner() { + var inner = new JPanel(new BorderLayout(2, 2)); + inner.setOpaque(false); + var corners = new JPanel(new GridLayout(2, 2, 2, 2)); + corners.setOpaque(false); + corners.add(spotButton("Top left", Dock.TOP_LEFT)); + corners.add(spotButton("Top right", Dock.TOP_RIGHT)); + corners.add(spotButton("Bottom left", Dock.BOTTOM_LEFT)); + corners.add(spotButton("Bottom right", Dock.BOTTOM_RIGHT)); + inner.add(spotButton("Left side", Dock.LEFT_SIDE), BorderLayout.WEST); + inner.add(corners); + inner.add(spotButton("Right side", Dock.RIGHT_SIDE), BorderLayout.EAST); + return inner; + } + + private JButton spotButton(String tooltip, Dock spot) { + return dockTarget(tooltip, dock == spot, () -> setDock(spot)); + } + + private JButton dockTarget(String tooltip, boolean selected, Runnable action) { + var button = new JButton() { + @Override protected void paintComponent(Graphics g) { + g.setColor(selected ? WorkspaceStyle.ACCENT : WorkspaceStyle.BORDER); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 3, 3); + } + }; + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setFocusPainted(false); + button.setToolTipText(tooltip); + button.setPreferredSize(new Dimension(24, 16)); + button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + button.addActionListener(e -> action.run()); + return button; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/HdContextMenu.java b/Tools/Dev/java/rs117/hd/dev/editor/HdContextMenu.java new file mode 100644 index 0000000..ee748eb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/HdContextMenu.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.function.Consumer; +import javax.swing.*; +import javax.swing.plaf.basic.BasicMenuItemUI; +import javax.swing.plaf.basic.BasicMenuUI; + +public final class HdContextMenu extends JPopupMenu { + private static final int MAX_CAPTION_WIDTH = 236; + private static final Font LABEL_FONT = WorkspaceStyle.UI.deriveFont(12f); + private static final Font SHORTCUT_FONT = WorkspaceStyle.MONO.deriveFont(10f); + private static final Color SURFACE = new Color(0x262626); + private static final Color ACTIVE = new Color(0x334D73); + private static final Color BORDER = new Color(0x3A3A3A); + + public HdContextMenu(String caption) { + this(null, null, caption); + } + + public HdContextMenu(String badge, Color color, String caption) { + stylePopup(this); + AWTEventListener closeOnScroll = event -> { + if (event instanceof MouseWheelEvent) + MenuSelectionManager.defaultManager().clearSelectedPath(); + }; + addPopupMenuListener(new javax.swing.event.PopupMenuListener() { + @Override public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent event) { + Toolkit.getDefaultToolkit().addAWTEventListener(closeOnScroll, AWTEvent.MOUSE_WHEEL_EVENT_MASK); + } + + @Override public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent event) { + Toolkit.getDefaultToolkit().removeAWTEventListener(closeOnScroll); + } + + @Override public void popupMenuCanceled(javax.swing.event.PopupMenuEvent event) { + Toolkit.getDefaultToolkit().removeAWTEventListener(closeOnScroll); + } + }); + var title = EditorText.builder(caption).font(WorkspaceStyle.MEDIUM.deriveFont(10f)) + .color(new Color(0x9A9A9A)).build(); + if (badge != null) + title.setIcon(WorkspaceStyle.badge(badge, color)); + title.setToolTipText(caption); + title.setIconTextGap(8); + title.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1E1E1E)), + BorderFactory.createEmptyBorder(5, 8, 6, 8))); + title.setPreferredSize(new Dimension(Math.min(title.getPreferredSize().width, MAX_CAPTION_WIDTH), 26)); + add(title); + } + + public static void install(JComponent target, Consumer open) { + target.addMouseListener(new MouseAdapter() { + @Override public void mousePressed(MouseEvent event) { handle(event); } + @Override public void mouseReleased(MouseEvent event) { handle(event); } + + private void handle(MouseEvent event) { + if (event.isPopupTrigger()) { + event.consume(); + open.accept(event.getPoint()); + } + } + }); + for (var key : new KeyStroke[] { KeyStroke.getKeyStroke("shift F10"), KeyStroke.getKeyStroke(KeyEvent.VK_CONTEXT_MENU, 0) }) + target.registerKeyboardAction(e -> open.accept(null), key, JComponent.WHEN_FOCUSED); + } + + public HdContextMenu item(String label, String icon, String key, Runnable action) { + return row(label, icon, key, false, null, action); + } + + public HdContextMenu check(String label, String icon, boolean selected, Consumer change) { + var item = new JCheckBoxMenuItem(label, icon(icon), selected); + item.setUI(new BasicMenuItemUI() { + @Override protected void doClick(MenuSelectionManager manager) { + item.doClick(0); + } + + @Override public void paint(Graphics graphics, JComponent component) { + paintRow(graphics, item, item.isSelected() ? "✓" : "", false); + } + }); + configure(item, "✓"); + item.addActionListener(event -> { + change.accept(item.isSelected()); + item.repaint(); + }); + add(item); + return this; + } + + public HdContextMenu disabled(String label, String icon, String reason) { + return row(label, icon, "", false, reason, null); + } + + public HdContextMenu danger(String label, String icon, String key, Runnable action) { + return row(label, icon, key, true, null, action); + } + + public HdContextMenu separator() { + if (getComponentCount() > 1 && !(getComponent(getComponentCount() - 1) instanceof JSeparator)) { + var line = new JSeparator(); + line.setForeground(new Color(0x333333)); + line.setBackground(SURFACE); + line.setPreferredSize(new Dimension(1, 8)); + add(line); + } + return this; + } + + private HdContextMenu row(String label, String icon, String key, boolean danger, String reason, Runnable action) { + var item = new JMenuItem(label, icon(icon)); + item.setUI(new BasicMenuItemUI() { + @Override public void paint(Graphics graphics, JComponent component) { + paintRow(graphics, item, key, danger); + } + }); + configure(item, key); + item.setEnabled(action != null); + item.setToolTipText(reason); + if (action != null) + item.addActionListener(e -> action.run()); + add(item); + return this; + } + + public HdContextMenu submenu(String label, String icon, Consumer entries) { + var menu = new JMenu(label); + menu.setIcon(icon(icon)); + menu.setDelay(150); + menu.setUI(new BasicMenuUI() { + @Override public void paint(Graphics graphics, JComponent component) { + paintRow(graphics, menu, "›", false); + } + }); + configure(menu, "›"); + stylePopup(menu.getPopupMenu()); + menu.getPopupMenu().setOpaque(true); + entries.accept(menu); + menu.setEnabled(menu.getItemCount() > 0); + add(menu); + return this; + } + + public static void subItem(JMenu menu, String label, Icon icon, Runnable action) { + var item = new JMenuItem(label, icon); + item.setUI(new BasicMenuItemUI() { + @Override public void paint(Graphics graphics, JComponent component) { + paintRow(graphics, item, "", false); + } + }); + configure(item, ""); + item.addActionListener(e -> action.run()); + menu.add(item); + } + + @Override public void show(Component invoker, int x, int y) { + if (getComponent(getComponentCount() - 1) instanceof JSeparator) + remove(getComponentCount() - 1); + var root = SwingUtilities.getRootPane(invoker); + var window = SwingUtilities.getWindowAncestor(invoker); + if (window instanceof JDialog && window.getOwner() instanceof RootPaneContainer) + root = ((RootPaneContainer) window.getOwner()).getRootPane(); + if (root != null) { + Point origin = SwingUtilities.convertPoint(invoker, x, y, root); + Dimension size = getPreferredSize(); + int left = origin.x + size.width > root.getWidth() - 8 ? origin.x - size.width : origin.x; + int top = origin.y + size.height > root.getHeight() - 8 ? origin.y - size.height : origin.y; + origin.setLocation(Math.max(8, left), Math.max(8, top)); + var local = SwingUtilities.convertPoint(root, origin, invoker); + x = local.x; + y = local.y; + } + super.show(invoker, x, y); + } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(SURFACE); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 12, 12); + g.setColor(BORDER); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 12, 12); + g.dispose(); + } + + private static Icon icon(String name) { return WorkspaceStyle.icon("context/" + name, 14); } + + private static void stylePopup(JPopupMenu menu) { + menu.setBackground(SURFACE); + menu.setOpaque(false); + menu.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + } + + private static void configure(JMenuItem item, String shortcut) { + item.setOpaque(false); + int labelWidth = item.getFontMetrics(LABEL_FONT).stringWidth(item.getText()); + int shortcutWidth = shortcut.isEmpty() ? 0 : 12 + item.getFontMetrics(SHORTCUT_FONT).stringWidth(shortcut); + item.setPreferredSize(new Dimension(42 + labelWidth + shortcutWidth, 26)); + } + + private static void paintRow(Graphics graphics, JMenuItem item, String key, boolean danger) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + boolean enabled = item.isEnabled(); + boolean active = enabled && (item.isArmed() || item.isSelected()); + if (active) { + g.setColor(danger ? new Color(0x3A2626) : ACTIVE); + g.fillRoundRect(0, 0, item.getWidth(), item.getHeight(), 8, 8); + } + if (item.getIcon() != null) { + g.setComposite(AlphaComposite.SrcOver.derive(enabled ? .85f : .5f)); + item.getIcon().paintIcon(item, g, 8, 6); + g.setComposite(AlphaComposite.SrcOver); + } + g.setFont(SHORTCUT_FONT); + int shortcutX = item.getWidth() - 8 - g.getFontMetrics().stringWidth(key); + g.setColor(!enabled ? new Color(0x4A4A4A) : active ? new Color(0xCFE0FF) : new Color(0x6F6F6F)); + g.drawString(key, shortcutX, 17); + g.setFont(LABEL_FONT); + g.setColor(!enabled ? new Color(0x5A5A5A) : danger ? new Color(active ? 0xFFB0B0 : 0xE8A0A0) + : active ? Color.WHITE : new Color(0xD6D6D6)); + var metrics = g.getFontMetrics(); + String label = item.getText(); + int available = shortcutX - 34; + if (metrics.stringWidth(label) > available) { + while (!label.isEmpty() && metrics.stringWidth(label + "…") > available) + label = label.substring(0, label.length() - 1); + label += "…"; + } + g.drawString(label, 30, 17); + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/NumberField.java b/Tools/Dev/java/rs117/hd/dev/editor/NumberField.java new file mode 100644 index 0000000..7361402 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/NumberField.java @@ -0,0 +1,327 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.function.Consumer; +import javax.swing.*; + +/** + * A compact numeric input with an optional unit suffix. The caller's own label for this field + * can be made "scrubbable" (drag left/right to change the value) by passing it to + * {@link #attachScrub(JComponent)}. + */ +public final class NumberField extends JPanel { + private static final int HEIGHT = 24; + private static final int MAX_WIDTH = 200; + private static final int PIXELS_PER_STEP = 4; + private static final Color UNIT_COLOR = new Color(0x6F6F6F); + + private final JTextField field; + private final double step; + private final Double min; + private final Double max; + private final boolean nullable; + private String emptyText = "Default"; + + private Double value; + private final JPanel valueCards = new JPanel(new CardLayout()); + private final JButton display; + private Double defaultValue; + private boolean editing; + private boolean scrubbing; + private Consumer listener; + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private Double value = 0.0; + private double step = 1; + private Double min, max; + private String unit; + private boolean nullable; + private String emptyText = "Default"; + private Consumer listener; + private Double defaultValue; + + public Builder value(Double initial) { value = initial; return this; } + public Builder step(double increment) { step = increment; return this; } + public Builder min(double bound) { min = bound; return this; } + public Builder max(double bound) { max = bound; return this; } + public Builder unit(String suffix) { unit = suffix; return this; } + public Builder nullable(boolean allowEmpty) { nullable = allowEmpty; return this; } + public Builder defaultValue(double value) { defaultValue = value; return this; } + public Builder emptyText(String text) { emptyText = text; return this; } + public Builder onChange(Consumer action) { listener = action; return this; } + + public NumberField build() { + var field = new NumberField(value, step, min, max, unit, nullable); + field.emptyText = emptyText; + field.defaultValue = defaultValue; + field.refreshText(); + field.onChange(listener); + return field; + } + } + + public NumberField(Double initial, double step, Double min, Double max, String unit, boolean nullable) { + this.step = step; + this.min = min; + this.max = max; + this.nullable = nullable; + this.value = clamp(initial); + + setLayout(new BorderLayout()); + setOpaque(false); + setPreferredSize(new Dimension(100, HEIGHT)); + setMaximumSize(new Dimension(MAX_WIDTH, HEIGHT)); + + field = new JTextField(); + field.setOpaque(false); + field.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); + field.setHorizontalAlignment(SwingConstants.CENTER); + field.setFont(WorkspaceStyle.MONO.deriveFont(11f)); + field.setForeground(WorkspaceStyle.TEXT); + field.setCaretColor(WorkspaceStyle.TEXT); + + display = EditorButton.builder().style(WorkspaceStyle.Button.TAB) + .tooltip("Drag to adjust or click to type").onClick(this::startEditing).build(); + display.setBorder(BorderFactory.createEmptyBorder()); + display.setRolloverEnabled(false); + display.setFont(field.getFont()); + attachScrub(display); + valueCards.setOpaque(false); + valueCards.add(display, "display"); + valueCards.add(field, "edit"); + + var center = new JPanel(new BorderLayout()); + center.setOpaque(false); + center.add(valueCards); + if (unit != null && !unit.isEmpty()) { + var unitLabel = EditorText.builder(unit).font(WorkspaceStyle.MONO.deriveFont(10f)).color(UNIT_COLOR) + .border(BorderFactory.createEmptyBorder(0, 2, 0, 3)).build(); + center.add(unitLabel, BorderLayout.EAST); + } + add(stepButton("‹", -1), BorderLayout.WEST); + add(center); + add(stepButton("›", 1), BorderLayout.EAST); + + refreshText(); + field.addActionListener(event -> finishEditing(true)); + field.addFocusListener(new FocusAdapter() { + @Override public void focusLost(FocusEvent event) { finishEditing(true); } + }); + field.addKeyListener(new KeyAdapter() { + @Override public void keyPressed(KeyEvent event) { + switch (event.getKeyCode()) { + case KeyEvent.VK_ESCAPE: + event.consume(); + finishEditing(false); + break; + case KeyEvent.VK_UP: + case KeyEvent.VK_DOWN: + event.consume(); + commit(adjusted(base(), (event.getKeyCode() == KeyEvent.VK_UP ? 1 : -1) * step * multiplier(event))); + break; + } + } + }); + } + + private JButton stepButton(String caption, int direction) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.TAB).text(caption) + .size(20, HEIGHT).tooltip(direction < 0 ? "Decrease" : "Increase") + .onClick(() -> commit(adjusted(base(), direction * step))).build(); + button.setBorder(BorderFactory.createEmptyBorder()); + button.setFocusable(false); + button.setRolloverEnabled(false); + return button; + } + + private void startEditing() { + if (!isEnabled() || scrubbing) + return; + editing = true; + ((CardLayout) valueCards.getLayout()).show(valueCards, "edit"); + field.requestFocusInWindow(); + field.selectAll(); + } + + private void finishEditing(boolean apply) { + if (!editing) + return; + editing = false; + if (apply) + commitTyped(); + else + refreshText(); + ((CardLayout) valueCards.getLayout()).show(valueCards, "display"); + } + + /** Makes dragging the given component horizontally scrub this field's value. */ + public void attachScrub(JComponent target) { + target.setCursor(WorkspaceStyle.cursor("scrub")); + var handler = new MouseAdapter() { + private int startX; + private Double original; + private boolean active; + + @Override public void mousePressed(MouseEvent event) { + if (!isEnabled() || !SwingUtilities.isLeftMouseButton(event)) + return; + startX = event.getXOnScreen(); + original = value; + active = true; + } + + @Override public void mouseDragged(MouseEvent event) { + if (!active) + return; + if (!isEnabled() || (event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) == 0) { + cancelDrag(); + return; + } + int pixels = event.getXOnScreen() - startX; + if (!scrubbing && Math.abs(pixels) < PIXELS_PER_STEP) + return; + scrubbing = true; + if (target instanceof AbstractButton) + ((AbstractButton) target).getModel().setArmed(false); + double start = original == null ? fallback() : original; + double delta = (pixels / PIXELS_PER_STEP) * step * multiplier(event); + value = delta == 0 ? original : clamp(adjusted(start, delta)); + refreshText(); + } + + @Override public void mouseMoved(MouseEvent event) { + if (active && (event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) == 0) + cancelDrag(); + } + + private void cancelDrag() { + active = false; + if (scrubbing) { + scrubbing = false; + setValue(original); + } + } + + @Override public void mouseReleased(MouseEvent event) { + if (!active || !SwingUtilities.isLeftMouseButton(event)) + return; + active = false; + if (scrubbing) { + Double next = value; + value = original; + scrubbing = false; + commit(next); + } + } + }; + target.addMouseListener(handler); + target.addMouseMotionListener(handler); + } + + public Double getValue() { return value; } + + public void setValue(Double value) { + this.value = clamp(value); + refreshText(); + } + + /** Fires on commit (Enter/blur/arrow/scrub-release), not on every keystroke. */ + public void onChange(Consumer listener) { + this.listener = listener; + } + + private double base() { + return value != null ? value : fallback(); + } + + private double fallback() { return defaultValue != null ? defaultValue : 0; } + + private static double multiplier(InputEvent event) { + return event.isShiftDown() ? 10 : event.isAltDown() ? 0.1 : 1; + } + + private void commitTyped() { + String text = field.getText().trim(); + Double parsed; + if (text.isEmpty()) { + parsed = nullable ? null : base(); + } else { + try { + parsed = Double.parseDouble(text); + if (!Double.isFinite(parsed)) + parsed = value; + } catch (NumberFormatException e) { + parsed = value; + } + } + commit(parsed); + } + + private void commit(Double newValue) { + Double previous = value; + value = clamp(newValue); + refreshText(); + if (listener != null && !java.util.Objects.equals(previous, value)) + listener.accept(value); + } + + private void refreshText() { + String text = value == null ? "" : formatValue(value); + field.setText(text); + display.setText(value == null && defaultValue != null ? emptyText + " · " + formatValue(defaultValue) + : value == null ? emptyText : text); + display.setForeground(value == null ? WorkspaceStyle.DIM : WorkspaceStyle.TEXT); + repaint(); + } + + private Double clamp(Double v) { + if (v == null) + return nullable ? null : (value != null ? value : (min != null ? min : 0.0)); + double clamped = v; + if (min != null) + clamped = Math.max(min, clamped); + if (max != null) + clamped = Math.min(max, clamped); + return clamped; + } + + private static double adjusted(double base, double delta) { + return java.math.BigDecimal.valueOf(base).add(java.math.BigDecimal.valueOf(delta)) + .round(java.math.MathContext.DECIMAL64).doubleValue(); + } + + private static String formatValue(double v) { + return Double.isFinite(v) ? java.math.BigDecimal.valueOf(v).stripTrailingZeros().toPlainString() : Double.toString(v); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.INPUT); + g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 4, 4); + var shape = new java.awt.geom.RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 4, 4); + var fill = (Graphics2D) g.create(); + fill.clip(shape); + double fraction = min != null && max != null && max > min && max < Double.MAX_VALUE + ? (base() - min) / (max - min) : 0; + int fillWidth = (int) Math.round(Math.max(0, Math.min(1, fraction)) * getWidth()); + if (value == null) { + fill.setColor(new Color(255, 255, 255, 14)); + fill.clipRect(0, 0, Math.max(20, fillWidth), getHeight()); + fill.setStroke(new BasicStroke(2)); + for (int x = -getHeight(); x < fillWidth + 20; x += 7) + fill.drawLine(x, getHeight(), x + getHeight(), 0); + } else if (fillWidth > 0 || scrubbing) { + fill.setColor(new Color(0x30425E)); + fill.fillRect(0, 0, Math.max(fillWidth, scrubbing ? 20 : 0), getHeight()); + } + fill.dispose(); + g.setColor(editing ? WorkspaceStyle.ACCENT : WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 4, 4); + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/PopupLayer.java b/Tools/Dev/java/rs117/hd/dev/editor/PopupLayer.java new file mode 100644 index 0000000..3a2248d --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/PopupLayer.java @@ -0,0 +1,221 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.RoundRectangle2D; +import javax.swing.*; +import javax.swing.event.ChangeListener; + +/** Shared placement/dismissal logic for every dropdown popup (material/texture pickers, ID pickers, swatch pickers). */ +public final class PopupLayer { + private static final int SHADOW_MARGIN = 20; + private static final int SHADOW_OFFSET = 3; + private static final int CORNER_ARC = 14; + private static final int SHADOW_RADIUS = SHADOW_MARGIN - SHADOW_OFFSET; + // Alpha only depends on spread/SHADOW_RADIUS, both compile-time constants, so this is shared by every popup. + private static final Color[] SHADOW_COLORS = new Color[SHADOW_RADIUS]; + static { + for (int spread = SHADOW_RADIUS; spread > 0; spread--) { + float falloff = 1f - spread / (float) SHADOW_RADIUS; + SHADOW_COLORS[spread - 1] = new Color(0, 0, 0, Math.round(22 * falloff * falloff)); + } + } + + private PopupLayer() {} + + public static final class Handle { + private final Runnable closeAction; + private final java.util.List onClose = new java.util.ArrayList<>(); + private boolean closed; + + private Handle(Runnable closeAction) { this.closeAction = closeAction; } + + public void close() { + if (closed) + return; + closed = true; + closeAction.run(); + for (Runnable listener : onClose) + listener.run(); + } + + public boolean isClosed() { return closed; } + + /** Called once, right after this popup closes for any reason (selection, Esc, outside click, window move/scroll). */ + public void onClose(Runnable listener) { onClose.add(listener); } + } + + /** Shows {@code content} anchored below (or above, flipped) {@code trigger}, at least {@code minWidth} wide. */ + public static Handle show(JComponent trigger, JComponent content, int minWidth) { + return show(trigger, content, minWidth, 0); + } + + public static Handle show(JComponent trigger, JComponent content, int minWidth, int maxHeight) { + return show(trigger, content, minWidth, maxHeight, 220); + } + + public static Handle show(JComponent trigger, JComponent content, int minWidth, int maxHeight, int flipThreshold) { + Window window = SwingUtilities.getWindowAncestor(trigger); + if (!(window instanceof JFrame)) + throw new IllegalStateException("PopupLayer needs a JFrame ancestor"); + JFrame frame = (JFrame) window; + JLayeredPane layered = frame.getLayeredPane(); + + JPanel inner = new JPanel(new BorderLayout()); + inner.setOpaque(false); + inner.add(content); + JPanel card = new JPanel(new BorderLayout()) { + private int shadowWidth = -1, shadowHeight = -1; + private final RoundRectangle2D[] shadowShapes = new RoundRectangle2D[SHADOW_RADIUS]; + + private RoundRectangle2D outline(double inset) { + double edge = SHADOW_MARGIN + inset; + double arc = CORNER_ARC - 2 * inset; + return new RoundRectangle2D.Double(edge, edge, getWidth() - 2 * edge - 1, + getHeight() - 2 * edge - 1, arc, arc); + } + + private void ensureShadowShapes() { + int width = getWidth(), height = getHeight(); + if (width == shadowWidth && height == shadowHeight) + return; + shadowWidth = width; + shadowHeight = height; + for (int spread = SHADOW_RADIUS; spread > 0; spread--) + shadowShapes[spread - 1] = outline(-spread); + } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + ensureShadowShapes(); + g.translate(0, SHADOW_OFFSET); + for (int spread = SHADOW_RADIUS; spread > 0; spread--) { + g.setColor(SHADOW_COLORS[spread - 1]); + g.fill(shadowShapes[spread - 1]); + } + g.translate(0, -SHADOW_OFFSET); + g.setColor(WorkspaceStyle.MENU); + g.fill(outline(0)); + g.dispose(); + } + + @Override protected void paintChildren(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.clip(outline(0.5)); + super.paintChildren(g); + g.dispose(); + + g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.BORDER); + g.draw(outline(0)); + g.dispose(); + } + + @Override public boolean contains(int x, int y) { + return outline(0).contains(x, y); + } + }; + card.setOpaque(false); + card.setBorder(BorderFactory.createEmptyBorder(SHADOW_MARGIN, SHADOW_MARGIN, SHADOW_MARGIN, SHADOW_MARGIN)); + card.add(inner); + card.setFocusable(true); + + int width = Math.max(trigger.getWidth(), minWidth); + int maxX = layered.getWidth() - 16 - width; + if (maxX < 8) { + width = Math.max(60, layered.getWidth() - 16); + maxX = 8; + } + Point triggerTop = SwingUtilities.convertPoint(trigger, 0, 0, layered); + int x = Math.max(8, Math.min(triggerTop.x, maxX)); + + Dimension preferred = inner.getPreferredSize(); + int wanted = maxHeight > 0 ? Math.min(preferred.height, maxHeight) : preferred.height; + int below = layered.getHeight() - (triggerTop.y + trigger.getHeight()) - 8; + int above = triggerTop.y - 8; + int y, height; + if (below >= Math.min(wanted, flipThreshold) || below >= above) { + y = triggerTop.y + trigger.getHeight() + 3; + height = Math.max(60, Math.min(wanted, below + 8 - 3)); + } else { + height = Math.max(60, Math.min(wanted, above)); + y = triggerTop.y - 3 - height; + } + + card.setBounds(x - SHADOW_MARGIN, y - SHADOW_MARGIN, width + 2 * SHADOW_MARGIN, height + 2 * SHADOW_MARGIN); + layered.add(card, JLayeredPane.POPUP_LAYER); + layered.revalidate(); + layered.repaint(); + + Handle[] handleRef = new Handle[1]; + + AWTEventListener outsideClick = event -> { + if (event.getID() != MouseEvent.MOUSE_PRESSED) + return; + MouseEvent mouse = (MouseEvent) event; + Object source = mouse.getSource(); + if (!(source instanceof Component)) + return; + Component component = (Component) source; + var menu = component instanceof JPopupMenu ? (JPopupMenu) component + : (JPopupMenu) SwingUtilities.getAncestorOfClass(JPopupMenu.class, component); + while (menu != null) { + var invoker = menu.getInvoker(); + if (invoker == null) + break; + if (SwingUtilities.isDescendingFrom(invoker, card)) + return; + menu = (JPopupMenu) SwingUtilities.getAncestorOfClass(JPopupMenu.class, invoker); + } + Point onCard = SwingUtilities.convertPoint(component, mouse.getPoint(), card); + if (card.contains(onCard)) + return; + Point onTrigger = SwingUtilities.convertPoint(component, mouse.getPoint(), trigger); + if (trigger.contains(onTrigger)) + return; + handleRef[0].close(); + }; + Toolkit.getDefaultToolkit().addAWTEventListener(outsideClick, AWTEvent.MOUSE_EVENT_MASK); + + ActionListener escapeAction = event -> handleRef[0].close(); + card.registerKeyboardAction(escapeAction, KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_IN_FOCUSED_WINDOW); + + ComponentAdapter windowTracking = new ComponentAdapter() { + @Override public void componentMoved(ComponentEvent e) { handleRef[0].close(); } + @Override public void componentResized(ComponentEvent e) { handleRef[0].close(); } + }; + frame.addComponentListener(windowTracking); + + ChangeListener scrollTracking = e -> handleRef[0].close(); + JScrollPane enclosingScroll = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, trigger); + if (enclosingScroll != null) + enclosingScroll.getViewport().addChangeListener(scrollTracking); + + HierarchyListener visibilityTracking = event -> { + if ((event.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && !trigger.isShowing()) + handleRef[0].close(); + }; + + handleRef[0] = new Handle(() -> { + Toolkit.getDefaultToolkit().removeAWTEventListener(outsideClick); + frame.removeComponentListener(windowTracking); + trigger.removeHierarchyListener(visibilityTracking); + if (enclosingScroll != null) + enclosingScroll.getViewport().removeChangeListener(scrollTracking); + layered.remove(card); + layered.revalidate(); + layered.repaint(); + }); + trigger.addHierarchyListener(visibilityTracking); + card.requestFocusInWindow(); + return handleRef[0]; + } + + /** Closes {@code handle} and runs {@code selection} — the common "pick a row/tile, then dismiss" pattern. */ + public static void select(Handle handle, Runnable selection) { + handle.close(); + selection.run(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/PreviewDropdown.java b/Tools/Dev/java/rs117/hd/dev/editor/PreviewDropdown.java new file mode 100644 index 0000000..0eb21b2 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/PreviewDropdown.java @@ -0,0 +1,447 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.geom.RoundRectangle2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +/** Generic thumbnail-preview dropdown: a compact trigger that opens a searchable grid of tiles via {@link PopupLayer}. */ +public final class PreviewDropdown extends JPanel { + public interface Provider { + List items(); + String label(T item); + + /** String to match against when filtering. Defaults to {@link #label(Object)}; override for e.g. gameval-name search. */ + default String searchKey(T item) { return label(item); } + + /** Returns a preview image sized for {@code size}px, or null to draw the checker "none" fallback. */ + Image preview(T item, int size); + default Image preview(T item, int size, JComponent observer) { return preview(item, size); } + } + + public static Builder builder(Provider provider) { + return new Builder<>(provider); + } + + public static final class Builder { + private final Provider provider; + private UnaryOperator> filter = UnaryOperator.identity(); + private String searchPlaceholder; + private boolean compact; + private String caption; + private String emptyText = ""; + + private Builder(Provider provider) { this.provider = provider; } + + /** Filters the available options each time the popup opens. Existing values stay visible. */ + public Builder filterItems(UnaryOperator> filter) { + this.filter = Objects.requireNonNull(filter); + return this; + } + + public Builder search(String placeholder) { + searchPlaceholder = placeholder; + return this; + } + + public Builder compact(boolean compact) { this.compact = compact; return this; } + public Builder caption(String caption) { this.caption = caption; return this; } + + public Builder emptyText(String text) { emptyText = Objects.requireNonNull(text); return this; } + + public PreviewDropdown build() { + var dropdown = new PreviewDropdown<>(provider, filter); + dropdown.compact = compact; + dropdown.caption = caption; + dropdown.emptyText = emptyText; + if (searchPlaceholder != null) { + dropdown.setSearchable(true); + dropdown.setSearchPlaceholder(searchPlaceholder); + } + return dropdown; + } + } + + private static final int TRIGGER_HEIGHT = 30; + private static final int THUMB_SIZE = 24; + private static final int THUMB_RADIUS = 3; + private static final int TRIGGER_RADIUS = 4; + private static final int PAD_LEFT = 3; + private static final int PAD_RIGHT = 6; + private static final int GAP_THUMB_TEXT = 6; + private static final int GAP_TEXT_CHEVRON = 6; + private static final int CHEVRON_SIZE = 10; + private static final int MAX_TRIGGER_WIDTH = 260; + + private static final int POPUP_WIDTH = 300; + private static final int GRID_PADDING = 6; + private static final int GRID_GAP = 6; + private static final int MIN_TILE = 80; + private static final int TILE_PADDING = 4; + private static final int TILE_RADIUS = 4; + private static final int TILE_LABEL_GAP = 4; + private static final int TILE_LABEL_HEIGHT = 12; + private static final int GRID_MAX_HEIGHT = 292; + + private static final Color HOVER_BORDER = new Color(0x555555); + private static final Color THUMB_INSET_BORDER = new Color(255, 255, 255, 20); + private static final Color CHECKER_LIGHT = new Color(0x3A3A3A); + private static final Color CHECKER_DARK = new Color(0x2A2A2A); + private static final Color TILE_SELECTED_BG = new Color(0x334D73); + private static final Color TILE_HOVER_BG = new Color(0x333333); + private static final Color LABEL_COLOR = new Color(0xDDDDDD); + private static final Color SEARCH_BORDER = new Color(0x1E1E1E); + + private final Provider provider; + private final UnaryOperator> filter; + private final Map> previewCache = new HashMap<>(); + private final List> listeners = new ArrayList<>(); + + private T value; + private boolean compact; + private String caption; + private String emptyText = ""; + private boolean searchable; + private String searchPlaceholder = "Search"; + private boolean hover; + private boolean open; + private PopupLayer.Handle popupHandle; + + public PreviewDropdown(Provider provider) { + this(provider, UnaryOperator.identity()); + } + + private PreviewDropdown(Provider provider, UnaryOperator> filter) { + this.provider = provider; + this.filter = filter; + setOpaque(false); + setFocusable(true); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hover = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hover = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { togglePopup(); } + }); + } + + public void setSearchable(boolean searchable) { + this.searchable = searchable; + } + + public void setSearchPlaceholder(String placeholder) { + this.searchPlaceholder = placeholder; + } + + public void setValue(T value) { + this.value = value; + setToolTipText(value == null ? null : provider.label(value)); + repaint(); + } + + public T getValue() { + return value; + } + + public void onChange(Consumer listener) { + listeners.add(listener); + } + + // ----- trigger ----- + + @Override + public Dimension getPreferredSize() { + FontMetrics metrics = getFontMetrics(WorkspaceStyle.MONO.deriveFont(11f)); + String label = value != null ? provider.label(value) : emptyText; + int textWidth = metrics != null ? metrics.stringWidth(label) : 0; + int width = PAD_LEFT + THUMB_SIZE + GAP_THUMB_TEXT + textWidth + GAP_TEXT_CHEVRON + CHEVRON_SIZE + PAD_RIGHT; + return new Dimension(Math.min(MAX_TRIGGER_WIDTH, width), compact ? 26 : TRIGGER_HEIGHT); + } + + @Override + public Dimension getMinimumSize() { + return new Dimension(80, compact ? 26 : TRIGGER_HEIGHT); + } + + @Override + public Dimension getMaximumSize() { + return new Dimension(MAX_TRIGGER_WIDTH, compact ? 26 : TRIGGER_HEIGHT); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + int width = getWidth(); + int height = getHeight(); + g.setColor(WorkspaceStyle.INPUT); + g.fillRoundRect(0, 0, width - 1, height - 1, TRIGGER_RADIUS, TRIGGER_RADIUS); + g.setColor(open ? WorkspaceStyle.ACCENT : hover ? HOVER_BORDER : WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, width - 1, height - 1, TRIGGER_RADIUS, TRIGGER_RADIUS); + + int x = PAD_LEFT; + int thumbSize = compact ? 18 : THUMB_SIZE; + int y = (height - thumbSize) / 2; + paintThumbnail(g, value, thumbSize, x, y, this); + x += thumbSize + GAP_THUMB_TEXT; + + int chevronX = width - PAD_RIGHT - CHEVRON_SIZE; + int chevronY = (height - CHEVRON_SIZE) / 2; + int textMaxWidth = Math.max(0, chevronX - GAP_TEXT_CHEVRON - x); + + String label = value != null ? provider.label(value) : emptyText; + g.setFont(WorkspaceStyle.MONO.deriveFont(11f)); + g.setColor(LABEL_COLOR); + FontMetrics metrics = g.getFontMetrics(); + String shown = ellipsize(metrics, label, textMaxWidth); + g.drawString(shown, x, (height - metrics.getHeight()) / 2 + metrics.getAscent()); + + WorkspaceStyle.icon("chevron-down", CHEVRON_SIZE).paintIcon(this, g, chevronX, chevronY); + g.dispose(); + } + + private void togglePopup() { togglePopup(this); } + + public void togglePopup(JComponent trigger) { + if (popupHandle != null && !popupHandle.isClosed()) { + popupHandle.close(); + return; + } + JComponent content = buildPopupContent(); + popupHandle = PopupLayer.show(trigger, content, POPUP_WIDTH); + open = true; + if (searchable && content.getClientProperty("searchField") instanceof JTextField) + ((JTextField) content.getClientProperty("searchField")).requestFocusInWindow(); + repaint(); + popupHandle.onClose(() -> { + popupHandle = null; + open = false; + previewCache.clear(); + repaint(); + }); + } + + // ----- popup content ----- + + private JComponent buildPopupContent() { + JPanel content = new JPanel(new BorderLayout()); + content.setOpaque(false); + + List allItems = filter.apply(new ArrayList<>(provider.items())); + List tiles = new ArrayList<>(); + + int contentWidth = POPUP_WIDTH - 2 * GRID_PADDING - 12; + int columns = Math.max(1, (contentWidth + GRID_GAP) / (MIN_TILE + GRID_GAP)); + int tileWidth = Math.max(MIN_TILE, (contentWidth - (columns - 1) * GRID_GAP) / columns); + int thumbSize = Math.max(16, tileWidth - 2 * TILE_PADDING); + int tileHeight = 2 * TILE_PADDING + thumbSize + TILE_LABEL_GAP + TILE_LABEL_HEIGHT; + + JPanel grid = new JPanel(new GridLayout(0, columns, GRID_GAP, GRID_GAP)); + grid.setOpaque(false); + + for (T item : allItems) { + Tile tile = new Tile(item, tileWidth, tileHeight, thumbSize, () -> { + setValue(item); + for (Consumer listener : listeners) + listener.accept(item); + if (popupHandle != null) + popupHandle.close(); + }); + tiles.add(tile); + grid.add(tile); + } + + JPanel gridWrapper = new JPanel(new BorderLayout()); + gridWrapper.setOpaque(false); + gridWrapper.setBorder(BorderFactory.createEmptyBorder(GRID_PADDING, GRID_PADDING, GRID_PADDING, GRID_PADDING)); + gridWrapper.add(grid, BorderLayout.NORTH); + + JScrollPane scroll = new EditorScrollPane( + gridWrapper, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(null); + scroll.setOpaque(false); + scroll.getViewport().setOpaque(true); + scroll.getViewport().setBackground(WorkspaceStyle.PANEL); + scroll.getVerticalScrollBar().setUnitIncrement(16); + scroll.setPreferredSize(new Dimension(POPUP_WIDTH, popupHeight(gridWrapper, tileHeight))); + + content.add(scroll, BorderLayout.CENTER); + + if (searchable) { + var field = EditorSearch.builder(searchPlaceholder).background(new Color(0x1A1A1A)) + .foreground(LABEL_COLOR).padding(7, 7).fieldHeight(24).build(); + JTextField search = field.field(); + content.putClientProperty("searchField", search); + + JPanel searchRow = new JPanel(new BorderLayout()); + searchRow.setOpaque(true); + searchRow.setBackground(WorkspaceStyle.MENU); + searchRow.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, SEARCH_BORDER), BorderFactory.createEmptyBorder(6, 6, 6, 6))); + searchRow.add(field); + if (caption != null) { + var label = EditorText.builder(caption.toUpperCase(java.util.Locale.ROOT)) + .font(WorkspaceStyle.UI.deriveFont(10f)).color(WorkspaceStyle.DIM) + .border(BorderFactory.createEmptyBorder(0, 0, 5, 0)).build(); + searchRow.add(label, BorderLayout.NORTH); + } + content.add(searchRow, BorderLayout.NORTH); + + search.getDocument().addDocumentListener(new DocumentListener() { + @Override public void insertUpdate(DocumentEvent event) { filter(); } + @Override public void removeUpdate(DocumentEvent event) { filter(); } + @Override public void changedUpdate(DocumentEvent event) { filter(); } + + private void filter() { + String query = search.getText().trim().toLowerCase(java.util.Locale.ROOT); + grid.removeAll(); + for (Tile tile : tiles) { + if (query.isEmpty() || tile.searchKey.contains(query)) + grid.add(tile); + } + if (grid.getComponentCount() == 0) + grid.add(EditorText.builder("No materials match.").color(WorkspaceStyle.DIM).build()); + scroll.getViewport().setViewPosition(new Point()); + grid.revalidate(); + scroll.getViewport().repaint(); + scroll.setPreferredSize(new Dimension(POPUP_WIDTH, popupHeight(gridWrapper, tileHeight))); + content.revalidate(); + } + }); + } + + return content; + } + + private int popupHeight(JPanel gridWrapper, int tileHeight) { + int wrapperHeight = gridWrapper.getPreferredSize().height; + return Math.min(GRID_MAX_HEIGHT, Math.max(tileHeight + 2 * GRID_PADDING, wrapperHeight)); + } + + // ----- shared painting helpers ----- + + private void paintThumbnail(Graphics2D g, T item, int size, int x, int y, JComponent observer) { + Image image = item != null ? getPreview(item, size, observer) : null; + Graphics2D clipped = (Graphics2D) g.create(); + clipped.clip(new RoundRectangle2D.Float(x, y, size, size, THUMB_RADIUS, THUMB_RADIUS)); + if (image != null) + clipped.drawImage(image, x, y, size, size, this); + else + paintChecker(clipped, x, y, size); + clipped.dispose(); + g.setColor(THUMB_INSET_BORDER); + g.drawRoundRect(x, y, size - 1, size - 1, THUMB_RADIUS, THUMB_RADIUS); + } + + private static void paintChecker(Graphics2D g, int x, int y, int size) { + int cell = Math.max(2, Math.round(size * 8f / 64f)); + for (int ry = 0, row = 0; ry < size; ry += cell, row++) { + for (int rx = 0, col = 0; rx < size; rx += cell, col++) { + g.setColor((row + col) % 2 == 0 ? CHECKER_LIGHT : CHECKER_DARK); + int w = Math.min(cell, size - rx); + int h = Math.min(cell, size - ry); + g.fillRect(x + rx, y + ry, w, h); + } + } + } + + private Image getPreview(T item, int size, JComponent observer) { + Map cache = previewCache.computeIfAbsent(size, key -> new java.util.LinkedHashMap(16, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > 48; } + }); + if (cache.containsKey(item)) + return cache.get(item); + Image image = provider.preview(item, size, observer); + if (image != null) + cache.put(item, image); + return image; + } + + private static String ellipsize(FontMetrics metrics, String text, int maxWidth) { + if (text == null) + return ""; + if (maxWidth <= 0) + return ""; + if (metrics.stringWidth(text) <= maxWidth) + return text; + String ellipsis = "..."; + int ellipsisWidth = metrics.stringWidth(ellipsis); + if (ellipsisWidth > maxWidth) + return ""; + int length = text.length(); + while (length > 0 && metrics.stringWidth(text.substring(0, length)) + ellipsisWidth > maxWidth) + length--; + return text.substring(0, length) + ellipsis; + } + + /** One tile in the popup grid: thumbnail + name, with hover/selected states. */ + private final class Tile extends JComponent { + private final T item; + private final int thumbSize; + private final String searchKey; + private boolean hoverState; + + Tile(T item, int width, int height, int thumbSize, Runnable onSelect) { + this.item = item; + this.thumbSize = thumbSize; + this.searchKey = searchable ? provider.searchKey(item).toLowerCase(java.util.Locale.ROOT) : ""; + setPreferredSize(new Dimension(width, height)); + setOpaque(false); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + setToolTipText(provider.label(item)); + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hoverState = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hoverState = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { onSelect.run(); } + }); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + boolean selected = Objects.equals(item, value); + int width = getWidth(); + int height = getHeight(); + if (selected) { + g.setColor(TILE_SELECTED_BG); + g.fillRoundRect(0, 0, width - 1, height - 1, TILE_RADIUS, TILE_RADIUS); + g.setColor(WorkspaceStyle.ACCENT); + g.drawRoundRect(0, 0, width - 1, height - 1, TILE_RADIUS, TILE_RADIUS); + } else if (hoverState) { + g.setColor(TILE_HOVER_BG); + g.fillRoundRect(0, 0, width - 1, height - 1, TILE_RADIUS, TILE_RADIUS); + } + + int thumbX = (width - thumbSize) / 2; + int thumbY = TILE_PADDING; + paintThumbnail(g, item, thumbSize, thumbX, thumbY, this); + + String label = provider.label(item); + g.setFont(WorkspaceStyle.MONO.deriveFont(9f)); + g.setColor(selected ? Color.WHITE : LABEL_COLOR); + FontMetrics metrics = g.getFontMetrics(); + int availableWidth = width - 2 * TILE_PADDING; + String shown = ellipsize(metrics, label, availableWidth); + int textWidth = metrics.stringWidth(shown); + int textX = (width - textWidth) / 2; + int textY = thumbY + thumbSize + TILE_LABEL_GAP + metrics.getAscent(); + g.drawString(shown, textX, textY); + + g.dispose(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/PropertyRow.java b/Tools/Dev/java/rs117/hd/dev/editor/PropertyRow.java new file mode 100644 index 0000000..e758fc6 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/PropertyRow.java @@ -0,0 +1,78 @@ +package rs117.hd.dev.editor; + +import java.awt.Color; +import java.awt.Dimension; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; + +public final class PropertyRow extends JPanel { + public enum Layout { SIMPLE, WIDE } + + private static final int GAP = 12; + private static final int VERTICAL_PADDING = 4; + private static final int CONTROL_WIDTH = 210; + + private final JLabel label; + private final JComponent control; + private final Layout layout; + + public PropertyRow(String name, JComponent control, Layout layout) { + super(null); + this.control = control; + this.layout = layout; + setName("field:" + name); + setOpaque(false); + setAlignmentX(LEFT_ALIGNMENT); + + label = EditorText.builder(name).font(WorkspaceStyle.UI.deriveFont(12f)).build(); + label.setToolTipText(name); + label.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 0, 0)); + if (control instanceof NumberField) + ((NumberField) control).attachScrub(label); + setChanged(false); + add(label); + add(control); + } + + /** A compact fixed-label row for inline cards and nested forms. */ + public static JPanel compact(String name, JComponent control) { + var row = new JPanel(new java.awt.BorderLayout(8, 0)); + row.setOpaque(false); + row.setAlignmentX(LEFT_ALIGNMENT); + row.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 2, 3, 2)); + var label = EditorText.builder(name).font(WorkspaceStyle.UI.deriveFont(11f)).color(WorkspaceStyle.DIM).build(); + label.setPreferredSize(new Dimension(64, 20)); + row.add(label, java.awt.BorderLayout.WEST); + row.add(control); + row.setMaximumSize(new Dimension(Integer.MAX_VALUE, row.getPreferredSize().height)); + return row; + } + + public void setChanged(boolean changed) { + label.setForeground(new Color(changed ? 0xE6E6E6 : 0x9A9A9A)); + } + + @Override public void doLayout() { + int available = Math.max(0, getWidth() - GAP); + int labelMinimum = layout == Layout.SIMPLE ? 70 : 90; + int desiredControlWidth = layout == Layout.SIMPLE ? CONTROL_WIDTH : Math.round(available * 2.2f / 3.2f); + int controlWidth = Math.min(desiredControlWidth, Math.max(0, available - labelMinimum)); + int labelWidth = available - controlWidth; + label.setBounds(0, VERTICAL_PADDING, labelWidth, label.getPreferredSize().height); + control.setBounds(getWidth() - controlWidth, VERTICAL_PADDING, controlWidth, control.getPreferredSize().height); + } + + @Override public Dimension getPreferredSize() { + int height = Math.max(label.getPreferredSize().height, control.getPreferredSize().height); + return new Dimension(70 + GAP + CONTROL_WIDTH, height + 2 * VERTICAL_PADDING); + } + + @Override public Dimension getMinimumSize() { + return new Dimension(0, getPreferredSize().height); + } + + @Override public Dimension getMaximumSize() { + return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/PropertySection.java b/Tools/Dev/java/rs117/hd/dev/editor/PropertySection.java new file mode 100644 index 0000000..5740426 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/PropertySection.java @@ -0,0 +1,226 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; + +public final class PropertySection extends JPanel { + private final EditorSection section; + private final String title; + private final JComponent fields; + private final JLabel changedBadge; + private final JLabel inactiveNote; + private final JLabel resetLink; + private boolean active = true; + private Runnable resetAction; + + public PropertySection(String title, JComponent content) { + this(title, content, null); + } + + public PropertySection(String title, JComponent content, java.util.function.Consumer onToggle) { + super(new BorderLayout()); + this.title = title; + this.fields = content; + setOpaque(false); + setAlignmentX(Component.LEFT_ALIGNMENT); + setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x2A2A2A)), + BorderFactory.createEmptyBorder(14, 0, 14, 0))); + + var body = new JPanel(new BorderLayout()); + body.setOpaque(false); + content.setAlignmentX(Component.LEFT_ALIGNMENT); + body.add(content, BorderLayout.CENTER); + body.setMinimumSize(new java.awt.Dimension(0, 0)); + + section = EditorSection.builder(title) + .content(body) + .bodyBorder(BorderFactory.createEmptyBorder(6, 17, 0, 10)) + .titleColor(new Color(0xE6E6E6)) + .onToggle(onToggle) + .build(); + section.setAlignmentX(Component.LEFT_ALIGNMENT); + add(section, BorderLayout.CENTER); + section.header().setOpaque(false); + section.header().setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + section.header().setPreferredSize(new java.awt.Dimension(0, 24)); + section.header().setMaximumSize(new java.awt.Dimension(Integer.MAX_VALUE, 24)); + + for (Component child : section.header().getComponents()) { + if (child instanceof JLabel && title.equals(((JLabel) child).getText())) { + JLabel titleLabel = (JLabel) child; + titleLabel.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(13f)); + titleLabel.setForeground(new Color(0xE6E6E6)); + } + } + + changedBadge = pill(new Color(0x334D73), new Color(0xCFE0FF)); + changedBadge.setVisible(false); + + inactiveNote = new JLabel(); + inactiveNote.setFont(WorkspaceStyle.UI.deriveFont(11f)); + inactiveNote.setForeground(new Color(0x7D7D7D)); + inactiveNote.setVisible(false); + + resetLink = resetLink(); + resetLink.setVisible(false); + + var trailing = new JPanel(); + trailing.setOpaque(false); + trailing.setLayout(new BoxLayout(trailing, BoxLayout.X_AXIS)); + var titleLabel = ((BorderLayout) section.header().getLayout()).getLayoutComponent(BorderLayout.CENTER); + section.header().remove(titleLabel); + var heading = new JPanel(new BorderLayout()); + heading.setOpaque(false); + var titleGroup = new JPanel(new java.awt.GridBagLayout()); + titleGroup.setOpaque(false); + var cell = new java.awt.GridBagConstraints(); + cell.gridy = 0; + titleGroup.add(titleLabel, cell); + cell.insets = new java.awt.Insets(0, 8, 0, 0); + titleGroup.add(changedBadge, cell); + heading.add(titleGroup, BorderLayout.WEST); + section.header().add(heading, BorderLayout.CENTER); + heading.addMouseListener(new MouseAdapter() { + @Override public void mouseClicked(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e)) + setExpanded(!isExpanded()); + } + }); + trailing.add(Box.createHorizontalStrut(8)); + trailing.add(inactiveNote); + trailing.add(Box.createHorizontalStrut(8)); + trailing.add(resetLink); + section.header().add(trailing, BorderLayout.EAST); + } + + @Override public java.awt.Dimension getMinimumSize() { + return new java.awt.Dimension(0, super.getMinimumSize().height); + } + + public String title() { return title; } + public JComponent fields() { return fields; } + + public void setChangedCount(int count) { + setChangedCount(count, count > 0); + } + + public void setChangedCount(int count, boolean showReset) { + changedBadge.setText(String.valueOf(count)); + changedBadge.setVisible(count > 0); + resetLink.setVisible(showReset && resetAction != null); + revalidate(); + repaint(); + } + + public void onReset(Runnable action) { + resetAction = action; + resetLink.setVisible(action != null && changedBadge.isVisible()); + } + + public void setActive(boolean active, String inactiveNoteText) { + this.active = active; + setInactiveNote(active ? null : inactiveNoteText); + } + + public void setInactiveNote(String text) { + inactiveNote.setText(text); + inactiveNote.setVisible(text != null && !text.isEmpty()); + revalidate(); + repaint(); + } + + public void setExpanded(boolean expanded) { + section.setExpanded(expanded); + } + + public boolean isExpanded() { + return section.isExpanded(); + } + + @Override + public void paint(Graphics graphics) { + super.paint(graphics); + if (active) + return; + Graphics2D g = (Graphics2D) graphics.create(); + g.setColor(new Color(0, 0, 0, 140)); + var bounds = SwingUtilities.convertRectangle(section, section.content().getBounds(), this); + if (section.isExpanded()) + g.fill(bounds); + g.dispose(); + } + + private static JLabel pill(Color background, Color foreground) { + JLabel label = new JLabel("", SwingConstants.CENTER) { + @Override public java.awt.Dimension getPreferredSize() { + return new java.awt.Dimension(super.getPreferredSize().width, 16); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(background); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 3, 3); + g.dispose(); + super.paintComponent(graphics); + } + }; + label.setOpaque(false); + label.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + label.setForeground(foreground); + label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); + return label; + } + + private JLabel resetLink() { + JLabel label = new JLabel("Reset") { + private boolean hover; + + @Override + protected void paintComponent(Graphics graphics) { + if (hover) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0x2C2C2C)); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 4, 4); + g.dispose(); + } + super.paintComponent(graphics); + } + + { + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hover = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hover = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event) && resetAction != null) + resetAction.run(); + } + }); + } + }; + label.setOpaque(false); + label.setFont(WorkspaceStyle.UI.deriveFont(11f)); + label.setForeground(new Color(0x9A9A9A)); + label.setBorder(BorderFactory.createEmptyBorder(2, 6, 2, 6)); + label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + return label; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/SearchableIdDropdown.java b/Tools/Dev/java/rs117/hd/dev/editor/SearchableIdDropdown.java new file mode 100644 index 0000000..84f2400 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/SearchableIdDropdown.java @@ -0,0 +1,167 @@ +package rs117.hd.dev.editor; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.FlowLayout; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; +import javax.swing.JPanel; + +/** Compact summary and draft editor for a list of IDs. */ +public final class SearchableIdDropdown extends JPanel { + + public static final class Choice { + public final int id; + public final String name; + private final String searchText; + public final String badgeLetter; // e.g. "N", "O", "G" — null/empty means no badge drawn for this row + public final Color badgeColor; // ignored if badgeLetter is null/empty + + public Choice(int id, String name, String badgeLetter, Color badgeColor) { + this(id, name, badgeLetter, badgeColor, name + " " + id); + } + + public Choice(int id, String name, String badgeLetter, Color badgeColor, String searchText) { + this.id = id; + this.name = name; + this.searchText = searchText.toLowerCase(Locale.ROOT); + this.badgeLetter = badgeLetter; + this.badgeColor = badgeColor; + } + } + + public interface Provider { + List items(); // full universe this dropdown can pick from + } + + private final Provider provider; + private final Set selectedIds = new LinkedHashSet<>(); + private final List>> listeners = new ArrayList<>(); + private final JPanel summary = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); + + private String searchPlaceholder = "Search by name or ID"; + private String title = "IDs"; + private java.util.function.IntFunction nearby = id -> null; + + public static Builder builder(Provider provider) { return new Builder(provider); } + + public static final class Builder { + private final Provider provider; + private String placeholder = "Search by name or ID"; + private Set selected; + private String title = "IDs"; + private java.util.function.IntFunction nearby = id -> null; + private Consumer> listener; + + private Builder(Provider provider) { this.provider = provider; } + public Builder searchPlaceholder(String value) { placeholder = value; return this; } + public Builder selected(Set ids) { selected = new LinkedHashSet<>(ids); return this; } + public Builder onChange(Consumer> action) { listener = action; return this; } + + public Builder title(String value) { title = value; return this; } + public Builder nearby(java.util.function.IntFunction value) { nearby = value; return this; } + + public SearchableIdDropdown build() { + var dropdown = new SearchableIdDropdown(provider); + dropdown.title = title; + dropdown.nearby = nearby; + dropdown.setSearchPlaceholder(placeholder); + if (selected != null) + dropdown.setSelected(selected); + if (listener != null) + dropdown.onChange(listener); + return dropdown; + } + } + + public SearchableIdDropdown(Provider provider) { + this.provider = Objects.requireNonNull(provider); + + setOpaque(false); + setLayout(new BorderLayout(0, 6)); + + summary.setOpaque(false); + add(summary, BorderLayout.CENTER); + + refreshSummary(); + } + + public void setSearchPlaceholder(String placeholder) { + this.searchPlaceholder = placeholder; + } + + public void setSelected(Set ids) { + selectedIds.clear(); + selectedIds.addAll(ids); + refreshSummary(); + notifyChange(); + } + + public Set getSelected() { + return new LinkedHashSet<>(selectedIds); + } + + public void onChange(Consumer> listener) { + listeners.add(Objects.requireNonNull(listener)); + } + + private void openModal(boolean selectedOnly) { + Map itemsById = new LinkedHashMap<>(); + for (Choice choice : provider.items()) + itemsById.put(choice.id, choice); + var options = new LinkedHashSet<>(selectedOnly ? selectedIds : itemsById.keySet()); + options.addAll(selectedIds); + new SelectionModal((selectedOnly ? "View " : "Add ") + title, new ArrayList<>(options), selectedIds, id -> { + Choice choice = itemsById.get(id); + return choice == null ? "ID " + id : choice.name; + }).search(searchPlaceholder, id -> itemsById.containsKey(id) ? itemsById.get(id).searchText : Integer.toString(id)) + .badge(title.startsWith("NPC") ? "N" : title.startsWith("Object") ? "O" : "G", + new Color(title.startsWith("NPC") ? 0xC25B5B : title.startsWith("Object") ? 0x5B8AC2 : 0x9A6BC2)) + .rowMeta(id -> Integer.toString(id)) + .nearby(nearby::apply) + .rawOption(query -> { + Integer id = parseInt(query); + return !selectedOnly && id != null && id >= 0 && !options.contains(id) ? id : null; + }).open(this, this::setSelected); + } + + private void refreshSummary() { + summary.removeAll(); + int count = selectedIds.size(); + if (count > 0) { + summary.add(EditorButton.builder().text("View - " + count).onClick(() -> openModal(true)).build()); + summary.add(javax.swing.Box.createHorizontalStrut(6)); + } else { + summary.add(EditorText.builder("None").color(WorkspaceStyle.DIM).build()); + summary.add(javax.swing.Box.createHorizontalStrut(6)); + } + summary.add(DashedAddButton.create("Add", () -> openModal(false))); + summary.revalidate(); + summary.repaint(); + } + + private void notifyChange() { + var copy = new LinkedHashSet<>(selectedIds); + for (Consumer> listener : listeners) + listener.accept(new LinkedHashSet<>(copy)); + } + + private static Integer parseInt(String text) { + String trimmed = text.trim(); + if (trimmed.isEmpty()) + return null; + try { + return Integer.valueOf(trimmed); + } catch (NumberFormatException e) { + return null; + } + } + +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/SegmentedControl.java b/Tools/Dev/java/rs117/hd/dev/editor/SegmentedControl.java new file mode 100644 index 0000000..ff8ba1b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/SegmentedControl.java @@ -0,0 +1,168 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Function; +import javax.swing.*; + +/** A single-select segmented button group, similar to {@code WorkspaceStyle.Button.SEGMENT}. */ +public final class SegmentedControl extends JPanel { + private static final int CONTROL_HEIGHT = 24; + private static final int PADDING = 2; + private static final int GAP = 2; + private static final Color TRACK = new Color(0x1A1A1A); + private static final Color TRACK_BORDER = new Color(0x333333); + private static final Color SEGMENT_HOVER = new Color(0x2C2C2C); + private final Function marker; + private final Font optionFont; + private final Font activeFont; + private static final Color IDLE_TEXT = new Color(0xA9A9A9); + + private final Function label; + private final List segments = new ArrayList<>(); + private T selected; + private Consumer listener; + + public static Builder builder(List options) { return new Builder<>(options); } + + public static final class Builder { + private final List options; + private Function label = String::valueOf; + private T selected; + private Consumer action; + private boolean values; + private Function marker; + + private Builder(List options) { + this.options = List.copyOf(options); + if (this.options.isEmpty()) + throw new IllegalArgumentException("A segmented control needs at least one option"); + selected = this.options.get(0); + } + + public Builder label(Function value) { label = Objects.requireNonNull(value); return this; } + public Builder values() { values = true; return this; } + public Builder marker(Function value) { marker = value; return this; } + public Builder selected(T value) { selected = value; return this; } + public Builder onChange(Consumer value) { action = value; return this; } + + public SegmentedControl build() { + if (!options.contains(selected)) + throw new IllegalArgumentException("The selected value must be one of the options"); + var control = new SegmentedControl<>(options, label, selected, values, marker); + control.onChange(action); + return control; + } + } + + public SegmentedControl(List options, Function label, T selected) { + this(options, label, selected, false, null); + } + + private SegmentedControl(List options, Function label, T selected, boolean values, Function marker) { + this.marker = marker; + optionFont = (values ? WorkspaceStyle.MONO : WorkspaceStyle.UI).deriveFont(11f); + activeFont = (values ? WorkspaceStyle.MONO_SEMIBOLD : WorkspaceStyle.SEMIBOLD).deriveFont(11f); + this.label = label; + this.selected = selected; + + setLayout(new GridLayout(1, options.size(), GAP, 0)); + setOpaque(false); + setBorder(BorderFactory.createEmptyBorder(PADDING, PADDING, PADDING, PADDING)); + + for (T option : options) { + var segment = new Segment(option); + segments.add(segment); + add(segment); + } + } + + public T getSelected() { return selected; } + + /** Sets the selection without firing {@link #onChange}. */ + public void setSelected(T value) { + selected = value; + repaintSegments(); + } + + public void onChange(Consumer listener) { + this.listener = listener; + } + + private void repaintSegments() { + for (Segment segment : segments) + segment.repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(TRACK); + g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 4, 4); + g.setColor(TRACK_BORDER); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 4, 4); + g.dispose(); + } + + private final class Segment extends JComponent { + private final T option; + private boolean hover; + + Segment(T option) { + this.option = option; + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hover = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hover = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event) && !Objects.equals(option, selected)) { + selected = option; + repaintSegments(); + if (listener != null) + listener.accept(selected); + } + } + }); + } + + @Override + public Dimension getPreferredSize() { + FontMetrics metrics = getFontMetrics(activeFont); + return new Dimension(metrics.stringWidth(label.apply(option)) + 16, CONTROL_HEIGHT - PADDING * 2); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + boolean active = Objects.equals(option, selected); + if (active) { + g.setColor(marker == null ? WorkspaceStyle.ACCENT : new Color(0x454545)); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 3, 3); + } else if (hover) { + g.setColor(SEGMENT_HOVER); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 3, 3); + } + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setFont(active ? activeFont : optionFont); + g.setColor(active ? Color.WHITE : IDLE_TEXT); + String text = label.apply(option); + FontMetrics metrics = g.getFontMetrics(); + int x = (getWidth() - metrics.stringWidth(text)) / 2; + if (marker != null) { + x += 3; + g.setColor(marker.apply(option)); + g.fillOval(x - 7, (getHeight() - 5) / 2, 5, 5); + g.setColor(active ? Color.WHITE : IDLE_TEXT); + } + int y = (getHeight() - metrics.getHeight()) / 2 + metrics.getAscent(); + g.drawString(text, x, y); + g.dispose(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/SelectionModal.java b/Tools/Dev/java/rs117/hd/dev/editor/SelectionModal.java new file mode 100644 index 0000000..9ee29bc --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/SelectionModal.java @@ -0,0 +1,371 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.function.*; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +/** Searchable multi-selection dialog. Only Done publishes the draft. */ +public final class SelectionModal { + private static final Color SURFACE = new Color(0x262626); + private static final Color FOOTER = new Color(0x222222); + private static final Color DIVIDER = new Color(0x1E1E1E); + private final String title; + private final List options; + private final Set original; + private final Function label; + private Function searchKey; + private Function rawOption = query -> null; + private Function nearby; + private Consumer hover = value -> {}; + private JComponent preview; + private Function rowContent; + private int rowHeight; + private String selectionLabel = "IDs"; + private Function rowMeta = value -> null; + private String badgeLetter; + private Color badgeColor; + private String placeholder = "Search by name or ID"; + + public SelectionModal(String title, List options, Set selected, Function label) { + this.title = title; + this.options = options; + this.original = new LinkedHashSet<>(selected); + this.label = label; + this.searchKey = label; + } + + public SelectionModal search(String placeholder, Function searchKey) { + this.placeholder = placeholder; + this.searchKey = searchKey; + return this; + } + + public SelectionModal rawOption(Function factory) { rawOption = factory; return this; } + public SelectionModal nearby(Function description) { nearby = description; return this; } + + public SelectionModal rowMeta(Function description) { rowMeta = description; return this; } + + public SelectionModal badge(String letter, Color color) { + badgeLetter = letter; + badgeColor = color; + return this; + } + + public SelectionModal rows(int height, String selectionLabel, Function renderer) { + rowHeight = height; + this.selectionLabel = selectionLabel; + rowContent = renderer; + return this; + } + + public SelectionModal preview(JComponent component, Consumer onHover) { + preview = component; + hover = onHover; + return this; + } + + public void open(JComponent anchor, Consumer> commit) { + var window = SwingUtilities.getWindowAncestor(anchor); + if (!(window instanceof JFrame)) + return; + + var owner = (JFrame) window; + var draft = new LinkedHashSet<>(original); + // options can be the entire NPC/object/graphic catalog (thousands of entries); precompute each + // one's lowercase search key once instead of redoing it for every item on every keystroke. + var searchKeysLower = new java.util.ArrayList(options.size()); + for (T item : options) + searchKeysLower.add(searchKey.apply(item).toLowerCase(Locale.ROOT)); + var content = panel(new BorderLayout()); + var titleRow = panel(new BorderLayout()); + titleRow.setPreferredSize(new Dimension(0, 45)); + titleRow.setBorder(sectionBorder(0, 16, 0, 10, false)); + if (badgeLetter != null) { + var badge = new JLabel(badgeLetter, SwingConstants.CENTER) { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(badgeColor); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 4, 4); + g.dispose(); + super.paintComponent(graphics); + } + }; + badge.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(10f)); + badge.setForeground(Color.WHITE); + badge.setPreferredSize(new Dimension(16, 16)); + var badgeSlot = new JPanel(new GridBagLayout()); + badgeSlot.setOpaque(false); + badgeSlot.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 9)); + badgeSlot.add(badge); + titleRow.add(badgeSlot, BorderLayout.WEST); + } + titleRow.add(EditorText.builder(title).font(WorkspaceStyle.SEMIBOLD.deriveFont(13f)).build()); + Runnable close = () -> SwingUtilities.getWindowAncestor(content).dispose(); + var closeSlot = new JPanel(new GridBagLayout()); + closeSlot.setOpaque(false); + closeSlot.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("close", 10).size(24, 24).tooltip("Close").onClick(close).build()); + titleRow.add(closeSlot, BorderLayout.EAST); + content.add(titleRow, BorderLayout.NORTH); + + var searchRow = EditorSearch.builder(placeholder).background(new Color(0x1A1A1A)) + .outline(WorkspaceStyle.ACCENT).gap(8).padding(8, 8).height(28).build(); + var search = searchRow.field(); + var results = EditorText.builder("").font(WorkspaceStyle.UI.deriveFont(11f)).color(new Color(0x7D7D7D)).build(); + var filters = panel(new BorderLayout(6, 8)); + filters.add(searchRow, BorderLayout.NORTH); + filters.add(results, BorderLayout.EAST); + + var model = new DefaultListModel(); + var list = new JList(model) { + @Override public String getToolTipText(MouseEvent event) { + int index = rowAt(this, event); + return rowContent != null && index >= 0 ? label.apply(model.get(index)) : null; + } + }; + if (rowContent != null) + ToolTipManager.sharedInstance().registerComponent(list); + list.setFixedCellHeight(rowHeight > 0 ? rowHeight : preview == null ? 32 : 34); + list.setFixedCellWidth(1); + list.setBackground(SURFACE); + list.setCellRenderer((source, item, index, highlighted, focused) -> { + var row = new JPanel(new BorderLayout(8, 0)); + row.setBackground(draft.contains(item) ? new Color(0x2A3446) : highlighted ? new Color(0x2E2E2E) : SURFACE); + row.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); + boolean checked = draft.contains(item); + var check = new JComponent() { + @Override protected void paintComponent(Graphics g) { + int y = (getHeight() - 14) / 2; + g.setColor(checked ? WorkspaceStyle.ACCENT : new Color(0x555555)); + if (checked) { + g.fillRoundRect(0, y, 14, 14, 4, 4); + g.setColor(Color.WHITE); + g.drawLine(3, y + 7, 6, y + 10); + g.drawLine(6, y + 10, 11, y + 4); + } else { + g.drawRoundRect(0, y, 13, 13, 4, 4); + } + } + }; + check.setPreferredSize(new Dimension(14, 14)); + row.add(check, BorderLayout.WEST); + if (rowContent != null) { + row.add(rowContent.apply(item)); + return row; + } + boolean isRaw = item.equals(rawOption.apply(search.getText().strip())); + row.add(EditorText.builder(isRaw ? "+ Add " + label.apply(item) + " (not in gamevals)" : label.apply(item)) + .font(WorkspaceStyle.MONO.deriveFont(12f)).build()); + if (isRaw) + row.setBackground(new Color(0x2A3446)); + String tag = nearby == null ? null : nearby.apply(item); + var meta = new JPanel(new BorderLayout(14, 0)); + meta.setOpaque(false); + if (tag != null) { + var badge = EditorText.builder(tag).font(WorkspaceStyle.SEMIBOLD.deriveFont(10f)) + .color(new Color(0x9FCF86)).build(); + badge.setOpaque(true); + badge.setBackground(new Color(0x24331F)); + badge.setBorder(BorderFactory.createEmptyBorder(1, 5, 1, 5)); + var badgeSlot = new JPanel(new GridBagLayout()); + badgeSlot.setOpaque(false); + badgeSlot.add(badge); + meta.add(badgeSlot, BorderLayout.WEST); + } + String details = rowMeta.apply(item); + if (details != null) { + var value = EditorText.builder(details).font(WorkspaceStyle.MONO.deriveFont(11f)) + .color(new Color(0x7D7D7D)).build(); + value.setHorizontalAlignment(SwingConstants.RIGHT); + if (preview == null) + value.setPreferredSize(new Dimension(52, 16)); + meta.add(value, BorderLayout.EAST); + } + row.add(meta, BorderLayout.EAST); + return row; + }); + var left = panel(new BorderLayout(0, 6)); + left.setBorder(BorderFactory.createEmptyBorder(12, 16, 0, 16)); + left.add(filters, BorderLayout.NORTH); + var resultsScroll = scroll(list); + resultsScroll.getVerticalScrollBar().setUnitIncrement(list.getFixedCellHeight()); + left.add(resultsScroll); + if (preview == null) { + content.add(left); + } else { + var columns = panel(new GridLayout(1, 2, 8, 0)); + columns.add(left); + columns.add(preview); + content.add(columns); + } + + var selected = new JPanel(); + selected.setLayout(new BoxLayout(selected, BoxLayout.X_AXIS)); + selected.setBackground(SURFACE); + var count = EditorText.builder("").font(WorkspaceStyle.UI.deriveFont(11f)).color(new Color(0x9A9A9A)).build(); + var caption = EditorText.builder("").font(WorkspaceStyle.SEMIBOLD.deriveFont(10f)) + .color(new Color(0x7D7D7D)).build(); + Runnable[] refreshSelection = new Runnable[1]; + refreshSelection[0] = () -> { + if (preview != null) { + selected.removeAll(); + if (draft.isEmpty()) + selected.add(EditorText.builder("Nothing selected yet.").color(WorkspaceStyle.DIM).build()); + for (T item : draft) { + if (selected.getComponentCount() > 0) + selected.add(Box.createHorizontalStrut(4)); + selected.add(EditorButton.builder().text(label.apply(item) + " ×").onClick(() -> { + draft.remove(item); + refreshSelection[0].run(); + }).build()); + } + caption.setText("SELECTED · " + draft.size()); + } + count.setText(draft.size() + " " + (preview == null ? selectionLabel : "areas") + " selected"); + selected.revalidate(); + selected.repaint(); + list.repaint(); + }; + refreshSelection[0].run(); + + Runnable applyFilter = () -> { + model.clear(); + String query = search.getText().strip(); + String lower = query.toLowerCase(Locale.ROOT); + T raw = rawOption.apply(query); + if (raw != null) + model.addElement(raw); + int matches = model.size(); + for (int i = 0; i < options.size(); i++) { + if (searchKeysLower.get(i).contains(lower)) { + model.addElement(options.get(i)); + matches++; + } + } + resultsScroll.getViewport().setViewPosition(new Point()); + results.setText(matches == 0 ? "No matches." : matches + (matches == 1 ? " result" : " results")); + }; + search.getDocument().addDocumentListener(new DocumentListener() { + public void insertUpdate(DocumentEvent e) { applyFilter.run(); } + public void removeUpdate(DocumentEvent e) { applyFilter.run(); } + public void changedUpdate(DocumentEvent e) { applyFilter.run(); } + }); + applyFilter.run(); + + list.addMouseMotionListener(new MouseMotionAdapter() { + @Override public void mouseMoved(MouseEvent e) { + int index = rowAt(list, e); + if (index >= 0) + hover.accept(model.get(index)); + } + }); + Consumer toggle = item -> { + hover.accept(item); + if (!draft.remove(item)) + draft.add(item); + if (item.equals(rawOption.apply(search.getText().strip()))) + search.setText(""); + refreshSelection[0].run(); + }; + list.addMouseListener(new MouseAdapter() { + @Override public void mousePressed(MouseEvent e) { showRemoveMenu(e); } + @Override public void mouseReleased(MouseEvent e) { showRemoveMenu(e); } + + private void showRemoveMenu(MouseEvent e) { + if (rowContent == null || !e.isPopupTrigger()) + return; + int index = rowAt(list, e); + if (index < 0 || !draft.contains(model.get(index))) + return; + T item = model.get(index); + new HdContextMenu("Area Edit") + .danger("Remove", "trash", "", () -> { + draft.remove(item); + refreshSelection[0].run(); + }).show(list, e.getX(), e.getY()); + } + + @Override public void mouseClicked(MouseEvent e) { + int index = rowAt(list, e); + if (index >= 0 && SwingUtilities.isLeftMouseButton(e)) + toggle.accept(model.get(index)); + } + }); + list.registerKeyboardAction(e -> { + if (list.getSelectedValue() != null) + toggle.accept(list.getSelectedValue()); + }, KeyStroke.getKeyStroke("SPACE"), JComponent.WHEN_FOCUSED); + + var footer = panel(new BorderLayout()); + if (preview != null) { + var selectedStrip = scroll(selected); + selectedStrip.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + selectedStrip.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); + selectedStrip.getViewport().setBackground(SURFACE); + selectedStrip.setPreferredSize(new Dimension(0, 29)); + var selectionPanel = panel(new BorderLayout(0, 2)); + selectionPanel.setPreferredSize(new Dimension(0, 55)); + selectionPanel.setBorder(sectionBorder(8, 16, 3, 16, true)); + selectionPanel.add(caption, BorderLayout.NORTH); + selectionPanel.add(selectedStrip); + footer.add(selectionPanel, BorderLayout.NORTH); + } + var actionRow = panel(new BorderLayout()); + actionRow.setBackground(FOOTER); + actionRow.setPreferredSize(new Dimension(0, 49)); + actionRow.setBorder(sectionBorder(0, 16, 0, 16, true)); + actionRow.add(count, BorderLayout.WEST); + var actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 10)); + actions.setOpaque(false); + actions.add(EditorButton.builder().style(WorkspaceStyle.Button.SECONDARY) + .text("Cancel").size(61, 28).onClick(close).build()); + var done = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY).text("Done").size(57, 28).onClick(() -> { + close.run(); + if (!original.equals(draft)) + commit.accept(draft); + }).build(); + actions.add(Box.createHorizontalStrut(8)); + done.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(11f)); + actions.add(done); + actionRow.add(actions, BorderLayout.EAST); + footer.add(actionRow, BorderLayout.SOUTH); + content.add(footer, BorderLayout.SOUTH); + search.addActionListener(e -> {}); + var dialog = EditorModal.builder(owner, title).content(content) + .size(Math.min(preview == null ? 520 : 720, owner.getWidth() - 40), + Math.min(preview == null ? 560 : 520, owner.getHeight() - 40)) + .initialFocus(search).open(); + dialog.getRootPane().setDefaultButton(done); + } + + private static int rowAt(JList list, MouseEvent event) { + int index = list.locationToIndex(event.getPoint()); + return index >= 0 && list.getCellBounds(index, index).contains(event.getPoint()) ? index : -1; + } + + private static JScrollPane scroll(JComponent component) { + var scroll = new EditorScrollPane(component, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(null); + return scroll; + } + + private static javax.swing.border.Border sectionBorder(int top, int left, int bottom, int right, boolean topDivider) { + return BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(topDivider ? 1 : 0, 0, + topDivider ? 0 : 1, 0, DIVIDER), BorderFactory.createEmptyBorder(top, left, bottom, right)); + } + + private static JPanel panel(LayoutManager layout) { + var panel = new JPanel(layout); + panel.setBackground(SURFACE); + return panel; + } +} + diff --git a/Tools/Dev/java/rs117/hd/dev/editor/SwatchDropdown.java b/Tools/Dev/java/rs117/hd/dev/editor/SwatchDropdown.java new file mode 100644 index 0000000..9a8be5e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/SwatchDropdown.java @@ -0,0 +1,417 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.RoundRectangle2D; +import java.util.List; +import java.util.function.Consumer; +import javax.swing.*; + +/** Trigger + popup for picking one color off a model's face-color palette (see §6.3). */ +public final class SwatchDropdown extends JPanel { + private static final int TRIGGER_HEIGHT = 30; + private static final int PREVIEW_SWATCH_WIDTH = 10; + private static final int PREVIEW_SWATCH_HEIGHT = 22; + private static final int PREVIEW_COUNT = 5; + private static final int POPUP_MIN_WIDTH = 280; + private static final int GRID_MAX_HEIGHT = 300; + private static final int TILE_MIN_WIDTH = 48; + private static final int TILE_GAP = 4; + private static final Color TRIGGER_TEXT = new Color(0xBD, 0xBD, 0xBD); + private static final Color CAPTION_COLOR = new Color(0x7D, 0x7D, 0x7D); + private static final Color HINT_COLOR = new Color(0x6F, 0x6F, 0x6F); + private static final Color SWATCH_INSET_BORDER = new Color(255, 255, 255, 26); + private static final Color FACE_COUNT_COLOR = new Color(0x8A, 0x8A, 0x8A); + + public static final class Swatch { + public final Color color; + public final int hue, saturation, lightness, faceCount; + public final boolean clickable; + + public Swatch(Color color, int hue, int saturation, int lightness, int faceCount, boolean clickable) { + this.color = color; + this.hue = hue; + this.saturation = saturation; + this.lightness = lightness; + this.faceCount = faceCount; + this.clickable = clickable; + } + } + + public interface Provider { + List allColors(); + List mostUsedColors(); + } + + private final Provider provider; + private final Trigger trigger; + private Consumer hoverListener; + private Consumer selectListener; + private PopupLayer.Handle openHandle; + + public static Builder builder(Provider provider) { return new Builder(provider); } + + public static final class Builder { + private final Provider provider; + private Consumer hover; + private Consumer selection; + + private Builder(Provider provider) { this.provider = provider; } + public Builder onHover(Consumer action) { hover = action; return this; } + public Builder onSelect(Consumer action) { selection = action; return this; } + + public SwatchDropdown build() { + var dropdown = new SwatchDropdown(provider); + dropdown.onHover(hover); + dropdown.onSelect(selection); + return dropdown; + } + } + + public SwatchDropdown(Provider provider) { + super(new BorderLayout()); + this.provider = provider; + setOpaque(false); + trigger = new Trigger(); + add(trigger, BorderLayout.CENTER); + } + + public void onHover(Consumer listener) { + this.hoverListener = listener; + } + + public void onSelect(Consumer listener) { + this.selectListener = listener; + } + + private void fireHover(Swatch swatch) { + if (hoverListener != null) + hoverListener.accept(swatch); + } + + private void fireSelect(Swatch swatch) { + if (selectListener != null) + selectListener.accept(swatch); + } + + private static void copy(String text) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(text), null); + } + + private void openPopup() { + if (openHandle != null && !openHandle.isClosed()) { + openHandle.close(); + return; + } + openHandle = PopupLayer.show(trigger, buildPopupContent(), POPUP_MIN_WIDTH); + trigger.repaint(); + } + + private JPanel buildPopupContent() { + JPanel root = new JPanel(new BorderLayout()); + root.setOpaque(false); + + JPanel header = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gap 8 0, fillx", "[grow][]", "[24!]")); + header.setOpaque(false); + header.setBorder(BorderFactory.createEmptyBorder(6, 8, 6, 8)); + + JLabel caption = new JLabel("MODEL COLORS".toUpperCase()); + caption.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(10f)); + caption.setForeground(CAPTION_COLOR); + header.add(caption, "aligny center"); + + SegmentedControl sort = SegmentedControl.builder(List.of("Hue", "Most used")).build(); + header.add(sort, "height 24!, aligny center"); + root.add(header, BorderLayout.NORTH); + + Grid grid = new Grid(); + grid.setItems(provider.allColors()); + sort.onChange(value -> grid.setItems("Hue".equals(value) ? provider.allColors() : provider.mostUsedColors())); + + JScrollPane scroll = new EditorScrollPane(grid, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) { + @Override + public Dimension getPreferredSize() { + Dimension preferred = super.getPreferredSize(); + return new Dimension(preferred.width, Math.min(preferred.height, GRID_MAX_HEIGHT)); + } + }; + scroll.setOpaque(false); + scroll.getViewport().setOpaque(false); + scroll.setBorder(BorderFactory.createEmptyBorder()); + root.add(scroll, BorderLayout.CENTER); + + JPanel footer = new JPanel(new BorderLayout()); + footer.setOpaque(false); + footer.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(1, 0, 0, 0, WorkspaceStyle.BORDER), + BorderFactory.createEmptyBorder(6, 8, 6, 8))); + JLabel hint = new JLabel("Hover to highlight on the model · number = faces"); + hint.setFont(WorkspaceStyle.UI.deriveFont(10f)); + hint.setForeground(HINT_COLOR); + footer.add(hint, BorderLayout.WEST); + root.add(footer, BorderLayout.SOUTH); + + return root; + } + + /** 30px tall trigger: most-used-color preview strip, color count, chevron. */ + private final class Trigger extends JComponent { + private boolean hover; + + Trigger() { + setOpaque(false); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hover = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hover = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) + openPopup(); + } + }); + } + + private List previewSwatches() { + List mostUsed = provider.mostUsedColors(); + return mostUsed.subList(0, Math.min(PREVIEW_COUNT, mostUsed.size())); + } + + private String labelText() { + return provider.allColors().size() + " colors on this model"; + } + + @Override + public Dimension getPreferredSize() { + int previewCount = previewSwatches().size(); + int stripWidth = previewCount * PREVIEW_SWATCH_WIDTH; + FontMetrics metrics = getFontMetrics(WorkspaceStyle.UI.deriveFont(12f)); + int textWidth = metrics.stringWidth(labelText()); + int width = 8 + stripWidth + (previewCount > 0 ? 8 : 0) + textWidth + 10 + 16 + 8; + return new Dimension(Math.max(width, 140), TRIGGER_HEIGHT); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + int width = getWidth(), height = getHeight(); + boolean open = openHandle != null && !openHandle.isClosed(); + g.setColor(WorkspaceStyle.INPUT); + g.fillRoundRect(0, 0, width - 1, height - 1, 4, 4); + g.setColor(open || hover ? WorkspaceStyle.ACCENT : WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, width - 1, height - 1, 4, 4); + + int x = 8; + List preview = previewSwatches(); + if (!preview.isEmpty()) { + int stripWidth = preview.size() * PREVIEW_SWATCH_WIDTH; + int stripY = (height - PREVIEW_SWATCH_HEIGHT) / 2; + Shape previousClip = g.getClip(); + g.clip(new RoundRectangle2D.Float(x, stripY, stripWidth, PREVIEW_SWATCH_HEIGHT, 3, 3)); + for (int i = 0; i < preview.size(); i++) { + g.setColor(preview.get(i).color); + g.fillRect(x + i * PREVIEW_SWATCH_WIDTH, stripY, PREVIEW_SWATCH_WIDTH, PREVIEW_SWATCH_HEIGHT); + } + g.setClip(previousClip); + x += stripWidth + 8; + } + + g.setFont(WorkspaceStyle.UI.deriveFont(12f)); + g.setColor(TRIGGER_TEXT); + FontMetrics metrics = g.getFontMetrics(); + g.drawString(labelText(), x, (height - metrics.getHeight()) / 2 + metrics.getAscent()); + + WorkspaceStyle.icon("chevron-down", 9).paintIcon(this, g, width - 17, (height - 9) / 2); + g.dispose(); + } + } + + /** Responsive wrap-grid of {@link Tile}s, scrolled by the enclosing {@link JScrollPane}. */ + private final class Grid extends JPanel implements Scrollable { + Grid() { + setOpaque(false); + setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); + setLayout(null); + } + + void setItems(List items) { + removeAll(); + for (Swatch swatch : items) + add(new Tile(swatch)); + revalidate(); + repaint(); + } + + private int innerWidth() { + Insets insets = getInsets(); + int width = getWidth(); + if (width <= 0) + width = POPUP_MIN_WIDTH - 2 * 6; + return Math.max(1, width - insets.left - insets.right); + } + + private int columns() { + return Math.max(1, innerWidth() / TILE_MIN_WIDTH); + } + + private int tileHeight() { + int height = 0; + for (int i = 0; i < getComponentCount(); i++) + height = Math.max(height, getComponent(i).getPreferredSize().height); + return height; + } + + @Override + public void doLayout() { + Insets insets = getInsets(); + int columns = columns(); + int tileWidth = Math.max(1, (innerWidth() - TILE_GAP * (columns - 1)) / columns); + int tileHeight = tileHeight(); + int count = getComponentCount(); + for (int i = 0; i < count; i++) { + int row = i / columns, col = i % columns; + int x = insets.left + col * (tileWidth + TILE_GAP); + int y = insets.top + row * (tileHeight + TILE_GAP); + getComponent(i).setBounds(x, y, tileWidth, tileHeight); + } + } + + @Override + public Dimension getPreferredSize() { + Insets insets = getInsets(); + int width = getWidth(); + if (width <= 0) + width = POPUP_MIN_WIDTH; + int columns = columns(); + int count = getComponentCount(); + int rows = count == 0 ? 0 : (count + columns - 1) / columns; + int height = insets.top + insets.bottom; + if (rows > 0) + height += rows * tileHeight() + (rows - 1) * TILE_GAP; + return new Dimension(width, height); + } + + @Override + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } + + @Override + public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { + return 24; + } + + @Override + public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { + return 96; + } + + @Override + public boolean getScrollableTracksViewportWidth() { + return true; + } + + @Override + public boolean getScrollableTracksViewportHeight() { + return false; + } + } + + /** One color tile: 28px swatch, face count below, hover/click driven by the owning dropdown. */ + private final class Tile extends JComponent { + private static final int SWATCH_SIZE = 28; + private static final int PADDING = 3; + + private final Swatch swatch; + private boolean hover; + + Tile(Swatch swatch) { + this.swatch = swatch; + setOpaque(false); + setToolTipText(String.format( + "h%d s%d l%d · %d faces", swatch.hue, swatch.saturation, swatch.lightness, swatch.faceCount)); + setCursor(swatch.clickable ? Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) : Cursor.getDefaultCursor()); + setFocusable(true); + HdContextMenu.install(this, point -> { + Point at = point == null ? new Point(0, getHeight()) : point; + int packed = swatch.hue << 10 | swatch.saturation << 7 | swatch.lightness; + var menu = new HdContextMenu("◐", swatch.color, + String.format("h%d · s%d · l%d · %d faces", swatch.hue, swatch.saturation, swatch.lightness, swatch.faceCount)); + if (swatch.clickable && selectListener != null) + menu.item("Use color for override", "plus", "", () -> { + if (openHandle != null) + openHandle.close(); + fireSelect(swatch); + }); + menu.separator() + .item("Copy HSL", "copy", "", () -> copy(swatch.hue + ", " + swatch.saturation + ", " + swatch.lightness)) + .item("Copy packed int", "copy", "", () -> copy(Integer.toString(packed))) + .show(this, at.x, at.y); + }); + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { + hover = true; + repaint(); + fireHover(swatch); + } + @Override public void mouseExited(MouseEvent event) { + hover = false; + repaint(); + fireHover(null); + } + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event) && swatch.clickable) { + if (openHandle != null) + openHandle.close(); + fireSelect(swatch); + } + } + }); + } + + @Override + public Dimension getPreferredSize() { + FontMetrics metrics = getFontMetrics(WorkspaceStyle.MONO.deriveFont(9f)); + int height = PADDING + SWATCH_SIZE + 2 + metrics.getHeight() + PADDING; + return new Dimension(SWATCH_SIZE + PADDING * 2, height); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + Composite previousComposite = g.getComposite(); + if (!swatch.clickable) + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.35f)); + + int width = getWidth(), height = getHeight(); + if (hover) { + g.setColor(WorkspaceStyle.HEADER); + g.fillRoundRect(0, 0, width, height, 4, 4); + } + + int swatchX = (width - SWATCH_SIZE) / 2; + int swatchY = PADDING; + g.setColor(swatch.color); + g.fillRoundRect(swatchX, swatchY, SWATCH_SIZE, SWATCH_SIZE, 3, 3); + g.setColor(SWATCH_INSET_BORDER); + g.drawRoundRect(swatchX, swatchY, SWATCH_SIZE - 1, SWATCH_SIZE - 1, 3, 3); + + g.setFont(WorkspaceStyle.MONO.deriveFont(9f)); + g.setColor(FACE_COUNT_COLOR); + FontMetrics metrics = g.getFontMetrics(); + String text = String.valueOf(swatch.faceCount); + int textX = (width - metrics.stringWidth(text)) / 2; + int textY = swatchY + SWATCH_SIZE + 2 + metrics.getAscent(); + g.drawString(text, textX, textY); + + g.setComposite(previousComposite); + g.dispose(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/SwatchStrip.java b/Tools/Dev/java/rs117/hd/dev/editor/SwatchStrip.java new file mode 100644 index 0000000..2e94d76 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/SwatchStrip.java @@ -0,0 +1,24 @@ +package rs117.hd.dev.editor; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.util.List; +import javax.swing.JPanel; + +public final class SwatchStrip extends JPanel { + public SwatchStrip(List beforeAfterPairs, int maxVisible) { + super(new FlowLayout(FlowLayout.LEFT, 2, 0)); + setOpaque(false); + int count = Math.min(beforeAfterPairs.size(), maxVisible); + for (int i = 0; i < count; i++) { + Color[] pair = beforeAfterPairs.get(i); + var swatch = new BeforeAfterSwatch(14, BeforeAfterSwatch.Split.HORIZONTAL, pair[0], pair[1]); + var size = new Dimension(22, 14); + swatch.setPreferredSize(size); + swatch.setMinimumSize(size); + swatch.setMaximumSize(size); + add(swatch); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/ToggleList.java b/Tools/Dev/java/rs117/hd/dev/editor/ToggleList.java new file mode 100644 index 0000000..33e9b51 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/ToggleList.java @@ -0,0 +1,198 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.List; +import java.util.function.Consumer; +import javax.swing.*; + +/** A vertical list of {@link ToggleSwitch} rows for a block of related booleans. */ +public final class ToggleList extends JPanel { + private static final int ROW_HEIGHT = 28; + private static final int GUTTER = 8; + private static final int DOT_SIZE = 5; + private static final Color HOVER = new Color(0x262626); + private static final Color DOT_CHANGED = new Color(0x7AA5E8); + private static final Color LABEL_CHANGED = new Color(0xE6E6E6); + private static final Color LABEL_DEFAULT = new Color(0x9A9A9A); + private static final Font ROW_FONT = WorkspaceStyle.UI.deriveFont(12f); + + public static final class Item { + final String label; + final String normalizedLabel; + final boolean value; + final boolean changed; + final Consumer onChange; + + public Item(String label, boolean value, boolean changed, Consumer onChange) { + this.label = label; + this.normalizedLabel = label.toLowerCase(java.util.Locale.ROOT).replaceAll("[^a-z0-9]", ""); + this.value = value; + this.changed = changed; + this.onChange = onChange; + } + } + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private final List items = new java.util.ArrayList<>(); + + public Builder add(String label, boolean selected, boolean changed, Consumer action) { + items.add(new Item(label, selected, changed, action)); + return this; + } + + public ToggleList build() { return new ToggleList(items); } + + public void update(ToggleList list) { list.setItems(items); } + } + + public ToggleList(List items) { + setLayout(new net.miginfocom.swing.MigLayout("insets 0, gap 32 2, fillx, hidemode 3", "[0,grow,fill]")); + setAlignmentX(LEFT_ALIGNMENT); + addComponentListener(new ComponentAdapter() { + @Override public void componentResized(ComponentEvent event) { + revalidate(); + } + }); + setOpaque(false); + setItems(items); + } + + private int columns(int width) { + return Math.max(1, (width + 32) / 332); + } + + @Override public Dimension getMaximumSize() { + int visible = 0; + for (Component child : getComponents()) + if (child.isVisible()) + visible++; + int columns = columns(getParent() == null ? getWidth() : getParent().getWidth() - getParent().getInsets().left - getParent().getInsets().right); + int rows = (visible + columns - 1) / columns; + return new Dimension(Integer.MAX_VALUE, Math.max(0, rows * (ROW_HEIGHT + 2) - 2)); + } + + @Override public void doLayout() { + var layout = (net.miginfocom.swing.MigLayout) getLayout(); + int columns = columns(getWidth()); + String constraints = "insets 0, gap 32 2, fillx, hidemode 3, wrap " + columns; + if (!constraints.equals(layout.getLayoutConstraints())) { + layout.setLayoutConstraints(constraints); + layout.setColumnConstraints("[0,grow,fill]".repeat(columns)); + } + super.doLayout(); + } + + private void setItems(List items) { + for (int i = 0; i < items.size(); i++) { + Item item = items.get(i); + if (i < getComponentCount() && ((Row) getComponent(i)).item.label.equals(item.label)) { + ((Row) getComponent(i)).update(item); + } else { + if (i < getComponentCount()) + remove(i); + var row = new Row(item); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + add(row, "h 28!", i); + } + } + while (getComponentCount() > items.size()) + remove(getComponentCount() - 1); + revalidate(); + repaint(); + } + + public boolean filter(String normalizedQuery, boolean wholeSection) { + boolean found = false; + for (Component child : getComponents()) { + var row = (Row) child; + boolean match = wholeSection || row.item.normalizedLabel.contains(normalizedQuery); + row.setVisible(match); + found |= match; + } + setVisible(found); + return found; + } + + private static final class Row extends JPanel { + private Item item; + private final ToggleSwitch toggle; + private boolean hover; + + Row(Item item) { + this.item = item; + setLayout(new BorderLayout()); + setOpaque(false); + setPreferredSize(new Dimension(0, ROW_HEIGHT)); + setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + setToolTipText(item.label); + + toggle = ToggleSwitch.builder().selected(item.value).onChange(value -> this.item.onChange.accept(value)).build(); + var togglePanel = new JPanel(new GridBagLayout()); + togglePanel.setOpaque(false); + togglePanel.setBorder(BorderFactory.createEmptyBorder(0, GUTTER, 0, 0)); + togglePanel.add(toggle); + add(togglePanel, BorderLayout.EAST); + + addMouseListener(new MouseAdapter() { + @Override public void mouseEntered(MouseEvent event) { hover = true; repaint(); } + @Override public void mouseExited(MouseEvent event) { hover = false; repaint(); } + @Override public void mouseClicked(MouseEvent event) { + if (SwingUtilities.isLeftMouseButton(event)) + toggle.toggle(); + } + }); + } + + void update(Item item) { + this.item = item; + toggle.setSelected(item.value); + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + if (hover) { + g.setColor(HOVER); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8); + } + + int dotX = getWidth() - getComponent(0).getWidth() - DOT_SIZE; + if (item.changed) { + g.setColor(DOT_CHANGED); + g.fillOval(dotX, (getHeight() - DOT_SIZE) / 2, DOT_SIZE, DOT_SIZE); + } + + g.setFont(ROW_FONT); + g.setColor(item.changed ? LABEL_CHANGED : LABEL_DEFAULT); + FontMetrics metrics = g.getFontMetrics(); + int availableWidth = dotX - GUTTER; + String text = ellipsize(item.label, metrics, availableWidth); + g.drawString(text, 0, (getHeight() - metrics.getHeight()) / 2 + metrics.getAscent()); + g.dispose(); + } + + private static String ellipsize(String text, FontMetrics metrics, int maxWidth) { + if (maxWidth <= 0) + return ""; + if (metrics.stringWidth(text) <= maxWidth) + return text; + String ellipsis = "\u2026"; + int low = 0, high = text.length(); + while (low < high) { + int mid = (low + high + 1) / 2; + if (metrics.stringWidth(text.substring(0, mid) + ellipsis) <= maxWidth) + low = mid; + else + high = mid - 1; + } + return low == 0 ? ellipsis : text.substring(0, low) + ellipsis; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/ToggleSwitch.java b/Tools/Dev/java/rs117/hd/dev/editor/ToggleSwitch.java new file mode 100644 index 0000000..3f008c4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/ToggleSwitch.java @@ -0,0 +1,150 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.function.Consumer; +import javax.swing.JComponent; +import javax.swing.Timer; + +/** A 28x16 on/off switch with an animated knob. */ +public final class ToggleSwitch extends JComponent { + private static final int WIDTH = 28; + private static final int HEIGHT = 16; + private static final int KNOB_SIZE = 12; + private static final int KNOB_OFF_X = 2; + private static final int KNOB_ON_X = 14; + private static final Color TRACK_OFF = WorkspaceStyle.BORDER; + private static final Color TRACK_ON = WorkspaceStyle.ACCENT; + private static final Color KNOB_COLOR = new Color(0xF0F0F0); + private static final int DURATION_MS = 120; + private static final int TICK_MS = 16; + + private boolean selected; + private double knobX; + private final Timer timer = new Timer(TICK_MS, event -> tickAnimation()); + private long animStart; + private double animFrom; + private double animTo; + private Consumer listener; + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private boolean selected; + private String tooltip; + private Consumer action; + + public Builder selected(boolean value) { selected = value; return this; } + public Builder tooltip(String value) { tooltip = value; return this; } + public Builder onChange(Consumer value) { action = value; return this; } + + public ToggleSwitch build() { + var toggle = new ToggleSwitch(selected); + toggle.setToolTipText(tooltip); + toggle.onChange(action); + return toggle; + } + } + + public ToggleSwitch(boolean initial) { + selected = initial; + knobX = selected ? KNOB_ON_X : KNOB_OFF_X; + setPreferredSize(new Dimension(WIDTH, HEIGHT)); + setMinimumSize(new Dimension(WIDTH, HEIGHT)); + setMaximumSize(new Dimension(WIDTH, HEIGHT)); + setFocusable(true); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + + addMouseListener(new MouseAdapter() { + @Override public void mousePressed(MouseEvent event) { + if (javax.swing.SwingUtilities.isLeftMouseButton(event)) { + requestFocusInWindow(); + toggle(); + } + } + }); + addKeyListener(new KeyAdapter() { + @Override public void keyPressed(KeyEvent event) { + if (event.getKeyCode() == KeyEvent.VK_SPACE || event.getKeyCode() == KeyEvent.VK_ENTER) + toggle(); + } + }); + addFocusListener(new FocusAdapter() { + @Override public void focusGained(FocusEvent event) { repaint(); } + @Override public void focusLost(FocusEvent event) { repaint(); } + }); + } + + public boolean isSelected() { return selected; } + + /** Sets the value without animating. Intended for programmatic/initial state. */ + public void setSelected(boolean value) { + if (selected == value) + return; + timer.stop(); + selected = value; + knobX = selected ? KNOB_ON_X : KNOB_OFF_X; + repaint(); + } + + /** Flips the value and animates the knob. Intended for user-driven toggles. */ + public void toggle() { + selected = !selected; + animate(); + if (listener != null) + listener.accept(selected); + } + + public void onChange(Consumer listener) { + this.listener = listener; + } + + private void animate() { + animFrom = knobX; + animTo = selected ? KNOB_ON_X : KNOB_OFF_X; + animStart = System.nanoTime(); + timer.restart(); + } + + private void tickAnimation() { + double progress = Math.min(1.0, (System.nanoTime() - animStart) / (DURATION_MS * 1_000_000.0)); + double eased = 1 - Math.pow(1 - progress, 3); + knobX = animFrom + (animTo - animFrom) * eased; + repaint(); + if (progress >= 1.0) + timer.stop(); + } + + @Override public void removeNotify() { + timer.stop(); + knobX = selected ? KNOB_ON_X : KNOB_OFF_X; + super.removeNotify(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + double t = Math.max(0, Math.min(1, (knobX - KNOB_OFF_X) / (double) (KNOB_ON_X - KNOB_OFF_X))); + g.setColor(blend(TRACK_OFF, TRACK_ON, t)); + g.fillRoundRect(0, 0, WIDTH, HEIGHT, 8, 8); + if (isFocusOwner()) { + g.setColor(WorkspaceStyle.ACCENT); + g.drawRoundRect(0, 0, WIDTH - 1, HEIGHT - 1, 8, 8); + } + int knobY = (HEIGHT - KNOB_SIZE) / 2; + int x = (int) Math.round(knobX); + g.setColor(new Color(0, 0, 0, 102)); + g.fillOval(x, knobY + 1, KNOB_SIZE, KNOB_SIZE); + g.setColor(KNOB_COLOR); + g.fillOval(x, knobY, KNOB_SIZE, KNOB_SIZE); + g.dispose(); + } + + private static Color blend(Color a, Color b, double t) { + int r = (int) Math.round(a.getRed() + (b.getRed() - a.getRed()) * t); + int g = (int) Math.round(a.getGreen() + (b.getGreen() - a.getGreen()) * t); + int bl = (int) Math.round(a.getBlue() + (b.getBlue() - a.getBlue()) * t); + return new Color(r, g, bl); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/UvTypeDropdown.java b/Tools/Dev/java/rs117/hd/dev/editor/UvTypeDropdown.java new file mode 100644 index 0000000..767bc2a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/UvTypeDropdown.java @@ -0,0 +1,158 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.util.List; +import java.util.function.Consumer; +import javax.swing.*; +import rs117.hd.scene.model_overrides.UvType; + +public final class UvTypeDropdown extends JButton { + private static final String[][] GROUPS = { + {"Keep", "VANILLA", "GEOMETRY"}, + {"Model space", "MODEL_XY", "MODEL_XZ", "MODEL_YZ"}, + {"World space", "WORLD_XY", "WORLD_XZ", "WORLD_YZ"}, + {"Multi-plane", "BOX"} + }; + private static final List DESCRIPTIONS = List.of("Keep the model’s own UVs", "Derived from each triangle", + "Front · along model Z", "Top · along model Y", "Side · along model X", "Front · fixed when the model rotates", + "Top · ground-aligned, tiles seamlessly", "Side · fixed when the model rotates", "Nearest of 6 sides, per face"); + + private static final Color SELECTED = new Color(0x334D73); + private static final Color HOVER = new Color(0x333333); + private UvType value; + private PopupLayer.Handle popup; + private Consumer change = next -> {}; + + public UvTypeDropdown(UvType initial, boolean compact) { + setFont(WorkspaceStyle.MONO.deriveFont(11f)); + setForeground(WorkspaceStyle.TEXT); + setBackground(WorkspaceStyle.INPUT); + setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true), + BorderFactory.createEmptyBorder(0, 4, 0, 6))); + setHorizontalAlignment(LEFT); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + setPreferredSize(new Dimension(compact ? 130 : 220, compact ? 26 : 30)); + setValue(initial); + addActionListener(e -> togglePopup()); + } + + public void setValue(UvType next) { + value = next == null ? UvType.VANILLA : next; + setIcon(diagram(value, 24)); + setText(value.name() + " ▾"); + setToolTipText(value.name()); + } + + public void onChange(Consumer listener) { change = listener; } + + private void togglePopup() { + if (popup != null && !popup.isClosed()) { + popup.close(); + return; + } + + var content = new JPanel(); + content.setBackground(WorkspaceStyle.MENU); + content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); + content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + Consumer pick = next -> { + popup.close(); + setValue(next); + change.accept(next); + }; + int description = 0; + for (String[] group : GROUPS) { + var heading = EditorText.builder(group[0].toUpperCase(java.util.Locale.ROOT)) + .color(WorkspaceStyle.DIM).font(WorkspaceStyle.UI.deriveFont(10f)) + .border(BorderFactory.createEmptyBorder(6, 8, 4, 0)).build(); + heading.setAlignmentX(LEFT_ALIGNMENT); + content.add(heading); + for (int i = 1; i < group.length; i++) { + UvType type = UvType.valueOf(group[i]); + boolean selected = value == type || value.name().startsWith(type.name() + "_MIRROR_"); + var row = new JPanel(new BorderLayout(6, 0)) { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(selected ? SELECTED : HOVER); + if (selected || getMousePosition(true) != null) + g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8); + g.dispose(); + } + }; + row.setOpaque(false); + row.setAlignmentX(LEFT_ALIGNMENT); + row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40)); + row.setPreferredSize(new Dimension(300, 40)); + var hover = new java.awt.event.MouseAdapter() { + @Override public void mouseEntered(java.awt.event.MouseEvent event) { row.repaint(); } + @Override public void mouseExited(java.awt.event.MouseEvent event) { row.repaint(); } + }; + row.addMouseListener(hover); + + var button = new JButton(); + button.setLayout(new BorderLayout(8, 0)); + button.setContentAreaFilled(false); + button.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); + button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + button.getAccessibleContext().setAccessibleName(type.name()); + button.addMouseListener(hover); + button.addActionListener(e -> pick.accept(type)); + var icon = new JLabel(diagram(type, 24), SwingConstants.CENTER); + icon.setBackground(new Color(0x1C1C1C)); + icon.setOpaque(true); + icon.setPreferredSize(new Dimension(28, 28)); + var iconSlot = new JPanel(new GridBagLayout()); + iconSlot.setOpaque(false); + iconSlot.add(icon); + button.add(iconSlot, BorderLayout.WEST); + var labels = new JPanel(); + labels.setLayout(new BoxLayout(labels, BoxLayout.Y_AXIS)); + labels.setOpaque(false); + labels.add(Box.createVerticalGlue()); + labels.add(EditorText.builder(type.name()).font((selected ? WorkspaceStyle.MONO_SEMIBOLD : WorkspaceStyle.MONO).deriveFont(11f)) + .color(selected ? Color.WHITE : WorkspaceStyle.TEXT).build()); + labels.add(EditorText.builder(DESCRIPTIONS.get(description++)).font(WorkspaceStyle.UI.deriveFont(10f)) + .color(selected ? new Color(0xB9C9E6) : new Color(0x7D7D7D)).build()); + labels.add(Box.createVerticalGlue()); + button.add(labels); + row.add(button); + + if (type.name().startsWith("MODEL_")) { + var mirror = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 9)); + mirror.setOpaque(false); + mirror.addMouseListener(hover); + mirror.add(EditorText.builder("Mirror").font(WorkspaceStyle.UI.deriveFont(10f)) + .color(new Color(0x8A8A8A)).build()); + var track = new JPanel(new GridLayout(1, 3)); + track.setBackground(new Color(0x1A1A1A)); + track.setBorder(BorderFactory.createLineBorder(new Color(0x3A3A3A), 1, true)); + track.setPreferredSize(new Dimension(90, 22)); + track.addMouseListener(hover); + for (String option : List.of("Off", "A", "B")) { + var variant = option.equals("Off") ? type : UvType.valueOf(type.name() + "_MIRROR_" + option); + var segment = EditorButton.builder().text(option) + .style(value == variant ? WorkspaceStyle.Button.PRIMARY : WorkspaceStyle.Button.TAB) + .onClick(() -> pick.accept(variant)).build(); + segment.setMargin(new Insets(0, 0, 0, 0)); + segment.setBorder(BorderFactory.createEmptyBorder()); + segment.setFont((value == variant ? WorkspaceStyle.MONO_SEMIBOLD : WorkspaceStyle.MONO).deriveFont(10f)); + segment.addMouseListener(hover); + track.add(segment); + } + mirror.add(track); + row.add(mirror, BorderLayout.EAST); + } + content.add(row); + } + } + var scroll = new EditorScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(null); + popup = PopupLayer.show(this, scroll, 330, 420); + } + + private static Icon diagram(UvType type, int size) { + return WorkspaceStyle.icon("uv/" + type.name(), size); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceActions.java b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceActions.java new file mode 100644 index 0000000..3c83f0f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceActions.java @@ -0,0 +1,562 @@ +package rs117.hd.dev.editor; + +import com.google.gson.*; +import java.awt.*; +import java.nio.file.*; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.Supplier; +import javax.swing.*; + +public final class WorkspaceActions { + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); + private final JFrame owner; + private final Supplier capture; + private final java.util.function.Consumer restore; + private final JLabel status; + private final Path draft = Path.of(System.getProperty("user.home"), ".runelite", "117hd-devtools", "draft.json"); + private final WorkspaceHistory history = new WorkspaceHistory(); + private final List commands = new ArrayList<>(); + private final List>> commandSources = new ArrayList<>(); + private final JButton undo = button("undo", null); + private final JButton redo = button("redo", null); + private final JButton steps = button("history", "0"); + private final Timer autosave = new Timer(30_000, e -> saveDraft(false)); + private boolean changed; + private boolean restoring; + private JDialog palette; + + public static final class Command { + final String group, label, keys; + final Runnable run; + final Supplier color; + + public Command(String group, String label, String keys, Runnable run) { + this(group, label, keys, run, () -> null); + } + + public Command(String group, String label, String keys, Runnable run, Supplier color) { + this.group = group; + this.label = label; + this.keys = keys; + this.run = run; + this.color = color; + } + + @Override public String toString() { return group + " " + label + (keys.isEmpty() ? "" : " " + keys); } + } + + public WorkspaceActions(JFrame owner, Supplier capture, java.util.function.Consumer restore, JLabel status) { + this.owner = owner; + this.capture = capture; + this.restore = restore; + this.status = status; + register("Edit", "Undo", "Ctrl Z", "ctrl Z", () -> jump(history.index() - 1, "Undo")); + register("Edit", "Redo", "Ctrl Shift Z", "ctrl shift Z", () -> jump(history.index() + 1, "Redo")); + bind("ctrl Y", () -> jump(history.index() + 1, "Redo"), false); + register("Edit", "Show history", "", null, this::showHistory); + register("File", "Autosave draft now", "", null, () -> saveDraft(true)); + register("File", "Restore autosaved draft", "", null, this::restoreDraft); + bind("ctrl K", this::showPalette, true); + register("Window", "Keyboard shortcuts", "?", "typed ?", this::showShortcuts); + updateHistory(); + } + + public void addCommandSource(Supplier> source) { commandSources.add(source); } + + public void start() { autosave.start(); } + public void stop() { autosave.stop(); } + + public void reset(String entity) { + history.reset("Opened " + entity, capture.get()); + updateHistory(); + } + + public void edit(String label, Runnable action) { + if (restoring) { + action.run(); + return; + } + JsonObject before = capture.get(); + action.run(); + JsonObject after = capture.get(); + history.add(label, before, after); + changed |= !before.equals(after); + updateHistory(); + } + + private void jump(int index, String operation) { + if (index < 0 || index >= history.size() || index == history.index()) + return; + String label = history.get(index < history.index() ? history.index() : index).label; + try { + restoreState(history.get(index).state.getAsJsonObject()); + history.moveTo(index); + changed = true; + status.setText(operation + ": " + label); + } catch (RuntimeException ex) { + status.setText("Could not restore history: " + ex.getMessage()); + } + updateHistory(); + } + + private void restoreState(JsonObject data) { + restoring = true; + try { + restore.accept(data); + } finally { + restoring = false; + } + } + + private void updateHistory() { + undo.setEnabled(history.canUndo()); + redo.setEnabled(history.canRedo()); + undo.setToolTipText(history.canUndo() ? "Undo " + history.get(history.index()).label + " (Ctrl+Z)" : "Nothing to undo"); + redo.setToolTipText(history.canRedo() ? "Redo " + history.get(history.index() + 1).label + " (Ctrl+Shift+Z)" : "Nothing to redo"); + steps.setText(String.valueOf(Math.max(0, history.size() - 1))); + } + + public JPanel toolbar() { + var panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 0)); + panel.setOpaque(false); + undo.addActionListener(e -> jump(history.index() - 1, "Undo")); + redo.addActionListener(e -> jump(history.index() + 1, "Redo")); + steps.addActionListener(e -> showHistory()); + panel.add(undo); + panel.add(redo); + panel.add(steps); + var search = new JButton() { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0x1A1A1A)); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8); + g.setColor(new Color(getModel().isRollover() ? 0x4A4A4A : 0x333333)); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 8, 8); + WorkspaceStyle.icon("search", 12).paintIcon(this, g, 8, 6); + paintKeycap(g, "Ctrl K", 29, 4, 45, 16); + g.dispose(); + } + }; + WorkspaceStyle.button(search, WorkspaceStyle.Button.TAB); + search.setPreferredSize(new Dimension(79, 24)); + search.setToolTipText("Command search (Ctrl+K)"); + search.getAccessibleContext().setAccessibleName("Command search"); + search.addActionListener(e -> showPalette()); + panel.add(search); + var help = button(null, "?"); + help.setPreferredSize(new Dimension(26, 26)); + help.addActionListener(e -> showShortcuts()); + panel.add(help); + return panel; + } + + private static JButton button(String icon, String text) { + var button = new JButton(text, icon == null ? null : WorkspaceStyle.icon(icon, 14)); + WorkspaceStyle.button(button, WorkspaceStyle.Button.TAB); + if (text == null) + button.setPreferredSize(new Dimension(26, 26)); + return button; + } + + public void register(String group, String label, String keys, String binding, Runnable run) { + commands.add(new Command(group, label, keys, run)); + if (binding != null) + bind(binding, run, false); + } + + private void bind(String binding, Runnable action, boolean allowText) { + owner.getRootPane().registerKeyboardAction(e -> { + if (allowText || !(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof javax.swing.text.JTextComponent)) + action.run(); + }, KeyStroke.getKeyStroke(binding), JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + private void showHistory() { + var menu = new WorkspaceMenu(280); + var title = new JLabel("History"); + title.setFont(WorkspaceStyle.SEMIBOLD); + title.setForeground(WorkspaceStyle.TEXT); + var count = new JLabel(history.index() + " steps · " + Math.max(0, history.size() - history.index() - 1) + " redo"); + count.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + count.setForeground(WorkspaceStyle.DIM); + var header = new JPanel(new BorderLayout()); + header.setOpaque(false); + header.setBorder(BorderFactory.createEmptyBorder(4, 6, 6, 6)); + header.add(title, BorderLayout.WEST); + header.add(count, BorderLayout.EAST); + menu.add(header); + var rows = new DefaultListModel(); + for (int i = history.size() - 1; i >= 0; i--) + rows.addElement(history.get(i)); + var list = new JList<>(rows); + list.setFixedCellHeight(24); + list.setCellRenderer((source, step, index, selected, focus) -> { + int position = history.size() - index - 1; + boolean current = position == history.index(); + var row = new JPanel(new BorderLayout(8, 0)); + row.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 8)); + row.setBackground(current ? WorkspaceStyle.ACCENT : selected ? WorkspaceStyle.BORDER : WorkspaceStyle.MENU); + var label = new JLabel(step.label, WorkspaceStyle.badge("", current ? Color.WHITE : WorkspaceStyle.DIM), SwingConstants.LEFT); + label.setFont(WorkspaceStyle.UI); + label.setForeground(current ? Color.WHITE : position > history.index() ? new Color(0x6A6A6A) : WorkspaceStyle.TEXT); + row.add(label); + var time = new JLabel(TIME.format(step.time)); + time.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + time.setForeground(current ? new Color(0xCFE0FF) : WorkspaceStyle.DIM); + row.add(time, BorderLayout.EAST); + return row; + }); + list.addMouseListener(new java.awt.event.MouseAdapter() { + @Override public void mouseClicked(java.awt.event.MouseEvent e) { + int row = list.locationToIndex(e.getPoint()); + if (row >= 0) { + menu.setVisible(false); + jump(history.size() - row - 1, "History"); + } + } + }); + var scroll = WorkspaceStyle.listScroll(list); + scroll.setPreferredSize(new Dimension(270, Math.min(320, rows.size() * 24))); + menu.add(scroll); + var footer = new JLabel("Click a step to jump to it · Ctrl+Z / Ctrl+Shift+Z"); + footer.setFont(WorkspaceStyle.UI.deriveFont(11f)); + footer.setForeground(WorkspaceStyle.DIM); + footer.setBorder(BorderFactory.createEmptyBorder(6, 6, 2, 6)); + menu.add(footer); + menu.show(steps, steps.getWidth() - 280, steps.getHeight() + 4); + } + private void showPalette() { + if (palette != null && palette.isVisible()) { + palette.dispose(); + return; + } + var input = WorkspaceStyle.search("Type a command, definition or light…"); + input.setBorder(BorderFactory.createEmptyBorder()); + input.setOpaque(false); + input.setFont(WorkspaceStyle.UI.deriveFont(14f)); + input.setForeground(new Color(0xE6E6E6)); + input.setCaretColor(WorkspaceStyle.TEXT); + var inputRow = new JPanel(new BorderLayout(10, 0)); + inputRow.setBackground(WorkspaceStyle.MENU); + inputRow.setPreferredSize(new Dimension(560, 44)); + inputRow.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x2A2A2A)), + BorderFactory.createEmptyBorder(0, 14, 0, 14))); + inputRow.add(new JLabel(WorkspaceStyle.icon("search", 14)), BorderLayout.WEST); + inputRow.add(input); + inputRow.add(keycap("Esc", 20), BorderLayout.EAST); + var rows = new DefaultListModel(); + var list = new JList<>(rows); + list.setFixedCellHeight(31); + list.setCellRenderer((source, command, index, selected, focus) -> commandRow(command, selected)); + list.setFont(WorkspaceStyle.UI); + var scroll = WorkspaceStyle.listScroll(list); + scroll.setPreferredSize(new Dimension(560, 368)); + scroll.setBorder(BorderFactory.createEmptyBorder(4, 4, 0, 4)); + scroll.setBackground(WorkspaceStyle.MENU); + scroll.getViewport().setBackground(WorkspaceStyle.MENU); + list.setBackground(WorkspaceStyle.MENU); + var resultCount = muted(""); + var footer = new JPanel(new BorderLayout()); + footer.setBackground(WorkspaceStyle.MENU); + footer.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(0x2A2A2A)), + BorderFactory.createEmptyBorder(6, 14, 6, 14))); + footer.add(muted("↑ ↓ move Enter run Esc close")); + footer.add(resultCount, BorderLayout.EAST); + var empty = muted("No commands match."); + empty.setBorder(BorderFactory.createEmptyBorder(14, 14, 0, 14)); + empty.setVerticalAlignment(SwingConstants.TOP); + var results = new JPanel(new CardLayout()); + results.setBackground(WorkspaceStyle.MENU); + results.add(scroll, "list"); + results.add(empty, "empty"); + Runnable filter = () -> { + rows.clear(); + String[] words = input.getText().strip().toLowerCase(Locale.ROOT).split("\\s+"); + var candidates = new ArrayList<>(commands); + if (!hasDraft()) + candidates.removeIf(command -> command.label.equals("Restore autosaved draft")); + for (var source : commandSources) + candidates.addAll(source.get()); + candidates.sort(java.util.Comparator.comparingInt(WorkspaceActions::commandOrder)); + for (Command command : candidates) { + String haystack = (command.group + " " + command.label).toLowerCase(Locale.ROOT); + if (java.util.Arrays.stream(words).allMatch(haystack::contains)) + rows.addElement(command); + if (rows.size() == 60) + break; + } + if (!rows.isEmpty()) + list.setSelectedIndex(0); + resultCount.setText(rows.size() + (rows.size() == 1 ? " result" : " results")); + ((CardLayout) results.getLayout()).show(results, rows.isEmpty() ? "empty" : "list"); + }; + input.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() { + public void insertUpdate(javax.swing.event.DocumentEvent e) { filter.run(); } + public void removeUpdate(javax.swing.event.DocumentEvent e) { filter.run(); } + public void changedUpdate(javax.swing.event.DocumentEvent e) { filter.run(); } + }); + var content = new JPanel(new BorderLayout()); + content.add(inputRow, BorderLayout.NORTH); + content.add(results); + content.add(footer, BorderLayout.SOUTH); + + Runnable run = () -> { + Command selected = list.getSelectedValue(); + if (selected != null) { + SwingUtilities.getWindowAncestor(input).dispose(); + SwingUtilities.invokeLater(selected.run); + } + }; + input.addActionListener(e -> run.run()); + for (int direction : new int[] { -1, 1 }) { + input.registerKeyboardAction(e -> { + if (rows.isEmpty()) + return; + int index = Math.floorMod(list.getSelectedIndex() + direction, rows.size()); + list.setSelectedIndex(index); + list.ensureIndexIsVisible(index); + }, KeyStroke.getKeyStroke(direction < 0 ? "UP" : "DOWN"), JComponent.WHEN_FOCUSED); + } + list.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { + @Override public void mouseMoved(java.awt.event.MouseEvent e) { + int index = list.locationToIndex(e.getPoint()); + var bounds = index < 0 ? null : list.getCellBounds(index, index); + if (bounds != null && bounds.contains(e.getPoint())) + list.setSelectedIndex(index); + } + }); + list.addMouseListener(new java.awt.event.MouseAdapter() { + @Override public void mouseClicked(java.awt.event.MouseEvent e) { + int index = list.locationToIndex(e.getPoint()); + var bounds = index < 0 ? null : list.getCellBounds(index, index); + if (bounds != null && bounds.contains(e.getPoint())) { + list.setSelectedIndex(index); + run.run(); + } + } + }); + content.registerKeyboardAction(e -> SwingUtilities.getWindowAncestor(content).dispose(), + KeyStroke.getKeyStroke("ctrl K"), JComponent.WHEN_IN_FOCUSED_WINDOW); + filter.run(); + palette = EditorModal.builder(owner, "Command search") + .content(content) + .topOffsetPercent(12) + .initialFocus(input) + .open(); + } + + private static int commandOrder(Command command) { + switch (command.group) { + case "Edit": return 0; + case "File": + switch (command.label) { + case "Save lights": return 10; + case "Save placement": return 11; + case "Save definitions": return 12; + default: return 13; + } + case "Tool": return 20; + case "View": return 30; + case "Window": return 40; + case "Light": return 50; + default: return 60; + } + } + + private JPanel commandRow(Command command, boolean selected) { + var row = new JPanel(new BorderLayout(10, 0)) { + @Override protected void paintComponent(Graphics graphics) { + if (!selected) + return; + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0x334D73)); + g.fillRoundRect(0, 0, getWidth(), getHeight() - 1, 10, 10); + g.dispose(); + } + }; + row.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); + row.setOpaque(false); + var group = new JLabel(command.group.toUpperCase(Locale.ROOT)); + group.setFont(WorkspaceStyle.UI.deriveFont(10f)); + group.setForeground(selected ? new Color(0xCFE0FF) : new Color(0x7D7D7D)); + group.setPreferredSize(new Dimension(72, 30)); + row.add(group, BorderLayout.WEST); + Color color = command.color.get(); + var label = new JLabel(command.label, color == null ? null : WorkspaceStyle.badge("", color), SwingConstants.LEFT); + label.setFont(WorkspaceStyle.UI); + label.setForeground(selected ? Color.WHITE : WorkspaceStyle.TEXT); + row.add(label); + if (!command.keys.isEmpty()) + row.add(keycaps(command.keys), BorderLayout.EAST); + return row; + } + + private JPanel keycaps(String keys) { + var panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); + panel.setOpaque(false); + for (String key : keys.split(" ")) + panel.add(keycap(key.replace('_', ' '), 20)); + var centered = new JPanel(new GridBagLayout()); + centered.setOpaque(false); + centered.add(panel); + return centered; + } + + private JComponent keycap(String key, int height) { + return new JComponent() { + @Override public Dimension getPreferredSize() { + return new Dimension(Math.max(18, getFontMetrics(WorkspaceStyle.MONO.deriveFont(10f)).stringWidth(key) + 10), height); + } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + paintKeycap(g, key, 0, (getHeight() - height) / 2, getWidth(), height); + g.dispose(); + } + }; + } + + private static void paintKeycap(Graphics2D g, String key, int x, int y, int width, int height) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.BORDER); + g.fillRoundRect(x, y, width, height, 8, 8); + g.setColor(WorkspaceStyle.HEADER); + g.fillRoundRect(x + 1, y + 1, width - 2, height - 3, 6, 6); + g.setColor(new Color(0xD6D6D6)); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + var metrics = g.getFontMetrics(); + g.drawString(key, x + (width - metrics.stringWidth(key)) / 2, y + (height - metrics.getHeight()) / 2 + metrics.getAscent()); + } + + private static JLabel muted(String text) { + var label = new JLabel(text); + label.setFont(WorkspaceStyle.UI.deriveFont(11f)); + label.setForeground(new Color(0x7D7D7D)); + return label; + } + + private JPanel shortcutGroup(String title, String[]... shortcuts) { + var group = new JPanel(new BorderLayout()); + group.setOpaque(false); + var heading = muted(title.toUpperCase(Locale.ROOT)); + heading.setFont(WorkspaceStyle.UI.deriveFont(10f)); + heading.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x2A2A2A)), + BorderFactory.createEmptyBorder(0, 0, 6, 0))); + group.add(heading, BorderLayout.NORTH); + var rows = new JPanel(new GridLayout(0, 1)); + rows.setOpaque(false); + for (String[] shortcut : shortcuts) { + var row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.setPreferredSize(new Dimension(300, 26)); + var label = new JLabel(shortcut[0]); + label.setFont(WorkspaceStyle.UI); + label.setForeground(WorkspaceStyle.TEXT); + row.add(label); + row.add(keycaps(shortcut[1]), BorderLayout.EAST); + rows.add(row); + } + group.add(rows, BorderLayout.CENTER); + var wrapper = new JPanel(new BorderLayout()); + wrapper.setOpaque(false); + wrapper.add(group, BorderLayout.NORTH); + return wrapper; + } + + private void showShortcuts() { + var rows = new JPanel(new net.miginfocom.swing.MigLayout("insets 0px 22px 22px 22px, gap 36px 20px, wrap 2", "[grow,fill][grow,fill]", "[top][top][top]")); + rows.setBackground(WorkspaceStyle.MENU); + rows.add(shortcutGroup("General", new String[]{"Command search", "Ctrl K"}, new String[]{"Keyboard shortcuts", "?"}, + new String[]{"Undo", "Ctrl Z"}, new String[]{"Redo", "Ctrl Shift Z"}, new String[]{"Redo (alt)", "Ctrl Y"}, + new String[]{"Close menu / clear group", "Esc"})); + rows.add(shortcutGroup("Tools", new String[]{"Select", "Q"}, new String[]{"Place light", "P"}, + new String[]{"Remove light", "X"}, new String[]{"Vertex pick", "1"}, new String[]{"Face pick", "2"}, + new String[]{"Apply tool to group", "Enter"})); + rows.add(shortcutGroup("Viewport", new String[]{"Orbit", "Drag"}, new String[]{"Pan", "Right_Drag"}, + new String[]{"Zoom", "Wheel"}, new String[]{"Box select", "Ctrl Drag"}, new String[]{"Frame all", "F"})); + rows.add(shortcutGroup("Layout", new String[]{"Together", "T"}, new String[]{"Side by side", "S"}, + new String[]{"Single", "G"})); + rows.add(shortcutGroup("Lights", new String[]{"Delete selected light", "Del"}, new String[]{"Mirror across X", "M"}, + new String[]{"Mirror across Z", "Shift M"})); + rows.add(shortcutGroup("Definitions", new String[]{"Duplicate definition", "Ctrl D"})); + var header = new JPanel(new BorderLayout()); + header.setBackground(WorkspaceStyle.MENU); + header.setBorder(BorderFactory.createEmptyBorder(16, 22, 14, 22)); + var title = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 4)); + title.setOpaque(false); + var heading = new JLabel("Keyboard shortcuts"); + heading.setFont(WorkspaceStyle.SEMIBOLD.deriveFont(15f)); + heading.setForeground(new Color(0xEEEEEE)); + title.add(heading); + title.add(Box.createHorizontalStrut(10)); + title.add(muted("Press ? anytime")); + header.add(title); + var close = button("close", null); + close.addActionListener(e -> SwingUtilities.getWindowAncestor(close).dispose()); + header.add(close, BorderLayout.EAST); + var scroll = new EditorScrollPane(rows); + scroll.setBorder(BorderFactory.createEmptyBorder()); + scroll.getViewport().setBackground(WorkspaceStyle.MENU); + var content = new JPanel(new BorderLayout()); + content.add(header, BorderLayout.NORTH); + content.add(scroll); + EditorModal.builder(owner, "Keyboard shortcuts") + .content(content) + .size(Math.min(760, owner.getWidth() - 40), + Math.min(owner.getHeight() - 80, rows.getPreferredSize().height + header.getPreferredSize().height + 2)) + .open(); + } + private void saveDraft(boolean manual) { + if (!changed && !manual) + return; + // Snapshot on the EDT (capture reads live UI state), then push the file I/O to a background + // thread so a large document doesn't stall the EDT on every autosave tick. + JsonObject data = capture.get(); + data.addProperty("time", TIME.format(LocalTime.now())); + changed = false; + new Thread(() -> { + try { + Files.createDirectories(draft.getParent()); + Path temporary = Files.createTempFile(draft.getParent(), "draft-", ".tmp"); + try { + Files.writeString(temporary, data.toString()); + Files.move(temporary, draft, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(temporary); + } + } catch (Exception ex) { + SwingUtilities.invokeLater(() -> status.setText("Draft autosave failed: " + ex.getMessage())); + } + }, "draft-autosave").start(); + } + + public boolean hasDraft() { return Files.isRegularFile(draft); } + + public String draftTime() { + try { + return new Gson().fromJson(Files.readString(draft), JsonObject.class).get("time").getAsString(); + } catch (Exception ex) { + return "an unknown time"; + } + } + + public void restoreDraft() { + if (!hasDraft()) + return; + try { + JsonObject data = new Gson().fromJson(Files.readString(draft), JsonObject.class); + String time = data.remove("time").getAsString(); + edit("Restore draft " + time, () -> restoreState(data)); + status.setText("Restored draft " + time); + } catch (Exception ex) { + status.setText("Draft restore failed: " + ex.getMessage()); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceDocks.java b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceDocks.java new file mode 100644 index 0000000..14fd149 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceDocks.java @@ -0,0 +1,342 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.List; +import javax.swing.*; + +public final class WorkspaceDocks extends JPanel { + private final List left = new ArrayList<>(); + private final List right = new ArrayList<>(); + private final JComponent viewport; + private final JComponent primaryPanel; + private JSplitPane leftSplit; + private JSplitPane rightSplit; + private boolean initializeRightWidth; + private boolean initializeLeftWidth; + private int leftWidth = 300; + private int rightWidth = 330; + private List target; + private int insertion; + private Point dragPoint; + private String dragTitle; + private Rectangle dirtyOverlay; + + public enum Side { LEFT, RIGHT } + + private final boolean resizable; + private final double leftStackWeight; + + private WorkspaceDocks(Builder builder) { + super(new BorderLayout()); + viewport = builder.viewport; + primaryPanel = builder.primaryPanel; + resizable = builder.resizable; + leftStackWeight = builder.leftStackWeight; + leftWidth = builder.leftWidth; + rightWidth = builder.rightWidth; + left.addAll(builder.left); + right.addAll(builder.right); + for (DragHandle panel : builder.headers) + draggable(panel.header, panel.content, panel.title); + rebuild(); + } + + public static Builder builder(JComponent viewport) { return new Builder(viewport); } + + private static final class DragHandle { + final JComponent header; + final JComponent content; + final String title; + + DragHandle(JComponent header, JComponent content, String title) { + this.header = header; + this.content = content; + this.title = title; + } + } + + public static final class Builder { + private final JComponent viewport; + private final List left = new ArrayList<>(); + private final List right = new ArrayList<>(); + private final List headers = new ArrayList<>(); + private JComponent primaryPanel; + private int leftWidth = 300; + private int rightWidth = 330; + private boolean resizable = true; + private double leftStackWeight = .4; + + private Builder(JComponent viewport) { this.viewport = viewport; } + + public Builder panel(JComponent panel, Side side) { + (side == Side.LEFT ? left : right).add(panel); + return this; + } + + public Builder primaryPanel(JComponent panel, Side side) { + primaryPanel = panel; + return panel(panel, side); + } + + public Builder movable(JComponent panel, JComponent handle, String title) { + headers.add(new DragHandle(handle, panel, title)); + return this; + } + + public Builder width(Side side, int width) { + if (side == Side.LEFT) + leftWidth = width; + else + rightWidth = width; + return this; + } + + public Builder leftStackWeight(double value) { + if (!(value > 0 && value < 1)) + throw new IllegalArgumentException("Stack weight must be between zero and one"); + leftStackWeight = value; + return this; + } + + public Builder resizable(boolean value) { resizable = value; return this; } + public WorkspaceDocks build() { return new WorkspaceDocks(this); } + } + + public void setSideVisible(Side side, boolean visible) { + rememberWidths(); + for (JComponent panel : side == Side.LEFT ? left : right) + panel.setVisible(visible); + rebuild(); + } + + public void setPrimaryPanelVisible(boolean visible) { + if (primaryPanel == null) + return; + rememberWidths(); + primaryPanel.setVisible(visible); + rebuild(); + } + + public void dockPanel(JComponent panel, Side side) { + var destination = side == Side.LEFT ? left : right; + if (!destination.isEmpty() && destination.get(0) == panel) + return; + rememberWidths(); + left.remove(panel); + right.remove(panel); + destination.add(0, panel); + rebuild(); + } + + public void undockPanel(JComponent panel) { + if (!left.contains(panel) && !right.contains(panel)) + return; + rememberWidths(); + left.remove(panel); + right.remove(panel); + rebuild(); + } + + public void draggable(JComponent header, JComponent panel, String title) { + header.setCursor(WorkspaceStyle.cursor("grab")); + var drag = new MouseAdapter() { + private Point start; + + @Override public void mousePressed(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e)) + start = SwingUtilities.convertPoint(header, e.getPoint(), WorkspaceDocks.this); + } + + @Override public void mouseDragged(MouseEvent e) { + if (start == null) + return; + Point point = SwingUtilities.convertPoint(header, e.getPoint(), WorkspaceDocks.this); + if (dragPoint == null && point.distance(start) < 5) + return; + dragPoint = point; + dragTitle = title; + Rectangle l = bounds(left, true); + Rectangle r = bounds(right, false); + target = l.contains(point) ? left : r.contains(point) ? right : null; + if (target != null) { + insertion = target.size(); + for (int i = 0; i < target.size(); i++) { + var item = target.get(i); + if (!item.isShowing()) + continue; + Rectangle area = SwingUtilities.convertRectangle(item.getParent(), item.getBounds(), WorkspaceDocks.this); + if (point.y < area.y + area.height / 2) { + insertion = i; + break; + } + } + } + // Only the dock-zone columns and a box around the cursor actually change while dragging; + // repainting the whole container (including the central viewport) on every pixel of + // mouse movement is unnecessary and can be expensive. + Rectangle overlay = l.union(r); + overlay.add(new Rectangle(point.x - 4, point.y - 4, 320, 48)); + Rectangle repaintArea = dirtyOverlay == null ? overlay : dirtyOverlay.union(overlay); + dirtyOverlay = overlay; + repaint(repaintArea); + } + + @Override public void mouseReleased(MouseEvent e) { + start = null; + if (dragPoint == null) + return; + boolean rebuilt = false; + if (target != null) { + rememberWidths(); + int previous = target.indexOf(panel); + left.remove(panel); + right.remove(panel); + target.add(previous >= 0 && previous < insertion ? insertion - 1 : insertion, panel); + rebuild(); + rebuilt = true; + } + dragPoint = null; + target = null; + if (rebuilt) { + // rebuild() already repainted the whole dock area. + dirtyOverlay = null; + } else if (dirtyOverlay != null) { + repaint(dirtyOverlay); + dirtyOverlay = null; + } else { + repaint(); + } + } + }; + header.addMouseListener(drag); + header.addMouseMotionListener(drag); + } + + private Rectangle bounds(List dock, boolean isLeft) { + for (JComponent item : dock) { + if (item.isVisible() && item.getParent() != null) { + Rectangle rect = SwingUtilities.convertRectangle(item.getParent(), item.getBounds(), this); + return new Rectangle(rect.x, 0, rect.width, getHeight()); + } + } + return new Rectangle(isLeft ? 0 : getWidth() - 90, 0, 90, getHeight()); + } + + private void rememberWidths() { + if (leftSplit != null && leftSplit.getDividerLocation() >= 220) + leftWidth = leftSplit.getDividerLocation(); + if (rightSplit != null && rightSplit.getWidth() - rightSplit.getDividerLocation() - rightSplit.getDividerSize() >= 220) + rightWidth = rightSplit.getWidth() - rightSplit.getDividerLocation() - rightSplit.getDividerSize(); + } + + private void rebuild() { + removeAll(); + Component l = stack(left); + Component r = stack(right); + if (l != null) + l.setPreferredSize(new Dimension(leftWidth, 420)); + if (r != null) + r.setPreferredSize(new Dimension(rightWidth, 420)); + rightSplit = r == null ? null : split(JSplitPane.HORIZONTAL_SPLIT, viewport, r, 1); + Component center = rightSplit == null ? viewport : rightSplit; + leftSplit = l == null ? null : split(JSplitPane.HORIZONTAL_SPLIT, l, center, 0); + add(leftSplit == null ? center : leftSplit); + if (leftSplit != null) + leftSplit.setDividerLocation(leftWidth); + revalidate(); + initializeRightWidth = rightSplit != null; + initializeLeftWidth = leftSplit != null; + repaint(); + } + + @Override public void doLayout() { + super.doLayout(); + if (getWidth() <= 0) + return; + if (initializeLeftWidth && leftSplit != null && leftSplit.getWidth() > leftWidth + leftSplit.getDividerSize()) { + initializeLeftWidth = false; + leftSplit.setDividerLocation(leftWidth); + leftSplit.doLayout(); + } + if (!initializeRightWidth) + return; + if (leftSplit != null) + leftSplit.doLayout(); + if (rightSplit.getWidth() > rightWidth + rightSplit.getDividerSize()) { + initializeRightWidth = false; + rightSplit.setDividerLocation(rightSplit.getWidth() - rightWidth - rightSplit.getDividerSize()); + rightSplit.doLayout(); + } + } + + private Component stack(List dock) { + Component result = null; + for (int i = dock.size() - 1; i >= 0; i--) { + JComponent panel = dock.get(i); + if (!panel.isVisible()) + continue; + panel.setMinimumSize(new Dimension(220, 70)); + if (result == null) { + result = panel; + } else { + double weight = dock == left ? leftStackWeight : .4; + JSplitPane split = split(JSplitPane.VERTICAL_SPLIT, panel, result, weight); + split.setPreferredSize(new Dimension(330, 420)); + split.setDividerLocation(panel instanceof FloatingDockWindow ? panel.getPreferredSize().height + : getHeight() > 0 ? (int) (getHeight() * weight) : (int) (840 * weight)); + result = split; + } + } + return result; + } + + private JSplitPane split(int orientation, Component first, Component second, double weight) { + var split = new JSplitPane(orientation, first, second); + WorkspaceStyle.divider(split); + split.setEnabled(resizable); + split.setResizeWeight(weight); + return split; + } + + @Override protected void paintChildren(Graphics graphics) { + super.paintChildren(graphics); + if (dragPoint == null) + return; + Graphics2D g = (Graphics2D) graphics.create(); + for (List dock : List.of(left, right)) { + Rectangle area = bounds(dock, dock == left); + g.setColor(new Color(71, 114, 179, dock == target ? 45 : 15)); + g.fill(area); + g.setColor(WorkspaceStyle.ACCENT); + g.drawRect(area.x, area.y, area.width - 1, area.height - 1); + if (dock.stream().noneMatch(Component::isVisible)) { + g.setFont(WorkspaceStyle.UI.deriveFont(11f)); + g.drawString(dock == left ? "Dock left" : "Dock right", area.x + 12, 22); + } + if (dock == target) { + int y = area.height - 4; + for (int i = insertion; i < dock.size(); i++) { + var panel = dock.get(i); + if (panel.isVisible()) { + y = SwingUtilities.convertPoint(panel, 0, 0, this).y; + break; + } + } + g.fillRoundRect(area.x + 2, y, area.width - 4, 4, 4, 4); + } + } + g.setFont(WorkspaceStyle.UI); + int x = dragPoint.x + 12; + int y = dragPoint.y + 8; + int width = g.getFontMetrics().stringWidth(dragTitle) + 20; + g.setColor(WorkspaceStyle.HEADER); + g.fillRoundRect(x, y, width, 24, 8, 8); + g.setColor(WorkspaceStyle.ACCENT); + g.drawRoundRect(x, y, width, 24, 8, 8); + g.setColor(WorkspaceStyle.TEXT); + g.drawString(dragTitle, x + 10, y + 16); + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceHistory.java b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceHistory.java new file mode 100644 index 0000000..513d407 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceHistory.java @@ -0,0 +1,58 @@ +package rs117.hd.dev.editor; + +import com.google.gson.JsonElement; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; + +final class WorkspaceHistory { + static final class Step { + final String label; + final JsonElement state; + final long millis; + final LocalTime time = LocalTime.now(); + + Step(String label, JsonElement state) { + this.label = label; + this.state = state; + this.millis = System.currentTimeMillis(); + } + } + + private final List steps = new ArrayList<>(); + private int index; + + void reset(String label, JsonElement state) { + steps.clear(); + steps.add(new Step(label, state)); + index = 0; + } + + void add(String label, JsonElement before, JsonElement after) { + if (before.equals(after)) + return; + if (steps.isEmpty()) + reset("Opened editor", before); + boolean atEnd = index == steps.size() - 1; + steps.subList(index + 1, steps.size()).clear(); + Step next = new Step(label, after); + Step previous = steps.get(index); + if (atEnd && index > 0 && label.equals(previous.label) && next.millis - previous.millis < 700) { + steps.set(index, next); + } else { + steps.add(next); + index++; + if (steps.size() > 101) { + steps.remove(0); + index--; + } + } + } + + int index() { return index; } + int size() { return steps.size(); } + Step get(int position) { return steps.get(position); } + boolean canUndo() { return index > 0; } + boolean canRedo() { return index + 1 < steps.size(); } + void moveTo(int position) { index = position; } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceMenu.java b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceMenu.java new file mode 100644 index 0000000..d55f02d --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceMenu.java @@ -0,0 +1,87 @@ +package rs117.hd.dev.editor; + +import java.awt.*; +import java.awt.event.ActionListener; +import java.util.function.BooleanSupplier; +import javax.swing.*; +import javax.swing.plaf.basic.BasicMenuItemUI; + +public final class WorkspaceMenu extends JPopupMenu { + private final int width; + + public WorkspaceMenu(int width) { + this.width = width; + setOpaque(false); + setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + } + + @Override protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.MENU); + g.fillRoundRect(0, 0, getWidth(), getHeight(), 12, 12); + g.setColor(WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 12, 12); + g.dispose(); + } + + public void addRow(String label, Icon icon, String shortcut, BooleanSupplier selected, ActionListener action) { + addRow(label, icon, shortcut, selected, false, action); + } + + public void addToggle(String label, boolean initial, java.util.function.Consumer action) { + var selected = new javax.swing.JToggleButton.ToggleButtonModel(); + selected.setSelected(initial); + addRow(label, null, "", selected::isSelected, true, e -> { + selected.setSelected(!selected.isSelected()); + action.accept(selected.isSelected()); + }); + } + + private void addRow(String label, Icon icon, String shortcut, BooleanSupplier selected, boolean toggle, ActionListener action) { + var item = new JMenuItem(label, icon); + item.setUI(new BasicMenuItemUI() { + @Override protected void doClick(MenuSelectionManager manager) { + if (toggle) + item.doClick(0); + else + super.doClick(manager); + } + + @Override public void paint(Graphics graphics, JComponent component) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + boolean active = selected.getAsBoolean(); + if (active && !toggle || item.isArmed()) { + g.setColor(active && !toggle ? WorkspaceStyle.ACCENT : new Color(0x333333)); + g.fillRoundRect(0, 0, component.getWidth(), component.getHeight(), 8, 8); + } + int x = 8; + if (toggle) { + g.setColor(active ? WorkspaceStyle.ACCENT : WorkspaceStyle.BORDER); + g.fillRoundRect(x, 6, 14, 14, 6, 6); + if (active) + WorkspaceStyle.icon("check", 10).paintIcon(component, g, x + 2, 8); + x += 22; + } else if (icon != null) { + icon.paintIcon(component, g, x, (component.getHeight() - icon.getIconHeight()) / 2); + x += icon.getIconWidth() + 8; + } + g.setFont(WorkspaceStyle.UI); + g.setColor(active ? Color.WHITE : WorkspaceStyle.TEXT); + g.drawString(label, x, 17); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.setColor(active ? new Color(0xCFE0FF) : WorkspaceStyle.DIM); + g.drawString(shortcut, component.getWidth() - 8 - g.getFontMetrics().stringWidth(shortcut), 17); + g.dispose(); + } + }); + item.setOpaque(false); + item.setBorderPainted(false); + item.setPreferredSize(new Dimension(width - 10, 26)); + item.addActionListener(action); + item.addActionListener(e -> item.repaint()); + add(item); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceStyle.java b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceStyle.java new file mode 100644 index 0000000..d62e34a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/editor/WorkspaceStyle.java @@ -0,0 +1,319 @@ +package rs117.hd.dev.editor; + +import com.google.gson.JsonObject; +import com.google.gson.Gson; +import java.awt.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import javax.swing.*; +import javax.swing.plaf.basic.BasicButtonUI; +import javax.swing.plaf.basic.BasicSplitPaneDivider; +import javax.swing.plaf.basic.BasicSplitPaneUI; + +public final class WorkspaceStyle { + public static final Color GAP = new Color(0x141414); + public static final Color BAR = new Color(0x232323); + public static final Color PANEL = new Color(0x262626); + public static final Color HEADER = new Color(0x2C2C2C); + public static final Color INPUT = new Color(0x1F1F1F); + public static final Color MENU = new Color(0x1E1E1E); + public static final Color BORDER = new Color(0x3A3A3A); + public static final Color ACCENT = new Color(0x4772B3); + public static final Color TEXT = new Color(0xCFCFCF); + public static final Color DIM = new Color(0x8A8A8A); + public static final Font UI = loadFont("ibmplexsans-400", 12); + public static final Font MEDIUM = loadFont("ibmplexsans-500", 12); + public static final Font SEMIBOLD = loadFont("ibmplexsans-600", 12); + public static final Font MONO = loadFont("jetbrainsmono-400", 11); + + public static final Font MONO_SEMIBOLD = loadFont("jetbrainsmono-600", 11); + + private static final String CURSOR_PATH = "/rs117/hd/dev/editor/cursors/"; + private static final java.util.Map CURSORS = new java.util.HashMap<>(); + + public static Cursor cursor(String name) { + if (GraphicsEnvironment.isHeadless()) + return Cursor.getDefaultCursor(); + return CURSORS.computeIfAbsent(name, WorkspaceStyle::loadCursor); + } + + private static Cursor loadCursor(String name) { + String key = "cursor-" + name; + var resource = WorkspaceStyle.class.getResource(CURSOR_PATH + key + ".png"); + if (resource == null) + return Cursor.getDefaultCursor(); + var icon = new ImageIcon(resource); + int width = icon.getIconWidth(), height = icon.getIconHeight(); + if (width <= 0 || height <= 0) + return Cursor.getDefaultCursor(); + Toolkit toolkit = Toolkit.getDefaultToolkit(); + Dimension size = toolkit.getBestCursorSize(width, height); + if (size.width <= 0 || size.height <= 0) + return Cursor.getDefaultCursor(); + + var hotspot = CursorHotspots.VALUES.getAsJsonArray(key); + int x = hotspot == null ? width / 2 : hotspot.get(0).getAsInt(); + int y = hotspot == null ? height / 2 : hotspot.get(1).getAsInt(); + var image = icon.getImage(); + if (size.width != width || size.height != height) { + image = image.getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH); + x = x * size.width / width; + y = y * size.height / height; + } + return toolkit.createCustomCursor(image, new Point(x, y), name); + } + + private static final class CursorHotspots { + static final JsonObject VALUES = load(); + + private static JsonObject load() { + try (var stream = WorkspaceStyle.class.getResourceAsStream(CURSOR_PATH + "hotspots.json")) { + if (stream != null) + return new Gson().fromJson(new InputStreamReader(stream, StandardCharsets.UTF_8), JsonObject.class); + } catch (IOException | RuntimeException e) { + throw new IllegalStateException("Unable to load editor cursor hotspots", e); + } + return new JsonObject(); + } + } + + private static final java.util.Map SVG_ICONS = new java.util.HashMap<>(); + + public static ImageIcon icon(String name) { + return icon(name, 16); + } + + public static ImageIcon icon(String name, int size) { + return SVG_ICONS.computeIfAbsent(name + "/" + size, key -> { + var resource = WorkspaceStyle.class.getResource("/rs117/hd/dev/editor/icons/" + name + ".svg"); + if (resource == null) + return new ImageIcon(); + var svg = new com.github.weisj.jsvg.parser.SVGLoader().load(resource); + if (svg == null) + return new ImageIcon(); + var image = new java.awt.image.BufferedImage(size, size, java.awt.image.BufferedImage.TYPE_INT_ARGB); + Graphics2D g = image.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + svg.render(null, g, new com.github.weisj.jsvg.attributes.ViewBox(0, 0, size, size)); + } finally { + g.dispose(); + } + return new ImageIcon(image); + }); + } + + public enum Button { TAB, PRIMARY, SECONDARY, DANGER, TOOL, SEGMENT, TRIGGER, SCENE_TOGGLE, DASHED_ADD } + + private static Font loadFont(String file, int size) { + try (InputStream in = WorkspaceStyle.class.getResourceAsStream("/rs117/hd/dev/editor/fonts/" + file + ".ttf")) { + if (in != null) + return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont((float) size); + } catch (IOException | FontFormatException e) { + throw new IllegalStateException("Unable to load editor font " + file, e); + } + throw new IllegalStateException("Missing editor font " + file); + } + + static boolean hasButtonStyle(AbstractButton button) { + return button.getClientProperty(Button.class) != null; + } + + public static void button(AbstractButton button, Button variant) { + button.putClientProperty(Button.class, variant); + int height = variant == Button.TOOL ? 32 : variant == Button.TRIGGER ? 28 : (variant == Button.SEGMENT || variant == Button.SCENE_TOGGLE) ? 22 : 24; + button.setUI(new BasicButtonUI() { + @Override + public Dimension getPreferredSize(JComponent component) { + Dimension size = super.getPreferredSize(component); + int width = size != null ? size.width + : component.getLayout() != null ? component.getLayout().preferredLayoutSize(component).width : 0; + return new Dimension(variant == Button.TOOL ? 32 : width, height); + } + @Override + protected void paintText(Graphics g, AbstractButton button, Rectangle textRect, String text) { + if (button.isEnabled()) { + if (variant == Button.SCENE_TOGGLE) + g.setColor(new Color(button.isSelected() ? 0xD6D6D6 : 0xF0C27A)); + else + g.setColor(button.isSelected() ? Color.WHITE : button.getForeground()); + } else { + g.setColor(new Color(0x666666)); + } + g.drawString(text, textRect.x, textRect.y + g.getFontMetrics().getAscent()); + } + + @Override + public void paint(Graphics graphics, JComponent component) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + ButtonModel model = button.getModel(); + Color background = null; + switch (variant) { + case PRIMARY: background = model.isRollover() ? new Color(0x5281C4) : ACCENT; break; + case DANGER: background = model.isRollover() ? new Color(0x4A2C2C) : new Color(0x3A2626); break; + case SCENE_TOGGLE: + background = new Color(model.isSelected() + ? (model.isRollover() ? 0x3D3D3D : 0x333333) + : (model.isRollover() ? 0x594629 : 0x4A3A22)); + break; + case SECONDARY: background = model.isRollover() ? new Color(0x3D3D3D) : new Color(0x333333); break; + case DASHED_ADD: background = model.isRollover() && button.isEnabled() ? new Color(ACCENT.getRGB() & 0xFFFFFF | 0x33000000, true) : null; break; + case TAB: background = model.isSelected() || model.isRollover() ? BORDER : null; break; + case TOOL: background = model.isSelected() ? ACCENT : model.isRollover() ? new Color(0x333333) : null; break; + case SEGMENT: background = model.isSelected() ? new Color(0x454545) : model.isRollover() ? HEADER : null; break; + case TRIGGER: background = model.isSelected() ? ACCENT : model.isRollover() ? PANEL : MENU; break; + } + if (background != null) { + g.setColor(background); + int arc = variant == Button.TOOL || variant == Button.TRIGGER ? 10 : 8; + g.fillRoundRect(0, 0, component.getWidth(), component.getHeight(), arc, arc); + } + super.paint(g, component); + if (Boolean.TRUE.equals(button.getClientProperty("dropdown"))) + icon("chevron-down", 9).paintIcon(component, g, component.getWidth() - 17, (component.getHeight() - 9) / 2); + g.dispose(); + } + }); + button.setOpaque(false); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setFocusPainted(false); + button.setRolloverEnabled(true); + button.setForeground(variant == Button.PRIMARY ? Color.WHITE : variant == Button.DANGER ? new Color(0xE8A0A0) : (variant == Button.TAB || variant == Button.DASHED_ADD) ? new Color(0x9A9A9A) : TEXT); + button.setFont(variant == Button.PRIMARY ? SEMIBOLD : MEDIUM); + button.setIconTextGap(6); + button.setBorder(BorderFactory.createEmptyBorder(0, variant == Button.TRIGGER ? 8 : 10, 0, variant == Button.TRIGGER ? 8 : 10)); + button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + + } + + public static void dropdown(AbstractButton button) { + button.putClientProperty("dropdown", true); + button.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 23)); + } + + public static void soon(AbstractButton button) { + Icon badge = new Icon() { + public int getIconWidth() { return 34; } + public int getIconHeight() { return 14; } + public void paintIcon(Component c, Graphics graphics, int x, int y) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0x444444)); + g.drawRoundRect(x, y, 33, 13, 5, 5); + g.setFont(UI.deriveFont(9f)); + g.setColor(new Color(0x7D7D7D)); + g.drawString("SOON", x + (34 - g.getFontMetrics().stringWidth("SOON")) / 2, y + 10); + g.dispose(); + } + }; + button.setHorizontalTextPosition(SwingConstants.LEFT); + button.setIcon(badge); + button.setDisabledIcon(badge); + } + + public static void divider(JSplitPane split) { + split.setUI(new BasicSplitPaneUI() { + @Override + public BasicSplitPaneDivider createDefaultDivider() { + var divider = new BasicSplitPaneDivider(this) { + @Override + public void paint(Graphics g) { + g.setColor(isMouseOver() && split.isEnabled() ? ACCENT : GAP); + g.fillRect(0, 0, getWidth(), getHeight()); + } + + @Override + public void setMouseOver(boolean over) { + super.setMouseOver(over); + repaint(); + } + }; + divider.setCursor(Cursor.getPredefinedCursor(split.getOrientation() == JSplitPane.HORIZONTAL_SPLIT + ? Cursor.E_RESIZE_CURSOR : Cursor.N_RESIZE_CURSOR)); + return divider; + } + }); + split.setBorder(null); + split.setDividerSize(8); + split.setContinuousLayout(true); + } + + public static JScrollPane listScroll(JList list) { + list.setBackground(PANEL); + list.setForeground(TEXT); + var scroll = new EditorScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, MENU)); + scroll.getViewport().setBackground(PANEL); + return scroll; + } + + public static JTextField search(String placeholder) { + return new JTextField() { + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + if (!getText().isEmpty()) + return; + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setFont(getFont()); + g.setColor(DIM); + FontMetrics metrics = g.getFontMetrics(); + g.drawString(placeholder, getInsets().left, (getHeight() - metrics.getHeight()) / 2 + metrics.getAscent()); + g.dispose(); + } + }; + } + + public static Icon badge(String text, Color color) { + int size = text.isEmpty() ? 8 : 16; + return new Icon() { + public int getIconWidth() { return size; } + public int getIconHeight() { return size; } + + public void paintIcon(Component c, Graphics graphics, int x, int y) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(color); + g.fillRoundRect(x, y, size, size, 4, 4); + g.setColor(GAP); + g.setFont(MONO_SEMIBOLD.deriveFont(9f)); + FontMetrics metrics = g.getFontMetrics(); + g.drawString(text, x + (size - metrics.stringWidth(text)) / 2, + y + (size - metrics.getHeight()) / 2 + metrics.getAscent()); + g.dispose(); + } + }; + } + + public static Icon countBadge(JComponent component, String text) { + Font font = MONO.deriveFont(9f); + FontMetrics metrics = component.getFontMetrics(font); + int width = metrics.stringWidth(text) + 8; + int height = 14; + return new Icon() { + public int getIconWidth() { return width; } + public int getIconHeight() { return height; } + + public void paintIcon(Component c, Graphics graphics, int x, int y) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setColor(new Color(0x334D73)); + g.fillRoundRect(x, y, width, height, 6, 6); + g.setColor(new Color(0xCFE0FF)); + g.setFont(font); + g.drawString(text, x + 4, y + (height - metrics.getHeight()) / 2 + metrics.getAscent()); + g.dispose(); + } + }; + } + + private WorkspaceStyle() {} +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/AreaListField.java b/Tools/Dev/java/rs117/hd/dev/overrides/AreaListField.java new file mode 100644 index 0000000..9e9c3ef --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/AreaListField.java @@ -0,0 +1,241 @@ +package rs117.hd.dev.overrides; + +import java.awt.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.function.Consumer; +import javax.swing.*; +import rs117.hd.dev.editor.*; +import rs117.hd.dev.sceneloader.map.MapProjection; +import rs117.hd.dev.sceneloader.map.MapTileCache; +import rs117.hd.scene.AreaManager; +import rs117.hd.scene.areas.AABB; +import rs117.hd.scene.areas.Area; + +final class AreaListField extends JPanel { + private static final MapTileCache MAP = new MapTileCache(() -> SwingUtilities.invokeLater(() -> { + for (Window window : Window.getWindows()) + if (window.isShowing()) + window.repaint(); + })); + + private final boolean hidden; + private final Consumer update; + private final JButton viewButton; + private final JLabel emptyHint; + private List choices = List.of(); + private List assignedBounds = List.of(); + private LinkedHashSet selected = new LinkedHashSet<>(); + + AreaListField(String label, boolean hidden, Consumer update) { + this.hidden = hidden; + this.update = update; + setOpaque(false); + setLayout(new BorderLayout(0, 4)); + setName("field:" + label); + setAlignmentX(LEFT_ALIGNMENT); + var actions = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gap 4 0, fillx, hidemode 3", "[grow,right][]")); + actions.setOpaque(false); + emptyHint = EditorText.builder(hidden ? "Not hidden anywhere" : "Applies everywhere") + .font(WorkspaceStyle.UI.deriveFont(11f)).color(WorkspaceStyle.DIM).build(); + actions.add(emptyHint, "cell 0 0, wmin 0"); + viewButton = EditorButton.builder().text("View").onClick(() -> openList(label)).build(); + viewButton.setVisible(false); + actions.add(viewButton, "cell 0 0"); + actions.add(DashedAddButton.create("Add area", () -> open(choices, selected)), "cell 1 0"); + add(new PropertyRow(label, actions, PropertyRow.Layout.WIDE), BorderLayout.NORTH); + } + + @Override public Dimension getMaximumSize() { + return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); + } + + void setAreas(AABB[] bounds) { + assignedBounds = bounds == null ? List.of() : Arrays.asList(bounds); + var remaining = new LinkedHashSet<>(assignedBounds); + var selected = new LinkedHashSet(); + var choices = new ArrayList(); + for (Area area : AreaManager.AREAS) { + if (area == Area.ALL || area == Area.NONE || area.areaBounds == null || area.aabbs.length == 0) + continue; + choices.add(area); + if (remaining.containsAll(Arrays.asList(area.aabbs))) { + selected.add(area); + for (AABB box : area.aabbs) + remaining.remove(box); + } + } + for (AABB box : remaining) { + var area = new Area("Custom area"); + area.areaBounds = box; + area.aabbs = new AABB[] { box }; + selected.add(area); + } + this.choices = choices; + this.selected = selected; + viewButton.setText("View - " + selected.size()); + viewButton.setVisible(!selected.isEmpty()); + emptyHint.setVisible(selected.isEmpty()); + revalidate(); + repaint(); + } + + private void open(List choices, LinkedHashSet selected) { + var preview = new AreaPreview(); + if (!selected.isEmpty()) + preview.showArea(selected.iterator().next()); + else if (!choices.isEmpty()) + preview.showArea(choices.get(0)); + new SelectionModal(hidden ? "Add Hide in areas" : "Add Areas", choices, selected, area -> area.name) + .badge("A", new Color(0x3F7A6A)).rowMeta(area -> size(area.areaBounds)) + .search("Search areas", area -> area.name).preview(preview, preview::showArea) + .open(this, draft -> update.accept(draft.stream().flatMap(area -> Arrays.stream(area.aabbs)) + .distinct().toArray(AABB[]::new))); + } + + private void openList(String label) { + var original = new LinkedHashSet<>(selected); + var originalBounds = new ArrayList<>(assignedBounds); + new SelectionModal("View " + label, new ArrayList<>(original), original, area -> area.name) + .badge("A", new Color(0x3F7A6A)) + .search("Search areas", area -> area.name + " " + from(area.areaBounds) + " " + to(area.areaBounds)) + .rows(68, "areas", AreaListField::renderAreaRow) + .open(this, draft -> { + for (Area area : original) + if (!draft.contains(area)) + for (AABB box : area.aabbs) + originalBounds.remove(box); + update.accept(originalBounds.toArray(AABB[]::new)); + }); + } + + private static JComponent renderAreaRow(Area area) { + var row = new JPanel(new BorderLayout(12, 0)); + row.setOpaque(false); + row.setBorder(BorderFactory.createEmptyBorder(6, 0, 6, 0)); + var thumbnail = new AreaMap(false); + thumbnail.area = area; + thumbnail.setPreferredSize(new Dimension(84, 56)); + row.add(thumbnail, BorderLayout.WEST); + + var details = new JPanel(new GridLayout(3, 1)); + details.setOpaque(false); + details.add(text(area.name, 12)); + details.add(text(from(area.areaBounds) + " → " + to(area.areaBounds), 10)); + details.add(text(size(area.areaBounds), 10)); + row.add(details); + return row; + } + + private static final class AreaPreview extends JPanel { + private final JLabel name = text("", 13); + private final JTextArea detail = new JTextArea(4, 20); + private final AreaMap map = new AreaMap(true); + + AreaPreview() { + super(new BorderLayout(0, 8)); + setBackground(new Color(0x1F1F1F)); + setBorder(BorderFactory.createEmptyBorder(12, 12, 8, 12)); + detail.setFont(WorkspaceStyle.MONO.deriveFont(11f)); + detail.setForeground(WorkspaceStyle.TEXT); + detail.setOpaque(false); + detail.setEditable(false); + add(name, BorderLayout.NORTH); + add(map); + add(detail, BorderLayout.SOUTH); + } + + void showArea(Area area) { + var box = area.areaBounds; + name.setText(area.name); + map.area = area; + map.repaint(); + detail.setText("From " + from(box) + "\nTo " + to(box) + "\nSize " + AreaListField.size(box) + + "\nRegions " + regions(box)); + } + } + + private static JLabel text(String value, float size) { + return EditorText.builder(value).font(WorkspaceStyle.MONO.deriveFont(size)).build(); + } + + private static String from(AABB b) { return b.minX + ", " + b.minY + (b.hasZ() ? ", " + b.minZ : ""); } + private static String to(AABB b) { return b.maxX + ", " + b.maxY + (b.hasZ() ? ", " + b.maxZ : ""); } + private static String size(AABB b) { return (1L + b.maxX - b.minX) + " × " + (1L + b.maxY - b.minY) + " tiles"; } + + private static String regions(AABB b) { + int x1 = b.minX >> 6, y1 = b.minY >> 6, x2 = b.maxX >> 6, y2 = b.maxY >> 6; + long total = (1L + x2 - x1) * (1L + y2 - y1); + var regions = new ArrayList(); + for (int x = x1; x <= x2 && regions.size() < 6; x++) + for (int y = y1; y <= y2 && regions.size() < 6; y++) + regions.add(Integer.toString(x << 8 | y)); + return String.join(", ", regions) + (total > regions.size() ? " +" + (total - regions.size()) : ""); + } + + private static final class AreaMap extends JComponent { + private final boolean large; + private Area area; + + AreaMap(boolean large) { this.large = large; } + + @Override protected void paintComponent(Graphics graphics) { + if (area == null || getWidth() == 0 || getHeight() == 0) + return; + var box = area.areaBounds; + var g = (Graphics2D) graphics.create(); + boolean underground = box.minY >= 4000; + g.setColor(underground ? new Color(0x2A2420) : new Color(0x24282A)); + g.fillRect(0, 0, getWidth(), getHeight()); + double padding = large ? 1.9 : 2.4; + double scale = Math.min(getWidth() / Math.max(48, (1.0 + box.maxX - box.minX) * padding), + getHeight() / Math.max(32, (1.0 + box.maxY - box.minY) * padding)); + double centerX = (box.minX + (double) box.maxX + 1) / 2; + double centerY = (box.minY + (double) box.maxY + 1) / 2; + double left = centerX - getWidth() / (2 * scale); + double top = centerY + getHeight() / (2 * scale); + if (!underground) + drawTiles(g, box.hasZ() ? box.minZ : 0, left, top, scale); + for (AABB bounds : area.aabbs) { + int x = (int) Math.round((bounds.minX - left) * scale); + int y = (int) Math.round((top - bounds.maxY - 1) * scale); + int w = Math.max(1, (int) Math.round((1.0 + bounds.maxX - bounds.minX) * scale)); + int h = Math.max(1, (int) Math.round((1.0 + bounds.maxY - bounds.minY) * scale)); + g.setColor(new Color(255, 179, 71, 56)); + g.fillRect(x, y, w, h); + g.setColor(new Color(0xFFB347)); + g.drawRect(x, y, w, h); + } + if (large) { + g.setColor(Color.WHITE); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.drawString("N ↑", getWidth() - 25, 15); + g.drawString(AreaListField.size(box) + (underground ? " · underground" : ""), 7, getHeight() - 8); + } + g.dispose(); + } + + private void drawTiles(Graphics2D g, int plane, double left, double top, double scale) { + int zoom = MapProjection.MIN_ZOOM; + while (zoom < MapProjection.MAX_ZOOM && MapProjection.WORLD_TILE_PX / MapProjection.scale(zoom) < scale) + zoom++; + int span = MapProjection.scale(zoom) * MapProjection.TILE_SIZE; + double px = MapProjection.pixelX(0) + left * MapProjection.WORLD_TILE_PX; + double py = MapProjection.pixelY(0) - top * MapProjection.WORLD_TILE_PX; + double ratio = scale / MapProjection.WORLD_TILE_PX; + int firstX = Math.max(0, MapProjection.tileIndex(px, zoom)); + int firstY = Math.max(0, MapProjection.tileIndex(py, zoom)); + int lastX = Math.min((1 << zoom) - 1, MapProjection.tileIndex(px + getWidth() / ratio, zoom)); + int lastY = Math.min((1 << zoom) - 1, MapProjection.tileIndex(py + getHeight() / ratio, zoom)); + for (int y = firstY; y <= lastY; y++) + for (int x = firstX; x <= lastX; x++) { + var image = MAP.get(plane, zoom, x, MapProjection.flipTileY(y, zoom)); + if (image != null) + g.drawImage(image, (int) Math.round((x * span - px) * ratio), (int) Math.round((y * span - py) * ratio), + (int) Math.ceil(span * ratio), (int) Math.ceil(span * ratio), this); + } + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpression.java b/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpression.java new file mode 100644 index 0000000..1e1a1b3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpression.java @@ -0,0 +1,88 @@ +package rs117.hd.dev.overrides; + +import com.google.gson.JsonElement; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import rs117.hd.utils.ExpressionParser; + +final class ColorExpression { + private static final Pattern CONDITION = Pattern.compile("([hsl])\\s*(==|!=|<=|>=|<|>)\\s*(-?\\d+)"); + + static final class Condition { + final String channel, operator; + final int value; + + Condition(String channel, String operator, int value) { + this.channel = channel; + this.operator = operator; + this.value = value; + } + + @Override public String toString() { return channel + " " + operator + " " + value; } + } + + static List> groups(String text) { + var groups = new ArrayList>(); + for (String group : text.split("\\|\\|", -1)) { + var conditions = new ArrayList(); + for (String term : group.split("&&", -1)) { + var match = CONDITION.matcher(term.strip()); + if (!match.matches()) + return null; + try { + conditions.add(new Condition(match.group(1), match.group(2), Integer.parseInt(match.group(3)))); + } catch (NumberFormatException e) { + return null; + } + } + groups.add(conditions); + } + return groups; + } + + static String format(List> groups) { + return groups.stream().map(group -> group.stream().map(Condition::toString) + .collect(Collectors.joining(" && "))).collect(Collectors.joining(" || ")); + } + + static boolean valid(String text) { + if (text.isBlank()) + return false; + try { + var expression = ExpressionParser.asExpression(ExpressionParser.parseExpression(text)); + for (var variable : expression.variables) + if (!List.of("h", "s", "l", "a", "hsl", "ahsl").contains(variable)) + return false; + return true; + } catch (RuntimeException e) { + return false; + } + } + + static String exact(int hsl) { + return "h == " + (hsl >> 10 & 63) + " && s == " + (hsl >> 7 & 7) + " && l == " + (hsl & 127); + } + + static String text(JsonElement value) { + if (value == null || value.isJsonNull()) + return ""; + if (value.isJsonArray()) { + var terms = new ArrayList(); + for (var item : value.getAsJsonArray()) { + String term = text(item); + if (!term.isBlank()) + terms.add(groups(term) == null ? "(" + term + ")" : term); + } + return String.join(" || ", terms); + } + if (!value.isJsonPrimitive()) + return "false"; + if (value.getAsJsonPrimitive().isNumber()) { + int packed = value.getAsInt(); + return packed >= 0 && packed <= 65535 ? exact(packed) : "false"; + } + return value.getAsString(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpressionPanel.java b/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpressionPanel.java new file mode 100644 index 0000000..3d5a997 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ColorExpressionPanel.java @@ -0,0 +1,313 @@ +package rs117.hd.dev.overrides; + +import java.awt.*; +import java.awt.datatransfer.StringSelection; +import java.awt.font.TextAttribute; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import rs117.hd.dev.editor.*; + +final class ColorExpressionPanel extends JPanel { + static final Font CODE = WorkspaceStyle.MONO.deriveFont(Map.of(TextAttribute.LIGATURES, 0)); + private static final Font OPERATOR = WorkspaceStyle.MONO_SEMIBOLD.deriveFont(Map.of(TextAttribute.LIGATURES, 0)); + private static final List OPERATORS = List.of("==", "!=", "<", "<=", ">", ">="); + private static final List WORDS = List.of("equals", "is not", "less than", "at most", "more than", "at least"); + private final JPanel fields = builderStack(); + private final JPanel pickRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0)); + private final JLabel status = EditorText.builder("").font(WorkspaceStyle.UI.deriveFont(11f)).build(); + private final JLabel output = EditorText.builder("").font(CODE).color(new Color(0xCFE0FF)).build(); + private final JTextField input = new JTextField(); + private final EditorButtonGroup tabs; + private final JToggleButton builder; + private final Consumer change; + private final Function evaluate; + private final Consumer viewChanged; + private String text; + private boolean syncing; + + ColorExpressionPanel(String text, boolean expressionView, Consumer change, + Function evaluate, Consumer viewChanged, Runnable pick, Consumer toast) { + this.text = text; + this.change = change; + this.evaluate = evaluate; + this.viewChanged = viewChanged; + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setAlignmentX(LEFT_ALIGNMENT); + setOpaque(false); + var bar = new JPanel(new BorderLayout(4, 0)); + bar.setOpaque(false); + bar.setAlignmentX(LEFT_ALIGNMENT); + bar.add(EditorText.builder("Match faces where").font(WorkspaceStyle.UI.deriveFont(11f)).color(WorkspaceStyle.DIM).build()); + tabs = EditorButtonGroup.builder(List.of("Builder", "Expression")).onChange(mode -> { + if ("Builder".equals(mode)) + showBuilder(); + else + showExpression(); + }).build(); + builder = tabs.button("Builder"); + bar.add(tabs, BorderLayout.EAST); + add(bar); + add(Box.createVerticalStrut(8)); + add(fields); + input.setFont(CODE.deriveFont(12f)); + input.setBackground(new Color(0x141414)); + input.setForeground(WorkspaceStyle.TEXT); + input.setCaretColor(WorkspaceStyle.TEXT); + input.setToolTipText("h == 63 && s > 0"); + input.setText(text); + input.setAlignmentX(LEFT_ALIGNMENT); + input.setMaximumSize(new Dimension(Integer.MAX_VALUE, 28)); + input.getDocument().addDocumentListener(new DocumentListener() { + public void insertUpdate(DocumentEvent e) { typed(); } + public void removeUpdate(DocumentEvent e) { typed(); } + public void changedUpdate(DocumentEvent e) { typed(); } + }); + var pickButton = EditorButton.builder().text("Pick on model").icon("eyedropper", 12).onClick(pick).build(); + pickButton.setAlignmentX(LEFT_ALIGNMENT); + pickRow.setOpaque(false); + pickRow.setAlignmentX(LEFT_ALIGNMENT); + pickRow.add(pickButton); + pickRow.add(EditorText.builder("adds an exact h/s/l group").font(WorkspaceStyle.UI.deriveFont(10f)) + .color(WorkspaceStyle.DIM).build()); + add(Box.createVerticalStrut(6)); + add(pickRow); + add(Box.createVerticalStrut(7)); + add(status); + add(Box.createVerticalStrut(7)); + var result = new JPanel(new BorderLayout(5, 0)); + result.setAlignmentX(LEFT_ALIGNMENT); + result.setBackground(new Color(0x141414)); + result.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(0x333333), 1, true), + BorderFactory.createEmptyBorder(4, 8, 4, 5))); + result.setMaximumSize(new Dimension(Integer.MAX_VALUE, 34)); + result.add(output); + result.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("copy", 12).size(22, 22) + .tooltip("Copy colors expression").onClick(() -> { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(output.getText()), null); + toast.accept("Copied colors expression"); + }).build(), BorderLayout.EAST); + add(result); + add(Box.createVerticalStrut(6)); + add(EditorText.builder("h hue 0–63 · s saturation 0–7 · l lightness 0–127
&& = and · || = or") + .font(CODE.deriveFont(10f)).color(WorkspaceStyle.DIM).build()); + if (expressionView || ColorExpression.groups(text) == null) + showExpression(); + else + showBuilder(); + updateStatus(); + } + + private void typed() { + if (syncing) + return; + text = input.getText(); + change.accept(text); + updateStatus(); + } + + private void updateStatus() { + boolean valid = ColorExpression.valid(text); + builder.setEnabled(ColorExpression.groups(text) != null && valid); + builder.setToolTipText(builder.isEnabled() ? null : valid ? "This expression uses syntax outside the builder" : "Fix the expression to use the builder"); + String message = valid ? evaluate.apply(text) : text.isBlank() ? "Empty · add at least one condition" + : "Can't read this expression · check the comparisons"; + if (!valid) + evaluate.apply(text); + status.setText(message); + boolean matches = valid && message.startsWith("Matches"); + status.setForeground(new Color(!valid ? 0xE8A0A0 : matches ? 0x9A9A9A : 0xE8C27A)); + status.setIcon(WorkspaceStyle.badge("", new Color(!valid ? 0xE06060 : matches ? 0x6CB348 : 0xE8A33D))); + status.setToolTipText(message); + output.setText("\"colors\": " + new com.google.gson.JsonPrimitive(text)); + output.setToolTipText(output.getText()); + input.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(valid ? WorkspaceStyle.BORDER : new Color(0xA04848)), + BorderFactory.createEmptyBorder(4, 7, 4, 7))); + } + + private void showExpression() { + viewChanged.accept(true); + fields.removeAll(); + removeOrButton(); + fields.add(input); + tabs.setSelected("Expression"); + fields.revalidate(); + fields.repaint(); + } + + private void showBuilder() { + var groups = ColorExpression.groups(text); + if (groups == null) + return; + viewChanged.accept(false); + builder.setSelected(true); + fields.removeAll(); + for (var conditions : groups) { + if (fields.getComponentCount() > 0) + fields.add(EditorText.builder("OR").font(WorkspaceStyle.SEMIBOLD.deriveFont(10f)).color(WorkspaceStyle.DIM).build()); + var box = builderStack(); + box.setBackground(new Color(0x1F1F1F)); + box.setOpaque(true); + box.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true), + BorderFactory.createEmptyBorder(6, 7, 6, 7))); + for (int i = 0; i < conditions.size(); i++) + box.add(conditionRow(groups, conditions, i), "growx, wmin 0"); + var footer = new JPanel(new BorderLayout()); + footer.setOpaque(false); + footer.setBorder(BorderFactory.createEmptyBorder(4, 43, 0, 0)); + footer.add(DashedAddButton.create("and", () -> { + conditions.add(new ColorExpression.Condition("s", ">", 0)); + apply(groups, true); + }), BorderLayout.WEST); + if (groups.size() > 1) + footer.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).text("Remove group").onClick(() -> { + groups.remove(conditions); + apply(groups, true); + }).build(), BorderLayout.EAST); + box.add(footer); + fields.add(box, "growx, wmin 0"); + } + removeOrButton(); + pickRow.add(DashedAddButton.create("Or group", () -> { + groups.add(new java.util.ArrayList<>(List.of(new ColorExpression.Condition("h", "==", 0)))); + apply(groups, true); + }), 0); + fields.revalidate(); + fields.repaint(); + } + + private void removeOrButton() { + if (pickRow.getComponentCount() == 3) + pickRow.remove(0); + } + + private JPanel conditionRow(List> groups, List conditions, int row) { + var controls = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gap 4, fillx, novisualpadding", "[32!,right][76!,fill][34:88:88,fill][48:60:,grow,fill][22!,fill]", "[22!,center]")); + controls.setOpaque(false); + controls.setAlignmentX(LEFT_ALIGNMENT); + controls.setMaximumSize(new Dimension(Integer.MAX_VALUE, 22)); + controls.add(EditorText.builder(row == 0 ? "where" : "and").font(WorkspaceStyle.UI.deriveFont(10f)).build()); + var condition = conditions.get(row); + var channel = SegmentedControl.builder(List.of("h", "s", "l")).values().label(v -> v.toUpperCase(java.util.Locale.ROOT)) + .marker(v -> new Color("h".equals(v) ? 0xD68957 : "s".equals(v) ? 0x78A477 : 0xB9B9B9)) + .selected(condition.channel).onChange(v -> { + var current = conditions.get(row); + conditions.set(row, new ColorExpression.Condition(v, current.operator, current.value)); + apply(groups, true); + }).build(); + controls.add(channel, "h 22!"); + controls.add(new ColorOperatorDropdown(condition, op -> { + var current = conditions.get(row); + conditions.set(row, new ColorExpression.Condition(current.channel, op, current.value)); + apply(groups, true); + }), "wmin 0"); + var value = NumberField.builder().value((double) condition.value).min((double) Integer.MIN_VALUE) + .max((double) Integer.MAX_VALUE).onChange(v -> { + var current = conditions.get(row); + conditions.set(row, new ColorExpression.Condition(current.channel, current.operator, v.intValue())); + apply(groups, false); + }).build(); + value.setToolTipText("Range 0–" + (condition.channel.equals("h") ? 63 : condition.channel.equals("s") ? 7 : 127)); + controls.add(value, "h 22!, wmin 0"); + if (groups.size() > 1 || conditions.size() > 1) + controls.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("close", 11).size(22, 22) + .tooltip("Remove condition").onClick(() -> { + conditions.remove(row); + if (conditions.isEmpty()) groups.remove(conditions); + apply(groups, true); + }).build()); + return controls; + } + + private void apply(List> groups, boolean rebuild) { + text = ColorExpression.format(groups); + syncing = true; + try { + input.setText(text); + } finally { + syncing = false; + } + change.accept(text); + updateStatus(); + if (rebuild) + showBuilder(); + } + + private static JPanel builderStack() { + var panel = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gapy 4, fillx, wrap 1", "[0,grow,fill]")); + panel.setAlignmentX(LEFT_ALIGNMENT); + panel.setOpaque(false); + return panel; + } + + private static final class ColorOperatorDropdown extends JButton { + private PopupLayer.Handle popup; + + ColorOperatorDropdown(ColorExpression.Condition condition, Consumer onChange) { + WorkspaceStyle.button(this, WorkspaceStyle.Button.TRIGGER); + setLayout(new BorderLayout(4, 0)); + setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.BORDER, 1, true), + BorderFactory.createEmptyBorder(0, 5, 0, 5))); + setBorderPainted(true); + add(parts(condition.operator, WORDS.get(OPERATORS.indexOf(condition.operator)), null)); + add(new JLabel(WorkspaceStyle.icon("chevron-down", 8)), BorderLayout.EAST); + getAccessibleContext().setAccessibleName("Comparison " + condition.operator); + addActionListener(e -> { + if (popup != null) { + popup.close(); + return; + } + var menu = EditorPanels.stack(); + menu.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + var options = new java.util.ArrayList(); + for (int i = 0; i < OPERATORS.size(); i++) { + String op = OPERATORS.get(i); + var option = EditorButton.builder().style(WorkspaceStyle.Button.SEGMENT) + .onClick(() -> { + if (popup != null) + popup.close(); + onChange.accept(op); + }).build(); + option.setLayout(new BorderLayout()); + option.add(parts(op, WORDS.get(i), condition.channel + " " + op + " " + condition.value)); + option.getAccessibleContext().setAccessibleName(op + " " + WORDS.get(i)); + option.setSelected(op.equals(condition.operator)); + option.setHorizontalAlignment(LEFT); + option.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + option.setAlignmentX(LEFT_ALIGNMENT); + options.add(option); + menu.add(option); + } + for (int i = 0; i < options.size(); i++) { + int index = i; + var option = options.get(i); + option.registerKeyboardAction(ev -> options.get((index + 1) % options.size()).requestFocusInWindow(), + KeyStroke.getKeyStroke("DOWN"), WHEN_FOCUSED); + option.registerKeyboardAction(ev -> options.get((index + options.size() - 1) % options.size()).requestFocusInWindow(), + KeyStroke.getKeyStroke("UP"), WHEN_FOCUSED); + option.registerKeyboardAction(ev -> option.doClick(), KeyStroke.getKeyStroke("ENTER"), WHEN_FOCUSED); + } + popup = PopupLayer.show(this, menu, 160); + setSelected(true); + popup.onClose(() -> { popup = null; setSelected(false); }); + options.get(OPERATORS.indexOf(condition.operator)).requestFocusInWindow(); + }); + } + private static JPanel parts(String operator, String word, String example) { + var panel = new JPanel(new BorderLayout(5, 0)); + panel.setOpaque(false); + var symbol = EditorText.builder(operator).font(OPERATOR).color(new Color(0xCFE0FF)).build(); + symbol.setPreferredSize(new Dimension(16, symbol.getPreferredSize().height)); + panel.add(symbol, BorderLayout.WEST); + panel.add(EditorText.builder(word).font(WorkspaceStyle.UI.deriveFont(10f)).build()); + if (example != null) + panel.add(EditorText.builder(example).font(CODE.deriveFont(9f)).color(WorkspaceStyle.DIM).build(), BorderLayout.EAST); + return panel; + } + + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/MaterialThumbnails.java b/Tools/Dev/java/rs117/hd/dev/overrides/MaterialThumbnails.java new file mode 100644 index 0000000..38774ed --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/MaterialThumbnails.java @@ -0,0 +1,198 @@ +package rs117.hd.dev.overrides; + +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.imageio.ImageIO; +import rs117.hd.scene.materials.Material; + +/** Cached thumbnails of the actual HD diffuse textures. */ +public final class MaterialThumbnails { + // Both the small trigger icon and larger grid tile can be cached for a material. + private static final int MAX_THUMBNAILS = 512; + private static final Map CACHE = new LinkedHashMap(64, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_THUMBNAILS; + } + }; + + private MaterialThumbnails() {} + + static Image vanillaPreview(int[] pixels) { + int size = rs117.hd.dev.sceneloader.standalone.Textures.SIZE; + if (pixels == null || pixels.length != size * size) + return null; + + int[] argb = new int[pixels.length]; + for (int i = 0; i < pixels.length; i++) + argb[i] = pixels[i] == 0 ? 0 : 0xFF000000 | (pixels[i] & 0xFFFFFF); + var image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + image.setRGB(0, 0, size, size, argb, 0, size); + return image; + } + + private static final class PreviewKey { + private final Material material; + private final int size; + + private PreviewKey(Material material, int size) { + this.material = material; + this.size = size; + } + + @Override public int hashCode() { return 31 * System.identityHashCode(material) + size; } + @Override public boolean equals(Object other) { + if (!(other instanceof PreviewKey)) + return false; + var key = (PreviewKey) other; + return key.material == material && key.size == size; + } + } + + private static final java.util.WeakHashMap waiting = new java.util.WeakHashMap<>(); + private static final Map> pending = new java.util.HashMap<>(); + private static final java.util.concurrent.ExecutorService loader = java.util.concurrent.Executors.newSingleThreadExecutor(task -> { + var thread = new Thread(task, "117HD material thumbnails"); + thread.setDaemon(true); + return thread; + }); + + public static Image preview(Material material, int size, java.awt.Component observer) { + if (material == null || material == Material.NONE) + return null; + var key = new PreviewKey(material, size); + synchronized (CACHE) { + if (CACHE.containsKey(key)) + return CACHE.get(key); + var observers = pending.get(key); + if (observers == null) { + // Rapid scrolling should not queue the entire texture library. + if (pending.size() >= 64) { + waiting.put(observer, Boolean.TRUE); + return null; + } + observers = new java.util.WeakHashMap<>(); + pending.put(key, observers); + loader.execute(() -> loadPreview(key)); + } + observers.put(observer, Boolean.TRUE); + } + return null; + } + + private static void loadPreview(PreviewKey key) { + Image image = null; + try { + image = load(key.material, key.size); + } finally { + java.util.List observers; + synchronized (CACHE) { + CACHE.put(key, image); + observers = new java.util.ArrayList<>(pending.remove(key).keySet()); + if (pending.isEmpty()) { + observers.addAll(waiting.keySet()); + waiting.clear(); + } + } + javax.swing.SwingUtilities.invokeLater(() -> observers.forEach(java.awt.Component::repaint)); + } + } + + /** Classifies maps by how RLHD references them, independent of their filenames. */ + static java.util.List withoutAuxiliaryMaps(java.util.List materials) { + var mapNames = new java.util.HashSet(); + try { + for (Material material : materials) { + for (var field : AUXILIARY_MAPS) { + var map = (Material) field.get(material); + if (map != null && map != Material.NONE) + mapNames.add(map.name); + } + } + } catch (IllegalAccessException e) { + throw new IllegalStateException("Unable to read auxiliary material maps", e); + } + materials.removeIf(material -> mapNames.contains(material.name)); + return materials; + } + + private static final java.lang.reflect.Field[] AUXILIARY_MAPS = java.util.stream.Stream.of( + "normalMap", "displacementMap", "roughnessMap", "ambientOcclusionMap", "flowMap", "shadowAlphaMap") + .map(MaterialThumbnails::materialField).toArray(java.lang.reflect.Field[]::new); + + private static Image load(Material material, int size) { + if (material == Material.NONE) + return null; + for (Material current = material; current != null; current = parentOf(current)) { + Image image = loadTexture(current.getTextureName(), size); + if (image != null) + return image; + } + // Untextured materials still have a surface. Show a neutral lighting sample. + var image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); + var g = image.createGraphics(); + try { + float center = size / 2f; + boolean unlit = "UNLIT".equals(material.name); + g.setPaint(new java.awt.RadialGradientPaint(center, center, size * .72f, new float[] {0, 1}, + new java.awt.Color[] {new java.awt.Color(unlit ? 0xFFFFFF : 0xACAAA5), new java.awt.Color(unlit ? 0xB0B0B0 : 0x62605D)})); + g.fillRect(0, 0, size, size); + } finally { + g.dispose(); + } + return image; + } + + private static final java.lang.reflect.Field PARENT = materialField("parent"); + + private static java.lang.reflect.Field materialField(String name) { + try { + var field = Material.class.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Unable to access material field " + name, e); + } + } + + private static Material parentOf(Material material) { + try { + return (Material) PARENT.get(material); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Unable to read material inheritance", e); + } + } + + private static Image loadTexture(String textureName, int size) { + if (textureName == null) + return null; + for (String extension : new String[] {".png", ".jpg", ".jpeg"}) { + try (InputStream stream = Material.class.getResourceAsStream("/rs117/hd/scene/textures/" + textureName + extension)) { + if (stream == null) + continue; + BufferedImage image = ImageIO.read(stream); + if (image != null) + return scale(image, size); + } catch (IOException ignored) { + // Try the next supported extension. + } + } + return null; + } + static BufferedImage scale(Image image, int size) { + var scaled = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + var graphics = scaled.createGraphics(); + try { + graphics.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, + java.awt.RenderingHints.VALUE_INTERPOLATION_BICUBIC); + graphics.drawImage(image, 0, 0, size, size, null); + } finally { + graphics.dispose(); + } + return scaled; + } + +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ModelColorPalette.java b/Tools/Dev/java/rs117/hd/dev/overrides/ModelColorPalette.java new file mode 100644 index 0000000..121a56c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ModelColorPalette.java @@ -0,0 +1,48 @@ +package rs117.hd.dev.overrides; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.runelite.api.Model; +import rs117.hd.utils.ColorUtils; + +/** Distinct packed-AHSL colors on a {@link Model}, with a face count per color — nothing in the + * codebase already does this, so it's built fresh here. Packing matches the renderer's own + * convention ({@code SceneUploader}: alpha in bits 16-23, 16-bit Jagex HSL below that). */ +final class ModelColorPalette { + static final class Entry { + final int ahsl; + final int hue, saturation, lightness; + final Color color; + int faceCount; + + private Entry(int ahsl) { + this.ahsl = ahsl; + int hsl = ahsl & 0xFFFF; + int[] unpacked = ColorUtils.unpackRawHsl(hsl); + hue = unpacked[0]; + saturation = unpacked[1]; + lightness = unpacked[2]; + float[] srgb = ColorUtils.packedHslToSrgb(hsl); + // Show the HSL independently of face opacity. Keep opacity in ahsl for matching. + color = new Color(srgb[0], srgb[1], srgb[2]); + } + } + + private ModelColorPalette() {} + + static List distinctColors(Model model) { + Map byAhsl = new LinkedHashMap<>(); + int[] colors1 = model.getFaceColors1(); + byte[] transparencies = model.getFaceTransparencies(); + int faceCount = model.getFaceCount(); + for (int face = 0; face < faceCount; face++) { + int transparency = transparencies == null ? 0 : transparencies[face] & 0xFF; + int ahsl = (0xFF - transparency) << 16 | (colors1[face] & 0xFFFF); + byAhsl.computeIfAbsent(ahsl, Entry::new).faceCount++; + } + return new ArrayList<>(byAhsl.values()); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideDocument.java b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideDocument.java new file mode 100644 index 0000000..20cea29 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideDocument.java @@ -0,0 +1,463 @@ +package rs117.hd.dev.overrides; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonParser; +import com.google.gson.JsonObject; +import com.google.gson.JsonElement; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.LinkedHashMap; +import java.util.Set; +import rs117.hd.dev.editor.CacheModels; +import rs117.hd.scene.materials.Material; +import rs117.hd.scene.model_overrides.ModelOverride; + +/** + * Edits {@link ModelOverride} entries one at a time while preserving everything else in + * {@code model_overrides.json} byte-for-byte — comments included. Never re-serializes the whole + * file; only the entry being saved is re-written and spliced back into the original text, exactly + * like the editor's previous raw-JSON incarnation (now typed against the real {@link ModelOverride} + * class instead of a generic {@code JsonObject}). + */ +final class ModelOverrideDocument { + private final Gson gson; + private final Path file; + private final Map> gamevals; + private final JsonObject defaults; + private String source; + private int arrayClose; + private int lastValueEnd; + private boolean trailingComma; + private final List entries = new ArrayList<>(); + + static final class Entry { + private int start; + private int end; + String savedBlock; + ModelOverride override; + + private Entry(int start, int end, ModelOverride override) { + this.start = start; + this.end = end; + this.override = override; + } + + /** True once this entry has actually been written into the file at least once. */ + boolean isPersisted() { return savedBlock != null; } + } + + ModelOverrideDocument(Gson gson, Path file, rs117.hd.scene.GamevalManager.Handle names) throws IOException { + gamevals = Map.of("npcIds", names.getNpcs(), "objectIds", names.getObjects(), + "projectileIds", names.getSpotanims(), "graphicsObjectIds", names.getSpotanims()); + // Material.Definition also matches RLHD's exclude-defaults factory, which writes objects. + // Register a factory ahead of it so both runtime material types and map keys use names. + this.gson = gson.newBuilder() + .registerTypeAdapterFactory(new TypeAdapterFactory() { + private final TypeAdapter materialAdapter = new Material.Adapter().nullSafe(); + + @Override + @SuppressWarnings("unchecked") + public TypeAdapter create(Gson gson, TypeToken type) { + return Material.class.isAssignableFrom(type.getRawType()) + ? (TypeAdapter) materialAdapter : null; + } + }) + .enableComplexMapKeySerialization() + .create(); + this.defaults = this.gson.toJsonTree(new ModelOverride(), ModelOverride.class).getAsJsonObject(); + this.file = file; + reload(); + } + + synchronized List entries() { return List.copyOf(entries); } + + Gson gson() { return gson; } + + private void reload() throws IOException { + source = Files.readString(file); + entries.clear(); + int cursor = skipTrivia(source, 0); + if (cursor == source.length() || source.charAt(cursor++) != '[') + throw new IOException("Expected an array of model overrides"); + lastValueEnd = cursor; + while (true) { + cursor = skipTrivia(source, cursor); + if (cursor == source.length()) + throw new IOException("Unclosed override array"); + char token = source.charAt(cursor); + if (token == ']') { + arrayClose = cursor; + break; + } + if (token == ',') { + trailingComma = true; + cursor++; + continue; + } + if (source.startsWith("null", cursor)) { + cursor += 4; + lastValueEnd = cursor; + trailingComma = false; + continue; + } + if (token != '{') + throw new IOException("Expected an override object at character " + cursor); + int end = objectEnd(source, cursor); + ModelOverride override = gson.fromJson(source.substring(cursor, end), ModelOverride.class); + var entry = new Entry(cursor, end, override); + entry.savedBlock = source.substring(cursor, end); + entries.add(entry); + cursor = lastValueEnd = end; + trailingComma = false; + } + } + + /** A brand new, not-yet-saved entry, appended to the in-memory list only. */ + synchronized Entry create(ModelOverride seed) { + Entry entry = new Entry(-1, -1, seed); + entries.add(entry); + return entry; + } + + /** A deep copy of {@code original}'s current state, as its own new not-yet-saved entry. */ + Entry duplicate(Entry original) { + ModelOverride copy = gson.fromJson(gson.toJson(original.override, ModelOverride.class), ModelOverride.class); + return create(copy); + } + + synchronized void discard(Entry entry) { entries.remove(entry); } + + /** True if the override directly targets the given category and ID. */ + boolean targets(ModelOverride override, CacheModels.Category category, int id) { + return targetIds(override, category).contains(id); + } + + synchronized Set targetIds(CacheModels.Category category) { + var ids = new HashSet(); + for (var entry : entries) + ids.addAll(targetIds(entry.override, category)); + return ids; + } + + private static Set targetIds(ModelOverride override, CacheModels.Category category) { + Set ids; + switch (category) { + case NPCs: ids = override.npcIds; break; + case Objects: ids = override.objectIds; break; + case Graphics: + var spotanims = new HashSet(); + if (override.graphicsObjectIds != null) + spotanims.addAll(override.graphicsObjectIds); + if (override.projectileIds != null) + spotanims.addAll(override.projectileIds); + return spotanims; + default: throw new AssertionError(category); + } + return ids == null ? Set.of() : ids; + } + + /** Serializes an override using the same sparse data as the on-disk block. */ + String toSparseJson(ModelOverride override) { + return format(sparse(gson.toJsonTree(override, ModelOverride.class).getAsJsonObject()), + "", "\n"); + } + + synchronized String toSparseJson(Entry entry) { + var edited = sparse(gson.toJsonTree(entry.override, ModelOverride.class).getAsJsonObject()); + var original = entry.isPersisted() + ? new JsonParser().parse(entry.savedBlock).getAsJsonObject() : new JsonObject(); + return format(orderLike(original, edited), "", "\n"); + } + + private JsonObject orderLike(JsonObject original, JsonObject edited) { + var ordered = new JsonObject(); + for (String originalKey : original.keySet()) { + String key = originalKey.equals("material") && edited.has("baseMaterial") ? "baseMaterial" : originalKey; + var value = edited.get(key); + if (value == null) + continue; + var previous = original.get(originalKey); + if (gamevals.containsKey(key) && previous.isJsonArray() && value.isJsonArray()) + value = orderTargets(previous.getAsJsonArray(), value.getAsJsonArray(), gamevals.get(key)); + else if (previous.isJsonObject() && value.isJsonObject()) + value = orderLike(previous.getAsJsonObject(), value.getAsJsonObject()); + else if (key.equals("colorOverrides") && previous.isJsonArray() && value.isJsonArray() + && previous.getAsJsonArray().size() == value.getAsJsonArray().size()) { + var rules = new JsonArray(); + for (int i = 0; i < value.getAsJsonArray().size(); i++) { + var oldRule = previous.getAsJsonArray().get(i); + var newRule = value.getAsJsonArray().get(i); + rules.add(oldRule.isJsonObject() && newRule.isJsonObject() + ? orderLike(oldRule.getAsJsonObject(), newRule.getAsJsonObject()) : newRule); + } + value = rules; + } + ordered.add(key, value); + } + for (var field : edited.entrySet()) + if (!ordered.has(field.getKey())) + ordered.add(field.getKey(), field.getValue()); + return ordered; + } + + private static JsonArray orderTargets(JsonArray previous, JsonArray edited, Map names) { + var remaining = new LinkedHashMap(); + for (var target : edited) + remaining.put(targetId(target, names), target); + var ordered = new JsonArray(); + var preservedIds = new HashSet(); + for (var target : previous) { + Integer id = targetId(target, names); + var current = remaining.get(id); + if (current != null) { + ordered.add(target.getAsJsonPrimitive().isString() ? target : current); + preservedIds.add(id); + } + } + preservedIds.forEach(remaining::remove); + remaining.values().forEach(ordered::add); + return ordered; + } + + private static Integer targetId(JsonElement target, Map names) { + return target.getAsJsonPrimitive().isNumber() ? Integer.valueOf(target.getAsInt()) : names.get(target.getAsString()); + } + + private JsonObject sparse(JsonObject full) { + JsonObject result = new JsonObject(); + for (var field : full.entrySet()) { + String key = field.getKey(); + JsonElement value = field.getValue(); + if (value.equals(defaults.get(key))) + continue; + if (key.equals("colorOverrides") && value.isJsonArray()) { + var rules = new com.google.gson.JsonArray(); + for (var rule : value.getAsJsonArray()) + rules.add(rule.isJsonObject() ? sparse(rule.getAsJsonObject()) : rule); + value = rules; + } else if (key.equals("materialOverrides") && value.isJsonObject()) { + var materials = new JsonObject(); + for (var material : value.getAsJsonObject().entrySet()) { + var rule = material.getValue(); + materials.add(material.getKey(), rule.isJsonObject() ? sparse(rule.getAsJsonObject()) : rule); + } + value = materials; + } + result.add(key.equals("material") ? "baseMaterial" : key, value); + } + return result; + } + + private String format(JsonElement value, String indent, String newline) { + String childIndent = indent + " "; + var lines = new ArrayList(); + if (value.isJsonObject()) { + for (var field : value.getAsJsonObject().entrySet()) + lines.add(gson.toJson(field.getKey()) + ": " + format(field.getValue(), childIndent, newline)); + return block("{", "}", lines, indent, newline); + } + if (value.isJsonArray()) { + boolean simple = true; + for (var item : value.getAsJsonArray()) { + lines.add(format(item, childIndent, newline)); + simple &= item.isJsonPrimitive() || item.isJsonNull(); + } + if (lines.isEmpty()) + return "[]"; + String inline = "[ " + String.join(", ", lines) + " ]"; + if (simple && indent.length() + inline.length() <= 100) + return inline; + return block("[", "]", lines, indent, newline); + } + return gson.toJson(value); + } + + private static String block(String open, String close, List lines, String indent, String newline) { + if (lines.isEmpty()) + return open + close; + String prefix = newline + indent + " "; + return open + prefix + String.join("," + prefix, lines) + newline + indent + close; + } + + /** Splices a single block and adjusts offsets without reloading the editor's entries. */ + synchronized void save(Entry entry, String json) throws IOException { + if (!entries.contains(entry)) + throw new IOException("This override is no longer open"); + String current = Files.readString(file); + if (!current.equals(source)) + rebaseOffsets(current, entry); + + if (entry.isPersisted() && entry.start < 0) + throw new IOException("This override changed on disk. Your edits are still open."); + + String newline = source.contains("\r\n") ? "\r\n" : "\n"; + boolean append = !entry.isPersisted(); + int closeLine = source.lastIndexOf('\n', arrayClose - 1) + 1; + boolean bracketOnOwnLine = source.substring(closeLine, arrayClose).isBlank(); + int insertAt = bracketOnOwnLine ? closeLine : arrayClose; + String indent = append ? " " : entryIndent(entry.start); + String replacement = json.replace("\n", newline + indent); + int newStart; + String result; + if (append) { + boolean comma = !trailingComma && lastValueEnd > 0 && source.charAt(lastValueEnd - 1) != '['; + String before = source.substring(0, insertAt); + if (comma) + before = before.substring(0, lastValueEnd) + "," + before.substring(lastValueEnd); + if (!before.endsWith("\n")) + before += newline; + before += indent; + newStart = before.length(); + result = before + replacement + newline + source.substring(insertAt); + } else { + newStart = entry.start; + result = source.substring(0, entry.start) + replacement + source.substring(entry.end); + } + if (result.equals(source)) + return; + + Path temporary = Files.createTempFile(file.toAbsolutePath().getParent(), ".model-overrides-", ".tmp"); + try { + Files.writeString(temporary, result); + if (!Files.readString(file).equals(current)) + throw new IOException("The file changed during saving. Try saving again."); + Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(temporary); + } + + int delta = result.length() - source.length(); + if (append) { + lastValueEnd = newStart + replacement.length(); + trailingComma = false; + } else { + for (var other : entries) { + if (other.start >= entry.end) { + other.start += delta; + other.end += delta; + } + } + lastValueEnd += delta; + } + entry.start = newStart; + entry.end = newStart + replacement.length(); + entry.savedBlock = replacement; + arrayClose += delta; + source = result; + } + + private void rebaseOffsets(String current, Entry selected) throws IOException { + var blocks = new LinkedHashMap>(); + int cursor = skipTrivia(current, 0); + if (cursor == current.length() || current.charAt(cursor++) != '[') + throw new IOException("Expected an array of model overrides"); + int last = cursor; + boolean comma = false; + while (true) { + cursor = skipTrivia(current, cursor); + if (cursor == current.length()) + throw new IOException("Unclosed override array"); + char token = current.charAt(cursor); + if (token == ']') + break; + if (token == ',') { + comma = true; + cursor++; + } else if (current.startsWith("null", cursor)) { + cursor += 4; + last = cursor; + comma = false; + } else if (token == '{') { + int end = objectEnd(current, cursor); + blocks.computeIfAbsent(blockKey(current.substring(cursor, end)), key -> new ArrayList<>()).add(cursor); + cursor = end; + last = end; + comma = false; + } else { + throw new IOException("Expected an override object at character " + cursor); + } + } + var positions = new LinkedHashMap(); + for (var entry : entries) { + if (entry.savedBlock == null) + continue; + var matches = blocks.get(blockKey(entry.savedBlock)); + if (matches != null && matches.size() == 1) + positions.put(entry, matches.get(0)); + } + if (selected.savedBlock != null && !positions.containsKey(selected)) + throw new IOException("This override was changed, removed, or duplicated on disk. Your edits are still open."); + for (var entry : entries) { + entry.start = positions.getOrDefault(entry, -1); + entry.end = entry.start < 0 ? -1 : objectEnd(current, entry.start); + } + source = current; + arrayClose = cursor; + lastValueEnd = last; + trailingComma = comma; + } + + private static String blockKey(String block) { + return new JsonParser().parse(block).toString(); + } + + private String entryIndent(int start) { + int lineStart = source.lastIndexOf('\n', start - 1) + 1; + String indent = source.substring(lineStart, start); + return indent.isBlank() ? indent : " "; + } + + private static int objectEnd(String text, int start) { + int depth = 0; + for (int i = start; i < text.length();) { + char c = text.charAt(i++); + if (c == '"' || c == '\'') { + while (i < text.length()) { + char next = text.charAt(i++); + if (next == '\\') + i++; + else if (next == c) + break; + } + } else if (c == '#' || c == '/' && i < text.length() + && (text.charAt(i) == '/' || text.charAt(i) == '*')) { + i = skipTrivia(text, i - 1); + } else if (c == '{') { + depth++; + } else if (c == '}' && --depth == 0) { + return i; + } + } + throw new IllegalArgumentException("Unclosed override object"); + } + + private static int skipTrivia(String text, int cursor) { + while (cursor < text.length()) { + char c = text.charAt(cursor); + if (Character.isWhitespace(c) || c == '') { + cursor++; + } else if (c == '#' || text.startsWith("//", cursor)) { + int end = text.indexOf('\n', cursor); + cursor = end < 0 ? text.length() : end + 1; + } else if (text.startsWith("/*", cursor)) { + int end = text.indexOf("*/", cursor + 2); + if (end < 0) + throw new IllegalArgumentException("Unclosed comment"); + cursor = end + 2; + } else { + break; + } + } + return cursor; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideFields.java b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideFields.java new file mode 100644 index 0000000..4b9bac9 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverrideFields.java @@ -0,0 +1,79 @@ +package rs117.hd.dev.overrides; + +import java.lang.reflect.Field; +import java.util.concurrent.ConcurrentHashMap; +import rs117.hd.scene.model_overrides.ModelOverride; + +/** + * Read access to the handful of {@link ModelOverride} fields that are {@code private} with no + * generated getter (the HSL/alpha ranges, hideAsWaterEffect, materials, faces, colors). Writing + * still goes through the class's own public fluent setters (Lombok {@code @Setter @Accessors(fluent=true)} + * already makes those public regardless of field visibility) — this is read-only, and never touches + * the RLHD submodule itself. + */ +final class ModelOverrideFields { + private static final ConcurrentHashMap FIELDS = new ConcurrentHashMap<>(); + + private static final java.lang.reflect.Method PARSE_COLORS = colorParser(); + + private ModelOverrideFields() {} + + private static java.lang.reflect.Method colorParser() { + try { + var method = ModelOverride.class.getDeclaredMethod("parseAhslConditions", com.google.gson.JsonElement.class); + method.setAccessible(true); + return method; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Cannot access the model override color parser", e); + } + } + + static ModelOverride.AhslPredicate colorPredicate(ModelOverride rule, com.google.gson.JsonElement colors) { + try { + return (ModelOverride.AhslPredicate) PARSE_COLORS.invoke(rule, colors); + } catch (java.lang.reflect.InvocationTargetException e) { + // A malformed condition should not prevent the editor from opening the rule. + if (e.getCause() instanceof RuntimeException) + return ahsl -> false; + throw new IllegalStateException(e.getCause()); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + private static Field field(String name) { + return FIELDS.computeIfAbsent(name, key -> { + try { + Field field = ModelOverride.class.getDeclaredField(key); + field.setAccessible(true); + return field; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("No such ModelOverride field: " + key, e); + } + }); + } + + static int getInt(ModelOverride override, String name) { + try { + return field(name).getInt(override); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + static boolean getBoolean(ModelOverride override, String name) { + try { + return field(name).getBoolean(override); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + static T get(ModelOverride override, String name, Class type) { + try { + return type.cast(field(name).get(override)); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverridesScreen.java b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverridesScreen.java new file mode 100644 index 0000000..e7738c3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/ModelOverridesScreen.java @@ -0,0 +1,2024 @@ +package rs117.hd.dev.overrides; + +import com.google.gson.JsonObject; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import javax.swing.*; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.GraphicsObject; +import net.runelite.api.Model; +import net.runelite.api.NPC; +import net.runelite.api.Renderable; +import rs117.hd.dev.editor.*; +import rs117.hd.dev.sceneloader.scene.*; +import rs117.hd.dev.sceneloader.standalone.HdRuntime; +import rs117.hd.dev.sceneloader.standalone.client.Fake; +import rs117.hd.scene.MaterialManager; +import rs117.hd.scene.model_overrides.ModelOverride; +import rs117.hd.utils.ModelHash; + +/** The Model Overrides workspace: entity browser, per-entity override list, 3D preview and the properties panel. */ +@Slf4j +public final class ModelOverridesScreen extends JPanel { + private static final int TILE_X = 34; + private static final int TILE_Z = 52; + private static final int GROUND_CLEARANCE = 8; + private static final int VANILLA_PASS = 1; + private static final int OVERRIDE_PASS = 2; + private static final int DOCK_PASS = 4; + + private final DefaultListModel rows = new DefaultListModel<>(); + private final JList list = new JList<>(rows); + private final EditorSearch browserSearch = EditorSearch.builder("Filter by name, ID or gameval").build(); + private final JTextField search = browserSearch.field(); + private final JLabel status = EditorText.builder("Select a model").color(WorkspaceStyle.DIM).build(); + private final OverridePreviewSurface centerPreview = new OverridePreviewSurface(true); + private final OverridePreviewSurface dockPreview = new OverridePreviewSurface(false); + private JPanel previewToolbar; + private JPanel previewInfo; + private volatile String previewMode = "Override"; + private volatile String previewShading = "Material"; + private volatile boolean previewActive = true; + private volatile long previewGeneration; + + public void setPreviewActive(boolean active) { + if (previewActive == active) + return; + previewActive = active; + previewGeneration++; + if (!active) { + cancelFinding(); + previewModel = null; + vanillaFacePicker = overrideFacePicker = null; + properties.setPreviewModel(null); + centerPreview.clear(); + dockPreview.clear(); + } + } + + private volatile boolean dockVisible = true; + private volatile String previewOverrideJson; + private final JPanel viewport = new JPanel(new BorderLayout()); + private final JLayeredPane viewerStage = new JLayeredPane(); + private final AtomicReference pending = new AtomicReference<>(); + private final AtomicReference worldSearch = new AtomicReference<>(); + private JButton findInWorld; + private final CardLayout gamePreviewCards = new CardLayout(); + private final JPanel gamePreviewBody = new JPanel(gamePreviewCards); + private final FindingOverlay findingOverlay = new FindingOverlay(); + private volatile ScenePreset scenePreset = ScenePreset.SKY; + private volatile boolean showSurroundings; + private volatile boolean showAllPlacements = true; + private volatile CacheModels.Entry findingEntry; + private enum ScenePreset { + SKY("Sky", 0, 0), LIVE("Live world", 3234, 3252), CAVE("Cave", 3170, 9565), + GRASS("Empty grass", 3194, 3236), LUMBRIDGE("Lumbridge", 3234, 3252); + final String label; + final int x, z; + ScenePreset(String label, int x, int z) { this.label = label; this.x = x; this.z = z; } + @Override public String toString() { return label; } + } + private volatile net.runelite.cache.region.Location foundLocation; + private JComboBox sceneSelector; + private final EditorSession session; + private final JFrame owner; + private CacheModels.Category category = CacheModels.Category.NPCs; + private final java.util.EnumMap categories = new java.util.EnumMap<>(CacheModels.Category.class); + private final java.util.EnumMap counts = new java.util.EnumMap<>(CacheModels.Category.class); + private final java.util.concurrent.atomic.AtomicBoolean refreshRequested = new java.util.concurrent.atomic.AtomicBoolean(); + private final Timer browserSearchDelay = new Timer(120, event -> filter(this.browserOverrideTargets)); + private final Timer overrideSearchDelay = new Timer(120, event -> refreshOverrideList()); + private List browserGroups = List.of(); + private CacheModels.Group activeGroup; + private boolean filteringBrowser; + private enum OverrideFilter { ALL, WITH, WITHOUT } + private OverrideFilter overrideFilter = OverrideFilter.ALL; + private final java.util.EnumMap overrideFilterBadges = new java.util.EnumMap<>(OverrideFilter.class); + private Set browserOverrideTargets; + private final JPanel variantPanel = new JPanel(new BorderLayout(6, 3)); + private final JLabel variantLabel = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(11f)).build(); + private volatile double yaw = .55; + private volatile double pitch = .30; + private volatile double zoom = 1; + private volatile Orbit gameCamera = new Orbit(.55, .30, 1); + private volatile CacheModels.Entry selectedEntity; + private volatile Model previewModel; + private PreviewFacePicker vanillaFacePicker, overrideFacePicker; + private volatile boolean windPreview; + private volatile float[] windPointer; + private volatile java.util.Map nearbyObjects = java.util.Map.of(); + + // Populated once the HD runtime (and its Gson) is ready — see render(). + private volatile ModelOverrideDocument document; + private Runnable selectionChangedListener = () -> {}; + private ModelOverrideDocument.Entry selectedOverride; + private final DefaultListModel overrideRows = new DefaultListModel<>(); + private final JList overrideList = new JList<>(overrideRows); + private final JLabel overrideCount = EditorText.builder("0 / 0").font(WorkspaceStyle.MONO.deriveFont(10f)).color(WorkspaceStyle.DIM).build(); + private boolean projectileTarget; + private final JLabel overrideEmpty = EditorText.builder("").color(WorkspaceStyle.DIM).build(); + private final JTextField overrideSearch = WorkspaceStyle.search("Search overrides"); + private final JLabel saveStatus = EditorText.builder("").build(); + private final JButton saveButton = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY) + .text("Save overrides").icon("save", 13).enabled(false).build(); + private SegmentedControl scope; + private boolean scopeAll; + private OverrideProperties properties; + private FloatingDockWindow inGameView; + private WorkspaceDocks docks; + private JToggleButton pickColorButton; + private JToggleButton inGameButton; + private boolean pickColorActive; + + public ModelOverridesScreen(JFrame owner, EditorSession session) { + super(new BorderLayout(1, 0)); + this.owner = owner; + this.session = session; + setBackground(WorkspaceStyle.GAP); + list.setFont(WorkspaceStyle.UI); + list.setFixedCellHeight(24); + list.setCellRenderer(new DefaultListCellRenderer() { + @Override public Component getListCellRendererComponent(JList source, Object value, int index, boolean selected, boolean focus) { + super.getListCellRendererComponent(source, value, index, selected, focus); + var group = (CacheModels.Group) value; + if (group != null) + setIcon(browserBadge(group.root.category)); + setFont(WorkspaceStyle.MONO.deriveFont(12f)); + setIconTextGap(8); + setForeground(WorkspaceStyle.TEXT); + setBackground(selected ? new Color(0x334D73) : WorkspaceStyle.PANEL); + setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 8)); + return this; + } + }); + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.addListSelectionListener(e -> { + if (!filteringBrowser && !e.getValueIsAdjusting() && list.getSelectedValue() != null) + selectGroup(list.getSelectedValue()); + }); + search.setPreferredSize(new Dimension(0, 24)); + browserSearchDelay.setRepeats(false); + EditorSearch.onChange(search, query -> browserSearchDelay.restart()); + var grid = new JPanel(new GridLayout(2, 2, 2, 2)); + grid.setBackground(WorkspaceStyle.MENU); + grid.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); + var group = new ButtonGroup(); + for (var item : CacheModels.Category.values()) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.SEGMENT) + .text(item.name()).onClick(() -> switchCategory(item)).buildToggle(item == category); + button.setHorizontalAlignment(SwingConstants.LEFT); + button.setFont(WorkspaceStyle.UI.deriveFont(11f)); + button.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 8)); + button.setLayout(new BorderLayout()); + var count = EditorText.builder("0").font(WorkspaceStyle.MONO.deriveFont(10f)).color(WorkspaceStyle.DIM).build(); + button.add(count, BorderLayout.EAST); + counts.put(item, count); + categories.put(item, button); + group.add(button); + grid.add(button); + } + grid.add(Box.createGlue()); + var refresh = EditorButton.builder().icon("refresh", 13).tooltip("Refresh cache index") + .size(26, 48).onClick(() -> refreshRequested.set(true)).build(); + var categoryRow = new JPanel(new BorderLayout(6, 0)); + categoryRow.setOpaque(false); + categoryRow.add(grid); + categoryRow.add(refresh, BorderLayout.EAST); + + + var controls = new JPanel(new BorderLayout(0, 6)); + controls.setBackground(WorkspaceStyle.PANEL); + controls.setBorder(BorderFactory.createEmptyBorder(8, 8, 6, 8)); + controls.add(categoryRow, BorderLayout.NORTH); + controls.add(browserSearch); + var overrideFilters = new JPanel(new GridBagLayout()); + overrideFilters.setOpaque(false); + var overrideFilterButtons = new ButtonGroup(); + String[] filterLabels = {"All", "With overrides", "Without"}; + for (var option : OverrideFilter.values()) { + var button = EditorButton.builder().style(WorkspaceStyle.Button.SEGMENT) + .text(filterLabels[option.ordinal()]).tooltip(option == OverrideFilter.WITHOUT ? "Without overrides" : null) + .onClick(() -> { overrideFilter = option; filter(); }).buildToggle(option == overrideFilter); + button.setFont(WorkspaceStyle.UI.deriveFont(11f)); + button.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 3)); + if (option != OverrideFilter.ALL) { + button.setHorizontalTextPosition(SwingConstants.LEFT); + button.setIconTextGap(4); + overrideFilterBadges.put(option, button); + } + overrideFilterButtons.add(button); + var cell = new GridBagConstraints(); + cell.gridx = option.ordinal(); + cell.weightx = 1; + cell.fill = GridBagConstraints.HORIZONTAL; + cell.insets = new Insets(0, 0, 0, option == OverrideFilter.WITHOUT ? 0 : 4); + overrideFilters.add(button, cell); + } + controls.add(overrideFilters, BorderLayout.SOUTH); + var browserHeader = header("Browser"); + var browser = panel(browserHeader); + var browseBody = new JPanel(new BorderLayout()); + browseBody.add(controls, BorderLayout.NORTH); + browseBody.add(WorkspaceStyle.listScroll(list)); + browseBody.add(buildVariantPanel(), BorderLayout.SOUTH); + browser.add(browseBody); + + var overridesHeader = header("Model overrides"); + var overridesPanel = panel(overridesHeader); + overridesPanel.add(buildOverrideList(), BorderLayout.CENTER); + + var propertiesHeader = header("Properties"); + var propertiesPanel = panel(propertiesHeader); + properties = new OverrideProperties(buildPropertiesContext()); + properties.onChange(this::onPropertyChanged); + properties.onCreate(this::createNewOverride); + properties.onCopyJson(this::copySelectedOverrideJson); + properties.onPickColorRequested(this::beginColorPick); + properties.onColorPickCancelled(() -> setColorPicking(false)); + registerKeyboardAction(e -> { + if (pickColorActive) { + properties.cancelColorPicking(); + setColorPicking(false); + } + }, KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_IN_FOCUSED_WINDOW); + propertiesPanel.add(properties); + + viewport.setMinimumSize(new Dimension(335, 0)); + viewport.add(centerPreview); + + previewToolbar = buildPreviewToolbar(); + previewInfo = buildPreviewInfo(); + viewerStage.setOpaque(false); + // null-layout containers report getPreferredSize() == getSize() (0,0 before the first real layout), + // which throws off WorkspaceDocks' nested JSplitPanes' initial divider placement — give it a real size hint. + viewerStage.setMinimumSize(new Dimension(260, 200)); + viewerStage.setPreferredSize(new Dimension(640, 480)); + viewerStage.add(viewport, JLayeredPane.DEFAULT_LAYER); + viewerStage.add(previewToolbar, JLayeredPane.PALETTE_LAYER); + viewerStage.add(previewInfo, JLayeredPane.PALETTE_LAYER); + viewerStage.addComponentListener(new java.awt.event.ComponentAdapter() { + @Override public void componentResized(java.awt.event.ComponentEvent e) { layoutViewerStage(); } + }); + + docks = WorkspaceDocks.builder(viewerStage) + .primaryPanel(browser, WorkspaceDocks.Side.LEFT) + .panel(overridesPanel, WorkspaceDocks.Side.LEFT) + .panel(propertiesPanel, WorkspaceDocks.Side.RIGHT) + .width(WorkspaceDocks.Side.LEFT, 270) + .leftStackWeight(.48) + .width(WorkspaceDocks.Side.RIGHT, 400) + .movable(browser, browserHeader, "Browser") + .movable(overridesPanel, overridesHeader, "Model overrides") + .movable(propertiesPanel, propertiesHeader, "Properties") + .build(); + + inGameView = new FloatingDockWindow(owner, viewerStage, "In-game view"); + inGameView.setStatus(false, ""); + inGameView.content().add(inGameViewBody()); + inGameView.onHide(() -> { inGameButton.setSelected(false); setInGameVisible(false); }); + inGameView.onDockChanged(dock -> { + if (dock == FloatingDockWindow.Dock.PANEL) { + docks.dockPanel(inGameView, inGameView.getPanelSide()); + } else if (inGameView.getParent() != viewerStage) { + docks.undockPanel(inGameView); + viewerStage.add(inGameView, JLayeredPane.MODAL_LAYER); + } + viewerStage.repaint(); + }); + docks.dockPanel(inGameView, inGameView.getPanelSide()); + inGameView.setVisible(true); + + var body = new JPanel(new BorderLayout()); + body.setBackground(WorkspaceStyle.GAP); + body.add(docks); + status.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10)); + status.setOpaque(true); + status.setBackground(WorkspaceStyle.BAR); + add(body); + add(status, BorderLayout.SOUTH); + + var mouse = new MouseAdapter() { + private Point previous; + private Point downAt; + private Integer dividerGrabOffset; + private boolean orbiting; + + @Override public void mouseEntered(MouseEvent e) { mouseMoved(e); } + @Override public void mouseMoved(MouseEvent e) { + updateViewportCursor(e.getPoint(), dividerGrabOffset != null, orbiting); + var bounds = centerPreview.imageBounds(false); + var point = e.getPoint(); + centerPreview.hoverPick(pickColorActive && !orbiting && dividerGrabOffset == null ? point : null); + windPointer = windPreview && !orbiting && dividerGrabOffset == null && bounds.contains(point) + && !"Vanilla".equals(previewMode) && (!"Split".equals(previewMode) || point.x >= centerPreview.dividerX()) + ? new float[] { 2f * (point.x - bounds.x) / bounds.width - 1, 1 - 2f * (point.y - bounds.y) / bounds.height } + : null; + } + @Override public void mouseExited(MouseEvent e) { + centerPreview.hoverPick(null); + windPointer = null; + updateViewportCursor(null, dividerGrabOffset != null, orbiting); + } + + @Override public void mousePressed(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e) && centerPreview.isOverDivider(e.getX())) { + dividerGrabOffset = e.getX() - centerPreview.dividerX(); + mouseMoved(e); + return; + } + centerPreview.requestFocusInWindow(); + previous = downAt = e.getPoint(); + } + + @Override public void mouseReleased(MouseEvent e) { + boolean pick = SwingUtilities.isLeftMouseButton(e) && dividerGrabOffset == null && pickColorActive && downAt != null + && downAt.distance(e.getPoint()) < 4; + dividerGrabOffset = null; + orbiting = false; + previous = downAt = null; + if (pick) + pickPreviewFace(e.getPoint()); + mouseMoved(e); + } + + @Override public void mouseDragged(MouseEvent e) { + if (dividerGrabOffset != null) { + centerPreview.moveDivider(e.getX() - dividerGrabOffset); + } else if (previous != null) { + orbiting = true; + yaw -= (e.getX() - previous.x) * .012; + pitch = Math.max(-1.35, Math.min(1.35, pitch + (e.getY() - previous.y) * .012)); + previous = e.getPoint(); + } + mouseMoved(e); + } + + @Override public void mouseWheelMoved(MouseWheelEvent e) { + zoom = Math.max(.1, Math.min(12, zoom * Math.pow(1.1, -e.getPreciseWheelRotation()))); + } + }; + centerPreview.setFocusable(true); + centerPreview.addMouseListener(mouse); + HdContextMenu.install(centerPreview, this::showFaceMenu); + centerPreview.addMouseMotionListener(mouse); + centerPreview.addMouseWheelListener(mouse); + centerPreview.setCursor(WorkspaceStyle.cursor("grab")); + setEntries(session.modelCatalog()); + selectInitialEntry(); + } + + // ---- Browser ---- + + private void setEntries(CacheModels.Index indexed) { + browserGroups = indexed.groups; + var totals = new java.util.EnumMap(CacheModels.Category.class); + for (var group : browserGroups) + totals.merge(group.root.category, 1, Integer::sum); + for (var item : CacheModels.Category.values()) + counts.get(item).setText(Integer.toString(totals.getOrDefault(item, 0))); + if (activeGroup != null) { + var root = activeGroup.root; + activeGroup = browserGroups.stream() + .filter(group -> group.root.category == root.category && group.root.id == root.id) + .findFirst().orElse(null); + if (activeGroup != null) + selectEntity(findVariant(activeGroup, selectedEntity.id)); + } + filter(); + } + + private void switchCategory(CacheModels.Category next) { + if (category == next) + return; + category = next; + if (search.getText().isEmpty()) + filter(); + else + search.setText(""); + } + + private static Icon browserBadge(CacheModels.Category category) { + switch (category) { + case NPCs: return WorkspaceStyle.badge("N", new Color(0xD97A7A)); + case Objects: return WorkspaceStyle.badge("O", new Color(0x5B8AC2)); + default: return WorkspaceStyle.badge("G", new Color(0x9A6BC2)); + } + } + + private void filter() { + var doc = document; + filter(doc == null ? null : doc.targetIds(category)); + } + + private void filter(Set targets) { + browserSearchDelay.stop(); + browserOverrideTargets = targets; + String query = search.getText().strip().toLowerCase(Locale.ROOT); + var matches = new ArrayList(); + int with = 0; + int without = 0; + for (var group : browserGroups) { + if (group.root.category != category) + continue; + boolean hasOverride = false, hasNoOverride = false; + boolean rootMatches = group.root.searchLabel.contains(query); + for (var variant : group.variants) { + if (!rootMatches && !variant.searchLabel.contains(query)) + continue; + if (targets != null && targets.contains(variant.id)) + hasOverride = true; + else + hasNoOverride = true; + if (hasOverride && hasNoOverride) + break; + } + if (hasOverride) + with++; + if (hasNoOverride) + without++; + boolean show = overrideFilter == OverrideFilter.ALL + ? hasOverride || hasNoOverride + : targets != null && (overrideFilter == OverrideFilter.WITH ? hasOverride : hasNoOverride); + if (show) + matches.add(group); + } + updateFilterBadge(OverrideFilter.WITH, targets == null ? "–" : Integer.toString(with)); + updateFilterBadge(OverrideFilter.WITHOUT, targets == null ? "–" : Integer.toString(without)); + + filteringBrowser = true; + try { + rows.clear(); + rows.addAll(matches); + if (activeGroup != null) + list.setSelectedValue(activeGroup, false); + } finally { + filteringBrowser = false; + } + updateVariantPanel(); + } + + private void updateFilterBadge(OverrideFilter filter, String count) { + var button = overrideFilterBadges.get(filter); + button.setIcon(WorkspaceStyle.countBadge(button, count)); + button.getAccessibleContext().setAccessibleName(button.getText() + " (" + count + ")"); + } + + private CacheModels.Entry matchingVariant(CacheModels.Group group, String query, Set targets, OverrideFilter filter) { + boolean rootMatches = group.root.searchLabel.contains(query); + for (var variant : group.variants) + if ((rootMatches || variant.searchLabel.contains(query)) + && (filter == OverrideFilter.ALL || targets != null && targets.contains(variant.id) == (filter == OverrideFilter.WITH))) + return variant; + return null; + } + + private void selectGroup(CacheModels.Group group) { + activeGroup = group; + var match = matchingVariant(group, search.getText().strip().toLowerCase(Locale.ROOT), browserOverrideTargets, overrideFilter); + selectEntity(match == null ? group.root : match); + } + + private static CacheModels.Entry findVariant(CacheModels.Group group, int id) { + for (var variant : group.variants) + if (variant.id == id) + return variant; + return group.root; + } + + private JComponent buildVariantPanel() { + var heading = EditorText.builder("Variants").font(WorkspaceStyle.SEMIBOLD).build(); + variantPanel.setBackground(WorkspaceStyle.HEADER); + variantPanel.setBorder(BorderFactory.createEmptyBorder(6, 8, 8, 8)); + variantPanel.add(heading, BorderLayout.NORTH); + var picker = new JPanel(new BorderLayout(6, 0)); + picker.setOpaque(false); + picker.add(EditorButton.builder().icon("chevron-left", 11).tooltip("Previous variant") + .size(24, 24).onClick(() -> cycleVariant(-1)).build(), BorderLayout.WEST); + picker.add(variantLabel); + picker.add(EditorButton.builder().icon("chevron-right", 11).tooltip("Next variant") + .size(24, 24).onClick(() -> cycleVariant(1)).build(), BorderLayout.EAST); + variantPanel.add(picker); + variantPanel.setVisible(false); + return variantPanel; + } + + private void cycleVariant(int direction) { + if (activeGroup == null) + return; + var variants = activeGroup.variants; + int current = variants.indexOf(selectedEntity); + selectEntity(variants.get(Math.floorMod(current + direction, variants.size()))); + } + + private void updateVariantPanel() { + boolean visible = activeGroup != null && list.getSelectedValue() == activeGroup && activeGroup.variants.size() > 1 + && selectedEntity != null && activeGroup.variants.contains(selectedEntity); + variantPanel.setVisible(visible); + if (visible) { + var variants = activeGroup.variants; + variantLabel.setText((variants.indexOf(selectedEntity) + 1) + "/" + variants.size() + " · " + selectedEntity.label); + variantLabel.setToolTipText(selectedEntity.label); + } + } + + private void refreshBrowserOverrides() { + var doc = document; + var targets = doc == null ? null : doc.targetIds(category); + if (!java.util.Objects.equals(browserOverrideTargets, targets)) + filter(targets); + } + + private void selectEntity(CacheModels.Entry entry) { + selectedEntity = entry; + previewModel = null; + properties.setPreviewModel(null); + worldSearch.set(null); + foundLocation = null; + finishFinding(false); + if (sceneSelector.getSelectedIndex() < 0) + sceneSelector.setSelectedItem(scenePreset); + findInWorld.setEnabled(entry != null); + findInWorld.setToolTipText("Find this entity in the game cache"); + updateVariantPanel(); + updatePreviewOverride(); + centerPreview.clear(); + dockPreview.clear(); + pending.set(entry); + refreshOverrideList(true); + } + + // ---- Model overrides list ---- + + private JPanel buildOverrideList() { + var headerRow = new JPanel(new BorderLayout()); + headerRow.setOpaque(false); + headerRow.setBorder(BorderFactory.createEmptyBorder(8, 8, 6, 8)); + var duplicate = EditorButton.builder().icon("duplicate", 13).tooltip("Duplicate (Ctrl+D)").size(26, 24) + .onClick(this::duplicateSelectedOverride).build(); + var add = EditorButton.builder().text("+ New").size(0, 22).onClick(this::createNewOverride).build(); + var actionsRow = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0)); + actionsRow.setOpaque(false); + actionsRow.add(duplicate); + actionsRow.add(add); + headerRow.add(overrideCount, BorderLayout.WEST); + headerRow.add(actionsRow, BorderLayout.EAST); + + scope = SegmentedControl.builder(List.of("This entity", "All overrides")).build(); + scope.onChange(value -> { scopeAll = value.equals("All overrides"); refreshOverrideList(); }); + + overrideSearch.setPreferredSize(new Dimension(0, 24)); + overrideSearchDelay.setRepeats(false); + EditorSearch.onChange(overrideSearch, query -> overrideSearchDelay.restart()); + + overrideList.setFont(WorkspaceStyle.UI); + overrideList.setFixedCellHeight(38); + overrideList.setCellRenderer(new OverrideRowRenderer()); + overrideList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + overrideList.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) + selectOverride(overrideList.getSelectedValue()); + }); + HdContextMenu.install(list, this::showBrowserMenu); + HdContextMenu.install(overrideList, this::showOverrideMenu); + overrideList.registerKeyboardAction(e -> renameOverride(), KeyStroke.getKeyStroke("F2"), JComponent.WHEN_FOCUSED); + overrideList.registerKeyboardAction(e -> copySelectedOverrideJson(), KeyStroke.getKeyStroke("ctrl shift J"), JComponent.WHEN_FOCUSED); + list.registerKeyboardAction(e -> { + if (selectedEntity != null) + copyText(Integer.toString(selectedEntity.id)); + }, KeyStroke.getKeyStroke("ctrl C"), JComponent.WHEN_FOCUSED); + list.registerKeyboardAction(e -> { + if (selectedEntity != null && selectedEntity.gamevalName() != null) + copyText(selectedEntity.gamevalName()); + }, KeyStroke.getKeyStroke("ctrl shift C"), JComponent.WHEN_FOCUSED); + list.registerKeyboardAction(e -> { + if (selectedEntity != null) + selectEntity(selectedEntity); + }, KeyStroke.getKeyStroke("ENTER"), JComponent.WHEN_FOCUSED); + overrideList.registerKeyboardAction(e -> duplicateSelectedOverride(), KeyStroke.getKeyStroke("ctrl D"), JComponent.WHEN_FOCUSED); + + var top = new JPanel(new BorderLayout(0, 6)); + top.setOpaque(false); + top.setBorder(BorderFactory.createEmptyBorder(0, 8, 6, 8)); + top.add(scope, BorderLayout.NORTH); + top.add(overrideSearch); + + var listArea = new JPanel(new BorderLayout()); + listArea.setBackground(WorkspaceStyle.PANEL); + overrideEmpty.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16)); + var listCards = new CardLayout(); + var listSwap = new JPanel(listCards); + listSwap.add(WorkspaceStyle.listScroll(overrideList), "list"); + listSwap.add(overrideEmpty, "empty"); + listArea.add(listSwap); + + var footer = new JPanel(new BorderLayout(0, 8)); + footer.setBackground(WorkspaceStyle.PANEL); + footer.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(1, 0, 0, 0, WorkspaceStyle.MENU), BorderFactory.createEmptyBorder(10, 10, 10, 10))); + saveStatus.setFont(WorkspaceStyle.UI.deriveFont(11f)); + footer.add(saveStatus, BorderLayout.NORTH); + saveButton.addActionListener(e -> saveSelectedOverride()); + saveButton.setPreferredSize(new Dimension(0, 30)); + footer.add(saveButton, BorderLayout.SOUTH); + + var body = new JPanel(new BorderLayout()); + body.setOpaque(false); + body.add(headerRow, BorderLayout.NORTH); + var middle = new JPanel(new BorderLayout()); + middle.setOpaque(false); + middle.add(top, BorderLayout.NORTH); + middle.add(listArea); + body.add(middle); + body.add(footer, BorderLayout.SOUTH); + overrideListSwap = listSwap; + return body; + } + + // Set once buildOverrideList() runs; used by refreshOverrideList() to swap the empty-state card. + private JPanel overrideListSwap; + + private static final Color SELECTED_ROW_BACKGROUND = new Color(0x334D73); + private static final Color SELECTED_NAME_COLOR = new Color(0xE6E6E6); + private static final Color NAME_COLOR = new Color(0xD6D6D6); + + /** Swing calls this for every visible row on every list repaint, so the row components are built once + * and only their text/colors are updated per call, instead of rebuilding the whole component tree. */ + private static final class OverrideRowRenderer implements ListCellRenderer { + private final JPanel row = new JPanel(new BorderLayout(8, 0)); + private final JLabel swatch = new JLabel(); + private final JLabel name = EditorText.builder("").build(); + private final JLabel meta = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(10f)).color(WorkspaceStyle.DIM).build(); + + OverrideRowRenderer() { + row.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10)); + row.add(swatch, BorderLayout.WEST); + var text = new JPanel(new GridLayout(2, 1)); + text.setOpaque(false); + text.add(name); + text.add(meta); + row.add(text); + } + + @Override + public Component getListCellRendererComponent( + JList list, ModelOverrideDocument.Entry entry, + int index, boolean selected, boolean cellHasFocus + ) { + row.setBackground(selected ? SELECTED_ROW_BACKGROUND : WorkspaceStyle.PANEL); + swatch.setIcon(WorkspaceStyle.badge("", materialColor(entry.override.material))); + name.setText(entry.override.description); + name.setForeground(selected ? SELECTED_NAME_COLOR : NAME_COLOR); + meta.setText(metaFor(entry.override)); + return row; + } + } + + private static Color materialColor(rs117.hd.scene.materials.Material material) { + return material == null ? WorkspaceStyle.DIM : new Color(0x7D7D7D); + } + + private static String metaFor(ModelOverride override) { + StringBuilder meta = new StringBuilder(); + if (override.model != null) + meta.append("model ").append(override.model); + if (!override.npcIds.isEmpty()) + append(meta, override.npcIds.size() + " NPC"); + if (!override.objectIds.isEmpty()) + append(meta, override.objectIds.size() + " Object"); + if (!override.graphicsObjectIds.isEmpty()) + append(meta, override.graphicsObjectIds.size() + " Graphic"); + return meta.length() == 0 ? "No targets" : meta.toString(); + } + + private static void append(StringBuilder meta, String part) { + if (meta.length() > 0) + meta.append(" · "); + meta.append(part); + } + + private void refreshOverrideList() { refreshOverrideList(false); } + + private void refreshOverrideList(boolean autoSelect) { + overrideSearchDelay.stop(); + var previous = selectedOverride; + overrideRows.clear(); + var doc = document; + if (doc == null) { + overrideEmpty.setText("Still loading overrides…"); + showEmptyOverrideCard(); + return; + } + String query = overrideSearch.getText().strip().toLowerCase(Locale.ROOT); + List candidates = new ArrayList<>(); + ModelOverrideDocument.Entry firstTarget = null; + int targetCount = 0; + for (var entry : doc.entries()) { + boolean targets = selectedEntity != null && doc.targets(entry.override, selectedEntity.category, selectedEntity.id); + if (targets) + targetCount++; + boolean inScope = scopeAll || selectedEntity == null || targets; + boolean matchesQuery = query.isEmpty() || entry.override.description.toLowerCase(Locale.ROOT).contains(query); + if (inScope && matchesQuery) { + candidates.add(entry); + if (targets && firstTarget == null) + firstTarget = entry; + } + } + properties.setEmptyEntity(selectedEntity, targetCount); + overrideCount.setText(candidates.size() + " / " + doc.entries().size()); + if (candidates.isEmpty()) { + overrideEmpty.setText(selectedEntity == null ? "Select an entity to see its overrides." + : "No overrides target " + selectedEntity.displayName + " yet. Use Create override in the Properties panel, or press New."); + showEmptyOverrideCard(); + return; + } + overrideRows.addAll(candidates); + var selection = autoSelect ? firstTarget : previous; + if (selection != null) + overrideList.setSelectedValue(selection, true); + if (overrideListSwap != null) + ((CardLayout) overrideListSwap.getLayout()).show(overrideListSwap, "list"); + } + + private void showEmptyOverrideCard() { + if (overrideListSwap != null) + ((CardLayout) overrideListSwap.getLayout()).show(overrideListSwap, "empty"); + } + + private void selectOverride(ModelOverrideDocument.Entry entry) { + selectedOverride = entry; + updatePreviewOverride(); + if (entry == null) { + saveButton.setEnabled(false); + properties.setOverride(null, null, null); + return; + } + saveButton.setEnabled(true); + properties.setOverride(entry.override, targetSummaryFor(entry), previewModel); + selectionChangedListener.run(); + } + + private String targetSummaryFor(ModelOverrideDocument.Entry entry) { + return selectedEntity == null ? entry.override.description + : selectedEntity.category + " " + selectedEntity.id + " · " + selectedEntity.displayName; + } + + /** Lets the owning shell reset its own undo history to whatever override is now selected. */ + public void onSelectionChanged(Runnable listener) { selectionChangedListener = listener; } + + /** The currently selected override's description, or null if nothing is selected — for the owning shell's undo history label. */ + public String selectedOverrideLabel() { return selectedOverride == null ? null : selectedOverride.override.description; } + + /** Shows/hides the left column (Browser + Model overrides) — the top bar's global sidebar toggle. */ + public void setSidebarVisible(boolean visible) { docks.setSideVisible(WorkspaceDocks.Side.LEFT, visible); } + + private static Point selectMenuRow(JList list, Point point) { + int index = point == null ? list.getSelectedIndex() : list.locationToIndex(point); + if (index < 0) + return null; + var bounds = list.getCellBounds(index, index); + if (point != null && !bounds.contains(point)) + return null; + list.setSelectedIndex(index); + return point == null ? new Point(bounds.x, bounds.y + bounds.height) : point; + } + + private void showBrowserMenu(Point point) { + point = selectMenuRow(list, point); + if (point == null || selectedEntity == null) + return; + var entry = selectedEntity; + var doc = document; + long count = doc == null ? 0 : doc.entries().stream() + .filter(row -> doc.targets(row.override, entry.category, entry.id)).count(); + String badge = entry.category == CacheModels.Category.NPCs ? "N" : entry.category == CacheModels.Category.Objects ? "O" : "G"; + int color = badge.equals("N") ? 0xC25B5B : badge.equals("O") ? 0x5B8AC2 : 0x9A6BC2; + var menu = new HdContextMenu(badge, new Color(color), entry.category + " · " + entry.label) + .item("Load", "load", "Enter", () -> selectEntity(entry)) + .item("Find in world", "find", "", () -> { setInGameVisible(true); findInWorld.doClick(); }) + .separator() + .item("New model override", "plus", "", this::createNewOverride) + .disabled("New light definition", "light", "Light editing is not available"); + if (count > 0) + menu.item("Show overrides (" + count + ")", "layers", "", this::showEntityOverrides); + else + menu.disabled("Show overrides (0)", "layers", "This entity has no overrides"); + menu.separator().item("Copy ID", "copy", "Ctrl+C", () -> copyText(Integer.toString(entry.id))); + if (entry.gamevalName() != null) + menu.item("Copy gameval name", "tag", "Ctrl+Shift+C", () -> copyText(entry.gamevalName())); + else + menu.disabled("Copy gameval name", "tag", "This entity has no gameval name"); + menu.show(list, point.x, point.y); + } + + private void showEntityOverrides() { + scopeAll = false; + scope.setSelected("This entity"); + overrideSearch.setText(""); + refreshOverrideList(true); + } + + private void showOverrideMenu(Point point) { + point = selectMenuRow(overrideList, point); + if (point == null || selectedOverride == null) + return; + var entry = selectedOverride; + var menu = new HdContextMenu("O", materialColor(entry.override.material), entry.override.description) + .item("Rename", "rename", "F2", this::renameOverride) + .item("Duplicate", "duplicate", "Ctrl+D", this::duplicateSelectedOverride) + .item("Copy JSON", "json", "Ctrl+Shift+J", this::copySelectedOverrideJson); + if (!entry.isPersisted()) { + menu.separator().danger("Delete override", "trash", "", () -> { + document.discard(entry); + refreshBrowserOverrides(); + refreshOverrideList(true); + }); + } else { + menu.separator().disabled("Delete override", "trash", "This override is saved in the project file"); + } + menu.show(overrideList, point.x, point.y); + } + + private void renameOverride() { + var entry = selectedOverride; + if (entry == null) + return; + var name = JOptionPane.showInputDialog(this, "Override name", entry.override.description); + if (name != null && !name.isBlank() && !name.equals(entry.override.description)) { + entry.override.description = name.strip(); + properties.setOverride(entry.override, targetSummaryFor(entry), previewModel); + onPropertyChanged(); + } + } + + private static void copyText(String text) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(text), null); + } + + private void duplicateSelectedOverride() { + var doc = document; + if (doc == null || selectedOverride == null) + return; + var copy = doc.duplicate(selectedOverride); + refreshBrowserOverrides(); + refreshOverrideList(); + overrideList.setSelectedValue(copy, true); + markUnsaved(); + } + + private void createNewOverride() { + var entity = selectedEntity; + if (entity == null || entity.category != CacheModels.Category.Graphics) { + createNewOverride(false); + return; + } + var content = new JPanel(new BorderLayout(0, 10)); + content.setBackground(WorkspaceStyle.MENU); + content.setBorder(BorderFactory.createEmptyBorder(14, 16, 12, 16)); + content.add(EditorText.builder("New override for " + entity.displayName) + .font(WorkspaceStyle.SEMIBOLD.deriveFont(14f)).build(), BorderLayout.NORTH); + var choices = new JPanel(new GridLayout(2, 1, 0, 6)); + choices.setOpaque(false); + var graphics = new JRadioButton("Graphics object · scene spot animations", true); + var projectile = new JRadioButton("Projectile · travelling effects"); + var group = new ButtonGroup(); + for (var choice : List.of(graphics, projectile)) { + group.add(choice); + choice.setFont(WorkspaceStyle.UI.deriveFont(12f)); + choice.setBackground(new Color(0x292929)); + choice.setForeground(WorkspaceStyle.TEXT); + choice.setBorder(BorderFactory.createEmptyBorder(8, 10, 8, 10)); + choices.add(choice); + } + content.add(choices); + Runnable close = () -> SwingUtilities.getWindowAncestor(content).dispose(); + var actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0)); + actions.setOpaque(false); + actions.add(EditorButton.builder().text("Cancel").onClick(close).build()); + var create = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY).text("Create override").onClick(() -> { + close.run(); + if (selectedEntity == entity) + createNewOverride(projectile.isSelected()); + }).build(); + actions.add(create); + content.add(actions, BorderLayout.SOUTH); + var dialog = EditorModal.builder(owner, "New override").content(content) + .size(Math.min(460, owner.getWidth() - 40), 218).initialFocus(graphics).open(); + dialog.getRootPane().setDefaultButton(create); + } + + private void createNewOverride(boolean projectile) { + var doc = document; + if (doc == null) + return; + var seed = new ModelOverride(); + if (selectedEntity != null) { + seed.description(selectedEntity.displayName); + switch (selectedEntity.category) { + case NPCs: seed.npcIds(new java.util.HashSet<>(Set.of(selectedEntity.id))); break; + case Objects: seed.objectIds(new java.util.HashSet<>(Set.of(selectedEntity.id))); break; + case Graphics: + projectileTarget = projectile; + if (projectileTarget) + seed.projectileIds(new java.util.HashSet<>(Set.of(selectedEntity.id))); + else + seed.graphicsObjectIds(new java.util.HashSet<>(Set.of(selectedEntity.id))); + break; + } + } + var created = doc.create(seed); + if (selectedEntity != null) { + scopeAll = false; + scope.setSelected("This entity"); + overrideSearch.setText(""); + } + refreshBrowserOverrides(); + refreshOverrideList(); + overrideList.setSelectedValue(created, true); + markUnsaved(); + status.setText("New override for " + seed.description); + centerPreview.toast("Created override · " + seed.description); + } + + private void saveSelectedOverride() { + var doc = document; + var entry = selectedOverride; + if (doc == null || entry == null) + return; + var rules = entry.override.colorOverrides; + if (rules != null) { + for (int i = 0; i < rules.length; i++) { + if (!ColorExpression.valid(ColorExpression.text(ModelOverrideFields.get(rules[i], "colors", com.google.gson.JsonElement.class)))) { + centerPreview.toast("Rule " + (i + 1) + " has an invalid colors expression"); + return; + } + } + } + String json = doc.toSparseJson(entry); + new Thread(() -> { + try { + doc.save(entry, json); + SwingUtilities.invokeLater(() -> { + saveStatus.setForeground(new Color(0x6CB348)); + saveStatus.setText("All changes saved"); + refreshBrowserOverrides(); + refreshOverrideList(); + }); + } catch (IOException e) { + log.error("Could not save model overrides", e); + SwingUtilities.invokeLater(() -> { + saveStatus.setForeground(new Color(0xE06060)); + saveStatus.setText("Could not save · " + e.getMessage()); + }); + } + }, "model-overrides save").start(); + } + + private void markUnsaved() { + saveStatus.setForeground(new Color(0xE8A33D)); + saveStatus.setText("Unsaved changes"); + } + + // ---- Bridge for EditorShell's shared undo history / command palette (different package, no access to our internals) ---- + + /** A snapshot of the currently selected override's state, for the owning shell's undo history. */ + public static JsonObject capture(ModelOverridesScreen screen) { + var result = new JsonObject(); + var doc = screen.document; + var entry = screen.selectedOverride; + if (doc != null && entry != null) + result.add("override", doc.gson().toJsonTree(entry.override, ModelOverride.class)); + return result; + } + + /** Restores a snapshot previously returned by {@link #capture}, onto whatever override is currently selected. */ + public static void restore(ModelOverridesScreen screen, JsonObject state) { + var doc = screen.document; + var entry = screen.selectedOverride; + if (doc == null || entry == null || !state.has("override")) + return; + entry.override = doc.gson().fromJson(state.get("override"), ModelOverride.class); + screen.properties.setOverride(entry.override, screen.targetSummaryFor(entry), screen.previewModel); + screen.updatePreviewOverride(); + screen.overrideList.repaint(); + screen.markUnsaved(); + screen.refreshBrowserOverrides(); + } + + /** Saves whatever override is currently selected — the Ctrl+K "Save model overrides" command. */ + public static void saveSelected(ModelOverridesScreen screen) { screen.saveSelectedOverride(); } + + private void onPropertyChanged() { + updatePreviewOverride(); + refreshBrowserOverrides(); + markUnsaved(); + if (overrideList.getSelectedValue() != null) + overrideList.repaint(); + } + + private void copySelectedOverrideJson() { + var doc = document; + if (doc == null || selectedOverride == null) + return; + var clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + String json = doc.toSparseJson(selectedOverride); + clipboard.setContents(new java.awt.datatransfer.StringSelection(json), null); + int fields = doc.gson().fromJson(json, JsonObject.class).entrySet().size(); + status.setText("Copied " + fields + " fields as JSON"); + } + + // ---- Viewport face and color picking ---- + + private void updateViewportCursor(Point point, boolean resizing, boolean orbiting) { + Cursor cursor; + if (resizing) { + cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); + } else if (orbiting) { + cursor = WorkspaceStyle.cursor("orbit"); + } else if (point != null && centerPreview.contains(point) && centerPreview.isOverDivider(point.x)) { + cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); + } else { + cursor = WorkspaceStyle.cursor(pickColorActive ? "pick-face" : "grab"); + } + centerPreview.setDividerActive(cursor.getType() == Cursor.E_RESIZE_CURSOR); + centerPreview.setCursor(cursor); + } + + private void setColorPicking(boolean active) { + pickColorActive = active; + centerPreview.hoverPick(active ? centerPreview.getMousePosition() : null); + if (pickColorButton == null) + return; + pickColorButton.setSelected(active); + updateViewportCursor(centerPreview.getMousePosition(), false, false); + } + + private void beginColorPick() { + setColorPicking(true); + } + + private int faceAt(Point point) { + boolean vanilla = "Vanilla".equals(previewMode) || ("Split".equals(previewMode) && point.x < centerPreview.dividerX()); + var picker = vanilla ? vanillaFacePicker : overrideFacePicker; + if (picker == null || !picker.matches(previewModel)) + return -1; + var imageBounds = centerPreview.imageBounds(vanilla); + if (!imageBounds.contains(point)) + return -1; + return picker.pick(new Point(point.x - imageBounds.x, point.y - imageBounds.y), imageBounds.width, imageBounds.height); + } + + private void showFaceMenu(Point point) { + if (point == null) + point = new Point(centerPreview.getWidth() / 2, centerPreview.getHeight() / 2); + int face = faceAt(point); + if (face < 0) + return; + var model = previewModel; + if (model == null || face >= model.getFaceCount()) + return; + var menu = new HdContextMenu("F", new Color(0x4772B3), "Face " + face) + .disabled("Place light here", "light", "Light editing is not available") + .disabled("Place light at face centre", "place-centre", "Light editing is not available") + .separator(); + if (selectedOverride != null) { + menu.item("Pick color for override", "eyedropper", "", () -> properties.colorPicked(PreviewFacePicker.faceColor(model, face))); + } else { + menu.disabled("Pick color for override", "eyedropper", "Select a model override first"); + } + menu.separator().item("Copy face ID", "copy", "", () -> copyText(Integer.toString(face))) + .show(centerPreview, point.x, point.y); + } + + private void pickPreviewFace(Point point) { + int face = faceAt(point); + if (face < 0) + return; + properties.colorPicked(PreviewFacePicker.faceColor(previewModel, face)); + setColorPicking(false); + } + + // ---- Preview toolbar / in-game view ---- + + private JPanel buildPreviewToolbar() { + var toolbar = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0)); + toolbar.setOpaque(false); + toolbar.setBounds(8, 8, 900, 40); + + toolbar.add(EditorButtonGroup.builder(List.of("Vanilla", "Override", "Split")).selected(previewMode).track().onChange(value -> { + previewMode = value; + centerPreview.mode(value); + updateViewportCursor(centerPreview.getMousePosition(), false, false); + }).build()); + toolbar.add(EditorButtonGroup.builder(List.of("Material", "UV checker", "Normals", "Wire")) + .selected(previewShading).track().onChange(value -> previewShading = value).build()); + + pickColorButton = EditorButton.builder().style(WorkspaceStyle.Button.TRIGGER) + .icon("eyedropper", 13).text("Pick color").tooltip("Pick color (I)").buildToggle(false); + pickColorButton.addActionListener(e -> { + boolean active = pickColorButton.isSelected(); + if (!active) + properties.cancelColorPicking(); + setColorPicking(active); + }); + registerKeyboardAction(e -> pickColorButton.doClick(), KeyStroke.getKeyStroke("pressed I"), JComponent.WHEN_IN_FOCUSED_WINDOW); + inGameButton = EditorButton.builder().style(WorkspaceStyle.Button.TRIGGER) + .icon("in-game-toggle", 14).text("In-game").tooltip("Toggle in-game view (G)") + .onToggle(this::setInGameVisible).buildToggle(true); + registerKeyboardAction(e -> inGameButton.doClick(), KeyStroke.getKeyStroke("pressed G"), JComponent.WHEN_IN_FOCUSED_WINDOW); + var frame = EditorButton.builder().style(WorkspaceStyle.Button.TRIGGER).text("Frame").icon("frame-all", 13) + .onClick(() -> { yaw = .55; pitch = .30; zoom = 1; }).build(); + + toolbar.add(pickColorButton); + toolbar.add(inGameButton); + toolbar.add(frame); + return toolbar; + } + + private JPanel buildPreviewInfo() { + var info = new JPanel(new GridLayout(0, 1, 0, 2)); + info.setOpaque(false); + var line1 = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(11f)).color(new Color(0xD6D6D6)).build(); + var line2 = EditorText.builder("Drag to orbit · wheel to zoom").font(WorkspaceStyle.UI.deriveFont(11f)).color(new Color(0x6F6F6F)).build(); + info.add(line1); + info.add(line2); + info.setBounds(10, 400, 500, 40); + previewInfoLine = line1; + return info; + } + + private JLabel previewInfoLine; + + private void layoutViewerStage() { + int width = viewerStage.getWidth(), height = viewerStage.getHeight(); + viewport.setBounds(0, 0, width, height); + int available = Math.max(0, width); + int rowWidth = 8, rowHeight = 0, toolbarHeight = 0; + for (Component item : previewToolbar.getComponents()) { + + var size = item.getPreferredSize(); + if (rowHeight != 0 && rowWidth + size.width + 8 > available) { + toolbarHeight += rowHeight; + rowWidth = 8; + rowHeight = 0; + } + rowWidth += size.width + 8; + rowHeight = Math.max(rowHeight, size.height); + } + previewToolbar.setBounds(0, 8, available, toolbarHeight + rowHeight); + centerPreview.splitLabelBaseline(previewToolbar.getY() + previewToolbar.getHeight()); + previewToolbar.doLayout(); + for (Component item : previewToolbar.getComponents()) + if (item instanceof Container) + ((Container) item).doLayout(); + previewInfo.setBounds(10, Math.max(0, height - 50), Math.max(0, Math.min(500, width - 20)), 40); + if (inGameView != null) { + inGameView.setOverlayTopInset(previewToolbar.getY() + previewToolbar.getHeight()); + inGameView.layoutOverlay(); + } + viewerStage.revalidate(); + viewerStage.repaint(); + } + + private static final class Orbit { + final double yaw, pitch, zoom; + + Orbit(double yaw, double pitch, double zoom) { + this.yaw = yaw; + this.pitch = pitch; + this.zoom = zoom; + } + } + + private JComponent inGameViewBody() { + var panel = new JPanel(new BorderLayout()); + panel.setOpaque(false); + var controls = new JPanel(new net.miginfocom.swing.MigLayout("insets 4 6, gap 6 4, flowx", "", "")); + controls.setBackground(WorkspaceStyle.BAR); + controls.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x1A1A1A))); + findInWorld = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY).icon("find-in-world", 12).text("Find in world") + .tooltip("Find this entity in the game cache").enabled(false).onClick(() -> { + var entry = selectedEntity; + if (entry != null) { + findingEntry = entry; + findInWorld.setEnabled(false); + findInWorld.setText("Finding…"); + gamePreviewCards.show(gamePreviewBody, "finding"); + findingOverlay.start(entry.displayName); + worldSearch.set(entry); + say("Searching map placements · " + entry.label); + } + }).build(); + findInWorld.setFont(WorkspaceStyle.UI.deriveFont(11f)); + controls.add(findInWorld); + sceneSelector = EditorSelect.builder().options(List.of(ScenePreset.values())) + .selected(ScenePreset.SKY).size(110, 22).tooltip("In-game backdrop") + .renderer(new DefaultListCellRenderer() { + @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value == null ? ScenePreset.LIVE : value, index, selected, focus); + setFont(WorkspaceStyle.UI.deriveFont(11f)); + setIcon(WorkspaceStyle.badge("", new Color(value == ScenePreset.CAVE ? 0x4A3A2C : value == ScenePreset.GRASS ? 0x618342 : 0x8FB3CF))); + return this; + } + }) + .onChange(value -> { scenePreset = value; foundLocation = null; cancelFinding(); }).build(); + controls.add(sceneSelector); + var surrounding = EditorButton.builder().style(WorkspaceStyle.Button.SCENE_TOGGLE) + .icon("scene-isolated", 12).text("Isolated").tooltip("Show or hide surrounding objects").buildToggle(false); + surrounding.setFont(WorkspaceStyle.UI.deriveFont(11f)); + surrounding.setBorder(BorderFactory.createEmptyBorder(0, 7, 0, 7)); + surrounding.addActionListener(e -> { + showSurroundings = surrounding.isSelected(); + surrounding.setText(showSurroundings ? "Scene" : "Isolated"); + surrounding.setIcon(WorkspaceStyle.icon(showSurroundings ? "scene-layers" : "scene-isolated", 12)); + }); + var instances = SegmentedControl.builder(List.of("One", "All")).selected("All").build(); + instances.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); + instances.onChange(value -> showAllPlacements = "All".equals(value)); + controls.add(surrounding); + controls.add(instances, "height 22!"); + panel.add(controls, BorderLayout.NORTH); + panel.addComponentListener(new java.awt.event.ComponentAdapter() { + @Override public void componentResized(java.awt.event.ComponentEvent event) { + var layout = (net.miginfocom.swing.MigLayout) controls.getLayout(); + layout.setLayoutConstraints(panel.getWidth() < 390 ? "insets 4 6, gap 6 4, wrap 2" : "insets 4 6, gap 6 4"); + panel.revalidate(); + } + }); + findingOverlay.addCancel(this::cancelFinding); + gamePreviewBody.add(dockPreview, "preview"); + gamePreviewBody.add(findingOverlay, "finding"); + panel.add(gamePreviewBody); + dockPreview.setCursor(WorkspaceStyle.cursor("grab")); + var mouse = new MouseAdapter() { + private Point previous; + + @Override public void mousePressed(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e)) + previous = e.getPoint(); + } + + @Override public void mouseDragged(MouseEvent e) { + if (previous == null) + return; + var camera = gameCamera; + gameCamera = new Orbit(camera.yaw - (e.getX() - previous.x) * .012, + Math.max(-1.35, Math.min(1.35, camera.pitch + (e.getY() - previous.y) * .012)), camera.zoom); + previous = e.getPoint(); + dockPreview.setCursor(WorkspaceStyle.cursor("orbit")); + } + + @Override public void mouseReleased(MouseEvent e) { + previous = null; + dockPreview.setCursor(WorkspaceStyle.cursor("grab")); + } + + @Override public void mouseWheelMoved(MouseWheelEvent e) { + var camera = gameCamera; + gameCamera = new Orbit(camera.yaw, camera.pitch, + Math.max(.25, Math.min(3, camera.zoom * Math.pow(1.1, -e.getPreciseWheelRotation())))); + } + }; + dockPreview.addMouseListener(mouse); + dockPreview.addMouseMotionListener(mouse); + dockPreview.addMouseWheelListener(mouse); + return panel; + } + + private void cancelFinding() { + worldSearch.set(null); + finishFinding(false); + } + + private void finishFinding(boolean failed) { + findingEntry = null; + findingOverlay.stop(); + gamePreviewCards.show(gamePreviewBody, "preview"); + findInWorld.setEnabled(selectedEntity != null); + findInWorld.setText("Find in world"); + if (failed) + dockPreview.toast("Could not find"); + } + + private static final class FindingOverlay extends JPanel { + private final JLabel entity = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(10f)) + .color(WorkspaceStyle.DIM).build(); + private final JComponent spinner = new JComponent() { + @Override public Dimension getPreferredSize() { return new Dimension(24, 24); } + + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + g.setColor(WorkspaceStyle.BORDER); + g.drawOval(2, 2, 20, 20); + g.setColor(WorkspaceStyle.ACCENT); + int angle = (int) (-(System.nanoTime() % 800_000_000L) * 360 / 800_000_000L); + g.drawArc(2, 2, 20, 20, angle, 110); + g.dispose(); + } + }; + private final Timer animation = new Timer(16, e -> spinner.repaint()); + + FindingOverlay() { + setBackground(new Color(0x202020)); + setLayout(new GridBagLayout()); + addRow(spinner, 0); + addRow(EditorText.builder("Finding in world…").build(), 1); + entity.setHorizontalAlignment(SwingConstants.CENTER); + entity.setPreferredSize(new Dimension(0, entity.getPreferredSize().height)); + addRow(entity, 2); + } + + void addCancel(Runnable cancel) { + addRow(EditorButton.builder().text("Cancel").onClick(cancel).build(), 3); + } + + private void addRow(JComponent component, int row) { + var cell = new GridBagConstraints(); + cell.gridx = 0; + cell.gridy = row; + cell.insets = new Insets(row == 0 ? 0 : 4, 8, 0, 8); + if (component == entity) { + cell.weightx = 1; + cell.fill = GridBagConstraints.HORIZONTAL; + } + add(component, cell); + } + + void start(String name) { + entity.setText(name); + entity.setToolTipText(name); + animation.start(); + } + + void stop() { animation.stop(); } + @Override public void removeNotify() { stop(); super.removeNotify(); } + @Override public void addNotify() { super.addNotify(); if (isVisible()) animation.start(); } + } + + private void updatePreviewOverride() { + var doc = document; + var entity = selectedEntity; + var selection = selectedOverride; + previewOverrideJson = doc != null && entity != null && selection != null + && doc.targets(selection.override, entity.category, entity.id) ? doc.toSparseJson(selection.override) : null; + } + + private void setInGameVisible(boolean visible) { + dockVisible = visible; + if (!visible) + dockPreview.clear(); + inGameView.setVisible(visible); + if (!visible && findingEntry != null) { + worldSearch.set(null); + finishFinding(false); + } + if (inGameView.getDock() == FloatingDockWindow.Dock.PANEL) { + if (visible) + docks.dockPanel(inGameView, inGameView.getPanelSide()); + else + docks.undockPanel(inGameView); + } else if (visible) { + if (inGameView.getParent() != viewerStage) + viewerStage.add(inGameView, JLayeredPane.MODAL_LAYER); + inGameView.layoutOverlay(); + } + viewerStage.repaint(); + } + + private void refreshPreview() { + var entry = selectedEntity; + if (entry != null) + pending.set(entry); + } + + // ---- Properties <-> ModelOverride wiring ---- + + private OverrideProperties.Context buildPropertiesContext() { + return new OverrideProperties.Context() { + private rs117.hd.scene.materials.Material[] materialSource; + private List sortedMaterials = List.of(); + @Override public void colorToast(String message) { centerPreview.toast(message); } + + @Override public void highlightColors(ModelOverride.AhslPredicate rule, Integer hover) { + centerPreview.highlightColors(rule, hover); + } + + @Override public void setWindPreview(boolean enabled) { + windPointer = null; + windPreview = enabled; + } + + @Override public int[] vanillaTexturePixels(int textureId) { + return session.vanillaTexturePixels(textureId); + } + + @Override public List materials() { + var source = MaterialManager.MATERIALS; + if (source == materialSource) + return sortedMaterials; + materialSource = source; + if (source == null) { + sortedMaterials = List.of(); + return sortedMaterials; + } + var featured = List.of("NONE", "UNLIT", "WOOD_GRAIN", "WOOD_GRAIN_LIGHT", "BARK", "STONE"); + sortedMaterials = java.util.Arrays.stream(source) + .sorted(java.util.Comparator.comparingInt((rs117.hd.scene.materials.Material material) -> { + int index = featured.indexOf(material.name); + return index >= 0 ? index : featured.size(); + }) + .thenComparing(material -> material.name)) + .collect(java.util.stream.Collectors.toList()); + return sortedMaterials; + } + + @Override public String nearbyObject(int id) { + Integer count = nearbyObjects.get(id); + return count == null ? null : "nearby · " + count + "×"; + } + + @Override public List npcChoices() { return choicesFor(CacheModels.Category.NPCs, "N", new Color(0xD97A7A)); } + @Override public List objectChoices() { return choicesFor(CacheModels.Category.Objects, "O", new Color(0x7CB6A0)); } + @Override public List spotanimChoices() { return choicesFor(CacheModels.Category.Graphics, "G", new Color(0xC79BE0)); } + }; + } + + private CacheModels.Index choicesCatalog; + private final java.util.Map> cachedChoices = + new java.util.EnumMap<>(CacheModels.Category.class); + + private List choicesFor(CacheModels.Category wanted, String letter, Color color) { + var catalog = session.modelCatalog(); + if (choicesCatalog != catalog) { + choicesCatalog = catalog; + cachedChoices.clear(); + } + return cachedChoices.computeIfAbsent(wanted, category -> { + List choices = new ArrayList<>(); + for (var entry : catalog.entries) + if (entry.category == category) + choices.add(new SearchableIdDropdown.Choice(entry.id, entry.displayName, letter, color, entry.searchLabel)); + return List.copyOf(choices); + }); + } + + // ---- Render loop ---- + + private Runnable initialPreviewReady; + + public void whenInitialPreviewReady(Runnable action) { + if (selectedEntity == null) + action.run(); + else + initialPreviewReady = action; + } + + private void signalInitialPreviewReady() { + var action = initialPreviewReady; + initialPreviewReady = null; + if (action != null) + action.run(); + } + + public void render(HdRuntime runtime, BuiltScene scene, rs117.hd.dev.definitions.DefinitionsScreen definitions) + throws InterruptedException { + try (var gamevals = runtime.openGamevals()) { + say("Cache loaded · Select a model"); + document = new ModelOverrideDocument(runtime.getGson(), modelOverridesFile(), gamevals); + SwingUtilities.invokeLater(() -> { refreshBrowserOverrides(); refreshOverrideList(true); }); + double distance = 300; + double targetY = -50; + int modelBaseY = 0; + int modelBottom = 0; + int tileX = TILE_X, tileZ = TILE_Z, plane = 0, orientation = 0, shape = 10; + BuiltScene previewScene = scene; + BuiltScene indexedScene = null; + ScenePreset appliedPreset = null; + boolean appliedSurroundings = false; + boolean appliedAll = true; + net.runelite.cache.region.Location appliedLocation = null; + CacheModels.Entry renderedEntry = null; + String appliedJson = null; + rs117.hd.scene.model_overrides.ModelOverride draft = null; + int dirtyPasses = 0; + int lastCenterPass = OVERRIDE_PASS; + long nextWindFrame = 0; + boolean previousWind = false; + float[] windProjection = null; + Orbit previousGameCamera = null; + double previousYaw = Double.NaN, previousPitch = Double.NaN, previousZoom = Double.NaN; + String previousMode = null, previousShading = null; + boolean previousDock = false; + var frameUpdates = new FrameUpdates(); + var previewGrid = new PreviewGrid(); + BuiltModel installedModel = null; + BuiltModel baseModel = null; + BuiltModel normals = null; + BuiltModel vanillaUv = null; + BuiltModel overrideUv = null; + var water = new rs117.hd.dev.definitions.WaterPreview(session, definitions); + long loadedGeneration = previewGeneration; + while (!Thread.currentThread().isInterrupted()) { + long generation = previewGeneration; + if (generation != loadedGeneration) { + loadedGeneration = generation; + frameUpdates.clear(); + session.clearPreviewCaches(); + if (previewScene != scene || baseModel != null) + runtime.releasePreviewScene(scene); + previewScene = scene; + indexedScene = null; + nearbyObjects = java.util.Map.of(); + renderedEntry = null; + baseModel = installedModel = normals = vanillaUv = overrideUv = null; + previewModel = null; + windProjection = null; + draft = null; + appliedJson = null; + appliedPreset = null; + previousMode = null; + dirtyPasses = 0; + if (previewActive && selectedEntity != null) + pending.set(selectedEntity); + } + if (water.render(runtime)) { + Thread.sleep(33); + continue; + } + if (water.detach(runtime)) { + runtime.releasePreviewScene(scene); + session.clearPreviewCaches(); + } + if (!previewActive) { + Thread.sleep(50); + continue; + } + + if (refreshRequested.getAndSet(false)) { + try { + var updated = session.refreshModelCatalog(runtime); + SwingUtilities.invokeLater(() -> setEntries(updated)); + } catch (IOException | RuntimeException e) { + say("Could not refresh cache · " + e.getMessage()); + } + } + var entry = pending.getAndSet(null); + if (entry != null) { + try { + BuiltModel model = entry.source.load(); + if (model == null) { + runtime.setPreviewModel(null, null, null); + renderedEntry = null; + previewModel = null; + say("Model unavailable · " + entry.label); + SwingUtilities.invokeLater(this::signalInitialPreviewReady); + } else { + installedModel = null; + windProjection = null; + previousMode = null; + renderedEntry = entry; + baseModel = model; + normals = vanillaUv = overrideUv = null; + previewModel = model; + double[] framing = framing(model); + distance = framing[0]; + targetY = framing[1]; + modelBottom = (int) Math.ceil(framing[2]); + appliedPreset = null; + zoom = 1; + say(entry.label + " · " + model.getFaceCount() + " faces"); + SwingUtilities.invokeLater(() -> { + if (!previewActive || previewGeneration != generation || selectedEntity != entry || previewModel != model) + return; + properties.setPreviewModel(model); + if (previewInfoLine != null) + previewInfoLine.setText(selectedOverride == null ? entry.label : entry.label + " › " + selectedOverride.override.description); + }); + log.info("Previewing {}", entry.label); + } + } catch (IOException | RuntimeException e) { + runtime.setPreviewModel(null, null, null); + renderedEntry = null; + log.warn("Could not build {}", entry.label, e); + say("Could not build " + entry.label + " · " + e.getMessage()); + SwingUtilities.invokeLater(this::signalInitialPreviewReady); + } + } + var requested = worldSearch.getAndSet(null); + if (requested != null && requested == selectedEntity) { + String result = "No map placement found · " + requested.label; + try { + if (requested.category == CacheModels.Category.Objects && requested == renderedEntry) { + var location = session.findObjectPlacement(requested.id, () -> previewActive && findingEntry == requested); + if (location != null && requested == selectedEntity && findingEntry == requested) { + foundLocation = location; + var position = location.getPosition(); + result = "Found at " + position.getX() + ", " + position.getY() + " · plane " + position.getZ(); + } + } + } catch (RuntimeException e) { + log.warn("Could not load map preview for {}", requested.label, e); + result = "Could not load map placement · " + requested.label; + } + String message = result; + SwingUtilities.invokeLater(() -> { + if (selectedEntity == requested && findingEntry == requested) { + findInWorld.setToolTipText(message); + if (message.startsWith("Found at ")) + sceneSelector.setSelectedIndex(-1); + else { + sceneSelector.setSelectedItem(ScenePreset.SKY); + finishFinding(true); + } + status.setText(message); + } + }); + } + var preset = scenePreset; + var placement = foundLocation; + boolean surroundings = showSurroundings; + if (!dockVisible) { + preset = ScenePreset.SKY; + placement = null; + surroundings = false; + } + boolean all = showAllPlacements; + if (renderedEntry != null && (preset != appliedPreset || placement != appliedLocation + || surroundings != appliedSurroundings || all != appliedAll)) { + appliedPreset = preset; + appliedLocation = placement; + appliedSurroundings = surroundings; + appliedAll = all; + previewScene = scene; + tileX = TILE_X; + tileZ = TILE_Z; + plane = orientation = modelBaseY = 0; + shape = 10; + if (placement != null || preset != ScenePreset.SKY) { + try { + var pos = placement == null ? null : placement.getPosition(); + int x = pos == null ? preset.x : pos.getX(); + int z = pos == null ? preset.z : pos.getY(); + int id = renderedEntry.category == CacheModels.Category.Objects ? renderedEntry.id : -1; + previewScene = session.buildPreviewScene(x, z, id, placement, surroundings, all); + tileX = x - previewScene.getBaseX(); + tileZ = z - previewScene.getBaseY(); + plane = pos == null ? 0 : pos.getZ(); + orientation = placement == null ? 0 : placement.getOrientation() * 512; + shape = placement == null ? 10 : placement.getType(); + modelBaseY = previewGroundHeight(previewScene, plane, tileX, tileZ) - GROUND_CLEARANCE - modelBottom; + } catch (IOException | RuntimeException e) { + log.warn("Could not load preview scene", e); + previewScene = scene; + tileX = TILE_X; + tileZ = TILE_Z; + plane = orientation = modelBaseY = 0; + shape = 10; + say("Could not load preview scene"); + var failedEntry = renderedEntry; + SwingUtilities.invokeLater(() -> { + if (findingEntry == failedEntry) + finishFinding(true); + }); + } + } + runtime.setScene(previewScene); + runtime.setLevels(plane, true, false); + installedModel = null; + previousMode = null; + } + if (previewScene != indexedScene) { + indexedScene = previewScene; + nearbyObjects = indexSceneObjects(previewScene); + } + double y = yaw; + double p = pitch; + double currentZoom = zoom; + if (renderedEntry == null) { + Thread.sleep(16); + continue; + } + + String mode = previewMode; + String centerShading = previewShading; + String json = previewOverrideJson; + boolean showDock = dockVisible; + var dockCamera = gameCamera; + boolean cameraChanged = y != previousYaw || p != previousPitch || currentZoom != previousZoom; + boolean overrideChanged = !java.util.Objects.equals(json, appliedJson); + int centerPasses = "Split".equals(mode) ? VANILLA_PASS | OVERRIDE_PASS + : "Vanilla".equals(mode) ? VANILLA_PASS : OVERRIDE_PASS; + if (cameraChanged || !mode.equals(previousMode) || !centerShading.equals(previousShading)) + dirtyPasses = (dirtyPasses & DOCK_PASS) | centerPasses; + if (overrideChanged) + dirtyPasses |= centerPasses & OVERRIDE_PASS; + if (showDock && (dockCamera != previousGameCamera || overrideChanged || !previousDock || previousMode == null)) { + dirtyPasses |= DOCK_PASS; + } else if (!showDock) { + dirtyPasses &= ~DOCK_PASS; + } + previousYaw = y; + previousPitch = p; + previousZoom = currentZoom; + previousMode = mode; + previousShading = centerShading; + previousDock = showDock; + previousGameCamera = dockCamera; + + if (overrideChanged) { + appliedJson = json; + overrideUv = null; + draft = null; + if (json != null) { + try { + draft = document.gson().fromJson(json, ModelOverride.class); + if (draft.colorOverrides != null) + draft.colorOverrides = java.util.Arrays.stream(draft.colorOverrides) + .filter(rule -> ColorExpression.valid(ColorExpression.text(ModelOverrideFields.get(rule, "colors", com.google.gson.JsonElement.class)))) + .toArray(ModelOverride[]::new); + draft.normalize(runtime.getPlugin()); + } catch (RuntimeException e) { + draft = null; + say("Override preview unavailable · " + e.getMessage()); + } + } + } + + boolean animateWind = windPreview && draft != null + && draft.windDisplacementMode != rs117.hd.scene.model_overrides.WindDisplacement.DISABLED + && ("Material".equals(centerShading) || "Wire".equals(centerShading)) + && (centerPasses & OVERRIDE_PASS) != 0; + long now = System.nanoTime(); + if (animateWind != previousWind || animateWind && now >= nextWindFrame) + dirtyPasses |= centerPasses & OVERRIDE_PASS; + previousWind = animateWind; + + int centerDirty = dirtyPasses & centerPasses; + if (centerDirty == 0 && (dirtyPasses & DOCK_PASS) == 0) { + Thread.sleep(8); + continue; + } + int pass = centerDirty == 0 ? DOCK_PASS : centerDirty != centerPasses || centerPasses != (VANILLA_PASS | OVERRIDE_PASS) + ? centerDirty : centerPasses ^ lastCenterPass; + boolean dock = pass == DOCK_PASS; + boolean vanilla = pass == VANILLA_PASS; + if (!dock) + lastCenterPass = pass; + String shading = dock ? "Material" : centerShading; + var effective = vanilla ? rs117.hd.scene.model_overrides.ModelOverride.NONE : draft; + BuiltModel shown = baseModel; + if ("Normals".equals(shading)) { + if (normals == null) + normals = PreviewDiagnostics.normals(baseModel); + shown = normals; + } else if ("UV checker".equals(shading)) { + if (vanilla || draft == null) { + if (vanillaUv == null) + vanillaUv = PreviewDiagnostics.uv(baseModel, rs117.hd.scene.model_overrides.ModelOverride.NONE); + shown = vanillaUv; + } else { + if (overrideUv == null) + overrideUv = PreviewDiagnostics.uv(baseModel, draft); + shown = overrideUv; + } + } + if (shown != baseModel) { + var diagnostic = new rs117.hd.scene.model_overrides.ModelOverride(); + diagnostic.material = rs117.hd.scene.materials.Material.UNLIT; + diagnostic.forceMaterialChanges = true; + if (effective != null) { + diagnostic.rotate = effective.rotate; + diagnostic.heightOffset = effective.heightOffset; + } + effective = diagnostic; + } + if (animateWind && pass == OVERRIDE_PASS) { + nextWindFrame = now + 33_333_333L; + shown = WindPreview.deform(baseModel, draft, now * 1e-9, + windPointer, windProjection, tileX * 128 + 64, modelBaseY, tileZ * 128 + 64, modelBottom); + } + if (shown != installedModel || orientation != 0) { + setPreview(runtime, previewScene, renderedEntry, shown, tileX, tileZ, plane, modelBaseY, dock ? orientation : 0, shape); + installedModel = shown; + } + int uuid = previewUuid(renderedEntry); + runtime.setPreviewOverride(effective != null ? uuid : null, effective); + runtime.setPreviewPass(dock, "Wire".equals(shading)); + var captured = renderedEntry; + var plugin = runtime.getPlugin(); + int modelGroundY = modelBaseY; + int previewX = tileX * 128 + 64, previewZ = tileZ * 128 + 64; + var effectiveForPicking = effective; + var sourceForPicking = baseModel; + var modelForPicking = animateWind && pass == OVERRIDE_PASS ? shown : baseModel; + float[][] renderedProjection = {null}; + boolean[] capturedFrame = {false}; + runtime.nextFrameTo(image -> { + if (image == null) + return; + capturedFrame[0] = true; + var picker = dock ? null : new PreviewFacePicker(sourceForPicking, modelForPicking, plugin.viewProjMatrix, + previewX, modelGroundY + (effectiveForPicking == null ? 0 : effectiveForPicking.heightOffset), + previewZ, effectiveForPicking == null ? 0 : effectiveForPicking.rotate); + if (pass == OVERRIDE_PASS) + renderedProjection[0] = picker.matrix(); + if (!dock && image instanceof BufferedImage) + previewGrid.draw((BufferedImage) image, plugin.viewProjMatrix, previewX, previewZ, modelGroundY); + frameUpdates.offer(pass, () -> { + if (!previewActive || previewGeneration != generation || selectedEntity != captured || dock && !dockVisible) + return; + if (dock) { + dockPreview.caption(selectedOverride == null ? captured.displayName : selectedOverride.override.description); + dockPreview.frame(false, image); + if (findingEntry == captured && foundLocation != null) { + finishFinding(false); + dockPreview.toast("Found " + captured.displayName); + } + } else { + if (vanilla) + vanillaFacePicker = picker; + else + overrideFacePicker = picker; + centerPreview.modelFrame(vanilla, image, picker); + signalInitialPreviewReady(); + } + }); + }); + if (dock) { + double focusY = modelBaseY + targetY + (effective == null ? 0 : effective.heightOffset); + var camera = previewCamera(dockCamera.yaw, dockCamera.pitch, distance / dockCamera.zoom, focusY, previewX, previewZ); + if (previewScene == scene) + runtime.frameModelPreview(camera, (float) dockCamera.yaw, (float) dockCamera.pitch); + else + runtime.frame(camera, + (float) dockCamera.yaw, (float) dockCamera.pitch); + } else { + runtime.frameModelPreview(previewCamera(y, p, distance / currentZoom, modelBaseY + targetY, previewX, previewZ), (float) y, (float) p); + } + if (renderedProjection[0] != null) + windProjection = renderedProjection[0]; + if (capturedFrame[0]) + dirtyPasses &= ~pass; + Thread.sleep(4); + } + } catch (IOException | RuntimeException e) { + log.error("Model preview failed", e); + say("Preview failed · " + e.getMessage()); + SwingUtilities.invokeLater(this::signalInitialPreviewReady); + } + } + + /** Keeps the latest image for each pane while the Swing event thread is busy. */ + private static final class FrameUpdates { + private final java.util.Map latest = new java.util.LinkedHashMap<>(); + + synchronized void offer(int pass, Runnable update) { + boolean schedule = latest.isEmpty(); + latest.put(pass, update); + if (schedule) + SwingUtilities.invokeLater(this::publish); + } + + synchronized void clear() { latest.clear(); } + + private void publish() { + List updates; + synchronized (this) { + updates = List.copyOf(latest.values()); + latest.clear(); + } + updates.forEach(Runnable::run); + } + } + + private static Path modelOverridesFile() throws IOException { + var source = rs117.hd.utils.Props.getFile("rlhd.model-overrides-path", + () -> rs117.hd.utils.ResourcePath.path(rs117.hd.scene.ModelOverrideManager.class, "model_overrides.json")); + if (!source.isFileSystemResource()) + throw new IOException("model_overrides.json isn't a real file here (running from a packaged jar?) — pass -Drlhd.model-overrides-path= to edit it"); + return source.toPath().toAbsolutePath(); + } + + private void selectInitialEntry() { + String initial = System.getProperty("rlhd.editor-model"); + if (initial == null) + return; + for (var group : browserGroups) { + for (var entry : group.variants) { + if ((entry.category.name() + ":" + entry.id).equalsIgnoreCase(initial)) { + category = entry.category; + categories.get(category).setSelected(true); + activeGroup = group; + filter(); + list.ensureIndexIsVisible(list.getSelectedIndex()); + selectEntity(entry); + return; + } + } + } + } + + private static java.util.Map indexSceneObjects(BuiltScene scene) { + var counts = new java.util.HashMap(); + var seen = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + for (var level : scene.getTiles()) + for (var column : level) + for (var tile : column) { + if (tile == null) + continue; + for (var object : tile.getGameObjects()) + if (object != null && seen.add(object)) + counts.merge(object.getId(), 1, Integer::sum); + for (var object : new net.runelite.api.TileObject[] { tile.getWallObject(), tile.getDecorativeObject(), tile.getGroundObject() }) + if (object != null && seen.add(object)) + counts.merge(object.getId(), 1, Integer::sum); + } + return counts; + } + + private static int previewGroundHeight(BuiltScene scene, int plane, int tileX, int tileZ) { + int x = tileX + BuiltScene.SCENE_OFFSET; + int z = tileZ + BuiltScene.SCENE_OFFSET; + int[][] heights = scene.getTileHeights()[plane]; + return Math.min(Math.min(heights[x][z], heights[x + 1][z]), + Math.min(heights[x][z + 1], heights[x + 1][z + 1])); + } + + private static float[] previewCamera(double yaw, double pitch, double distance, double targetY, int x, int z) { + return new float[] { + (float) (x + Math.sin(yaw) * Math.cos(pitch) * distance), + (float) (targetY - Math.sin(pitch) * distance), + (float) (z - Math.cos(yaw) * Math.cos(pitch) * distance) + }; + } + + private static int previewUuid(CacheModels.Entry entry) { + int type = entry.category == CacheModels.Category.NPCs ? ModelHash.TYPE_NPC + : entry.category == CacheModels.Category.Graphics ? ModelHash.TYPE_GRAPHICS_OBJECT : ModelHash.TYPE_OBJECT; + return ModelHash.packUuid(type, entry.id); + } + + private static void setPreview(HdRuntime runtime, BuiltScene scene, CacheModels.Entry entry, BuiltModel model, + int tileX, int tileZ, int plane, int height, int orientation, int shape) { + int type = entry.category == CacheModels.Category.NPCs ? ModelHash.TYPE_NPC : ModelHash.TYPE_OBJECT; + long hash = entry.category == CacheModels.Category.Graphics ? -1 : + ObjectPlacer.hash(plane, tileX, tileZ, type, true, entry.id, scene.getWorldViewId()); + var answers = new EntityModel(entry.id, model); + Renderable renderable = entry.category == CacheModels.Category.NPCs ? Fake.of(NPC.class, answers) + : entry.category == CacheModels.Category.Graphics ? Fake.of(GraphicsObject.class, answers) : model; + var tile = new BuiltGameObject(scene, hash, shape, tileX * 128 + 64, tileZ * 128 + 64, height, plane, + renderable, orientation, tileX, tileZ, tileX, tileZ); + runtime.setPreviewModel(tile, renderable, model); + } + + public static final class EntityModel { + private final int id; + private final Model model; + EntityModel(int id, Model model) { this.id = id; this.model = model; } + public int getId() { return id; } + public Model getModel() { return model; } + } + + private static double[] framing(Model model) { + double radius = 1; + double minY = 0, maxY = 0; + for (int i = 0; i < model.getVerticesCount(); i++) { + radius = Math.max(radius, Math.hypot(model.getVerticesX()[i], model.getVerticesZ()[i])); + minY = Math.min(minY, model.getVerticesY()[i]); + maxY = Math.max(maxY, model.getVerticesY()[i]); + } + return new double[] {Math.max(110, Math.max(radius * 3.1, (maxY - minY) * 1.55)), (minY + maxY) / 2, maxY}; + } + + private void say(String message) { + SwingUtilities.invokeLater(() -> status.setText(message)); + } + + private static JLabel header(String name) { + var title = EditorText.builder(name).font(WorkspaceStyle.SEMIBOLD).icon(WorkspaceStyle.icon("grip", 12)) + .border(BorderFactory.createEmptyBorder(0, 8, 0, 8)).build(); + title.setPreferredSize(new Dimension(0, 30)); + title.setOpaque(true); + title.setBackground(WorkspaceStyle.HEADER); + return title; + } + + private static JPanel panel(JComponent header) { + var panel = new JPanel(new BorderLayout()); + panel.setBackground(WorkspaceStyle.PANEL); + panel.add(header, BorderLayout.NORTH); + return panel; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/OverridePreviewSurface.java b/Tools/Dev/java/rs117/hd/dev/overrides/OverridePreviewSurface.java new file mode 100644 index 0000000..3597f6c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/OverridePreviewSurface.java @@ -0,0 +1,218 @@ +package rs117.hd.dev.overrides; + +import java.awt.*; +import javax.swing.JPanel; +import javax.swing.Timer; +import rs117.hd.dev.editor.WorkspaceStyle; + +final class OverridePreviewSurface extends JPanel { + private static final Color DIVIDER_COLOR = new Color(0xE8A33D); + private static final Color VANILLA_LABEL_COLOR = new Color(0x9A9A9A); + private static final Color CAPTION_SHADOW_COLOR = new Color(0, 0, 0, 204); + private static final Color CAPTION_TEXT_COLOR = new Color(255, 255, 255, 191); + private static final Font SPLIT_LABEL_FONT = WorkspaceStyle.SEMIBOLD.deriveFont(10f); + private static final Font CAPTION_FONT = WorkspaceStyle.UI.deriveFont(10f); + private static final int DIVIDER_HIT_RADIUS = 6; + private double splitPosition = .5; + private boolean dividerActive; + private String toast; + private String caption; + private long toastStarted; + private final Timer toastAnimation = new Timer(16, event -> { + if (toastElapsed() >= 2.2) + clearToast(); + repaint(); + }); + private Image vanilla; + private Image overridden; + private PreviewFacePicker vanillaPicker, overridePicker; + private rs117.hd.scene.model_overrides.ModelOverride.AhslPredicate colorRule; + private Integer hoverColor; + private Point pickPoint; + + private String mode = "Override"; + private final boolean comparison; + private int splitLabelBaseline = 58; + + OverridePreviewSurface(boolean comparison) { + this.comparison = comparison; + setBackground(WorkspaceStyle.HEADER); + } + + void splitLabelBaseline(int toolbarBottom) { splitLabelBaseline = Math.max(58, toolbarBottom + 16); } + + void mode(String mode) { + this.mode = mode; + repaint(); + } + + int dividerX() { + return (int) Math.round(getWidth() * splitPosition); + } + + boolean isOverDivider(int x) { + return comparison && "Split".equals(mode) && Math.abs(x - dividerX()) <= DIVIDER_HIT_RADIUS; + } + + void setDividerActive(boolean active) { + if (dividerActive != active) { + dividerActive = active; + repaint(); + } + } + + void moveDivider(int x) { + if (getWidth() <= 0) + return; + splitPosition = Math.max(.05, Math.min(.95, x / (double) getWidth())); + repaint(); + } + + void frame(boolean isVanilla, Image image) { + if (isVanilla) + vanilla = image; + else + overridden = image; + repaint(); + } + + void modelFrame(boolean isVanilla, Image image, PreviewFacePicker picker) { + if (isVanilla) + vanillaPicker = picker; + else + overridePicker = picker; + frame(isVanilla, image); + } + + void hoverPick(Point point) { + if (!java.util.Objects.equals(pickPoint, point)) { + pickPoint = point; + repaint(); + } + } + + void highlightColors(rs117.hd.scene.model_overrides.ModelOverride.AhslPredicate rule, Integer hover) { + colorRule = rule; + hoverColor = hover; + repaint(); + } + + void caption(String text) { caption = text; } + + void toast(String text) { + toast = text; + toastStarted = System.nanoTime(); + toastAnimation.start(); + repaint(); + } + + private double toastElapsed() { + return (System.nanoTime() - toastStarted) / 1e9; + } + + private void clearToast() { + toast = null; + toastAnimation.stop(); + } + + @Override public void removeNotify() { + clearToast(); + super.removeNotify(); + } + + void clear() { + vanilla = overridden = null; + vanillaPicker = overridePicker = null; + clearToast(); + repaint(); + } + + @Override protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + int width = getWidth(); + int height = getHeight(); + if (comparison && "Split".equals(mode)) { + int divider = dividerX(); + var clip = g.getClip(); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + g.setFont(SPLIT_LABEL_FONT); + g.clipRect(0, 0, divider, height); + drawFrame(g, vanilla, 0, width, height); + g.setColor(VANILLA_LABEL_COLOR); + g.drawString("VANILLA", divider - 10 - g.getFontMetrics().stringWidth("VANILLA"), splitLabelBaseline); + g.setClip(clip); + g.clipRect(divider, 0, width - divider, height); + drawFrame(g, overridden, 0, width, height); + g.setColor(DIVIDER_COLOR); + g.drawString("OVERRIDE", divider + 10, splitLabelBaseline); + g.setClip(clip); + g.fillRect(divider - (dividerActive ? 1 : 0), 0, dividerActive ? 3 : 1, height); + } else { + drawFrame(g, comparison && "Vanilla".equals(mode) ? vanilla : overridden, 0, width, height); + } + if (caption != null && !comparison) { + g.setFont(CAPTION_FONT); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setColor(CAPTION_SHADOW_COLOR); + g.drawString(caption, 8, height - 7); + g.setColor(CAPTION_TEXT_COLOR); + g.drawString(caption, 8, height - 8); + } + paintToast(g, width, height); + g.dispose(); + } + + private void paintToast(Graphics2D g, int width, int height) { + if (toast == null) + return; + double elapsed = toastElapsed(); + float alpha = (float) Math.max(0, Math.min(1, Math.min(elapsed / .18, (2.2 - elapsed) / .3))); + g.setComposite(AlphaComposite.SrcOver.derive(alpha)); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g.setFont(WorkspaceStyle.SEMIBOLD); + int pillWidth = g.getFontMetrics().stringWidth(toast) + 24; + int x = (width - pillWidth) / 2, y = height - 40 + (int) ((1 - alpha) * 8); + g.setColor(WorkspaceStyle.MENU); + g.fillRoundRect(x, y, pillWidth, 28, 10, 10); + g.setColor(WorkspaceStyle.BORDER); + g.drawRoundRect(x, y, pillWidth, 28, 10, 10); + g.setColor(WorkspaceStyle.TEXT); + g.drawString(toast, x + 12, y + 18); + } + + Rectangle imageBounds(boolean isVanilla) { + return imageBounds(isVanilla ? vanilla : overridden, 0, getWidth(), getHeight()); + } + + private Rectangle imageBounds(Image image, int x, int width, int height) { + if (image == null || width <= 0 || height <= 0) + return new Rectangle(); + int iw = image.getWidth(this), ih = image.getHeight(this); + if (iw <= 0 || ih <= 0) + return new Rectangle(); + double scale = Math.min(width / (double) iw, height / (double) ih); + int w = (int) (iw * scale), h = (int) (ih * scale); + return new Rectangle(x + (width - w) / 2, (height - h) / 2, w, h); + } + + private void drawFrame(Graphics2D g, Image image, int x, int width, int height) { + var bounds = imageBounds(image, x, width, height); + if (!bounds.isEmpty()) { + g.drawImage(image, bounds.x, bounds.y, bounds.width, bounds.height, this); + var picker = image == vanilla ? vanillaPicker : overridePicker; + if (picker == null) + return; + boolean pickThisSide = pickPoint != null && !isOverDivider(pickPoint.x) && bounds.contains(pickPoint) + && (!"Split".equals(mode) || (pickPoint.x < dividerX()) == (image == vanilla)); + int hoveredFace = pickThisSide + ? picker.pick(new Point(pickPoint.x - bounds.x, pickPoint.y - bounds.y), bounds.width, bounds.height) + : -1; + if (colorRule != null || hoverColor != null || hoveredFace >= 0) + picker.highlight(g, bounds, colorRule, hoverColor, hoveredFace); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/OverrideProperties.java b/Tools/Dev/java/rs117/hd/dev/overrides/OverrideProperties.java new file mode 100644 index 0000000..ba09a8a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/OverrideProperties.java @@ -0,0 +1,1986 @@ +package rs117.hd.dev.overrides; + +import rs117.hd.dev.editor.EditorScrollPane; +import rs117.hd.dev.editor.HdContextMenu; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Image; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.function.Consumer; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.ScrollPaneConstants; +import net.runelite.api.Model; +import rs117.hd.config.SeasonalTheme; +import rs117.hd.dev.editor.BeforeAfterSwatch; +import rs117.hd.dev.editor.CacheModels; +import rs117.hd.dev.editor.ColorPicker; +import rs117.hd.dev.editor.EditorButton; +import rs117.hd.dev.editor.EditorPanels; +import rs117.hd.dev.editor.EditorSearch; +import rs117.hd.dev.editor.EditorSelect; +import rs117.hd.dev.editor.EditorText; +import rs117.hd.dev.editor.NumberField; +import rs117.hd.dev.editor.PreviewDropdown; +import rs117.hd.dev.editor.PropertySection; +import rs117.hd.dev.editor.PropertyRow; +import rs117.hd.dev.editor.SearchableIdDropdown; +import rs117.hd.dev.editor.SegmentedControl; +import rs117.hd.dev.editor.SwatchDropdown; +import rs117.hd.dev.editor.ToggleList; +import rs117.hd.dev.editor.WorkspaceStyle; +import rs117.hd.dev.editor.UvTypeDropdown; +import rs117.hd.dev.editor.DashedAddButton; +import rs117.hd.scene.areas.AABB; +import rs117.hd.scene.materials.Material; +import rs117.hd.scene.model_overrides.InheritTileColorType; +import rs117.hd.scene.model_overrides.ModelOverride; +import rs117.hd.scene.model_overrides.TzHaarRecolorType; +import rs117.hd.scene.model_overrides.UvType; +import rs117.hd.scene.model_overrides.WindDisplacement; +import rs117.hd.utils.ColorUtils; + +/** Right-side "Properties" panel for the Model Overrides editor tab: reads/writes every field of one {@link ModelOverride}. */ +final class OverrideProperties extends JPanel { + interface Context { + void colorToast(String message); + void highlightColors(ModelOverride.AhslPredicate rule, Integer hover); + void setWindPreview(boolean enabled); + List materials(); + int[] vanillaTexturePixels(int textureId); + List npcChoices(); + List objectChoices(); + List spotanimChoices(); + String nearbyObject(int id); + } + + private static final Color FORM_BACKGROUND = new Color(0x1F1F1F); + private static final Color HEADER_BORDER = new Color(0x1A1A1A); + + private final Context context; + private static final int MAX_VANILLA_PREVIEWS = 256; + private final java.util.Map vanillaTexturePreviews = new java.util.LinkedHashMap(32, .75f, true) { + @Override protected boolean removeEldestEntry(java.util.Map.Entry eldest) { + return size() > MAX_VANILLA_PREVIEWS; + } + }; + private final MaterialSwatch swatch = new MaterialSwatch(); + private final JLabel titleLabel; + private final JLabel targetLabel; + private final JTextField filterField; + private boolean filterActive; + private final JPanel sectionsPanel; + private final java.awt.CardLayout cards = new java.awt.CardLayout(); + private final JPanel pages = new JPanel(cards); + private final JPanel emptyContent = new JPanel(new GridBagLayout()); + private Runnable createOverride; + private final JScrollPane scroll; + private final java.util.Map expansion = new java.util.HashMap<>(); + private final List
sections = new ArrayList<>(); + + private ModelOverride override; + private ModelOverride baseline = new ModelOverride(); + private Model previewModel; + private List modelColors = List.of(); + private final JPanel noMatches = new JPanel(new GridBagLayout()); + private final JLabel noMatchesLabel = new JLabel(); + private ModelOverride openColorRule; + private ModelOverride expressionViewRule; + private Integer hoveredColor; + private Runnable stopColorPicking = () -> {}; + private boolean refreshing; + + private Runnable changeListener; + private Runnable copyJsonListener; + private Runnable pickColorListener; + private ModelOverride pendingColorRule; + private Runnable refreshColorRules; + private Section colorRulesSection; + + OverrideProperties(Context context) { + super(new BorderLayout()); + this.context = Objects.requireNonNull(context); + setOpaque(true); + setBackground(WorkspaceStyle.PANEL); + + titleLabel = EditorText.builder("").font(WorkspaceStyle.SEMIBOLD.deriveFont(13f)).color(new Color(0xEEEEEE)).build(); + targetLabel = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(10f)).color(new Color(0x7D7D7D)).build(); + + var titles = new JPanel(); + titles.setOpaque(false); + titles.setLayout(new BoxLayout(titles, BoxLayout.Y_AXIS)); + titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + targetLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + titles.add(titleLabel); + titles.add(targetLabel); + + var swatchWrap = EditorPanels.centered(swatch); + + var left = new JPanel(new BorderLayout(10, 0)); + left.setOpaque(false); + left.add(swatchWrap, BorderLayout.WEST); + var centeredTitles = new JPanel(new GridBagLayout()); + centeredTitles.setOpaque(false); + var titleCell = new java.awt.GridBagConstraints(); + titleCell.weightx = 1; + titleCell.fill = java.awt.GridBagConstraints.HORIZONTAL; + centeredTitles.add(titles, titleCell); + left.add(centeredTitles, BorderLayout.CENTER); + + var jsonButton = EditorButton.builder().style(WorkspaceStyle.Button.SECONDARY) + .text("JSON").icon("copy", 12).tooltip("Copy override JSON") + .onClick(() -> { if (copyJsonListener != null) copyJsonListener.run(); }).build(); + + var header = new JPanel(new BorderLayout(10, 0)); + header.setBackground(new Color(0x262626)); + header.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createMatteBorder(0, 0, 1, 0, HEADER_BORDER), + BorderFactory.createEmptyBorder(0, 12, 0, 12))); + header.setPreferredSize(new Dimension(0, 48)); + header.setMaximumSize(new Dimension(Integer.MAX_VALUE, 48)); + header.add(left, BorderLayout.CENTER); + var jsonSlot = EditorPanels.centered(jsonButton); + header.add(jsonSlot, BorderLayout.EAST); + + var search = EditorSearch.builder("Filter properties").background(new Color(0x1A1A1A)) + .fontSize(11f).gap(5).padding(7, 0).textInset(8).fieldHeight(26).onChange(this::setFilter).build(); + filterField = search.field(); + var filterWrap = new JPanel(new BorderLayout()); + filterWrap.setBackground(WorkspaceStyle.PANEL); + filterWrap.setBorder(BorderFactory.createEmptyBorder(6, 12, 6, 12)); + filterWrap.add(search); + + var top = new JPanel(new BorderLayout()); + top.setOpaque(false); + top.add(header, BorderLayout.NORTH); + top.add(filterWrap, BorderLayout.SOUTH); + + sectionsPanel = new SectionsPanel(); + sectionsPanel.setLayout(new BoxLayout(sectionsPanel, BoxLayout.Y_AXIS)); + sectionsPanel.setBackground(FORM_BACKGROUND); + + buildSections(); + for (Section section : sections) { + section.view.setAlignmentX(Component.LEFT_ALIGNMENT); + sectionsPanel.add(section.view); + } + + scroll = new EditorScrollPane(sectionsPanel, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, WorkspaceStyle.MENU)); + scroll.getViewport().setBackground(FORM_BACKGROUND); + + var editor = new JPanel(new BorderLayout()); + editor.add(top, BorderLayout.NORTH); + editor.add(scroll); + emptyContent.setBackground(FORM_BACKGROUND); + var emptyScroll = new EditorScrollPane(emptyContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + emptyScroll.setBorder(null); + emptyScroll.getVerticalScrollBar().setUnitIncrement(16); + pages.add(emptyScroll, "empty"); + pages.add(editor, "editor"); + add(pages); + setEmptyEntity(null, 0); + } + + private static final class SectionsPanel extends JPanel implements javax.swing.Scrollable { + @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } + @Override public int getScrollableUnitIncrement(java.awt.Rectangle visible, int orientation, int direction) { return 16; } + @Override public int getScrollableBlockIncrement(java.awt.Rectangle visible, int orientation, int direction) { + return Math.max(16, visible.height - 16); + } + @Override public boolean getScrollableTracksViewportWidth() { return true; } + @Override public boolean getScrollableTracksViewportHeight() { return false; } + } + + void onCreate(Runnable action) { createOverride = action; } + + void setEmptyEntity(CacheModels.Entry entity, int matches) { + emptyContent.removeAll(); + var column = new JPanel(new net.miginfocom.swing.MigLayout("insets 32 20, gap 0 14, wrap 1", "[grow,center]")); + column.setOpaque(false); + var icon = new JLabel(WorkspaceStyle.icon("override-cube", 20), javax.swing.SwingConstants.CENTER) { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(WorkspaceStyle.PANEL); + g.fillOval(0, 0, 43, 43); + g.setColor(new Color(0x333333)); + g.drawOval(0, 0, 43, 43); + g.dispose(); + super.paintComponent(graphics); + } + }; + column.add(icon, "w 44!, h 44!"); + String heading = entity == null ? "Nothing loaded" : matches == 0 + ? entity.displayName + " has no model overrides" : "No override selected"; + column.add(emptyText(heading, WorkspaceStyle.SEMIBOLD.deriveFont(14f), new Color(0xE6E6E6)), "growx"); + String kind = entity == null ? "" : entity.category == CacheModels.Category.NPCs ? "NPC" + : entity.category == CacheModels.Category.Objects ? "object" : "graphic"; + String message = entity == null ? "Pick an NPC, object or graphic in the Browser to see or create its overrides." + : matches == 0 ? "Create one to change how this " + kind + + " looks in 117 HD: material, UVs, colors and shadows. Targets are filled in from what is loaded." + : entity.displayName + " has " + matches + (matches == 1 ? " override." : " overrides.") + + " Select one in the list to edit it, or create another."; + column.add(emptyText(message, WorkspaceStyle.UI, WorkspaceStyle.DIM), "growx"); + if (entity != null) { + var target = new JPanel(new BorderLayout(8, 6)); + target.setBackground(new Color(0x1A1A1A)); + target.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(0x333333), 1, true), + BorderFactory.createEmptyBorder(10, 10, 10, 10))); + target.add(EditorText.builder("WILL TARGET").font(WorkspaceStyle.SEMIBOLD.deriveFont(10f)).color(WorkspaceStyle.DIM).build(), BorderLayout.NORTH); + boolean npc = entity.category == CacheModels.Category.NPCs; + boolean graphic = entity.category == CacheModels.Category.Graphics; + var label = new JLabel(npc ? "NPC ID" : graphic ? "Spotanim ID" : "Object ID", + WorkspaceStyle.badge(npc ? "N" : graphic ? "G" : "O", new Color(npc ? 0xC25B5B : graphic ? 0x9A6BC2 : 0x5B8AC2)), + javax.swing.SwingConstants.LEFT); + label.setFont(WorkspaceStyle.UI); + label.setForeground(WorkspaceStyle.DIM); + target.add(label, BorderLayout.WEST); + var value = EditorText.builder(entity.id + " · " + entity.displayName).font(WorkspaceStyle.MONO).build(); + value.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); + value.setToolTipText(value.getText()); + target.add(value); + if (graphic) + target.add(emptyText("You'll be asked whether to use it as a graphics object or a projectile.", + WorkspaceStyle.UI.deriveFont(11f), WorkspaceStyle.DIM), BorderLayout.SOUTH); + column.add(target, "growx"); + var createButton = EditorButton.builder().style(WorkspaceStyle.Button.PRIMARY) + .text(matches == 0 ? "Create override" : "Create another override").icon("plus", 11) + .onClick(() -> { if (createOverride != null) createOverride.run(); }).build(); + createButton.setFont(WorkspaceStyle.SEMIBOLD); + createButton.setBorder(BorderFactory.createEmptyBorder(0, 16, 0, 16)); + column.add(createButton, "h 30!"); + column.add(emptyText("Targets can be changed after creating.", WorkspaceStyle.UI.deriveFont(11f), new Color(0x6F6F6F)), "growx"); + } + var cell = new java.awt.GridBagConstraints(); + cell.weightx = 1; + cell.fill = java.awt.GridBagConstraints.HORIZONTAL; + var centered = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, fillx", "[grow][0:340:340,fill][grow]")); + centered.setOpaque(false); + centered.add(column, "cell 1 0"); + emptyContent.add(centered, cell); + emptyContent.revalidate(); + emptyContent.repaint(); + } + + private static JLabel emptyText(String text, Font font, Color color) { + var label = new JLabel() { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + var layout = new java.awt.font.LineBreakMeasurer(attributedText().getIterator(), g.getFontRenderContext()); + float y = 0; + g.setColor(getForeground()); + while (layout.getPosition() < text.length()) { + var line = layout.nextLayout(Math.max(1, getWidth())); + y += line.getAscent(); + line.draw(g, (getWidth() - line.getAdvance()) / 2, y); + y += line.getDescent() + line.getLeading() + 4; + } + g.dispose(); + } + + private java.text.AttributedString attributedText() { + var value = new java.text.AttributedString(text); + value.addAttribute(java.awt.font.TextAttribute.FONT, font); + return value; + } + + @Override public Dimension getPreferredSize() { + var metrics = getFontMetrics(font); + int width = Math.min(300, metrics.stringWidth(text)); + var layout = new java.awt.font.LineBreakMeasurer(attributedText().getIterator(), metrics.getFontRenderContext()); + int lines = 0; + while (layout.getPosition() < text.length()) { + layout.nextLayout(Math.max(1, width)); + lines++; + } + return new Dimension(width, lines * (metrics.getHeight() + 4) - 4); + } + }; + label.setFont(font); + label.setForeground(color); + label.getAccessibleContext().setAccessibleName(text); + return label; + } + + // ----- public API ----- + + void setOverride(ModelOverride override, String targetSummary, Model previewModel) { + boolean selectionChanged = this.override != override; + this.override = override; + cards.show(pages, override == null ? "empty" : "editor"); + if (override == null) { + openColorRule = expressionViewRule = pendingColorRule = null; + hoveredColor = null; + updateColorHighlight(); + return; + } + if (selectionChanged) { + openColorRule = expressionViewRule = null; + pendingColorRule = null; + stopColorPicking.run(); + } + if (selectionChanged) + scroll.getVerticalScrollBar().setValue(0); + updateModelColors(previewModel); + this.baseline = new ModelOverride(); + this.pendingColorRule = null; + + titleLabel.setText(override.description == null ? "" : override.description); + targetLabel.setText(targetSummary == null ? "" : targetSummary); + swatch.setColor(materialColor(override.material)); + + withRefreshGuard(() -> { + for (Section section : sections) + section.refresh.run(); + }); + } + + void setPreviewModel(Model model) { + if (previewModel == model) + return; + updateModelColors(model); + if (override != null) + withRefreshGuard(() -> { + for (Section section : sections) + section.refresh.run(); + }); + } + + private void updateModelColors(Model model) { + if (previewModel == model) + return; + previewModel = model; + modelColors = model == null ? List.of() : ModelColorPalette.distinctColors(model); + } + + void setFilter(String query) { + String q = normalizeSearch(query); + // Most fireChange() calls happen while editing a field with no active search filter; skip the + // full section/field tree walk and panel revalidate when there's nothing to (un)filter. + if (q.isEmpty() && !filterActive) + return; + filterActive = !q.isEmpty(); + boolean anyMatch = false; + for (Section section : sections) { + if (q.isEmpty()) { + Boolean previous = expansion.remove(section.view); + if (previous != null) + section.view.setExpanded(previous); + section.view.setVisible(true); + filterFields(section.view.fields(), "", true); + } else { + expansion.putIfAbsent(section.view, section.view.isExpanded()); + boolean wholeSection = normalizeSearch(section.view.title()).contains(q); + boolean fieldsMatch = filterFields(section.view.fields(), q, wholeSection); + boolean match = wholeSection || fieldsMatch || section.labels.stream() + .anyMatch(label -> normalizeSearch(label).contains(q)); + section.view.setVisible(match); + anyMatch |= match; + if (match) + section.view.setExpanded(true); + } + } + if (noMatches.getParent() == null) { + noMatches.setOpaque(false); + noMatches.setAlignmentX(LEFT_ALIGNMENT); + noMatches.setPreferredSize(new Dimension(0, 144)); + var message = new JPanel(new BorderLayout(0, 8)); + message.setOpaque(false); + noMatchesLabel.setForeground(new Color(0x9A9A9A)); + noMatchesLabel.setHorizontalAlignment(JLabel.CENTER); + message.add(noMatchesLabel); + message.add(EditorButton.builder().text("Clear filter").onClick(() -> filterField.setText("")).build(), BorderLayout.SOUTH); + noMatches.add(message); + sectionsPanel.add(noMatches); + } + noMatchesLabel.setText("No properties match “" + query + "”."); + noMatches.setVisible(!q.isEmpty() && !anyMatch); + sectionsPanel.revalidate(); + sectionsPanel.repaint(); + } + + private static String normalizeSearch(String text) { + return text == null ? "" : text.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + } + + private static boolean filterFields(JComponent body, String query, boolean wholeSection) { + boolean found = false; + for (Component child : body.getComponents()) { + if (child instanceof JPanel) { + var panel = (JPanel) child; + String key = panel.getName(); + if (panel instanceof rs117.hd.dev.editor.ToggleList) { + found |= ((rs117.hd.dev.editor.ToggleList) panel).filter(query, wholeSection); + continue; + } + if (key != null && key.startsWith("field:")) { + boolean match = wholeSection || normalizeSearch(key.substring(6)).contains(query); + panel.setVisible(match); + found |= match; + } else { + found |= filterFields(panel, query, wholeSection); + } + } + } + return found; + } + + void onChange(Runnable listener) { this.changeListener = listener; } + + void onCopyJson(Runnable listener) { this.copyJsonListener = listener; } + + void onPickColorRequested(Runnable listener) { this.pickColorListener = listener; } + + void onColorPickCancelled(Runnable listener) { stopColorPicking = listener; } + + void cancelColorPicking() { + if (pendingColorRule == null) + return; + pendingColorRule = null; + stopColorPicking.run(); + refreshColorRules.run(); + } + + private void chooseColor(ModelOverride rule) { + pendingColorRule = rule; + refreshColorRules.run(); + if (pickColorListener != null) + pickColorListener.run(); + } + + void colorPicked(int ahsl) { + var rule = pendingColorRule == null ? new ModelOverride() : pendingColorRule; + String before = expressionText(rule); + int hsl = ahsl & 65535; + if (ModelOverrideFields.colorPredicate(rule, ruleColors(rule)).test(ahsl)) { + context.colorToast("This rule already matches " + hslLabel(hsl)); + cancelColorPicking(); + return; + } + boolean newRule = before.isBlank(); + String exact = ColorExpression.exact(hsl); + rule.colors(new JsonPrimitive(newRule ? exact : + (ColorExpression.groups(before) == null ? "(" + before + ")" : before) + " || " + exact)); + if (newRule) + rule.setHue(hsl >> 10).setSaturation(hsl >> 7 & 7).setLightness(hsl & 127); + context.colorToast((newRule ? "New color override for " : "Added color ") + hslLabel(hsl)); + var current = override.colorOverrides; + var rules = current == null ? new ArrayList() : new ArrayList<>(java.util.Arrays.asList(current)); + if (!rules.contains(rule)) { + rules.add(rule); + override.colorOverrides(rules.toArray(ModelOverride[]::new)); + } + openColorRule = rule; + pendingColorRule = null; + stopColorPicking.run(); + onFieldEdited(refreshColorRules); + } + + private static String hslLabel(int hsl) { + return (hsl >> 10 & 63) + " · " + (hsl >> 7 & 7) + " · " + (hsl & 127); + } + + private static String expressionText(ModelOverride rule) { + return ColorExpression.text(ModelOverrideFields.get(rule, "colors", JsonElement.class)); + } + + private void updateColorHighlight() { + context.highlightColors(openColorRule == null ? null : ModelOverrideFields.colorPredicate(openColorRule, ruleColors(openColorRule)), hoveredColor); + } + + private static JsonArray ruleColors(ModelOverride rule) { + var colors = ModelOverrideFields.get(rule, "colors", JsonElement.class); + if (colors != null && colors.isJsonArray()) + return colors.getAsJsonArray().deepCopy(); + var values = new JsonArray(); + if (colors != null) + values.add(colors); + return values; + } + + // ----- shared helpers ----- + + private void withRefreshGuard(Runnable body) { + boolean previous = refreshing; + refreshing = true; + try { + body.run(); + } finally { + refreshing = previous; + } + } + + private void onFieldEdited(Runnable refresh) { + if (refreshing) + return; + refresh.run(); + fireChange(); + } + + private void fireChange() { + if (override != null) { + titleLabel.setText(override.description); + swatch.setColor(materialColor(override.material)); + } + setFilter(filterField.getText()); + if (changeListener != null) + changeListener.run(); + } + + private static int count(boolean... flags) { + int n = 0; + for (boolean flag : flags) + if (flag) + n++; + return n; + } + + private static boolean arrayChanged(Object[] a, Object[] b) { + int la = a == null ? -1 : a.length; + int lb = b == null ? -1 : b.length; + return la != lb; + } + + private static boolean floatArrayChanged(float[] a, float[] b) { + int la = a == null ? -1 : a.length; + int lb = b == null ? -1 : b.length; + return la != lb; + } + + + private static Color materialColor(Material material) { + if (material == null || material.name == null) + return WorkspaceStyle.BORDER; + int hash = material.name.hashCode(); + float hue = (hash & 0xFFFF) / 65535f; + return Color.getHSBColor(hue, 0.45f, 0.65f); + } + + private static void copyFieldText(String value) { + java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents( + new java.awt.datatransfer.StringSelection(value), null); + } + + static JPanel fieldRow(String label, JComponent control) { + return new PropertyRow(label, control, PropertyRow.Layout.SIMPLE); + } + + private static void setFieldChanged(JPanel row, boolean changed) { + ((PropertyRow) row).setChanged(changed); + } + + private static JLabel infoLabel(String text) { + return EditorText.builder(text).font(WorkspaceStyle.UI.deriveFont(11f)).color(WorkspaceStyle.DIM).build(); + } + + private static Component spacer() { + return Box.createVerticalStrut(8); + } + + private static JTextField plainTextField() { + var field = new JTextField(); + field.setFont(WorkspaceStyle.MONO.deriveFont(11f)); + field.setBackground(WorkspaceStyle.INPUT); + field.setForeground(WorkspaceStyle.TEXT); + field.setCaretColor(WorkspaceStyle.TEXT); + field.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createLineBorder(WorkspaceStyle.BORDER), BorderFactory.createEmptyBorder(3, 6, 3, 6))); + field.setColumns(16); + return field; + } + + private static void setTextIfChanged(JTextField field, String text) { + if (!Objects.equals(field.getText(), text)) + field.setText(text); + } + + private static void commitOnEdit(JTextField field, Consumer commit) { + field.addActionListener(e -> commit.accept(field.getText())); + field.addFocusListener(new FocusAdapter() { + @Override public void focusLost(FocusEvent event) { commit.accept(field.getText()); } + }); + } + + /** Small 14x14 rounded color chip used in the header. */ + private static final class MaterialSwatch extends JComponent { + private Color color = WorkspaceStyle.BORDER; + + MaterialSwatch() { + var size = new Dimension(14, 14); + setPreferredSize(size); + setMinimumSize(size); + setMaximumSize(size); + setOpaque(false); + } + + void setColor(Color color) { + this.color = color; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(color); + g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 3, 3); + g.setColor(WorkspaceStyle.BORDER); + g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 3, 3); + g.dispose(); + } + } + + private static final class Section { + final PropertySection view; + final Runnable refresh; + final List labels; + + Section(PropertySection view, Runnable refresh, List labels) { + this.view = view; + this.refresh = refresh; + this.labels = labels; + } + } + + // ----- sections ----- + + private void buildSections() { + sections.add(buildGeneralSection()); + sections.add(buildTargetsSection()); + sections.add(buildMaterialSection()); + sections.add(buildUvsSection()); + sections.add(buildNormalsSection()); + sections.add(buildShadowsSection()); + sections.add(buildColorSection()); + sections.add(colorRulesSection); + sections.add(buildMaterialSwapsSection()); + sections.add(buildTerrainSection()); + sections.add(buildWindSection()); + } + + private Section buildGeneralSection() { + var content = EditorPanels.stack(); + + JTextField descriptionField = plainTextField(); + descriptionField.setFont(WorkspaceStyle.UI); + descriptionField.setPreferredSize(new Dimension(descriptionField.getPreferredSize().width, 24)); + List themeNames = new ArrayList<>(); + themeNames.add("(none)"); + for (SeasonalTheme theme : SeasonalTheme.values()) + if (theme != SeasonalTheme.AUTOMATIC) + themeNames.add(theme.name()); + SegmentedControl seasonalControl = SegmentedControl.builder(themeNames).values().build(); + SegmentedControl rotateControl = SegmentedControl.builder(List.of(0, 90, 180, 270)).values().label(r -> r + "°").build(); + NumberField heightOffsetField = NumberField.builder().build(); + NumberField depthBiasField = NumberField.builder().value(-1.0).min(-1.0).build(); + + var descriptionFieldRow = fieldRow("Description", descriptionField); + content.add(descriptionFieldRow); + HdContextMenu.install(descriptionField, point -> { + Point at = point == null ? new Point(0, descriptionField.getHeight()) : point; + String current = descriptionField.getText(); + var menu = new HdContextMenu("#", new Color(0x5A5A5A), "description · " + current); + if (Objects.equals(current, baseline.description)) + menu.disabled("Reset to default", "reset", "Description is already the default"); + else + menu.item("Reset to default", "reset", "", () -> { + descriptionField.setText(baseline.description); + descriptionField.postActionEvent(); + }); + menu.separator().item("Copy value", "copy", "", () -> copyFieldText(current)) + .item("Copy JSON key", "key", "", () -> copyFieldText("description")) + .show(descriptionField, at.x, at.y); + }); + var seasonalControlRow = fieldRow("Seasonal theme", seasonalControl); + content.add(seasonalControlRow); + var rotateControlRow = fieldRow("Rotate", rotateControl); + content.add(rotateControlRow); + var heightOffsetFieldRow = fieldRow("Height offset", heightOffsetField); + content.add(heightOffsetFieldRow); + var depthBiasFieldRow = fieldRow("Depth bias", depthBiasField); + content.add(depthBiasFieldRow); + + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + + PropertySection view = new PropertySection("General", content); + Runnable[] self = new Runnable[1]; + + commitOnEdit(descriptionField, text -> { + if (override != null && !Objects.equals(text, override.description)) { + override.description = text; + onFieldEdited(self[0]); + } + }); + seasonalControl.onChange(value -> { + override.seasonalTheme = "(none)".equals(value) ? null : SeasonalTheme.valueOf(value); + onFieldEdited(self[0]); + }); + rotateControl.onChange(value -> { override.rotate = value; onFieldEdited(self[0]); }); + heightOffsetField.onChange(value -> { override.heightOffset = value.intValue(); onFieldEdited(self[0]); }); + depthBiasField.onChange(value -> { override.depthBias = value.intValue(); onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + setTextIfChanged(descriptionField, override.description == null ? "" : override.description); + seasonalControl.setSelected(override.seasonalTheme == null || override.seasonalTheme == SeasonalTheme.AUTOMATIC + ? "(none)" : override.seasonalTheme.name()); + rotateControl.setSelected(override.rotate); + heightOffsetField.setValue((double) override.heightOffset); + depthBiasField.setValue((double) override.depthBias); + + setFieldChanged(descriptionFieldRow, !Objects.equals(override.description, baseline.description)); + setFieldChanged(seasonalControlRow, override.seasonalTheme != baseline.seasonalTheme); + setFieldChanged(rotateControlRow, override.rotate != baseline.rotate); + setFieldChanged(heightOffsetFieldRow, override.heightOffset != baseline.heightOffset); + setFieldChanged(depthBiasFieldRow, override.depthBias != baseline.depthBias); + boolean hideAsWaterEffect = ModelOverrideFields.getBoolean(override, "hideAsWaterEffect"); + boolean baseHideAsWaterEffect = ModelOverrideFields.getBoolean(baseline, "hideAsWaterEffect"); + ToggleList.builder() + .add("Hide model", override.hide, override.hide != baseline.hide, + v -> { override.hide = v; onFieldEdited(self[0]); }) + .add("Hide as water effect", hideAsWaterEffect, hideAsWaterEffect != baseHideAsWaterEffect, + v -> { override.hideAsWaterEffect(v); onFieldEdited(self[0]); }) + .add("No priority sorting", override.disablePrioritySorting, + override.disablePrioritySorting != baseline.disablePrioritySorting, + v -> { override.disablePrioritySorting = v; onFieldEdited(self[0]); }) + .add("No detail culling", override.disableDetailCulling, + override.disableDetailCulling != baseline.disableDetailCulling, + v -> { override.disableDetailCulling = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + !Objects.equals(override.description, baseline.description), + override.seasonalTheme != baseline.seasonalTheme, + override.rotate != baseline.rotate, + override.heightOffset != baseline.heightOffset, + override.depthBias != baseline.depthBias, + override.hide != baseline.hide, + hideAsWaterEffect != baseHideAsWaterEffect, + override.disablePrioritySorting != baseline.disablePrioritySorting, + override.disableDetailCulling != baseline.disableDetailCulling + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.description = baseline.description; + override.seasonalTheme = baseline.seasonalTheme; + override.rotate = baseline.rotate; + override.heightOffset = baseline.heightOffset; + override.depthBias = baseline.depthBias; + override.hide = baseline.hide; + override.hideAsWaterEffect(ModelOverrideFields.getBoolean(baseline, "hideAsWaterEffect")); + override.disablePrioritySorting = baseline.disablePrioritySorting; + override.disableDetailCulling = baseline.disableDetailCulling; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "Description", "Seasonal theme", "Rotate", "Height offset", "Depth bias", + "Hide", "Hide as water effect", "Disable priority sorting", "Disable detail culling")); + } + + private Section buildTargetsSection() { + var content = EditorPanels.stack(); + + SearchableIdDropdown npcDropdown = SearchableIdDropdown.builder(context::npcChoices) + .title("NPC IDs").build(); + SearchableIdDropdown objectDropdown = SearchableIdDropdown.builder(context::objectChoices) + .title("Object IDs").nearby(context::nearbyObject).build(); + SearchableIdDropdown projectileDropdown = SearchableIdDropdown.builder(context::spotanimChoices) + .title("Projectile IDs").build(); + SearchableIdDropdown graphicsObjectDropdown = SearchableIdDropdown.builder(context::spotanimChoices) + .title("Graphics object IDs").build(); + + Runnable[] self = new Runnable[1]; + var areasList = new AreaListField("Areas", false, areas -> { override.areas = areas; onFieldEdited(self[0]); }); + var hiddenAreasList = new AreaListField("Hide in areas", true, areas -> { override.hideInAreas = areas; onFieldEdited(self[0]); }); + + content.add(new PropertyRow("NPC IDs", npcDropdown, PropertyRow.Layout.WIDE)); + content.add(new PropertyRow("Object IDs", objectDropdown, PropertyRow.Layout.WIDE)); + content.add(new PropertyRow("Projectile IDs", projectileDropdown, PropertyRow.Layout.WIDE)); + content.add(new PropertyRow("Graphics object IDs", graphicsObjectDropdown, PropertyRow.Layout.WIDE)); + content.add(areasList); + content.add(hiddenAreasList); + + PropertySection view = new PropertySection("Targets", content); + + npcDropdown.onChange(ids -> { override.npcIds = new LinkedHashSet<>(ids); onFieldEdited(self[0]); }); + objectDropdown.onChange(ids -> { override.objectIds = new LinkedHashSet<>(ids); onFieldEdited(self[0]); }); + projectileDropdown.onChange(ids -> { override.projectileIds = new LinkedHashSet<>(ids); onFieldEdited(self[0]); }); + graphicsObjectDropdown.onChange(ids -> { override.graphicsObjectIds = new LinkedHashSet<>(ids); onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + npcDropdown.setSelected(override.npcIds == null ? Collections.emptySet() : override.npcIds); + objectDropdown.setSelected(override.objectIds == null ? Collections.emptySet() : override.objectIds); + projectileDropdown.setSelected(override.projectileIds == null ? Collections.emptySet() : override.projectileIds); + graphicsObjectDropdown.setSelected(override.graphicsObjectIds == null ? Collections.emptySet() : override.graphicsObjectIds); + areasList.setAreas(override.areas); + hiddenAreasList.setAreas(override.hideInAreas); + + view.setChangedCount(count( + !Objects.equals(override.npcIds, baseline.npcIds), + !Objects.equals(override.objectIds, baseline.objectIds), + !Objects.equals(override.projectileIds, baseline.projectileIds), + !Objects.equals(override.graphicsObjectIds, baseline.graphicsObjectIds), + arrayChanged(override.areas, baseline.areas), + arrayChanged(override.hideInAreas, baseline.hideInAreas) + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.npcIds = baseline.npcIds; + override.objectIds = baseline.objectIds; + override.projectileIds = baseline.projectileIds; + override.graphicsObjectIds = baseline.graphicsObjectIds; + override.areas = baseline.areas; + override.hideInAreas = baseline.hideInAreas; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "NPC IDs", "Object IDs", "Projectile IDs", "Graphics object IDs", "Areas", "Hide in areas")); + } + + private Section buildMaterialSection() { + var content = EditorPanels.stack(); + + var picker = materialPicker(false, null); + var materialDropdown = picker.build(); + var textureMaterialDropdown = picker.build(); + + content.add(fieldRow("Material", materialDropdown)); + content.add(fieldRow("Texture material", textureMaterialDropdown)); + + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + + PropertySection view = new PropertySection("Material", content); + Runnable[] self = new Runnable[1]; + + materialDropdown.onChange(material -> { override.material = material; onFieldEdited(self[0]); }); + textureMaterialDropdown.onChange(material -> { override.textureMaterial = material; onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + materialDropdown.setValue(override.material); + textureMaterialDropdown.setValue(override.textureMaterial); + + ToggleList.builder() + .add("Force material changes", override.forceMaterialChanges, + override.forceMaterialChanges != baseline.forceMaterialChanges, + v -> { override.forceMaterialChanges = v; onFieldEdited(self[0]); }) + .add("Undo vanilla shading", override.undoVanillaShading, + override.undoVanillaShading != baseline.undoVanillaShading, + v -> { override.undoVanillaShading = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + !Objects.equals(override.material, baseline.material), + !Objects.equals(override.textureMaterial, baseline.textureMaterial), + override.forceMaterialChanges != baseline.forceMaterialChanges, + override.undoVanillaShading != baseline.undoVanillaShading + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.material = baseline.material; + override.textureMaterial = baseline.textureMaterial; + override.forceMaterialChanges = baseline.forceMaterialChanges; + override.undoVanillaShading = baseline.undoVanillaShading; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of("Material", "Texture material", "Force material changes", "Undo vanilla shading")); + } + + private Section buildUvsSection() { + var content = EditorPanels.stack(); + + var uvTypeCombo = new UvTypeDropdown(UvType.VANILLA, false); + NumberField uvScaleField = NumberField.builder().value(1.0).step(0.05).min(0.01).build(); + NumberField uvOrientationField = NumberField.builder().step(64).min(0.0).max(2047.0).unit("jau").build(); + NumberField uvOrientationXField = NumberField.builder().step(64).min(0.0).max(2047.0).unit("jau").build(); + NumberField uvOrientationYField = NumberField.builder().step(64).min(0.0).max(2047.0).unit("jau").build(); + NumberField uvOrientationZField = NumberField.builder().step(64).min(0.0).max(2047.0).unit("jau").build(); + JLabel uvsLabel = infoLabel("No custom UVs"); + + content.add(fieldRow("UV type", uvTypeCombo)); + content.add(fieldRow("UV scale", uvScaleField)); + content.add(fieldRow("UV orientation", uvOrientationField)); + content.add(fieldRow("UV orientation X", uvOrientationXField)); + content.add(fieldRow("UV orientation Y", uvOrientationYField)); + content.add(fieldRow("UV orientation Z", uvOrientationZField)); + + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + content.add(fieldRow("Custom UVs", uvsLabel)); + + PropertySection view = new PropertySection("UVs", content); + Runnable[] self = new Runnable[1]; + + uvTypeCombo.onChange(value -> { + override.uvType = value; + onFieldEdited(self[0]); + }); + uvScaleField.onChange(v -> { override.uvScale = v.floatValue(); onFieldEdited(self[0]); }); + uvOrientationField.onChange(v -> { override.uvOrientation = v.intValue(); onFieldEdited(self[0]); }); + uvOrientationXField.onChange(v -> { override.uvOrientationX = v.intValue(); onFieldEdited(self[0]); }); + uvOrientationYField.onChange(v -> { override.uvOrientationY = v.intValue(); onFieldEdited(self[0]); }); + uvOrientationZField.onChange(v -> { override.uvOrientationZ = v.intValue(); onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + uvTypeCombo.setValue(override.uvType); + uvScaleField.setValue((double) override.uvScale); + uvOrientationField.setValue((double) override.uvOrientation); + uvOrientationXField.setValue((double) override.uvOrientationX); + uvOrientationYField.setValue((double) override.uvOrientationY); + uvOrientationZField.setValue((double) override.uvOrientationZ); + uvsLabel.setText(override.uvs == null ? "No custom UVs" : "Custom UVs set (" + override.uvs.length + ")"); + + ToggleList.builder() + .add("Retain vanilla UVs", override.retainVanillaUvs, + override.retainVanillaUvs != baseline.retainVanillaUvs, + v -> { override.retainVanillaUvs = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + override.uvType != baseline.uvType, + override.uvScale != baseline.uvScale, + override.uvOrientation != baseline.uvOrientation, + override.uvOrientationX != baseline.uvOrientationX, + override.uvOrientationY != baseline.uvOrientationY, + override.uvOrientationZ != baseline.uvOrientationZ, + override.retainVanillaUvs != baseline.retainVanillaUvs, + floatArrayChanged(override.uvs, baseline.uvs) + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.uvType = baseline.uvType; + override.uvScale = baseline.uvScale; + override.uvOrientation = baseline.uvOrientation; + override.uvOrientationX = baseline.uvOrientationX; + override.uvOrientationY = baseline.uvOrientationY; + override.uvOrientationZ = baseline.uvOrientationZ; + override.retainVanillaUvs = baseline.retainVanillaUvs; + override.uvs = baseline.uvs; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "UV type", "UV scale", "UV orientation", "UV orientation X", "UV orientation Y", "UV orientation Z", + "Retain vanilla UVs", "Custom UVs")); + } + + private Section buildNormalsSection() { + var content = EditorPanels.stack(); + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + + PropertySection view = new PropertySection("Normals & faces", content); + Runnable[] self = new Runnable[1]; + + Runnable refresh = () -> withRefreshGuard(() -> { + ToggleList.builder() + .add("Flat normals", override.flatNormals, + override.flatNormals != baseline.flatNormals, + v -> { override.flatNormals = v; onFieldEdited(self[0]); }) + .add("Upwards normals", override.upwardsNormals, + override.upwardsNormals != baseline.upwardsNormals, + v -> { override.upwardsNormals = v; onFieldEdited(self[0]); }) + .add("Double sided faces", override.doubleSidedFaces, + override.doubleSidedFaces != baseline.doubleSidedFaces, + v -> { override.doubleSidedFaces = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + override.flatNormals != baseline.flatNormals, + override.upwardsNormals != baseline.upwardsNormals, + override.doubleSidedFaces != baseline.doubleSidedFaces + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.flatNormals = baseline.flatNormals; + override.upwardsNormals = baseline.upwardsNormals; + override.doubleSidedFaces = baseline.doubleSidedFaces; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of("Flat normals", "Upwards normals", "Double sided faces")); + } + + private Section buildShadowsSection() { + var content = EditorPanels.stack(); + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + NumberField thresholdField = NumberField.builder().step(0.05).min(0.0).max(1.0).build(); + content.add(fieldRow("Shadow opacity threshold", thresholdField)); + + PropertySection view = new PropertySection("Shadows", content); + Runnable[] self = new Runnable[1]; + thresholdField.onChange(v -> { override.shadowOpacityThreshold = v.floatValue(); onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + thresholdField.setValue((double) override.shadowOpacityThreshold); + ToggleList.builder() + .add("Cast shadows", override.castShadows, + override.castShadows != baseline.castShadows, + v -> { override.castShadows = v; onFieldEdited(self[0]); }) + .add("Receive shadows", override.receiveShadows, + override.receiveShadows != baseline.receiveShadows, + v -> { override.receiveShadows = v; onFieldEdited(self[0]); }) + .add("Hide vanilla shadows", override.hideVanillaShadows, + override.hideVanillaShadows != baseline.hideVanillaShadows, + v -> { override.hideVanillaShadows = v; onFieldEdited(self[0]); }) + .add("Retain vanilla shadows in PVM", override.retainVanillaShadowsInPvm, + override.retainVanillaShadowsInPvm != baseline.retainVanillaShadowsInPvm, + v -> { override.retainVanillaShadowsInPvm = v; onFieldEdited(self[0]); }) + .add("Hide HD shadows in PVM", override.hideHdShadowsInPvm, + override.hideHdShadowsInPvm != baseline.hideHdShadowsInPvm, + v -> { override.hideHdShadowsInPvm = v; onFieldEdited(self[0]); }) + .add("Shadow normal bias", override.shadowNormalBias, + override.shadowNormalBias != baseline.shadowNormalBias, + v -> { override.shadowNormalBias = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + override.castShadows != baseline.castShadows, + override.receiveShadows != baseline.receiveShadows, + override.hideVanillaShadows != baseline.hideVanillaShadows, + override.retainVanillaShadowsInPvm != baseline.retainVanillaShadowsInPvm, + override.hideHdShadowsInPvm != baseline.hideHdShadowsInPvm, + override.shadowNormalBias != baseline.shadowNormalBias, + override.shadowOpacityThreshold != baseline.shadowOpacityThreshold + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.castShadows = baseline.castShadows; + override.receiveShadows = baseline.receiveShadows; + override.hideVanillaShadows = baseline.hideVanillaShadows; + override.retainVanillaShadowsInPvm = baseline.retainVanillaShadowsInPvm; + override.hideHdShadowsInPvm = baseline.hideHdShadowsInPvm; + override.shadowNormalBias = baseline.shadowNormalBias; + override.shadowOpacityThreshold = baseline.shadowOpacityThreshold; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "Cast shadows", "Receive shadows", "Hide vanilla shadows", "Retain vanilla shadows in PVM", + "Hide HD shadows in PVM", "Shadow normal bias", "Shadow opacity threshold")); + } + + private Section buildTerrainSection() { + var content = EditorPanels.stack(); + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + NumberField thresholdField = NumberField.builder().value(0.125).step(0.005).min(0.0).build(); + content.add(fieldRow("Vertex snap threshold", thresholdField)); + + PropertySection view = new PropertySection("Terrain", content); + view.setExpanded(false); + Runnable[] self = new Runnable[1]; + thresholdField.onChange(v -> { override.terrainVertexSnapThreshold = v.floatValue(); onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + thresholdField.setValue((double) override.terrainVertexSnapThreshold); + ToggleList.builder() + .add("Terrain vertex snap", override.terrainVertexSnap, + override.terrainVertexSnap != baseline.terrainVertexSnap, + v -> { override.terrainVertexSnap = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + override.terrainVertexSnap != baseline.terrainVertexSnap, + override.terrainVertexSnapThreshold != baseline.terrainVertexSnapThreshold + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.terrainVertexSnap = baseline.terrainVertexSnap; + override.terrainVertexSnapThreshold = baseline.terrainVertexSnapThreshold; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of("Terrain vertex snap", "Vertex snap threshold")); + } + + private Section buildWindSection() { + var content = EditorPanels.stack(); + var modeControl = new WindModeDropdown(); + var modeRow = fieldRow("Mode", modeControl); + var modifierField = new WindStrength(); + var preview = EditorButton.builder().style(WorkspaceStyle.Button.TRIGGER).text("Preview wind") + .tooltip("Animate the override preview. Move across the grid to simulate a player in Object sway mode.") + .onToggle(context::setWindPreview).buildToggle(false); + content.add(fieldRow("Viewport", preview)); + content.add(modeRow); + content.add(modifierField); + var toggles = ToggleList.builder().build(); + toggles.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(toggles); + + PropertySection view = new PropertySection("Wind", content); + view.setExpanded(false); + Runnable[] self = new Runnable[1]; + modeControl.onChange(v -> { override.windDisplacementMode = v; onFieldEdited(self[0]); }); + modifierField.onChange(v -> { override.windDisplacementModifier = v; onFieldEdited(self[0]); }); + + Runnable refresh = () -> withRefreshGuard(() -> { + modeControl.setSelected(override.windDisplacementMode == null ? WindDisplacement.DISABLED : override.windDisplacementMode); + boolean disabled = modeControl.getSelected() == WindDisplacement.DISABLED; + setFieldChanged(modeRow, override.windDisplacementMode != baseline.windDisplacementMode); + modifierField.update(override.windDisplacementModifier, disabled, + override.windDisplacementModifier != baseline.windDisplacementModifier); + view.setInactiveNote(disabled ? "Wind is disabled" : null); + ToggleList.builder() + .add("Invert strength (sway more at the base)", override.invertDisplacementStrength, + override.invertDisplacementStrength != baseline.invertDisplacementStrength, + v -> { override.invertDisplacementStrength = v; onFieldEdited(self[0]); }) + .update(toggles); + + view.setChangedCount(count( + override.windDisplacementMode != baseline.windDisplacementMode, + override.windDisplacementModifier != baseline.windDisplacementModifier, + override.invertDisplacementStrength != baseline.invertDisplacementStrength + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.windDisplacementMode = baseline.windDisplacementMode; + override.windDisplacementModifier = baseline.windDisplacementModifier; + override.invertDisplacementStrength = baseline.invertDisplacementStrength; + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "Mode", "Strength", "Invert strength (sway more at the base)")); + } + + private Section buildColorSection() { + var content = EditorPanels.stack(); + + var paletteHolder = new JPanel(); + paletteHolder.setLayout(new BoxLayout(paletteHolder, BoxLayout.Y_AXIS)); + paletteHolder.setOpaque(false); + paletteHolder.setAlignmentX(Component.LEFT_ALIGNMENT); + + var rulesHolder = new JPanel(); + rulesHolder.setLayout(new BoxLayout(rulesHolder, BoxLayout.Y_AXIS)); + rulesHolder.setOpaque(false); + rulesHolder.setAlignmentX(Component.LEFT_ALIGNMENT); + + JButton newRuleButton = DashedAddButton.create("Add color override"); + newRuleButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + newRuleButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + newRuleButton.setAlignmentX(Component.LEFT_ALIGNMENT); + newRuleButton.setBorderPainted(true); + newRuleButton.setBorder(BorderFactory.createDashedBorder(new Color(0x444444), 3, 3)); + + SegmentedControl tzControl = SegmentedControl.builder(List.of(TzHaarRecolorType.values())) + .values().label(Enum::name).selected(TzHaarRecolorType.NONE).build(); + SegmentedControl inheritControl = SegmentedControl.builder(List.of(InheritTileColorType.values())) + .values().label(Enum::name).selected(InheritTileColorType.NONE).build(); + + var mode = SegmentedControl.builder(List.of("Set", "Shift", "Min", "Max")).build(); + var sliders = new JPanel(new GridLayout(4, 1, 0, 2)); + sliders.setOpaque(false); + var sample = new BeforeAfterSwatch(36, BeforeAfterSwatch.Split.HORIZONTAL, Color.GRAY, Color.GRAY); + sample.setToolTipText("Model color before and after"); + var sliderPanel = new JPanel(new BorderLayout(8, 0)); + sliderPanel.setOpaque(false); + var picker = EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("eyedropper", 12) + .tooltip("Pick the whole-model color").build(); + var swatchColumn = EditorPanels.stack(); + swatchColumn.add(sample); + swatchColumn.add(picker); + var swatchSlot = EditorPanels.centered(swatchColumn); + sliderPanel.add(swatchSlot, BorderLayout.WEST); + sliderPanel.add(sliders); + String[] channels = {"Hue", "Saturation", "Lightness", "Alpha"}; + int[] limits = {63, 7, 127, 255}; + int[] bits = {10, 7, 0, 16}; + int[] source = {0xFF0040}; + java.util.function.IntSupplier output = () -> { + int alpha = ModelOverrideFields.getInt(override, "setAlpha"); + if (alpha < 0) + alpha = override.modifyAlpha(source[0] >>> 16); + return alpha << 16 | ruleOutput(override, source[0]); + }; + Runnable updateSamples = () -> { + sample.setColors(sampleColor(source[0]), sampleColor(output.getAsInt())); + sliders.repaint(); + }; + var controls = new ArrayList(); + for (int i = 0; i < channels.length; i++) { + String name = channels[i]; + int max = limits[i], shift = bits[i], mask = max << shift; + var slider = new javax.swing.JSlider(0, max); + controls.add(slider); + var row = gradientSlider(slider, name, position -> { + int packed = override == null ? source[0] : output.getAsInt(); + int value = Math.round(position * max); + if (override != null && "Shift".equals(mode.getSelected())) { + int lower = ModelOverrideFields.getInt(override, "min" + name); + int upper = ModelOverrideFields.getInt(override, "max" + name); + value = Math.min(Math.max((source[0] >> shift & max) + 2 * value - max, lower), upper); + value = Math.max(0, Math.min(max, value)); + } + if (shift == 16) + return sampleColor(value << 16 | packed & 0xFFFF); + if (shift == 10) + packed = 4 << 7 | 64; + else if (shift == 7) + packed = packed & 0xFC00 | 64; + return sampleColor(0xFF0000 | packed & 0xFFFF & ~mask | value << shift); + }); + sliders.add(row); + } + Runnable refreshSliders = () -> withRefreshGuard(() -> { + String operation = mode.getSelected(); + for (int i = 0; i < channels.length; i++) { + var slider = controls.get(i); + int min = "Shift".equals(operation) ? -limits[i] : "Set".equals(operation) ? -1 : 0; + int value = ModelOverrideFields.getInt(override, operation.toLowerCase(Locale.ROOT) + channels[i]); + slider.putClientProperty("unsetAllowed", "Set".equals(operation)); + slider.setModel(new javax.swing.DefaultBoundedRangeModel( + Math.max(min, Math.min(limits[i], value)), 0, min, limits[i])); + } + updateSamples.run(); + }); + Runnable[] self = new Runnable[1]; + ColorPicker.builder(picker, () -> sampleColor(output.getAsInt())) + .palette("MODEL COLORS", () -> pickerPalette(modelColors)).onApply(color -> { + if (override == null) + return; + setPickedColor(override, color); + mode.setSelected("Set"); + onFieldEdited(self[0]); + }).bind(); + mode.onChange(ignored -> refreshSliders.run()); + content.add(paletteHolder); + content.add(spacer()); + content.add(infoLabel("Whole model")); + content.add(PropertyRow.compact("Change", mode)); + content.add(PropertyRow.compact("", sliderPanel)); + content.add(spacer()); + content.add(fieldRow("TzHaar recolor", tzControl)); + content.add(fieldRow("Inherit tile color", inheritControl)); + content.add(spacer()); + PropertySection view = new PropertySection("Color", content); + + var rulesContent = new JPanel(); + rulesContent.setOpaque(false); + rulesContent.setLayout(new BoxLayout(rulesContent, BoxLayout.Y_AXIS)); + rulesContent.add(rulesHolder); + rulesContent.add(newRuleButton); + var rulesSection = new PropertySection("Color overrides", rulesContent); + + Runnable refreshRules = () -> { + rulesHolder.removeAll(); + if (pendingColorRule != null) { + var choose = new JPanel(new BorderLayout(4, 8)); + choose.setBackground(new Color(0x1C2330)); + choose.setAlignmentX(LEFT_ALIGNMENT); + choose.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(WorkspaceStyle.ACCENT, 1, true), + BorderFactory.createEmptyBorder(10, 10, 10, 10))); + var heading = new JPanel(new BorderLayout()); + heading.setOpaque(false); + int ruleIndex = override.colorOverrides == null ? -1 : java.util.Arrays.asList(override.colorOverrides).indexOf(pendingColorRule); + heading.add(EditorText.builder(ruleIndex < 0 ? "New color override · choose a color" : "Add a color to Rule " + (ruleIndex + 1)) + .font(WorkspaceStyle.SEMIBOLD).icon(WorkspaceStyle.icon("eyedropper", 12)).build()); + heading.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).text("Cancel").onClick(this::cancelColorPicking).build(), BorderLayout.EAST); + choose.add(heading, BorderLayout.NORTH); + var hint = new javax.swing.JTextArea("Choose from the model colors, or click a face on the model in the viewer."); + hint.setFont(WorkspaceStyle.UI.deriveFont(11f)); + hint.setForeground(new Color(0x8A9AB3)); + hint.setOpaque(false); + hint.setEditable(false); + hint.setFocusable(false); + hint.setLineWrap(true); + hint.setWrapStyleWord(true); + hint.setRows(2); + choose.add(hint); + if (previewModel != null) + choose.add(buildModelColorPalette(), BorderLayout.SOUTH); + rulesHolder.add(choose); + rulesHolder.add(Box.createVerticalStrut(6)); + } + ModelOverride[] rules = override.colorOverrides; + if (rules != null) { + for (int i = 0; i < rules.length; i++) { + JPanel card = buildRuleCard(rules[i], i); + card.setAlignmentX(Component.LEFT_ALIGNMENT); + rulesHolder.add(card); + rulesHolder.add(Box.createVerticalStrut(4)); + } + } + rulesSection.setChangedCount(rules == null ? 0 : rules.length); + hoveredColor = null; + updateColorHighlight(); + rulesHolder.revalidate(); + rulesHolder.repaint(); + }; + refreshColorRules = refreshRules; + rulesSection.onReset(() -> { + override.colorOverrides(baseline.colorOverrides); + pendingColorRule = null; + refreshRules.run(); + fireChange(); + }); + colorRulesSection = new Section(rulesSection, refreshRules, List.of("Color overrides", "colorOverrides")); + + newRuleButton.addActionListener(event -> chooseColor(new ModelOverride())); + + tzControl.onChange(v -> { override.tzHaarRecolorType = v; onFieldEdited(self[0]); }); + inheritControl.onChange(v -> { override.inheritTileColorType = v; onFieldEdited(self[0]); }); + + List>> setters = List.of( + List.of(ModelOverride::setHue, ModelOverride::setSaturation, ModelOverride::setLightness, ModelOverride::setAlpha), + List.of(ModelOverride::shiftHue, ModelOverride::shiftSaturation, ModelOverride::shiftLightness, ModelOverride::shiftAlpha), + List.of(ModelOverride::minHue, ModelOverride::minSaturation, ModelOverride::minLightness, ModelOverride::minAlpha), + List.of(ModelOverride::maxHue, ModelOverride::maxSaturation, ModelOverride::maxLightness, ModelOverride::maxAlpha)); + var operations = List.of("Set", "Shift", "Min", "Max"); + for (int i = 0; i < controls.size(); i++) { + int channel = i; + var slider = controls.get(i); + slider.addChangeListener(e -> { + if (refreshing || slider.getValueIsAdjusting() || override == null) + return; + setters.get(operations.indexOf(mode.getSelected())).get(channel).accept(override, slider.getValue()); + onFieldEdited(self[0]); + }); + } + + Runnable refresh = () -> withRefreshGuard(() -> { + tzControl.setSelected(override.tzHaarRecolorType == null ? TzHaarRecolorType.NONE : override.tzHaarRecolorType); + inheritControl.setSelected(override.inheritTileColorType == null ? InheritTileColorType.NONE : override.inheritTileColorType); + + source[0] = previewModel == null ? 0xFF0040 : modelColors.stream() + .max(Comparator.comparingInt(entry -> entry.faceCount)).map(entry -> entry.ahsl).orElse(0xFF0040); + refreshSliders.run(); + + paletteHolder.removeAll(); + if (previewModel != null) { + paletteHolder.add(buildModelColorPalette()); + } else { + JLabel none = infoLabel("No preview model loaded"); + none.setAlignmentX(Component.LEFT_ALIGNMENT); + paletteHolder.add(none); + } + paletteHolder.revalidate(); + paletteHolder.repaint(); + + view.setChangedCount(count( + override.tzHaarRecolorType != baseline.tzHaarRecolorType, + override.inheritTileColorType != baseline.inheritTileColorType, + (ModelOverrideFields.getInt(override, "setHue") != ModelOverrideFields.getInt(baseline, "setHue") || + ModelOverrideFields.getInt(override, "shiftHue") != ModelOverrideFields.getInt(baseline, "shiftHue") || + ModelOverrideFields.getInt(override, "minHue") != ModelOverrideFields.getInt(baseline, "minHue") || + ModelOverrideFields.getInt(override, "maxHue") != ModelOverrideFields.getInt(baseline, "maxHue") || + ModelOverrideFields.getInt(override, "setSaturation") != ModelOverrideFields.getInt(baseline, "setSaturation") || + ModelOverrideFields.getInt(override, "shiftSaturation") != ModelOverrideFields.getInt(baseline, "shiftSaturation") || + ModelOverrideFields.getInt(override, "minSaturation") != ModelOverrideFields.getInt(baseline, "minSaturation") || + ModelOverrideFields.getInt(override, "maxSaturation") != ModelOverrideFields.getInt(baseline, "maxSaturation") || + ModelOverrideFields.getInt(override, "setLightness") != ModelOverrideFields.getInt(baseline, "setLightness") || + ModelOverrideFields.getInt(override, "shiftLightness") != ModelOverrideFields.getInt(baseline, "shiftLightness") || + ModelOverrideFields.getInt(override, "minLightness") != ModelOverrideFields.getInt(baseline, "minLightness") || + ModelOverrideFields.getInt(override, "maxLightness") != ModelOverrideFields.getInt(baseline, "maxLightness") || + ModelOverrideFields.getInt(override, "setAlpha") != ModelOverrideFields.getInt(baseline, "setAlpha") || + ModelOverrideFields.getInt(override, "shiftAlpha") != ModelOverrideFields.getInt(baseline, "shiftAlpha") || + ModelOverrideFields.getInt(override, "minAlpha") != ModelOverrideFields.getInt(baseline, "minAlpha") || + ModelOverrideFields.getInt(override, "maxAlpha") != ModelOverrideFields.getInt(baseline, "maxAlpha")) + )); + }); + self[0] = refresh; + + view.onReset(() -> { + override.tzHaarRecolorType = baseline.tzHaarRecolorType; + override.inheritTileColorType = baseline.inheritTileColorType; + override.setHue(ModelOverrideFields.getInt(baseline, "setHue")); + override.shiftHue(ModelOverrideFields.getInt(baseline, "shiftHue")); + override.minHue(ModelOverrideFields.getInt(baseline, "minHue")); + override.maxHue(ModelOverrideFields.getInt(baseline, "maxHue")); + override.setSaturation(ModelOverrideFields.getInt(baseline, "setSaturation")); + override.shiftSaturation(ModelOverrideFields.getInt(baseline, "shiftSaturation")); + override.minSaturation(ModelOverrideFields.getInt(baseline, "minSaturation")); + override.maxSaturation(ModelOverrideFields.getInt(baseline, "maxSaturation")); + override.setLightness(ModelOverrideFields.getInt(baseline, "setLightness")); + override.shiftLightness(ModelOverrideFields.getInt(baseline, "shiftLightness")); + override.minLightness(ModelOverrideFields.getInt(baseline, "minLightness")); + override.maxLightness(ModelOverrideFields.getInt(baseline, "maxLightness")); + override.setAlpha(ModelOverrideFields.getInt(baseline, "setAlpha")); + override.shiftAlpha(ModelOverrideFields.getInt(baseline, "shiftAlpha")); + override.minAlpha(ModelOverrideFields.getInt(baseline, "minAlpha")); + override.maxAlpha(ModelOverrideFields.getInt(baseline, "maxAlpha")); + self[0].run(); + fireChange(); + }); + + return new Section(view, self[0], List.of( + "TzHaar recolor", "Inherit tile color", "Hue", "Saturation", "Lightness", "Alpha", + "Set", "Shift", "Min", "Max", "Color rules")); + } + + private Section buildMaterialSwapsSection() { + var content = new JPanel(); + content.setOpaque(false); + content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); + var view = new PropertySection("Material overrides", content); + var add = DashedAddButton.create("Add material swap"); + add.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + Runnable[] refresh = new Runnable[1]; + refresh[0] = () -> { + content.removeAll(); + var swaps = override.materialOverrides; + var sources = vanillaSwapSources(); + if (swaps != null) { + swaps.forEach((source, rule) -> { + if (rule == null) + return; + var row = new JPanel(new net.miginfocom.swing.MigLayout("insets 6, gap 4, fillx, wrap 4", "[][grow,fill][][grow,fill]")); + row.setBackground(new Color(0x1A1A1A)); + row.setBorder(BorderFactory.createLineBorder(new Color(0x333333), 1, true)); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + row.add(infoLabel("When")); + var when = PreviewDropdown.builder(new PreviewDropdown.Provider() { + @Override public List items() { + return sources.keySet().stream() + .filter(candidate -> candidate == source || !swaps.containsKey(candidate)) + .collect(java.util.stream.Collectors.toList()); + } + + @Override public String label(Material material) { return material.name; } + + @Override public Image preview(Material material, int size) { + Integer textureId = sources.get(material); + return textureId == null ? null : vanillaTexturePreview(textureId, size); + } + }).search("Search vanilla materials").compact(true).caption("When the face material is").build(); + when.setValue(source); + when.onChange(value -> { + if (value != null && value != source && !swaps.containsKey(value)) { + swaps.remove(source); + swaps.put(value, rule); + } + onFieldEdited(refresh[0]); + }); + row.add(when, "w 0:80:120"); + row.add(infoLabel("→")); + row.add(swapMaterial(rule.textureMaterial != Material.NONE ? rule.textureMaterial : rule.material, + "Replace it with", value -> { + rule.textureMaterial = value; + rule.material = Material.NONE; + fireChange(); + }), "w 0:80:120"); + var swapUv = new UvTypeDropdown(rule.uvType, true); + swapUv.onChange(value -> { rule.uvType = value; fireChange(); }); + row.add(swapUv, "span 3, growx"); + row.add(EditorButton.builder().icon("close", 10).tooltip("Remove material swap").size(22, 22) + .onClick(() -> { + swaps.remove(source); + if (swaps.isEmpty()) + override.materialOverrides = null; + onFieldEdited(refresh[0]); + }).build()); + content.add(row); + }); + } + boolean canAdd = sources.keySet().stream().anyMatch(source -> swaps == null || !swaps.containsKey(source)); + add.setEnabled(canAdd); + add.setToolTipText(canAdd ? null : sources.isEmpty() + ? "The preview model has no mapped vanilla textures" + : "All vanilla materials already have a swap"); + if (previewModel != null && sources.isEmpty()) { + var empty = infoLabel("No vanilla textures"); + empty.setAlignmentX(Component.LEFT_ALIGNMENT); + content.add(empty); + } else { + content.add(add); + } + view.setChangedCount(swaps == null || swaps.isEmpty() ? 0 : 1); + content.revalidate(); + content.repaint(); + }; + add.setAlignmentX(Component.LEFT_ALIGNMENT); + add.addActionListener(e -> { + var swaps = override.materialOverrides == null ? new java.util.LinkedHashMap() + : new java.util.LinkedHashMap<>(override.materialOverrides); + var available = context.materials(); + var source = vanillaSwapSources().keySet().stream().filter(value -> !swaps.containsKey(value)) + .findFirst().orElse(null); + if (source == null) + return; + var rule = new ModelOverride(); + rule.textureMaterial = available.stream().filter(value -> value != null && "HD_MARBLE".equals(value.name)) + .findFirst().orElse(source); + swaps.put(source, rule); + override.materialOverrides = swaps; + onFieldEdited(refresh[0]); + }); + view.onReset(() -> { override.materialOverrides = null; onFieldEdited(refresh[0]); }); + return new Section(view, refresh[0], List.of("Material overrides", "Material swaps")); + } + + private java.util.Map vanillaSwapSources() { + var mapping = rs117.hd.scene.MaterialManager.VANILLA_TEXTURE_MAPPING; + var textures = previewModel == null ? null : previewModel.getFaceTextures(); + if (mapping == null || textures == null) + return java.util.Map.of(); + + var sources = new java.util.LinkedHashMap(); + for (short texture : textures) { + if (texture >= 0 && texture < mapping.length) { + var material = mapping[texture]; + if (material != null && material != Material.NONE) + sources.putIfAbsent(material, (int) texture); + } + } + return sources; + } + + private Image vanillaTexturePreview(int textureId, int size) { + long key = (long) textureId << 32 | size; + if (!vanillaTexturePreviews.containsKey(key)) { + int nativeSize = rs117.hd.dev.sceneloader.standalone.Textures.SIZE; + Image image; + if (size == nativeSize) { + image = MaterialThumbnails.vanillaPreview(context.vanillaTexturePixels(textureId)); + } else { + var original = vanillaTexturePreview(textureId, nativeSize); + image = original == null ? null : MaterialThumbnails.scale(original, size); + } + vanillaTexturePreviews.put(key, image); + } + return vanillaTexturePreviews.get(key); + } + + private Image materialPreview(Material material, int size, JComponent observer) { + if (material.vanillaTextureIndex >= 0) { + Image image = vanillaTexturePreview(material.vanillaTextureIndex, size); + if (image != null) + return image; + } + return MaterialThumbnails.preview(material, size, observer); + } + + private PreviewDropdown.Builder materialPicker(boolean compact, String caption) { + return PreviewDropdown.builder(new PreviewDropdown.Provider() { + @Override public List items() { return context.materials(); } + @Override public String label(Material material) { return material.name; } + @Override public Image preview(Material material, int size) { return preview(material, size, OverrideProperties.this); } + @Override public Image preview(Material material, int size, JComponent observer) { + return materialPreview(material, size, observer); + } + }).search("Search materials").filterItems(MaterialThumbnails::withoutAuxiliaryMaps) + .compact(compact).caption(caption); + } + + private PreviewDropdown swapMaterial(Material initial, String caption, Consumer change) { + var dropdown = materialPicker(true, caption).build(); + dropdown.setValue(initial); + dropdown.onChange(change); + return dropdown; + } + + private JPanel buildRuleCard(ModelOverride rule, int index) { + var card = new JPanel(new BorderLayout(0, 8)); + card.setBackground(new Color(0x1A1A1A)); + boolean expanded = openColorRule == rule; + card.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createLineBorder(expanded || pendingColorRule == rule ? WorkspaceStyle.ACCENT : new Color(0x333333), 1, true), + BorderFactory.createEmptyBorder(5, 8, 5, 8))); + var header = new JPanel(new BorderLayout(6, 0)); + header.setPreferredSize(new Dimension(0, 34)); + header.setOpaque(false); + var colors = ruleColors(rule); + var heading = new JPanel(new FlowLayout(FlowLayout.LEFT, 7, 0)); + heading.setOpaque(false); + var title = EditorButton.builder().style(WorkspaceStyle.Button.TAB).text("Rule " + (index + 1)) + .icon(expanded ? "chevron-down" : "chevron-right", 9).onClick(() -> { + openColorRule = expanded ? null : rule; + refreshColorRules.run(); + }).build(); + title.setFont(WorkspaceStyle.SEMIBOLD); + heading.add(title); + var matches = new LinkedHashSet(); + for (var color : colors) + if (color.isJsonPrimitive() && color.getAsJsonPrimitive().isNumber()) + matches.add(color.getAsInt() & 0xFFFF); + var predicate = ModelOverrideFields.colorPredicate(rule, colors); + var matchedColors = previewModel == null ? List.of() + : modelColors.stream() + .filter(entry -> predicate.test(entry.ahsl)).collect(java.util.stream.Collectors.toList()); + int source = matchedColors.stream().max(Comparator.comparingInt(entry -> entry.faceCount)) + .map(entry -> entry.ahsl & 0xFFFF).orElseGet(() -> matches.isEmpty() ? -1 : matches.iterator().next()); + for (int rgb : matchedColors.stream().mapToInt(entry -> entry.ahsl & 65535).distinct().limit(4).toArray()) + heading.add(ruleSample(rule, rgb)); + String expressionText = expressionText(rule); + var summary = EditorText.builder("").font(ColorExpressionPanel.CODE.deriveFont(10f)).build(); + var palette = modelColors; + java.util.function.Function evaluate = expression -> { + boolean valid = ColorExpression.valid(expression); + var test = valid ? ModelOverrideFields.colorPredicate(rule, new JsonPrimitive(expression)) : null; + var hits = palette.stream().filter(entry -> test != null && test.test(entry.ahsl)).collect(java.util.stream.Collectors.toList()); + int faces = hits.stream().mapToInt(entry -> entry.faceCount).sum(); + String caption = (valid ? expression : "invalid expression") + " · " + faces + " faces"; + summary.setText(caption); + summary.setToolTipText(caption); + summary.setForeground(new Color(valid ? 0x9FB8E0 : 0xE8A0A0)); + return hits.isEmpty() ? "Valid, but no colors on this model match" + : "Matches " + hits.size() + " of " + palette.size() + " model colors · " + faces + " faces"; + }; + evaluate.apply(expressionText); + header.add(heading, BorderLayout.WEST); + header.add(summary); + + var actions = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0)); + actions.setOpaque(false); + actions.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("eyedropper", 12).tooltip("Add a color").onClick(() -> chooseColor(rule)).build()); + actions.add(EditorButton.builder().style(WorkspaceStyle.Button.TAB).icon("trash", 12).tooltip("Delete rule").onClick(() -> { + var rules = new ArrayList<>(java.util.Arrays.asList(override.colorOverrides)); + rules.remove(rule); + override.colorOverrides(rules.isEmpty() ? null : rules.toArray(ModelOverride[]::new)); + if (openColorRule == rule) + openColorRule = null; + if (pendingColorRule == rule) + cancelColorPicking(); + onFieldEdited(refreshColorRules); + }).build()); + header.add(actions, BorderLayout.EAST); + if (expanded) + header.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x2A2A2A))); + card.add(header, BorderLayout.NORTH); + if (!expanded) + return card; + + var body = new JPanel(); + body.setOpaque(false); + body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); + + var changeMode = SegmentedControl.builder(List.of("Set color", "Shift")).build(); + boolean shifted = ModelOverrideFields.getInt(rule, "shiftHue") != 0 + || ModelOverrideFields.getInt(rule, "shiftSaturation") != 0 + || ModelOverrideFields.getInt(rule, "shiftLightness") != 0; + boolean hasAbsoluteColor = ModelOverrideFields.getInt(rule, "setHue") >= 0 + && ModelOverrideFields.getInt(rule, "setSaturation") >= 0 + && ModelOverrideFields.getInt(rule, "setLightness") >= 0; + changeMode.setSelected(shifted && !hasAbsoluteColor ? "Shift" : "Set color"); + var fields = new JPanel(new java.awt.CardLayout()); + fields.setOpaque(false); + var set = new JPanel(new GridLayout(3, 1, 0, 0)); + var sliderPanel = new JPanel(new BorderLayout(8, 0)); + sliderPanel.setOpaque(false); + sliderPanel.add(fields); + var result = EditorButton.builder().style(WorkspaceStyle.Button.TAB).size(40, 40).tooltip("Pick the replacement color").build(); + var preview = new JPanel(new net.miginfocom.swing.MigLayout("insets 0, gap 4, wrap 3", "[]")); + preview.setOpaque(false); + Runnable updateSamples = () -> { + int color = ruleOutput(rule, source < 0 ? 0 : source); + result.setIcon(colorIcon(color, 36, 36)); + preview.removeAll(); + var test = ModelOverrideFields.colorPredicate(rule, ruleColors(rule)); + var inputs = palette.stream().filter(entry -> test.test(entry.ahsl)) + .mapToInt(entry -> entry.ahsl & 65535).distinct().limit(10).toArray(); + for (int input : inputs) { + var pair = new JPanel(new FlowLayout(FlowLayout.LEFT, 3, 0)); + pair.setOpaque(false); + pair.add(colorSample(input, 18, 18)); + pair.add(infoLabel("→")); + pair.add(colorSample(ruleOutput(rule, input), 18, 18)); + preview.add(pair); + } + if (inputs.length == 0) + preview.add(infoLabel("No colors on this model match yet."), "span"); + preview.revalidate(); + preview.repaint(); + }; + updateSamples.run(); + var resultSlot = EditorPanels.centered(result); + sliderPanel.add(resultSlot, BorderLayout.WEST); + var shift = new JPanel(new GridLayout(3, 1, 0, 2)); + set.setOpaque(false); + shift.setOpaque(false); + var hueSlider = addColorChannel(set, shift, rule, "Hue", 63, rule::setHue, rule::shiftHue, source, updateSamples); + var saturationSlider = addColorChannel(set, shift, rule, "Saturation", 7, rule::setSaturation, rule::shiftSaturation, source, updateSamples); + var lightnessSlider = addColorChannel(set, shift, rule, "Lightness", 127, rule::setLightness, rule::shiftLightness, source, updateSamples); + fields.add(set, "Set color"); + fields.add(shift, "Shift"); + ColorPicker.builder(result, () -> sampleColor(0xFF0000 | ruleOutput(rule, Math.max(0, source)))) + .palette("MODEL COLORS", () -> pickerPalette(palette)).onApply(color -> { + setPickedColor(rule, color); + changeMode.setSelected("Set color"); + ((java.awt.CardLayout) fields.getLayout()).show(fields, "Set color"); + int packed = ruleOutput(rule, Math.max(0, source)); + withRefreshGuard(() -> { + hueSlider.setValue(packed >> 10 & 63); + saturationSlider.setValue(packed >> 7 & 7); + lightnessSlider.setValue(packed & 127); + }); + updateSamples.run(); + fireChange(); + }).bind(); + var fieldLayout = (java.awt.CardLayout) fields.getLayout(); + fieldLayout.show(fields, changeMode.getSelected()); + changeMode.onChange(mode -> fieldLayout.show(fields, mode)); + body.add(new ColorExpressionPanel(expressionText, expressionViewRule == rule, text -> { + rule.colors(new JsonPrimitive(text)); + updateColorHighlight(); + updateSamples.run(); + fireChange(); + }, evaluate, expression -> expressionViewRule = expression ? rule : null, () -> chooseColor(rule), context::colorToast)); + body.add(Box.createVerticalStrut(8)); + + body.add(PropertyRow.compact("Change", changeMode)); + body.add(PropertyRow.compact("", sliderPanel)); + body.add(PropertyRow.compact("Material", swapMaterial(rule.material, "Material for rule " + (index + 1), + material -> { rule.material = material; fireChange(); }))); + body.add(new PropertyRow("Preview", preview, PropertyRow.Layout.WIDE)); + card.add(body); + return card; + } + + private static JLabel ruleSample(ModelOverride rule, int source) { + var image = new java.awt.image.BufferedImage(22, 14, java.awt.image.BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + g.setClip(new java.awt.geom.RoundRectangle2D.Float(0, 0, 22, 14, 3, 3)); + colorIcon(source, 11, 14).paintIcon(null, g, 0, 0); + colorIcon(ruleOutput(rule, source), 11, 14).paintIcon(null, g, 11, 0); + g.dispose(); + return new JLabel(new javax.swing.ImageIcon(image)); + } + + + private static int ruleOutput(ModelOverride rule, int source) { + int hue = ModelOverrideFields.getInt(rule, "setHue"); + int saturation = ModelOverrideFields.getInt(rule, "setSaturation"); + int lightness = ModelOverrideFields.getInt(rule, "setLightness"); + int shifted = rule.modifyColor(source); + return (hue < 0 ? shifted & 0xFC00 : hue << 10) + | (saturation < 0 ? shifted & 0x380 : saturation << 7) + | (lightness < 0 ? shifted & 0x7F : lightness); + } + + private static JLabel colorSample(int hsl, int width, int height) { + return new JLabel(colorIcon(hsl, width, height)); + } + + private static javax.swing.Icon colorIcon(int hsl, int width, int height) { + float[] rgb = ColorUtils.packedHslToSrgb(hsl & 0xFFFF); + var sample = new java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB); + var graphics = sample.createGraphics(); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics.setColor(new Color(rgb[0], rgb[1], rgb[2])); + graphics.fillRoundRect(0, 0, width, height, 7, 7); + graphics.dispose(); + return new javax.swing.ImageIcon(sample); + } + + private javax.swing.JSlider addColorChannel(JPanel set, JPanel shift, ModelOverride rule, String name, int max, + java.util.function.IntConsumer setValue, java.util.function.IntConsumer shiftValue, int source, Runnable updateSamples) { + int bits = name.equals("Hue") ? 10 : name.equals("Saturation") ? 7 : 0; + var absolute = new javax.swing.JSlider(0, max, (ruleOutput(rule, Math.max(0, source)) >> bits) & max); + int initialShift = ModelOverrideFields.getInt(rule, "shift" + name); + var offset = NumberField.builder().min((double) -max).max((double) max) + .value((double) Math.max(-max, Math.min(max, initialShift))).build(); + boolean[] syncing = {false}; + set.add(colorSlider(absolute, name, bits, max, source, rule, false, value -> { + if (syncing[0] || refreshing) + return; + setValue.accept(value); + updateSamples.run(); + set.repaint(); + fireChange(); + })); + shift.add(new PropertyRow(name.substring(0, 1) + "+", offset, PropertyRow.Layout.SIMPLE)); + offset.onChange(value -> { + shiftValue.accept(value.intValue()); + setValue.accept(-1); + syncing[0] = true; + try { + absolute.setValue((ruleOutput(rule, Math.max(0, source)) >> bits) & max); + } finally { + syncing[0] = false; + } + updateSamples.run(); + shift.repaint(); + fireChange(); + }); + return absolute; + } + + private JPanel colorSlider(javax.swing.JSlider slider, String name, int bits, int max, int source, + ModelOverride rule, boolean signed, java.util.function.IntConsumer commit) { + var row = gradientSlider(slider, name, position -> { + int packed = ruleOutput(rule, Math.max(0, source)); + int channel = Math.round(position * max); + if (signed) { + int original = (Math.max(0, source) >> bits) & max; + int offset = Math.round(position * 2 * max) - max; + int min = ModelOverrideFields.getInt(rule, "min" + name); + int upper = ModelOverrideFields.getInt(rule, "max" + name); + channel = Math.max(min, Math.min(upper, original + offset)); + } + int base = bits == 10 ? 4 << 7 | 64 : bits == 7 ? (packed & 0xFC00) | 64 : packed & ~127; + return sampleColor(0xFF0000 | (base & ~(max << bits)) | channel << bits); + }); + slider.addChangeListener(e -> { + if (!slider.getValueIsAdjusting()) + commit.accept(slider.getValue()); + }); + slider.getAccessibleContext().setAccessibleName(name + (signed ? " shift" : "")); + return row; + } + + private static List pickerPalette(List palette) { + return palette.stream().sorted(Comparator.comparingInt((ModelColorPalette.Entry entry) -> entry.faceCount).reversed()) + .map(entry -> sampleColor(0xFF0000 | (entry.ahsl & 0xFFFF))).distinct().limit(20) + .collect(java.util.stream.Collectors.toList()); + } + + private static void setPickedColor(ModelOverride target, Color color) { + int packed = ColorUtils.hsl(color.getRGB() & 0xffffff); + target.setHue(packed >> 10 & 63); + target.setSaturation(packed >> 7 & 7); + target.setLightness(packed & 127); + } + + private static Color sampleColor(int ahsl) { + float[] rgb = ColorUtils.packedHslToSrgb(ahsl & 0xFFFF); + return new Color(rgb[0], rgb[1], rgb[2], (ahsl >>> 16 & 255) / 255f); + } + + private static JPanel gradientSlider(javax.swing.JSlider slider, String name, + java.util.function.Function colorAt) { + slider.setOpaque(false); + slider.setPreferredSize(new Dimension(100, 19)); + slider.setUI(new javax.swing.plaf.basic.BasicSliderUI(slider) { + @Override protected Dimension getThumbSize() { return new Dimension(8, 16); } + + @Override public void paintTrack(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int steps = 32; + float[] positions = new float[steps + 1]; + Color[] colors = new Color[steps + 1]; + for (int i = 0; i <= steps; i++) { + positions[i] = i / (float) steps; + colors[i] = colorAt.apply(positions[i]); + } + if (trackRect.width > 0) { + g.setPaint(new java.awt.LinearGradientPaint(trackRect.x, 0, trackRect.x + trackRect.width, 0, positions, colors)); + g.fillRoundRect(trackRect.x, trackRect.y + (trackRect.height - 10) / 2, trackRect.width, 10, 10, 10); + } + g.dispose(); + } + + @Override public void paintThumb(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0xF2F2F2)); + g.fillRoundRect(thumbRect.x, thumbRect.y, thumbRect.width, thumbRect.height, 5, 5); + g.dispose(); + } + }); + var valueLabel = EditorText.builder("").font(WorkspaceStyle.MONO.deriveFont(11f)).build(); + valueLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); + valueLabel.setPreferredSize(new Dimension(30, 18)); + Runnable updateLabel = () -> { + int value = slider.getValue(); + if (value == -1 && Boolean.TRUE.equals(slider.getClientProperty("unsetAllowed"))) + valueLabel.setText("—"); + else + valueLabel.setText(slider.getMinimum() < 0 && !Boolean.TRUE.equals(slider.getClientProperty("unsetAllowed")) + && value > 0 ? "+" + value : Integer.toString(value)); + }; + updateLabel.run(); + slider.addChangeListener(e -> updateLabel.run()); + slider.addPropertyChangeListener("model", e -> updateLabel.run()); + slider.getAccessibleContext().setAccessibleName(name); + var channel = new JPanel(new BorderLayout(5, 0)); + channel.setOpaque(false); + channel.add(infoLabel(name.substring(0, 1)), BorderLayout.WEST); + channel.add(slider); + channel.add(valueLabel, BorderLayout.EAST); + return channel; + } + + private SwatchDropdown buildModelColorPalette() { + List entries = modelColors; + List swatches = new ArrayList<>(); + var rules = override == null || override.colorOverrides == null ? new ModelOverride[0] : override.colorOverrides; + var unavailable = pendingColorRule == null + ? java.util.Arrays.stream(rules).map(rule -> ModelOverrideFields.colorPredicate(rule, ruleColors(rule))) + .collect(java.util.stream.Collectors.toList()) + : List.of(ModelOverrideFields.colorPredicate(pendingColorRule, ruleColors(pendingColorRule))); + for (ModelColorPalette.Entry entry : entries) + swatches.add(new SwatchDropdown.Swatch(entry.color, entry.hue, entry.saturation, entry.lightness, entry.faceCount, unavailable.stream().noneMatch(test -> test.test(entry.ahsl)))); + List byHue = new ArrayList<>(swatches); + byHue.sort(Comparator.comparingInt((SwatchDropdown.Swatch s) -> s.hue).thenComparingInt(s -> s.lightness)); + List byUsage = new ArrayList<>(swatches); + byUsage.sort((a, b) -> Integer.compare(b.faceCount, a.faceCount)); + return SwatchDropdown.builder(new SwatchDropdown.Provider() { + @Override public List allColors() { return byHue; } + @Override public List mostUsedColors() { return byUsage; } + }).onHover(swatch -> { + hoveredColor = swatch == null ? null : swatch.hue << 10 | swatch.saturation << 7 | swatch.lightness; + updateColorHighlight(); + }).onSelect(swatch -> colorPicked(swatch.hue << 10 | swatch.saturation << 7 | swatch.lightness)).build(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/PreviewDiagnostics.java b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewDiagnostics.java new file mode 100644 index 0000000..bffd0ae --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewDiagnostics.java @@ -0,0 +1,63 @@ +package rs117.hd.dev.overrides; + +import rs117.hd.dev.sceneloader.scene.BuiltModel; +import rs117.hd.scene.model_overrides.ModelOverride; +import rs117.hd.utils.ColorUtils; + +final class PreviewDiagnostics { + private PreviewDiagnostics() {} + + static BuiltModel normals(BuiltModel model) { + var colors = new int[model.getFaceCount()]; + for (int face = 0; face < colors.length; face++) { + int a = model.getFaceIndices1()[face], b = model.getFaceIndices2()[face], c = model.getFaceIndices3()[face]; + float ax = model.getVerticesX()[b] - model.getVerticesX()[a]; + float ay = model.getVerticesY()[b] - model.getVerticesY()[a]; + float az = model.getVerticesZ()[b] - model.getVerticesZ()[a]; + float bx = model.getVerticesX()[c] - model.getVerticesX()[a]; + float by = model.getVerticesY()[c] - model.getVerticesY()[a]; + float bz = model.getVerticesZ()[c] - model.getVerticesZ()[a]; + float x = ay * bz - az * by, y = az * bx - ax * bz, z = ax * by - ay * bx; + float length = (float) Math.sqrt(x * x + y * y + z * z); + colors[face] = length == 0 ? 0 : packedRgb(x / length * .5f + .5f, y / length * .5f + .5f, z / length * .5f + .5f); + } + return model.withDiagnosticColors(colors); + } + + static BuiltModel uv(BuiltModel model, ModelOverride override) { + int light = packedRgb(.89f, .89f, .89f); + int dark = packedRgb(.28f, .45f, .70f); + var colors = new int[model.getFaceCount()]; + var coordinates = new float[12]; + var working = new float[12]; + for (int face = 0; face < colors.length; face++) { + var type = override.uvType; + float u, v; + switch (type) { + case VANILLA: + case GEOMETRY: + case WORLD_XY: + case WORLD_XZ: + case WORLD_YZ: + int a = model.getFaceIndices1()[face], b = model.getFaceIndices2()[face], c = model.getFaceIndices3()[face]; + float x = (model.getVerticesX()[a] + model.getVerticesX()[b] + model.getVerticesX()[c]) / 384f; + float y = (model.getVerticesY()[a] + model.getVerticesY()[b] + model.getVerticesY()[c]) / 384f; + float z = (model.getVerticesZ()[a] + model.getVerticesZ()[b] + model.getVerticesZ()[c]) / 384f; + u = type == rs117.hd.scene.model_overrides.UvType.WORLD_YZ ? y : x; + v = type == rs117.hd.scene.model_overrides.UvType.WORLD_YZ || type == rs117.hd.scene.model_overrides.UvType.WORLD_XZ ? z : y; + break; + default: + override.fillUvsForFace(coordinates, model, 0, type, face, working); + u = (coordinates[0] + coordinates[4] + coordinates[8]) / 3; + v = (coordinates[1] + coordinates[5] + coordinates[9]) / 3; + } + int checker = (int) Math.floor(u * 8) + (int) Math.floor(v * 8); + colors[face] = (checker & 1) == 0 ? light : dark; + } + return model.withDiagnosticColors(colors); + } + + private static int packedRgb(float r, float g, float b) { + return ColorUtils.packHsl(ColorUtils.srgbToHsl(r, g, b)); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/PreviewFacePicker.java b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewFacePicker.java new file mode 100644 index 0000000..d0a17e2 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewFacePicker.java @@ -0,0 +1,131 @@ +package rs117.hd.dev.overrides; + +import java.awt.Point; +import net.runelite.api.Model; +import rs117.hd.utils.Mat4; + +/** Finds the nearest projected triangle using the matrix from the displayed frame. */ +final class PreviewFacePicker { + private static final java.awt.Color HOVER_FILL_COLOR = new java.awt.Color(122, 165, 232, 89); + private static final java.awt.Color OUTLINE_COLOR = new java.awt.Color(0xE8A33D); + private static final java.awt.BasicStroke OUTLINE_STROKE = new java.awt.BasicStroke(2f); + private final Model source, model; + private final float[] matrix; + private final int originX, originY, originZ, rotation; + private float[][] projected; + private int projectedWidth, projectedHeight; + + PreviewFacePicker(Model source, Model model, float[] matrix, int x, int y, int z, int rotation) { + this.source = source; + this.model = model; + this.matrix = matrix.clone(); + originX = x; + originY = y; + originZ = z; + this.rotation = rotation; + } + + boolean matches(Model current) { return source == current; } + + float[] matrix() { return matrix; } + + int pick(Point point, int width, int height) { + if (model == null || width <= 0 || height <= 0) + return -1; + var projected = project(width, height); + int[] first = model.getFaceIndices1(), second = model.getFaceIndices2(), third = model.getFaceIndices3(); + int[] faceColors = model.getFaceColors3(); + int face = -1; + float depth = Float.POSITIVE_INFINITY; + for (int i = 0; i < model.getFaceCount(); i++) { + float[] a = projected[first[i]], b = projected[second[i]], c = projected[third[i]]; + if (a[3] <= 0 || b[3] <= 0 || c[3] <= 0 || faceColors[i] == -2) + continue; + float area = edge(a, b, c[0], c[1]); + if (area == 0) + continue; + float u = edge(b, c, point.x, point.y) / area; + float v = edge(c, a, point.x, point.y) / area; + float w = 1 - u - v; + float hitDepth = u * a[2] + v * b[2] + w * c[2]; + if (u >= 0 && v >= 0 && w >= 0 && hitDepth < depth) { + depth = hitDepth; + face = i; + } + } + return face; + } + + static int faceColor(Model model, int face) { + byte[] alpha = model.getFaceTransparencies(); + return ((255 - (alpha == null ? 0 : alpha[face] & 255)) << 16) | (model.getFaceColors1()[face] & 65535); + } + + void highlight(java.awt.Graphics2D graphics, java.awt.Rectangle bounds, + rs117.hd.scene.model_overrides.ModelOverride.AhslPredicate rule, Integer hover, int hoveredFace) { + var vertices = project(bounds.width, bounds.height); + var g = (java.awt.Graphics2D) graphics.create(); + try { + g.clip(bounds); + g.translate(bounds.x, bounds.y); + g.setStroke(OUTLINE_STROKE); + int[] a = model.getFaceIndices1(), b = model.getFaceIndices2(), c = model.getFaceIndices3(); + var faceShape = new java.awt.geom.Path2D.Float(); + int[] faceColors = model.getFaceColors3(); + for (int face = 0; face < model.getFaceCount(); face++) { + if (faceColors[face] == -2) + continue; + int ahsl = faceColor(source, face); + boolean hovered = face == hoveredFace || hover != null && (ahsl & 65535) == hover; + if (!hovered && (rule == null || !rule.test(ahsl))) + continue; + float[] first = vertices[a[face]], second = vertices[b[face]], third = vertices[c[face]]; + if (first[3] <= 0 || second[3] <= 0 || third[3] <= 0) + continue; + faceShape.reset(); + faceShape.moveTo(first[0], first[1]); + faceShape.lineTo(second[0], second[1]); + faceShape.lineTo(third[0], third[1]); + faceShape.closePath(); + if (hovered) { + g.setColor(HOVER_FILL_COLOR); + g.fill(faceShape); + } + g.setColor(hovered ? java.awt.Color.WHITE : OUTLINE_COLOR); + g.draw(faceShape); + } + } finally { + g.dispose(); + } + } + + private float[][] project(int width, int height) { + if (projected != null && projectedWidth == width && projectedHeight == height) + return projected; + float[] x = model.getVerticesX(), y = model.getVerticesY(), z = model.getVerticesZ(); + if (projected == null) + projected = new float[model.getVerticesCount()][4]; + projectedWidth = width; + projectedHeight = height; + double angle = rotation * Math.PI / 180; + float sin = (float) Math.sin(angle), cos = (float) Math.cos(angle); + var position = new float[] {0, 0, 0, 1}; + for (int i = 0; i < projected.length; i++) { + position[0] = originX + x[i] * cos + z[i] * sin; + position[1] = originY + y[i]; + position[2] = originZ + z[i] * cos - x[i] * sin; + float[] vertex = projected[i]; + Mat4.mulVec(vertex, matrix, position); + if (vertex[3] <= 0) + continue; + vertex[0] = (1 + vertex[0] / vertex[3]) * width / 2; + vertex[1] = (1 - vertex[1] / vertex[3]) * height / 2; + vertex[2] /= vertex[3]; + } + return projected; + } + + private static float edge(float[] a, float[] b, float x, float y) { + return (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0]); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/PreviewGrid.java b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewGrid.java new file mode 100644 index 0000000..ded6be3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/PreviewGrid.java @@ -0,0 +1,102 @@ +package rs117.hd.dev.overrides; + +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import rs117.hd.utils.Mat4; + +final class PreviewGrid { + private static final int EXTENT = 256; + private static final int SPACING = 32; + private static final Color GRID = new Color(0x343434); + private static final Color AXIS = new Color(0x3F3F3F); + + private BufferedImage overlay; + private float[] projection; + private int[] gridPixels = new int[256]; + private int gridPixelCount; + private int x, z, y; + + void draw(BufferedImage frame, float[] viewProjection, int originX, int originZ, int groundY) { + if (frame.getType() != BufferedImage.TYPE_INT_RGB) + return; + int width = frame.getWidth(); + int height = frame.getHeight(); + if (overlay == null || overlay.getWidth() != width || overlay.getHeight() != height + || x != originX || z != originZ || y != groundY || !java.util.Arrays.equals(projection, viewProjection)) { + rebuild(width, height, viewProjection, originX, originZ, groundY); + } + + // The center pass clears to a flat color. Keep model pixels above the grid. + int[] pixels = ((DataBufferInt) frame.getRaster().getDataBuffer()).getData(); + int[] grid = ((DataBufferInt) overlay.getRaster().getDataBuffer()).getData(); + int background = pixels[0] & 0xFFFFFF; + for (int i = 0; i < gridPixelCount; i++) { + int pixel = gridPixels[i]; + if ((pixels[pixel] & 0xFFFFFF) == background) + pixels[pixel] = grid[pixel]; + } + } + + private void rebuild(int width, int height, float[] viewProjection, int originX, int originZ, int groundY) { + projection = viewProjection.clone(); + x = originX; + z = originZ; + y = groundY; + if (overlay == null || overlay.getWidth() != width || overlay.getHeight() != height) + overlay = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + else + java.util.Arrays.fill(((DataBufferInt) overlay.getRaster().getDataBuffer()).getData(), 0); + var g = overlay.createGraphics(); + try { + for (int offset = -EXTENT; offset <= EXTENT; offset += SPACING) { + if (offset == 0) + continue; + g.setColor(GRID); + line(g, viewProjection, width, height, originX, originZ, groundY, offset, false); + line(g, viewProjection, width, height, originX, originZ, groundY, offset, true); + } + g.setColor(AXIS); + line(g, viewProjection, width, height, originX, originZ, groundY, 0, false); + line(g, viewProjection, width, height, originX, originZ, groundY, 0, true); + } finally { + g.dispose(); + } + gridPixelCount = 0; + int[] grid = ((DataBufferInt) overlay.getRaster().getDataBuffer()).getData(); + for (int pixel = 0; pixel < grid.length; pixel++) { + if (grid[pixel] == 0) + continue; + if (gridPixelCount == gridPixels.length) + gridPixels = java.util.Arrays.copyOf(gridPixels, gridPixels.length * 2); + gridPixels[gridPixelCount++] = pixel; + } + } + + private static void line(java.awt.Graphics2D g, float[] viewProjection, int width, int height, + int originX, int originZ, int groundY, int offset, boolean alongX) { + float[] start = {originX + (alongX ? -EXTENT : offset), groundY, originZ + (alongX ? offset : -EXTENT), 1}; + float[] end = {originX + (alongX ? EXTENT : offset), groundY, originZ + (alongX ? offset : EXTENT), 1}; + float[] a = new float[4]; + float[] b = new float[4]; + Mat4.mulVec(a, viewProjection, start); + Mat4.mulVec(b, viewProjection, end); + if (a[3] < 1 && b[3] < 1) + return; + clipBehindCamera(a, b); + clipBehindCamera(b, a); + g.drawLine(Math.round((a[0] / a[3] + 1) * width / 2), + Math.round((1 - a[1] / a[3]) * height / 2), + Math.round((b[0] / b[3] + 1) * width / 2), + Math.round((1 - b[1] / b[3]) * height / 2)); + } + + private static void clipBehindCamera(float[] point, float[] other) { + if (point[3] >= 1) + return; + float t = (1 - point[3]) / (other[3] - point[3]); + point[0] += t * (other[0] - point[0]); + point[1] += t * (other[1] - point[1]); + point[3] = 1; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/WindModeDropdown.java b/Tools/Dev/java/rs117/hd/dev/overrides/WindModeDropdown.java new file mode 100644 index 0000000..550ada1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/WindModeDropdown.java @@ -0,0 +1,201 @@ +package rs117.hd.dev.overrides; + +import java.awt.*; +import java.util.function.Consumer; +import javax.swing.*; +import rs117.hd.dev.editor.*; +import rs117.hd.scene.model_overrides.WindDisplacement; + +final class WindModeDropdown extends JButton { + private enum Mode { + DISABLED("No wind", "The model never moves.", "disabled", "Off"), + OBJECT("Object sway", "Bends upward and reacts to nearby characters.", "object", "Whole object \u00b7 sways as one piece"), + OBJECT_NO_GROUND_DISPLACEMENT("Object sway \u00b7 loose base", "Sways without reacting to characters.", "object-no-ground", null), + VERTEX("Vertex", "Higher vertices move more.", "vertex", "Per vertex \u00b7 each point moves on its own"), + VERTEX_WITH_HEMISPHERE_BLEND("Vertex \u00b7 smooth blend", "Blends by height and distance from center.", "vertex-hemisphere", null), + VERTEX_JIGGLE("Vertex jiggle", "Vertices jiggle more higher up.", "vertex-jiggle", null); + + final WindDisplacement value = WindDisplacement.valueOf(name()); + final String title, description, icon, group; + + Mode(String title, String description, String icon, String group) { + this.title = title; + this.description = description; + this.icon = "wind-" + icon; + this.group = group; + } + } + + private static final Color MUTED = new Color(0x7D7D7D); + private static final Color BORDER = new Color(0x3A3A3A); + private static final Color BLUE = new Color(0x4772B3); + private final JLabel icon = new JLabel("", SwingConstants.CENTER); + private final JLabel title = label("", WorkspaceStyle.UI.deriveFont(12f), new Color(0xDDDDDD)); + private final JLabel enumName = label("", WorkspaceStyle.MONO.deriveFont(9f), MUTED); + private Mode selected; + private PopupLayer.Handle popup; + private Consumer onChange = value -> {}; + + WindModeDropdown() { + setLayout(new BorderLayout(7, 0)); + setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 6)); + setContentAreaFilled(false); + setRolloverEnabled(true); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + setPreferredSize(new Dimension(210, 30)); + add(tile(icon, 22, new Color(0x262626)), BorderLayout.WEST); + add(lines(title, enumName)); + add(new JLabel(WorkspaceStyle.icon("chevron-down", 10)), BorderLayout.EAST); + addActionListener(event -> toggle()); + setSelected(WindDisplacement.DISABLED); + } + + WindDisplacement getSelected() { + return selected.value; + } + + void setSelected(WindDisplacement value) { + selected = Mode.valueOf(value.name()); + title.setText(selected.title); + enumName.setText(value.name()); + icon.setIcon(modeIcon(selected, 16, 0x9FB8E0)); + setToolTipText(selected.title + " (" + value.name() + ")"); + getAccessibleContext().setAccessibleName("Wind mode: " + selected.title); + repaint(); + } + + void onChange(Consumer action) { + onChange = action; + } + + private void toggle() { + if (popup != null) { + popup.close(); + return; + } + var list = new OptionsList(); + list.setBackground(new Color(0x262626)); + for (Mode mode : Mode.values()) { + if (mode.group != null) { + var group = label(mode.group.toUpperCase(java.util.Locale.ROOT), WorkspaceStyle.SEMIBOLD.deriveFont(10f), MUTED); + group.setBorder(BorderFactory.createEmptyBorder(3, 6, 1, 6)); + list.add(group); + } + list.add(option(mode)); + } + var scroll = new EditorScrollPane(list); + scroll.setBorder(null); + scroll.getViewport().setBackground(list.getBackground()); + scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + popup = PopupLayer.show(this, scroll, 340, 0, Integer.MAX_VALUE); + popup.onClose(() -> { popup = null; repaint(); }); + repaint(); + } + + private static final class OptionsList extends JPanel implements Scrollable { + OptionsList() { + super(new net.miginfocom.swing.MigLayout("insets 4, gapy 1, fillx, wrap 1, novisualpadding", "[0,grow,fill]")); + } + + @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } + @Override public boolean getScrollableTracksViewportWidth() { return true; } + @Override public boolean getScrollableTracksViewportHeight() { return false; } + @Override public int getScrollableUnitIncrement(Rectangle bounds, int axis, int direction) { return 20; } + @Override public int getScrollableBlockIncrement(Rectangle bounds, int axis, int direction) { + return Math.max(20, bounds.height - 20); + } + } + + private JButton option(Mode mode) { + boolean current = mode == selected; + var row = new JButton() { + @Override protected void paintComponent(Graphics graphics) { + paintBackground(graphics, this, current ? new Color(0x334D73) + : getModel().isRollover() || isFocusOwner() ? new Color(0x333333) : null, null); + super.paintComponent(graphics); + } + }; + row.setLayout(new BorderLayout(8, 0)); + row.setBorder(BorderFactory.createEmptyBorder(3, 6, 3, 6)); + row.setContentAreaFilled(false); + row.setRolloverEnabled(true); + row.setCursor(getCursor()); + row.add(tile(new JLabel(modeIcon(mode, 16, current ? 0xCFE0FF : 0x8A8A8A), SwingConstants.CENTER), + 22, new Color(0x1C1C1C)), BorderLayout.WEST); + var heading = label(mode.title, WorkspaceStyle.SEMIBOLD.deriveFont(12f), WorkspaceStyle.TEXT); + var description = label(mode.description, WorkspaceStyle.UI.deriveFont(11f), + current ? new Color(0xB9C9E6) : MUTED); + row.add(lines(heading, description)); + row.getAccessibleContext().setAccessibleName(mode.title); + row.getAccessibleContext().setAccessibleDescription(mode.name() + ". " + mode.description); + row.addActionListener(event -> { + if (popup == null) + return; + popup.close(); + requestFocusInWindow(); + if (mode != selected) { + setSelected(mode.value); + onChange.accept(mode.value); + } + }); + return row; + } + + private static JPanel lines(JComponent top, JComponent bottom) { + var lines = new JPanel(new BorderLayout()); + lines.setOpaque(false); + lines.add(top, BorderLayout.NORTH); + lines.add(bottom); + return lines; + } + + private static JLabel label(String text, Font font, Color color) { + return EditorText.builder(text).font(font).color(color).build(); + } + + private static Icon modeIcon(Mode mode, int size, int tint) { + ImageIcon source = WorkspaceStyle.icon(mode.icon, size); + var image = new java.awt.image.BufferedImage(size, size, java.awt.image.BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + source.paintIcon(null, g, 0, 0); + g.setComposite(AlphaComposite.SrcIn); + g.setColor(new Color(tint)); + g.fillRect(0, 0, size, size); + g.dispose(); + return new ImageIcon(image); + } + + private static JPanel tile(JLabel icon, int size, Color color) { + var tile = new JPanel(new GridBagLayout()) { + @Override protected void paintComponent(Graphics graphics) { + int y = (getHeight() - size) / 2; + graphics.setColor(color); + graphics.fillRoundRect(0, y, size, size, 4, 4); + } + }; + tile.setOpaque(false); + tile.setPreferredSize(new Dimension(size, size)); + tile.add(icon); + return tile; + } + + @Override protected void paintComponent(Graphics graphics) { + Color border = popup != null ? BLUE : getModel().isRollover() || isFocusOwner() ? new Color(0x555555) : BORDER; + paintBackground(graphics, this, new Color(0x1F1F1F), border); + super.paintComponent(graphics); + } + + private static void paintBackground(Graphics graphics, JComponent component, Color fill, Color border) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + if (fill != null) { + g.setColor(fill); + g.fillRoundRect(0, 0, component.getWidth(), component.getHeight(), 8, 8); + } + if (border != null) { + g.setColor(border); + g.drawRoundRect(0, 0, component.getWidth() - 1, component.getHeight() - 1, 8, 8); + } + g.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/WindPreview.java b/Tools/Dev/java/rs117/hd/dev/overrides/WindPreview.java new file mode 100644 index 0000000..935a1a8 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/WindPreview.java @@ -0,0 +1,87 @@ +package rs117.hd.dev.overrides; + +import rs117.hd.dev.sceneloader.scene.BuiltModel; +import rs117.hd.scene.model_overrides.ModelOverride; +import rs117.hd.scene.model_overrides.WindDisplacement; + +final class WindPreview { + private static final double PLAYER_RADIUS = 48; + private static final double[] STRENGTH = { .25, .5, .75, 1, 1.25, 1.5, 2 }; + + private WindPreview() {} + + static BuiltModel deform(BuiltModel model, ModelOverride override, double time, float[] pointer, + float[] projection, int originX, int originY, int originZ, int bottom) { + int count = model.getVerticesCount(); + float[] x = model.getVerticesX().clone(); + float[] y = model.getVerticesY().clone(); + float[] z = model.getVerticesZ().clone(); + double height = 1; + for (int i = 0; i < count; i++) + height = Math.max(height, bottom - y[i]); + + var mode = override.windDisplacementMode; + double[] player = mode == WindDisplacement.OBJECT + ? groundPoint(pointer, projection, originY) : null; + double angle = Math.toRadians(override.rotate); + double sin = Math.sin(angle), cos = Math.cos(angle); + double playerX = player == null ? 0 : (player[0] - originX) * cos - (player[1] - originZ) * sin; + double playerZ = player == null ? 0 : (player[1] - originZ) * cos + (player[0] - originX) * sin; + int modifier = Math.max(-3, Math.min(3, override.windDisplacementModifier)); + double amplitude = Math.min(24, Math.max(2, height * .09)) * STRENGTH[modifier + 3]; + double gust = Math.sin(time * 2.4) * .7 + Math.sin(time * 4.1) * .3; + + for (int i = 0; i < count; i++) { + double weight = (bottom - y[i]) / height; + if (override.invertDisplacementStrength) + weight = 1 - weight; + double wave = gust; + switch (mode) { + case VERTEX_JIGGLE: + wave = .35 * Math.sin(time * 9 + x[i] * .09 + z[i] * .07); + break; + case VERTEX: + case VERTEX_WITH_HEMISPHERE_BLEND: + wave += .25 * Math.sin(time * 4 + x[i] * .07 + z[i] * .04); + if (mode == WindDisplacement.VERTEX_WITH_HEMISPHERE_BLEND) + weight *= Math.min(1, Math.max(0, (weight - .3) * 2 + Math.hypot(x[i], z[i]) / 120)); + break; + default: + break; + } + + if (player != null) { + double dx = x[i] - playerX, dz = z[i] - playerZ; + double distance = Math.hypot(dx, dz); + if (distance < PLAYER_RADIUS) { + double falloff = 1 - distance / PLAYER_RADIUS; + double bend = Math.min(height, 96) * weight * falloff * falloff; + x[i] += dx * bend * .5 / PLAYER_RADIUS; + z[i] += dz * bend * .5 / PLAYER_RADIUS; + y[i] += bend * falloff; + } + } + x[i] += wave * amplitude * weight; + z[i] += wave * amplitude * weight * .4; + } + return model.withVertices(x, y, z); + } + + // Solve screenX = clipX / clipW and screenY = clipY / clipW on the ground plane. + static double[] groundPoint(float[] pointer, float[] matrix, double groundY) { + if (pointer == null || matrix == null) + return null; + double sx = pointer[0], sy = pointer[1]; + double a = matrix[0] - sx * matrix[3], b = matrix[8] - sx * matrix[11]; + double c = matrix[1] - sy * matrix[3], d = matrix[9] - sy * matrix[11]; + double w = groundY * matrix[7] + matrix[15]; + double u = sx * w - groundY * matrix[4] - matrix[12]; + double v = sy * w - groundY * matrix[5] - matrix[13]; + double determinant = a * d - b * c; + if (Math.abs(determinant) < 1e-9) + return null; + double x = (u * d - b * v) / determinant; + double z = (a * v - u * c) / determinant; + return matrix[3] * x + matrix[11] * z + w > 0 ? new double[] { x, z } : null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/overrides/WindStrength.java b/Tools/Dev/java/rs117/hd/dev/overrides/WindStrength.java new file mode 100644 index 0000000..840b85d --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/overrides/WindStrength.java @@ -0,0 +1,146 @@ +package rs117.hd.dev.overrides; + +import java.awt.*; +import java.util.function.IntConsumer; +import javax.swing.*; +import rs117.hd.dev.editor.EditorText; +import rs117.hd.dev.editor.WorkspaceStyle; + +final class WindStrength extends JPanel { + private static final String[] LEVELS = { + "much weaker", "weaker", "slightly weaker", "mode default", + "slightly stronger", "stronger", "much stronger" + }; + private static final Color MUTED = new Color(0x6F6F6F); + private final JLabel title = label("Strength", 12, new Color(0x9A9A9A), false); + private final JLabel readout = label("", 11, new Color(0xCFCFCF), true); + private final JTextArea hint = new JTextArea(); + private IntConsumer onChange = value -> {}; + private int value; + private boolean faded; + + WindStrength() { + setName("field:Strength"); + setOpaque(false); + setAlignmentX(LEFT_ALIGNMENT); + setLayout(new BorderLayout(0, 4)); + setBorder(BorderFactory.createEmptyBorder(5, 0, 4, 0)); + var header = new JPanel(new BorderLayout(12, 0)); + header.setOpaque(false); + var names = new JPanel(new BorderLayout()); + names.setOpaque(false); + names.add(title, BorderLayout.NORTH); + hint.setFont(WorkspaceStyle.UI.deriveFont(11f)); + hint.setForeground(MUTED); + hint.setOpaque(false); + hint.setEditable(false); + hint.setFocusable(false); + hint.setLineWrap(true); + hint.setWrapStyleWord(true); + hint.setRows(2); + names.add(hint); + header.add(names); + readout.setVerticalAlignment(SwingConstants.TOP); + header.add(readout, BorderLayout.EAST); + add(header, BorderLayout.NORTH); + var track = new JPanel(new GridLayout(1, 7, 3, 0)) { + @Override protected void paintComponent(Graphics graphics) { + rounded(graphics, new Color(0x1A1A1A), getWidth(), getHeight(), 5); + graphics.setColor(new Color(0x333333)); + graphics.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 5, 5); + } + }; + track.setOpaque(false); + track.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + for (int step = -3; step <= 3; step++) + track.add(stepButton(step)); + add(track); + var footer = new JPanel(new BorderLayout()); + footer.setOpaque(false); + footer.add(label("Weaker", 10, MUTED, false), BorderLayout.WEST); + footer.add(label("Stronger", 10, MUTED, false), BorderLayout.EAST); + add(footer, BorderLayout.SOUTH); + registerKeyboardAction(e -> choose(Math.max(-3, value - 1)), KeyStroke.getKeyStroke("LEFT"), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + registerKeyboardAction(e -> choose(Math.min(3, value + 1)), KeyStroke.getKeyStroke("RIGHT"), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + update(0, true, false); + } + + void update(int value, boolean disabled, boolean changed) { + this.value = value; + faded = disabled; + title.setForeground(new Color(changed ? 0xE6E6E6 : 0x9A9A9A)); + String level = value >= -3 && value <= 3 ? LEVELS[value + 3] : "custom"; + readout.setText(format(value) + " \u00b7 " + level); + hint.setText(disabled ? "Pick a wind mode first" : "How much the model sways compared to the mode default"); + revalidate(); + repaint(); + } + + void onChange(IntConsumer action) { + onChange = action; + } + + private void choose(int step) { + if (value != step) + onChange.accept(step); + } + + private JButton stepButton(int step) { + var button = new JButton() { + @Override protected void paintComponent(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + boolean selected = step == value; + boolean lit = step >= Math.min(0, value) && step <= Math.max(0, value); + if (selected || getModel().isRollover() || isFocusOwner()) + rounded(g, new Color(selected ? 0x2A3446 : 0x2C2C2C), getWidth(), getHeight(), 3); + int barHeight = 6 + (step + 3) * 3; + g.translate((getWidth() - 10) / 2, 28 - barHeight); + rounded(g, new Color(selected ? 0x7AA5E8 : step == 0 ? 0x6A6A6A : lit ? 0x4772B3 : 0x3A3A3A), 10, barHeight, 3); + g.translate(-(getWidth() - 10) / 2, barHeight - 28); + g.setFont(WorkspaceStyle.MONO.deriveFont(10f)); + g.setColor(new Color(selected ? 0xFFFFFF : step == 0 ? 0xBDBDBD : 0x8A8A8A)); + String text = format(step); + g.drawString(text, (getWidth() - g.getFontMetrics().stringWidth(text)) / 2, 40); + g.dispose(); + } + }; + button.setPreferredSize(new Dimension(26, 44)); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + button.setRolloverEnabled(true); + button.setToolTipText(LEVELS[step + 3]); + button.getAccessibleContext().setAccessibleName(format(step) + " " + LEVELS[step + 3]); + button.addActionListener(e -> choose(step)); + return button; + } + + @Override public Dimension getMaximumSize() { + return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); + } + + @Override public void paint(Graphics graphics) { + var g = (Graphics2D) graphics.create(); + if (faded) + g.setComposite(AlphaComposite.SrcOver.derive(0.45f)); + super.paint(g); + g.dispose(); + } + + private static void rounded(Graphics graphics, Color color, int width, int height, int radius) { + var g = (Graphics2D) graphics.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(color); + g.fillRoundRect(0, 0, width, height, radius, radius); + g.dispose(); + } + + private static JLabel label(String text, int size, Color color, boolean mono) { + return EditorText.builder(text).font((mono ? WorkspaceStyle.MONO : WorkspaceStyle.UI).deriveFont((float) size)) + .color(color).build(); + } + + private static String format(int step) { + return step > 0 ? "+" + step : step < 0 ? "\u2212" + -(long) step : "0"; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java new file mode 100644 index 0000000..198b882 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java @@ -0,0 +1,445 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.KeyEventDispatcher; +import java.awt.KeyboardFocusManager; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import javax.swing.SwingUtilities; +import javax.swing.text.JTextComponent; +import javax.inject.Inject; +import javax.inject.Singleton; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import net.runelite.api.events.BeforeRender; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.input.MouseAdapter; +import net.runelite.client.input.MouseManager; + +@Slf4j +@Singleton +public class FreeCamera { + private static final int ANGLE_UNITS = 16384; + private static final float RADIANS_PER_UNIT = (float) (2 * Math.PI / ANGLE_UNITS); + private static final int QUARTER_TURN = ANGLE_UNITS / 4; + + private static final float CLIENT_FRAMES_PER_SECOND = 50; + + private static final int NORMAL_SPEED = 12; + private static final int SLOW_SPEED = 6; + private static final int SPEED_FRACTION = 16; + private static final float SPEED_GAINED_PER_FRAME = 1 / 8f; + private static final float SPEED_KEPT_PER_FRAME = 0.9f; + + private static final float MIN_PITCH = 1 * RADIANS_PER_UNIT; + private static final float MAX_PITCH = 4160 * RADIANS_PER_UNIT; + + private static final int YAW_TURN_UNITS = 24 << 3; + private static final int PITCH_TURN_UNITS = 12 << 3; + private static final float TURN_GAP_CLOSED_PER_FRAME = 0.5f; + + private static final float DRAG_UNITS_PER_PIXEL = 8; + + private static final float MAX_STEP_SECONDS = 0.1f; + + @Inject + private Client client; + + @Inject + private MouseManager mouseManager; + + @Inject + private EventBus eventBus; + + private boolean started; + private volatile boolean enabled; + private volatile float speed = 1; + + private final float[] position = new float[3]; + private volatile float yaw, pitch; + + private final float[] gamePosition = new float[3]; + private volatile float gameYaw, gamePitch; + private volatile boolean placed; + + private final Set heldKeys = ConcurrentHashMap.newKeySet(); + private long lastMoveNanos; + + private float travelSpeed; + private int travelHeading = -1; + private int travelVertical; + private float yawSpeed, pitchSpeed; + private boolean relaxedPitch; + + private static final float VIEWING_DISTANCE = 6 * 128; + private static final float AIM_ABOVE_GROUND = 128; + + private final KeyEventDispatcher keys = this::dispatchKey; + + private volatile boolean dragging; + private volatile int dragX, dragY; + + private final MouseAdapter lookAround = new MouseAdapter() { + @Override + public MouseEvent mousePressed(MouseEvent event) { + if (enabled && SwingUtilities.isMiddleMouseButton(event)) { + dragging = true; + dragX = event.getX(); + dragY = event.getY(); + event.consume(); + } + return event; + } + + @Override + public MouseEvent mouseDragged(MouseEvent event) { + if (!dragging || !enabled) + return event; + + int x = event.getX(); + int y = event.getY(); + turnUnits(-(x - dragX) * DRAG_UNITS_PER_PIXEL, (y - dragY) * DRAG_UNITS_PER_PIXEL); + dragX = x; + dragY = y; + event.consume(); + return event; + } + + @Override + public MouseEvent mouseReleased(MouseEvent event) { + if (dragging && SwingUtilities.isMiddleMouseButton(event)) { + dragging = false; + event.consume(); + } + return event; + } + }; + + public void startUp() { + if (started) + return; + started = true; + eventBus.register(this); + KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keys); + mouseManager.registerMouseListener(lookAround); + } + + public void shutDown() { + if (!started) + return; + started = false; + eventBus.unregister(this); + KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keys); + mouseManager.unregisterMouseListener(lookAround); + setEnabled(false); + restoreGameCamera(); + } + + private void restoreGameCamera() { + if (!relaxedPitch) + return; + relaxedPitch = false; + client.setCameraPitchRelaxerEnabled(false); + } + + public boolean isEnabled() { + return enabled; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) + return; + + heldKeys.clear(); + lastMoveNanos = 0; + dragging = false; + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + yawSpeed = 0; + pitchSpeed = 0; + + this.enabled = enabled; + if (enabled) { + placed = false; + takeKeyboardFocus(); + } + } + + public void goTo(float x, float y, float z) { + if (!enabled) + setEnabled(true); + + float cosPitch = (float) Math.cos(pitch); + float forwardX = -(float) Math.sin(yaw) * cosPitch; + float forwardZ = (float) Math.cos(yaw) * cosPitch; + float forwardY = (float) Math.sin(pitch); + + float aimY = y - AIM_ABOVE_GROUND; + position[0] = x - forwardX * VIEWING_DISTANCE; + position[1] = aimY - forwardY * VIEWING_DISTANCE; + position[2] = z - forwardZ * VIEWING_DISTANCE; + + placed = true; + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + + private void takeKeyboardFocus() { + SwingUtilities.invokeLater(() -> { + var canvas = client.getCanvas(); + if (canvas != null) + canvas.requestFocusInWindow(); + }); + } + + @Subscribe + public void onBeforeRender(BeforeRender event) { + if (relaxedPitch != enabled) { + relaxedPitch = enabled; + client.setCameraPitchRelaxerEnabled(enabled); + } + + long now = System.nanoTime(); + float seconds = lastMoveNanos == 0 ? 0 : Math.min((now - lastMoveNanos) / 1e9f, MAX_STEP_SECONDS); + lastMoveNanos = now; + + if (!enabled || seconds <= 0) + return; + + if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow() == null) { + heldKeys.clear(); + dragging = false; + } + + float frames = seconds * CLIENT_FRAMES_PER_SECOND; + turnWithKeys(frames); + travel(frames); + pointGameCameraAlong(); + } + + private void pointGameCameraAlong() { + client.setCameraYawTarget(toJagexUnits(yaw) & 2047); + client.setCameraPitchTarget(toJagexUnits(pitch)); + } + + private static int toJagexUnits(float radians) { + return Math.round(radians / (float) (2 * Math.PI) * 2048); + } + + private void turnWithKeys(float frames) { + int wantedYaw = heldKeys.contains(KeyEvent.VK_LEFT) ? -YAW_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_RIGHT) ? YAW_TURN_UNITS : 0; + int wantedPitch = heldKeys.contains(KeyEvent.VK_UP) ? PITCH_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_DOWN) ? -PITCH_TURN_UNITS : 0; + + float closed = 1 - (float) Math.pow(1 - TURN_GAP_CLOSED_PER_FRAME, frames); + yawSpeed += (wantedYaw - yawSpeed) * closed; + pitchSpeed += (wantedPitch - pitchSpeed) * closed; + + turnUnits(yawSpeed / 2 * frames, pitchSpeed / 2 * frames); + } + + private void travel(float frames) { + int heading = headingOf(heldKeys); + int vertical = verticalOf(heldKeys); + + float wanted = 0; + if (heading >= 0 || vertical != 0) { + int perFrame = heldKeys.contains(KeyEvent.VK_CONTROL) ? SLOW_SPEED : NORMAL_SPEED; + wanted = perFrame * speed * SPEED_FRACTION; + travelHeading = heading; + travelVertical = vertical; + } + + if (travelSpeed < wanted) { + travelSpeed = Math.min(wanted, travelSpeed + wanted * SPEED_GAINED_PER_FRAME * frames); + } else if (travelSpeed > wanted) { + travelSpeed *= (float) Math.pow(SPEED_KEPT_PER_FRAME, frames); + if (travelSpeed < 1) { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + } + if (travelSpeed <= 0) + return; + + float distance = travelSpeed / SPEED_FRACTION * frames; + if (travelHeading >= 0) { + float angle = (travelHeading - yaw / RADIANS_PER_UNIT) * RADIANS_PER_UNIT; + position[0] += distance * (float) Math.sin(angle); + position[2] += distance * (float) Math.cos(angle); + } + position[1] += travelVertical * distance; + } + + static int headingOf(Set held) { + int heading = -1; + if (held.contains(KeyEvent.VK_W)) { + heading = 0; + } else if (held.contains(KeyEvent.VK_S)) { + heading = QUARTER_TURN * 2; + } + + if (held.contains(KeyEvent.VK_A)) { + heading = heading == 0 ? QUARTER_TURN * 7 / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 5 / 2 + : QUARTER_TURN * 3; + } else if (held.contains(KeyEvent.VK_D)) { + heading = heading == 0 ? QUARTER_TURN / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 3 / 2 + : QUARTER_TURN; + } + return heading; + } + + static int verticalOf(Set held) { + boolean up = held.contains(KeyEvent.VK_R) || held.contains(KeyEvent.VK_E) + || held.contains(KeyEvent.VK_SPACE); + boolean down = held.contains(KeyEvent.VK_F) || held.contains(KeyEvent.VK_Q) + || held.contains(KeyEvent.VK_SHIFT); + if (up == down) + return 0; + return up ? -1 : 1; + } + + private void turnUnits(float yawUnits, float pitchUnits) { + if (yawUnits == 0 && pitchUnits == 0) + return; + yaw += yawUnits * RADIANS_PER_UNIT; + pitch = clampPitch(pitch + pitchUnits * RADIANS_PER_UNIT); + } + + private static float clampPitch(float pitch) { + return Math.max(MIN_PITCH, Math.min(MAX_PITCH, pitch)); + } + + static int cameraValuesAt(Object[] args) { + if (args == null || args.length < 6) + return -1; + if (args[0] instanceof Scene && ((Scene) args[0]).getWorldViewId() != WorldView.TOPLEVEL) + return -1; + + for (int i = 0; i + 5 <= args.length; i++) + if (args[i] instanceof Float) + return i; + return -1; + } + + void interceptPreSceneDraw(Object[] args) { + int first = cameraValuesAt(args); + if (first >= 0) + swapCamera(args, first, true); + } + + void interceptDrawScene(Object[] args) { + if (args == null || args.length < 6) + return; + swapCamera(args, args.length - 6, false); + } + + private void swapCamera(Object[] args, int first, boolean asFloat) { + gamePosition[0] = ((Number) args[first]).floatValue(); + gamePosition[1] = ((Number) args[first + 1]).floatValue(); + gamePosition[2] = ((Number) args[first + 2]).floatValue(); + gamePitch = ((Number) args[first + 3]).floatValue(); + gameYaw = ((Number) args[first + 4]).floatValue(); + + if (!enabled) + return; + + if (!placed) { + System.arraycopy(gamePosition, 0, position, 0, 3); + yaw = gameYaw; + pitch = clampPitch(gamePitch); + placed = true; + log.debug( + "Flying from {}, {}, {} facing yaw {} pitch {}", + position[0], position[1], position[2], yaw, pitch + ); + } + + if (asFloat) { + args[first] = position[0]; + args[first + 1] = position[1]; + args[first + 2] = position[2]; + args[first + 3] = pitch; + args[first + 4] = yaw; + } else { + args[first] = (double) position[0]; + args[first + 1] = (double) position[1]; + args[first + 2] = (double) position[2]; + args[first + 3] = (double) pitch; + args[first + 4] = (double) yaw; + } + } + + private boolean dispatchKey(KeyEvent event) { + if (!enabled || isTyping()) + return false; + + int id = event.getID(); + int code = id == KeyEvent.KEY_TYPED + ? KeyEvent.getExtendedKeyCodeForChar(event.getKeyChar()) + : event.getKeyCode(); + + if (isModifier(code)) { + hold(id, code); + return false; + } + if (!isCameraKey(code)) + return false; + + hold(id, code); + return true; + } + + private void hold(int eventId, int keyCode) { + if (eventId == KeyEvent.KEY_PRESSED) { + if (heldKeys.isEmpty()) + log.debug("Flying on {}", KeyEvent.getKeyText(keyCode)); + heldKeys.add(keyCode); + } else if (eventId == KeyEvent.KEY_RELEASED) { + heldKeys.remove(keyCode); + } + } + + private static boolean isModifier(int keyCode) { + return keyCode == KeyEvent.VK_SHIFT || keyCode == KeyEvent.VK_CONTROL; + } + + private static boolean isTyping() { + return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof JTextComponent; + } + + private static boolean isCameraKey(int keyCode) { + switch (keyCode) { + case KeyEvent.VK_W: + case KeyEvent.VK_A: + case KeyEvent.VK_S: + case KeyEvent.VK_D: + case KeyEvent.VK_Q: + case KeyEvent.VK_E: + case KeyEvent.VK_R: + case KeyEvent.VK_F: + case KeyEvent.VK_SPACE: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_UP: + case KeyEvent.VK_DOWN: + return true; + default: + return false; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java new file mode 100644 index 0000000..a30b09a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Graphics; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.annotation.Nullable; +import javax.swing.JComponent; +import javax.swing.ToolTipManager; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; +import rs117.hd.dev.sceneloader.scene.BuiltModel; + +public class ModelPreview extends JComponent { + private static final double START_YAW = 0.6; + private static final double START_PITCH = 0.5; + private static final double RADIANS_PER_PIXEL = 0.012; + private static final double MAX_PITCH = Math.PI / 2 - 0.05; + private static final int CAPTION_HEIGHT = 13; + private static final int PADDING = 4; + + @Nullable + private BuiltModel model; + @Nullable + private int[] faceColors; + private String caption = ""; + private String emptyText = ""; + + private double yaw = START_YAW; + private double pitch = START_PITCH; + + private float[] rotatedX = new float[0], rotatedY = new float[0], rotatedZ = new float[0]; + private int[] faceOrder = new int[0]; + private float[] faceDepth = new float[0]; + private final int[] polyX = new int[3], polyY = new int[3]; + + public ModelPreview(int size) { + var bounds = new Dimension(size, size + CAPTION_HEIGHT); + setPreferredSize(bounds); + setMinimumSize(bounds); + setMaximumSize(bounds); + setFont(FontManager.getRunescapeSmallFont()); + ToolTipManager.sharedInstance().registerComponent(this); + + var drag = new MouseAdapter() { + private int lastX, lastY; + + @Override + public void mousePressed(MouseEvent e) { + lastX = e.getX(); + lastY = e.getY(); + } + + @Override + public void mouseDragged(MouseEvent e) { + yaw -= (e.getX() - lastX) * RADIANS_PER_PIXEL; + pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, pitch + (e.getY() - lastY) * RADIANS_PER_PIXEL)); + lastX = e.getX(); + lastY = e.getY(); + repaint(); + } + + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + yaw = START_YAW; + pitch = START_PITCH; + repaint(); + } + } + }; + addMouseListener(drag); + addMouseMotionListener(drag); + } + + public static final class Shape { + final BuiltModel model; + final int[] faceColors; + + public Shape(BuiltModel model, int[] faceColors) { + this.model = model; + this.faceColors = faceColors; + } + } + + public void show(@Nullable Shape shape, String caption, String emptyText) { + this.model = shape == null ? null : shape.model; + this.faceColors = shape == null ? null : shape.faceColors; + this.caption = caption; + this.emptyText = emptyText; + setToolTipText(caption.isEmpty() ? null : caption + " — drag to turn, double click to straighten"); + repaint(); + } + + public String getCaption() { + return caption; + } + + public void matchAngleOf(ModelPreview other) { + yaw = other.yaw; + pitch = other.pitch; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + try { + int width = getWidth(); + int height = getHeight() - CAPTION_HEIGHT; + + g.setColor(ColorScheme.DARKER_GRAY_COLOR); + g.fillRect(0, 0, width, height); + g.setColor(ColorScheme.MEDIUM_GRAY_COLOR); + g.drawRect(0, 0, width - 1, height - 1); + + if (model != null && faceColors != null && model.getFaceCount() > 0) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + paintModel(g, width, height); + } else { + g.setColor(ColorScheme.LIGHT_GRAY_COLOR); + g.setFont(getFont()); + int textWidth = g.getFontMetrics().stringWidth(emptyText); + g.drawString(emptyText, (width - textWidth) / 2, height / 2); + } + + if (!caption.isEmpty()) { + g.setColor(Color.LIGHT_GRAY); + g.setFont(getFont()); + int textWidth = g.getFontMetrics().stringWidth(caption); + g.drawString(caption, Math.max(0, (width - textWidth) / 2), height + CAPTION_HEIGHT - 3); + } + } finally { + g.dispose(); + } + } + + private void paintModel(Graphics2D g, int width, int height) { + assert model != null && faceColors != null; + + int vertexCount = model.getVerticesCount(); + float[] sourceX = model.getVerticesX(); + float[] sourceY = model.getVerticesY(); + float[] sourceZ = model.getVerticesZ(); + + if (rotatedX.length < vertexCount) { + rotatedX = new float[vertexCount]; + rotatedY = new float[vertexCount]; + rotatedZ = new float[vertexCount]; + } + + float sinYaw = (float) Math.sin(yaw), cosYaw = (float) Math.cos(yaw); + float sinPitch = (float) Math.sin(pitch), cosPitch = (float) Math.cos(pitch); + + float minX = Float.MAX_VALUE, maxX = -Float.MAX_VALUE; + float minY = Float.MAX_VALUE, maxY = -Float.MAX_VALUE; + for (int v = 0; v < vertexCount; v++) { + float x = sourceX[v], y = sourceY[v], z = sourceZ[v]; + + float turnedX = x * cosYaw - z * sinYaw; + float turnedZ = x * sinYaw + z * cosYaw; + float tippedY = y * cosPitch - turnedZ * sinPitch; + float tippedZ = y * sinPitch + turnedZ * cosPitch; + + rotatedX[v] = turnedX; + rotatedY[v] = tippedY; + rotatedZ[v] = tippedZ; + + if (turnedX < minX) minX = turnedX; + if (turnedX > maxX) maxX = turnedX; + if (tippedY < minY) minY = tippedY; + if (tippedY > maxY) maxY = tippedY; + } + + float spanX = Math.max(1, maxX - minX); + float spanY = Math.max(1, maxY - minY); + float scale = Math.min((width - 2 * PADDING) / spanX, (height - 2 * PADDING) / spanY); + float offsetX = width / 2f - (minX + maxX) / 2f * scale; + float offsetY = height / 2f - (minY + maxY) / 2f * scale; + + int faceCount = model.getFaceCount(); + int[] indicesA = model.getFaceIndices1(); + int[] indicesB = model.getFaceIndices2(); + int[] indicesC = model.getFaceIndices3(); + + if (faceOrder.length < faceCount) { + faceOrder = new int[faceCount]; + faceDepth = new float[faceCount]; + } + + int drawable = 0; + for (int f = 0; f < faceCount; f++) { + if (faceColors[f] < 0) + continue; + int a = indicesA[f], b = indicesB[f], c = indicesC[f]; + if (a >= vertexCount || b >= vertexCount || c >= vertexCount) + continue; + faceDepth[f] = rotatedZ[a] + rotatedZ[b] + rotatedZ[c]; + faceOrder[drawable++] = f; + } + + sortByDepthDescending(faceOrder, faceDepth, drawable); + + for (int i = 0; i < drawable; i++) { + int f = faceOrder[i]; + int a = indicesA[f], b = indicesB[f], c = indicesC[f]; + + polyX[0] = Math.round(rotatedX[a] * scale + offsetX); + polyX[1] = Math.round(rotatedX[b] * scale + offsetX); + polyX[2] = Math.round(rotatedX[c] * scale + offsetX); + polyY[0] = Math.round(rotatedY[a] * scale + offsetY); + polyY[1] = Math.round(rotatedY[b] * scale + offsetY); + polyY[2] = Math.round(rotatedY[c] * scale + offsetY); + + g.setColor(new Color(faceColors[f])); + g.fillPolygon(polyX, polyY, 3); + g.drawPolygon(polyX, polyY, 3); + } + } + + private static void sortByDepthDescending(int[] order, float[] depth, int count) { + for (int i = 1; i < count; i++) { + int face = order[i]; + float d = depth[face]; + int j = i - 1; + while (j >= 0 && depth[order[j]] < d) { + order[j + 1] = order[j]; + j--; + } + order[j + 1] = face; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java new file mode 100644 index 0000000..c3298b7 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java @@ -0,0 +1,874 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.Color; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Actor; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.Model; +import net.runelite.api.Projection; +import net.runelite.api.Renderable; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import net.runelite.api.events.GameTick; +import net.runelite.api.hooks.DrawCallbacks; +import net.runelite.client.callback.ClientThread; +import net.runelite.client.callback.RenderCallback; +import net.runelite.client.callback.RenderCallbackManager; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.ui.ClientToolbar; +import net.runelite.client.ui.NavigationButton; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.devtools.CameraOverlay; +import rs117.hd.dev.sceneloader.devtools.DevToolBridge; +import rs117.hd.dev.sceneloader.devtools.LocationOverlay; +import rs117.hd.dev.sceneloader.devtools.SceneToolsOverlay; +import rs117.hd.dev.sceneloader.devtools.SelectionHighlight; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantObject; +import rs117.hd.dev.sceneloader.scene.VariantOptions; +import rs117.hd.renderer.zone.ZoneRenderer; +import rs117.hd.scene.GamevalManager; + +import static net.runelite.api.Constants.MAX_Z; +import static rs117.hd.dev.sceneloader.scene.SceneBuilder.OFFSET; +import static rs117.hd.renderer.zone.SceneManager.NUM_ZONES; + +@Slf4j +@Singleton +public class SceneLoader implements RenderCallback { + @Inject + private Client client; + + @Inject + private ClientThread clientThread; + + @Inject + private ClientToolbar clientToolbar; + + @Inject + private EventBus eventBus; + + @Inject + private HdPlugin plugin; + + @Inject + private GamevalManager gamevalManager; + + @Inject + private RenderCallbackManager renderCallbackManager; + + @Inject + private FreeCamera camera; + + @Inject + private SelectionHighlight highlight; + + @Inject + private DevToolBridge runeliteDevTools; + + @Inject + private SceneToolsOverlay runeliteDevOverlay; + + @Inject + private LocationOverlay runeliteLocation; + + @Inject + private CameraOverlay runeliteCamera; + + private boolean started; + private NavigationButton button; + private SceneLoaderPanel panel; + + private ExecutorService worker; + + @Nullable + private volatile Definitions defs; + @Nullable + private volatile SceneBuilder builder; + + @Nullable + private volatile BuiltScene loaded; + private volatile boolean keepLoaded = true; + private volatile boolean loading; + + private volatile int plane; + private volatile boolean planesBelow = true; + private volatile boolean showRoofs; + private volatile Set allRoofIds = Set.of(); + private volatile boolean wantFreeCamera = true; + + private final VariantOptions variants = new VariantOptions(); + private volatile int lastWorldX = 3222, lastWorldY = 3218, lastChunks; + @Nullable + private volatile int[] lastStitched; + + @Nullable + private DrawCallbacks wrapped; + @Nullable + private DrawCallbacks wrapper; + + public void startUp() { + if (started) + return; + started = true; + eventBus.register(this); + renderCallbackManager.register(this); + camera.startUp(); + highlight.startUp(); + runeliteDevOverlay.startUp(); + runeliteLocation.startUp(); + runeliteCamera.startUp(); + worker = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "117 HD cache scene"); + thread.setDaemon(true); + return thread; + }); + + SwingUtilities.invokeLater(() -> { + if (button != null) + return; + panel = new SceneLoaderPanel(this); + button = NavigationButton.builder() + .tooltip("117 HD Cache Scene") + .icon(SceneLoaderPanel.createIcon()) + .priority(2) + .panel(panel) + .build(); + clientToolbar.addNavigation(button); + }); + } + + public void shutDown() { + if (!started) + return; + started = false; + eventBus.unregister(this); + renderCallbackManager.unregister(this); + camera.shutDown(); + highlight.shutDown(); + runeliteDevOverlay.shutDown(); + runeliteLocation.shutDown(); + runeliteCamera.shutDown(); + + restoreGameScene(); + releaseDetailDistance(); + runeliteDevTools.standDown(); + clientThread.invoke(this::unwrap); + + SwingUtilities.invokeLater(() -> { + if (panel != null) + panel.closeMap(); + if (button != null) { + clientToolbar.removeNavigation(button); + button = null; + panel = null; + } + }); + + if (worker != null) { + worker.shutdownNow(); + worker = null; + } + + var open = defs; + defs = null; + builder = null; + if (open != null) { + try { + open.close(); + } catch (Exception ex) { + log.warn("Failed to close the cache", ex); + } + } + } + + Client client() { + return client; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + public void setPlanesBelow(boolean planesBelow) { + this.planesBelow = planesBelow; + } + + public void setShowRoofs(boolean showRoofs) { + this.showRoofs = showRoofs; + } + + private void overrideLevels(Object[] args, int cameraValuesAt) { + int levels = cameraValuesAt + 5; + if (levels + 3 >= args.length) + return; + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + args[levels] = planesBelow ? 0 : level; + args[levels + 1] = level; + args[levels + 2] = MAX_Z - 1; + args[levels + 3] = showRoofs ? Set.of() : allRoofIds; + } + + private static final int DETAIL_DISTANCE_WHILE_LOADED = 320; + + private volatile int detailDistanceBefore = -1; + + private void holdDetailDistanceOpen() { + if (plugin.configDetailDrawDistance == DETAIL_DISTANCE_WHILE_LOADED) + return; + if (detailDistanceBefore < 0) + detailDistanceBefore = plugin.configDetailDrawDistance; + plugin.configDetailDrawDistance = DETAIL_DISTANCE_WHILE_LOADED; + } + + private void releaseDetailDistance() { + if (detailDistanceBefore < 0) + return; + plugin.configDetailDrawDistance = detailDistanceBefore; + detailDistanceBefore = -1; + } + + private void drawDynamics() { + var scene = loaded; + if (scene == null || scene.getDynamics().isEmpty()) + return; + + if (!(plugin.renderer instanceof ZoneRenderer)) + return; + Projection projection = ((ZoneRenderer) plugin.renderer).sceneCamera; + + int cycle = client.getGameCycle(); + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + int minLevel = planesBelow ? 0 : level; + var hiddenRoofIds = showRoofs ? Set.of() : allRoofIds; + int[][][] roofs = scene.getRoofs(); + + int drawn = 0; + for (BuiltScene.Dynamic dynamic : scene.getDynamics()) { + if (!isDrawnAt(dynamic, roofs, minLevel, level, hiddenRoofIds)) + continue; + + Model model = dynamic.renderable.modelAt(cycle); + if (model == null) + continue; + + plugin.renderer.drawDynamic( + -1, projection, scene, dynamic.tileObject, dynamic.renderable, model, + dynamic.orientation, dynamic.x, dynamic.y, dynamic.z + ); + drawn++; + } + reportDynamics(scene, cycle, drawn); + } + + private static boolean isDrawnAt( + BuiltScene.Dynamic dynamic, int[][][] roofs, int minLevel, int level, Set hiddenRoofIds + ) { + int objectLevel = dynamic.tileObject.getPlane(); + if (objectLevel < minLevel) + return false; + if (objectLevel <= level || objectLevel >= MAX_Z || hiddenRoofIds.isEmpty()) + return true; + + int tileX = (dynamic.x >> 7) + OFFSET; + int tileZ = (dynamic.z >> 7) + OFFSET; + var plan = roofs[objectLevel]; + if (tileX < 0 || tileX >= plan.length || tileZ < 0 || tileZ >= plan[tileX].length) + return true; + + int roofId = plan[tileX][tileZ]; + return roofId == 0 || !hiddenRoofIds.contains(roofId); + } + + /** + * Hands 117 HD the scene a zone at a time, solid parts first and see through parts last. + * + *

This is the game's job normally, and it does it by walking its own scene outwards from its own + * camera. Neither of those is what is on screen here, so the order it asks for is an order for + * somewhere else, and it hands over solid and see through parts of one zone before it reaches the next. + * + *

That order is not a detail. See through surfaces are drawn without writing depth, so nothing + * sorts them afterwards: whatever is drawn last is on top. 117 HD says as much where it draws them, + * that it relies on the zones arriving back to front. Water is drawn at the start of a zone's see + * through pass, so with the whole scene's solid parts laid down first it ends up between the two, which + * is where it belongs. Out of order, a river is painted over the bank in front of it. + */ + private void drawZones() { + var scene = loaded; + if (scene == null || !(plugin.renderer instanceof ZoneRenderer)) + return; + var renderer = (ZoneRenderer) plugin.renderer; + Projection projection = renderer.sceneCamera; + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + int minLevel = planesBelow ? 0 : level; + + // Solid first, and in any order: it writes depth, so it sorts itself + for (int zx = 0; zx < NUM_ZONES; zx++) + for (int zz = 0; zz < NUM_ZONES; zz++) + renderer.drawZoneOpaque(projection, scene, zx, zz); + + int[] order = zonesFurthestFirst(scene); + for (int at = minLevel; at <= MAX_Z - 1; at++) + for (int zone : order) + renderer.drawZoneAlpha(projection, scene, at, zone >> 8, zone & 0xFF); + } + + /** The zones, furthest from the camera first, which is the order see through parts have to be drawn in */ + private int[] zonesFurthestFirst(BuiltScene scene) { + int count = NUM_ZONES * NUM_ZONES; + int offset = scene.getSceneOffset(); + float cameraX = plugin.cameraPosition[0]; + float cameraZ = plugin.cameraPosition[2]; + // The camera rarely moves between consecutive frames, so skip re-sorting when nothing changed. + if (zoneOrder != null && zoneOrder.length == count && sortedScene == scene && sortedOffset == offset + && cameraX == sortedCameraX && cameraZ == sortedCameraZ) + return zoneOrder; + sortedScene = scene; + sortedOffset = offset; + sortedCameraX = cameraX; + sortedCameraZ = cameraZ; + + if (zoneOrder == null || zoneOrder.length != count) { + zoneOrder = new int[count]; + zoneDistance = new long[count]; + } + + for (int zx = 0, at = 0; zx < NUM_ZONES; zx++) { + for (int zz = 0; zz < NUM_ZONES; zz++, at++) { + // The middle of the zone, in the units the scene is measured in + float x = (zx * 8 - offset) * 128 + 512; + float z = (zz * 8 - offset) * 128 + 512; + float dx = x - cameraX; + float dz = z - cameraZ; + zoneOrder[at] = zx << 8 | zz; + zoneDistance[at] = (long) (dx * dx + dz * dz); + } + } + + // A plain insertion sort, since the order barely changes between one frame and the next + for (int i = 1; i < count; i++) { + int zone = zoneOrder[i]; + long distance = zoneDistance[i]; + int j = i - 1; + while (j >= 0 && zoneDistance[j] < distance) { + zoneOrder[j + 1] = zoneOrder[j]; + zoneDistance[j + 1] = zoneDistance[j]; + j--; + } + zoneOrder[j + 1] = zone; + zoneDistance[j + 1] = distance; + } + return zoneOrder; + } + + private int[] zoneOrder; + private long[] zoneDistance; + private BuiltScene sortedScene; + private int sortedOffset; + private float sortedCameraX = Float.NaN; + private float sortedCameraZ = Float.NaN; + + private volatile int dynamicsDrawnOnFrame = -1; + private long lastDynamicReport; + private volatile int acceptedLastFrame; + + private void reportDynamics(BuiltScene scene, int cycle, int drawn) { + long now = System.currentTimeMillis(); + if (now - lastDynamicReport < 1000) + return; + lastDynamicReport = now; + + var first = scene.getDynamics().get(0); + int posed = 0; + for (var dynamic : scene.getDynamics()) { + if (dynamic.renderable.posesDiffer()) { + if (posed == 0) + first = dynamic; + posed++; + } + } + int accepted = acceptedLastFrame; + + var current = panel; + if (current != null) { + current.setSummary(String.format( + "%s \u2014 animating %d (%d move), drawn %d, frame %d", + describe(scene), drawn, posed, accepted, first.renderable.getAnimFrame() + )); + } + + log.debug( + "Animating: handed over {} of {} ({} actually move), 117 HD drew {}, cycle {}, " + + "sampling {} on frame {} at {}, {}, {}", + drawn, scene.getDynamics().size(), posed, accepted, cycle, + first.renderable, first.renderable.getAnimFrame(), + first.x, first.y, first.z + ); + } + + private void nameFromGamevals(List found) { + if (found.isEmpty()) + return; + + try (var gamevals = gamevalManager.obtainHandle()) { + var byId = new HashMap(); + for (var gameval : gamevals.getObjects().entrySet()) + byId.putIfAbsent(gameval.getValue(), gameval.getKey()); + + for (VariantObject object : found) { + object.gameval = byId.get(object.baseId); + + var names = new String[object.variantIds.length]; + for (int i = 0; i < names.length; i++) + if (object.variantIds[i] != -1) + names[i] = byId.get(object.variantIds[i]); + object.variantGamevals = names; + } + } catch (Exception ex) { + log.warn("Could not name the variable objects", ex); + } + } + + private static Set roofIdsOf(BuiltScene scene) { + var ids = new HashSet(); + for (int[][] plane : scene.getRoofs()) + for (int[] column : plane) + for (int roofId : column) + if (roofId > 0) + ids.add(roofId); + return ids; + } + + public void setKeepLoaded(boolean keepLoaded) { + this.keepLoaded = keepLoaded; + } + + @Nullable + public String goToPlacement(VariantObject object, int which) { + var placements = object.placements; + if (placements.isEmpty()) + return null; + + int index = Math.floorMod(which, placements.size()); + var placed = placements.get(index); + String label = (index + 1) + " of " + placements.size(); + + clientThread.invoke(() -> { + camera.goTo(placed.x, placed.y, placed.z); + highlight.mark(placed, label); + }); + return label; + } + + public void setFreeCamera(boolean free) { + wantFreeCamera = free; + camera.setEnabled(free); + clientThread.invoke(this::updateHooks); + } + + public void setCameraSpeed(float speed) { + camera.setSpeed(speed); + } + + @Override + public boolean addEntity(Renderable renderable, boolean drawingUi) { + return loaded == null || !(renderable instanceof Actor); + } + + public VariantOptions getVariants() { + return variants; + } + + public boolean hasScene() { + return loaded != null; + } + + /** The scene on screen, or null while the game's own is being drawn */ + @Nullable + public BuiltScene getLoaded() { + return loaded; + } + + public void reload() { + var stitched = lastStitched; + if (stitched != null) { + loadStitched(stitched); + return; + } + load(lastWorldX, lastWorldY, lastChunks); + } + + public void loadStitched(int[] regionIds) { + if (regionIds.length == 0) + return; + if (regionIds.length == 1) { + lastStitched = null; + load(worldXOfRegion(regionIds[0]), worldYOfRegion(regionIds[0]), lastChunks); + return; + } + + var executor = worker; + if (executor == null) + return; + + lastStitched = regionIds.clone(); + var wanted = lastStitched; + + executor.submit(() -> { + try { + loading = true; + long start = System.nanoTime(); + + var scene = openCache().buildStitched(wanted, 0, variants); + long ms = (System.nanoTime() - start) / 1_000_000; + + int[] placed = scene.getMapRegions(); + var names = new StringBuilder(); + for (int i = 0; i < placed.length; i++) + names.append(i == 0 ? "" : ", ").append(placed[i]); + + String status = "Stitched " + names + " in " + ms + "ms"; + if (placed.length < wanted.length) + status += " — " + (wanted.length - placed.length) + " would not fit"; + finish(scene, status); + } catch (Throwable ex) { + log.error("Failed to stitch regions", ex); + setStatus("Could not stitch: " + ex.getMessage(), Color.RED.darker()); + } finally { + loading = false; + } + }); + } + + private static int worldXOfRegion(int region) { + return ((region >> 8) << 6) + 32; + } + + private static int worldYOfRegion(int region) { + return ((region & 0xFF) << 6) + 32; + } + + private void finish(BuiltScene scene, String status) { + loaded = scene; + runeliteDevTools.standIn(); + allRoofIds = roofIdsOf(scene); + var found = variants.getFound(); + nameFromGamevals(found); + var current = panel; + if (current != null) + current.setVariantObjects(found); + + apply(scene, () -> { + setStatus(status, Color.GREEN.darker()); + setSummary(describe(scene) + ", " + found.size() + " variable, " + + scene.getDynamics().size() + " animating"); + if (wantFreeCamera) + camera.setEnabled(true); + }); + } + + public void load(int worldX, int worldY, int expandedChunks) { + var executor = worker; + if (executor == null) + return; + + lastStitched = null; + lastWorldX = worldX; + lastWorldY = worldY; + lastChunks = expandedChunks; + + executor.submit(() -> { + try { + loading = true; + long start = System.nanoTime(); + + var sceneBuilder = openCache(); + var scene = sceneBuilder.build(worldX, worldY, expandedChunks, 0, variants); + long ms = (System.nanoTime() - start) / 1_000_000; + + loaded = scene; + runeliteDevTools.standIn(); + allRoofIds = roofIdsOf(scene); + var found = variants.getFound(); + nameFromGamevals(found); + var current = panel; + if (current != null) + current.setVariantObjects(found); + + apply(scene, () -> { + setStatus("Loaded " + worldX + ", " + worldY + " in " + ms + "ms", Color.GREEN.darker()); + setSummary(describe(scene) + ", " + found.size() + " variable, " + + scene.getDynamics().size() + " animating"); + if (wantFreeCamera) + camera.setEnabled(true); + }); + } catch (Throwable ex) { + log.error("Failed to build a scene from the cache", ex); + setStatus(String.valueOf(ex.getMessage()), Color.RED.brighter()); + } finally { + loading = false; + } + }); + } + + public void restoreGameScene() { + if (loaded == null) + return; + loaded = null; + releaseDetailDistance(); + runeliteDevTools.standDown(); + camera.setEnabled(false); + clientThread.invoke(() -> { + var worldView = client.getTopLevelWorldView(); + if (worldView == null || client.getGameState() != GameState.LOGGED_IN) + return; + handOver(worldView, worldView.getScene()); + updateHooks(); + }); + setStatus("Back to the game's scene", Color.LIGHT_GRAY); + setSummary(" "); + } + + public void previewObject(int objectId, Consumer onReady) { + var pool = worker; + if (pool == null) + return; + if (objectId < 0) { + SwingUtilities.invokeLater(() -> onReady.accept(null)); + return; + } + + pool.submit(() -> { + ModelPreview.Shape shape = null; + try { + shape = openCache().preview(objectId, -1); + } catch (Exception ex) { + log.warn("Could not build a preview of object {}", objectId, ex); + } + + var built = shape; + SwingUtilities.invokeLater(() -> onReady.accept(built)); + }); + } + + private SceneBuilder openCache() throws Exception { + var existing = builder; + if (existing != null) + return existing; + + synchronized (this) { + if (builder == null) { + var opened = new Definitions(Definitions.findDefaultCache()); + defs = opened; + builder = new SceneBuilder(opened); + } + return builder; + } + } + + private void apply(BuiltScene scene, Runnable onApplied) { + clientThread.invoke(() -> { + if (client.getGameState() != GameState.LOGGED_IN) + return false; + + var worldView = client.getTopLevelWorldView(); + if (worldView == null) + return false; + + handOver(worldView, scene); + updateHooks(); + onApplied.run(); + return true; + }); + } + + private void handOver(WorldView worldView, Scene scene) { + assert client.isClientThread(); + plugin.renderer.loadScene(worldView, scene); + plugin.renderer.swapScene(scene); + + for (int x = 0; x < NUM_ZONES; x++) + for (int z = 0; z < NUM_ZONES; z++) + plugin.renderer.invalidateZone(scene, x, z); + } + + private static final Set PER_FRAME_DRAWS = Set.of("draw", "drawDynamic", "drawTemp"); + + /** + * The two calls that say which part of the scene to draw next, and in what order. + * + *

The game makes these as it walks its own scene outwards from its own camera, and neither is this + * one. They are dropped and reissued in {@link #drawZones} instead. + */ + private static final Set ZONE_DRAWS = Set.of("drawZoneOpaque", "drawZoneAlpha"); + + private void updateHooks() { + assert client.isClientThread(); + if (loaded != null || camera.isEnabled()) { + wrap(); + } else { + unwrap(); + } + } + + private void wrap() { + DrawCallbacks current = client.getDrawCallbacks(); + if (current == wrapper) + return; + if (current == null) { + log.warn("Nothing is drawing the scene, so there is nothing to step in front of"); + return; + } + + wrapped = current; + wrapper = (DrawCallbacks) Proxy.newProxyInstance( + DrawCallbacks.class.getClassLoader(), + new Class[] { DrawCallbacks.class }, + new Hooks(current) + ); + client.setDrawCallbacks(wrapper); + log.debug("Stepped in front of {}", current.getClass().getSimpleName()); + } + + private void unwrap() { + if (wrapper != null && client.getDrawCallbacks() == wrapper) + client.setDrawCallbacks(wrapped); + wrapper = null; + wrapped = null; + } + + private class Hooks implements InvocationHandler { + private final DrawCallbacks target; + + Hooks(DrawCallbacks target) { + this.target = target; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String name = method.getName(); + + boolean preSceneDraw = "preSceneDraw".equals(name); + int cameraValuesAt = -1; + + if (preSceneDraw) { + acceptedLastFrame = plugin.drawnDynamicRenderableCount; + cameraValuesAt = FreeCamera.cameraValuesAt(args); + if (cameraValuesAt >= 0) { + camera.interceptPreSceneDraw(args); + if (loaded != null) + overrideLevels(args, cameraValuesAt); + } + if (loaded != null) + holdDetailDistanceOpen(); + } else if ("drawScene".equals(name)) { + camera.interceptDrawScene(args); + } else if (loaded != null && ZONE_DRAWS.contains(name)) { + return null; + } else if (skipsDraw(name, args, loaded)) { + return null; + } + + Object result; + try { + result = method.invoke(target, args); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + + if (preSceneDraw && cameraValuesAt >= 0 && plugin.frame != dynamicsDrawnOnFrame) { + dynamicsDrawnOnFrame = plugin.frame; + // Animating things first: they hand their see through parts to the zone they stand in, and + // a zone sorts what it has been given when it is asked to draw it + drawDynamics(); + drawZones(); + } + return result; + } + } + + static boolean skipsDraw(String method, @Nullable Object[] args, @Nullable BuiltScene loaded) { + if (loaded == null || args == null || !PER_FRAME_DRAWS.contains(method)) + return false; + + for (Object arg : args) + if (arg instanceof Scene) + return arg != loaded; + return false; + } + + @Subscribe + public void onGameTick(GameTick event) { + var scene = loaded; + if (!keepLoaded || scene == null || loading) + return; + + var context = plugin.renderer.getSceneContext(); + if (context == null || context.scene == scene) + return; + + log.debug("The game replaced the cache scene, putting it back"); + apply(scene, () -> {}); + } + + private static String describe(BuiltScene scene) { + int floors = 0; + int objects = 0; + var tiles = scene.getExtendedTiles(); + for (int plane = 0; plane < tiles.length; plane++) { + for (int x = 0; x < tiles[plane].length; x++) { + for (int y = 0; y < tiles[plane][x].length; y++) { + var tile = tiles[plane][x][y]; + if (tile == null) + continue; + if (tile.getSceneTilePaint() != null || tile.getSceneTileModel() != null) + floors++; + for (var object : tile.getGameObjects()) + if (object != null) + objects++; + if (tile.getWallObject() != null) + objects++; + if (tile.getDecorativeObject() != null) + objects++; + if (tile.getGroundObject() != null) + objects++; + } + } + } + return floors + " floors, " + objects + " objects"; + } + + private void setStatus(String text, Color color) { + var current = panel; + if (current != null) + current.setStatus(text, color); + } + + private void setSummary(String text) { + var current = panel; + if (current != null) + current.setSummary(text); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java new file mode 100644 index 0000000..a0cd998 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java @@ -0,0 +1,863 @@ +package rs117.hd.dev.sceneloader; + +import rs117.hd.dev.editor.EditorScrollPane; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.PluginPanel; +import rs117.hd.dev.sceneloader.map.MapHost; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantObject; +import rs117.hd.dev.sceneloader.scene.VariantOptions; + +import static net.runelite.api.Constants.REGION_SIZE; + +public class SceneLoaderPanel extends PluginPanel { + /** Somewhere recognisable for the map to open looking at, which is not the same as picking it */ + private static final int LUMBRIDGE = 50 << 8 | 50; + + private static final int ROW_HEIGHT = 24; + private static final int SPINNER_WIDTH = 66; + private static final int WIDE_SPINNER_WIDTH = 100; + private static final int ICON_BUTTON_WIDTH = 26; + private static final int LIST_HEIGHT = 150; + private static final int PREVIEW_SIZE = 86; + private static final int FIRST_FORM_ITEM = 2; + + private final SceneLoader tools; + + private final JTextField regionIds = new JTextField(); + private final JLabel regionNote = note(Color.GRAY); + private final JSpinner expandedChunks = spinner(5, 0, 5); + private final JSpinner plane = spinner(0, 0, 3); + private final JCheckBox planesBelow = new JCheckBox("Draw planes below", true); + private final JCheckBox showRoofs = new JCheckBox("Draw roofs", false); + private final JCheckBox keepLoaded = new JCheckBox("Keep loaded", true); + private final JCheckBox freeCamera = new JCheckBox("Free camera", true); + private final JSpinner cameraSpeed = spinner(1, 1, 20); + + private final JLabel status = note(Color.LIGHT_GRAY); + private final JLabel summary = note(Color.GRAY); + + private final DefaultListModel variantModel = new DefaultListModel<>(); + private final JList variantList = new JList<>(variantModel); + private final JComboBox formChoice = new JComboBox<>(); + private final JLabel variantHeading = heading("Variable objects"); + private final JLabel formLabel = heading("Form"); + private final ModelPreview nowPreview = new ModelPreview(PREVIEW_SIZE); + private final ModelPreview nextPreview = new ModelPreview(PREVIEW_SIZE); + private JPanel previewRow; + private int[] formOptions = new int[0]; + private JButton goTo; + private int goToIndex; + private JButton applyForm; + private JButton resetForm; + private JScrollPane variantScroll; + + @Nullable + private MapHost mapHost; + + private int filling; + + public SceneLoaderPanel(SceneLoader tools) { + super(true); + this.tools = tools; + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + setBackground(ColorScheme.DARK_GRAY_COLOR); + + regionIds.setToolTipText( + "One region id, or several separated by commas to lay them out side by side. " + + "Up to " + SceneBuilder.MAX_STITCHED_REGIONS + " fit, " + + SceneBuilder.REGIONS_PER_SIDE + " to a side, and extra chunks are ignored for those."); + regionIds.setFont(FontManager.getRunescapeSmallFont()); + add(labelled("Region ID", narrow(regionIds, WIDE_SPINNER_WIDTH), mapButton())); + add(regionNote); + add(Box.createVerticalStrut(6)); + + expandedChunks.setToolTipText("How far past the usual scene to build, in chunks of eight tiles"); + expandedChunks.addChangeListener(e -> { + if (mapHost != null) + mapHost.refresh(); + }); + add(labelled("Extra chunks", expandedChunks, SPINNER_WIDTH)); + add(Box.createVerticalStrut(8)); + + plane.setToolTipText("Which plane to look at, in place of the one the player is standing on"); + plane.addChangeListener(e -> { + tools.setPlane((Integer) plane.getValue()); + if (filling == 0) + reloadForPlane(); + }); + add(labelled("Plane", plane, SPINNER_WIDTH)); + add(Box.createVerticalStrut(4)); + + checkBox(planesBelow, "Keep the planes under the one being looked at, rather than only that one"); + planesBelow.addActionListener(e -> tools.setPlanesBelow(planesBelow.isSelected())); + add(planesBelow); + add(Box.createVerticalStrut(4)); + + checkBox(showRoofs, "Leave the roofs on. Turning them off opens up everything above the plane below."); + showRoofs.addActionListener(e -> tools.setShowRoofs(showRoofs.isSelected())); + add(showRoofs); + add(Box.createVerticalStrut(8)); + + checkBox(keepLoaded, "Put the scene back whenever the game replaces it, such as when you move"); + keepLoaded.addActionListener(e -> tools.setKeepLoaded(keepLoaded.isSelected())); + add(keepLoaded); + add(Box.createVerticalStrut(4)); + + checkBox(freeCamera, + "Flies the view instead of following the player, and comes on whenever a scene is loaded. " + + "Moves the way the game's own detached camera does: WASD travels level, space or R to rise, " + + "shift or Q or F to drop, control to go slowly, and the arrow keys or a drag with the mouse " + + "wheel held to look around."); + freeCamera.addActionListener(e -> { + tools.setFreeCamera(freeCamera.isSelected()); + cameraSpeed.setEnabled(freeCamera.isSelected()); + }); + cameraSpeed.setToolTipText("How fast flying moves. One is exactly the speed of the game's own camera."); + cameraSpeed.addChangeListener(e -> tools.setCameraSpeed((Integer) cameraSpeed.getValue())); + add(alongside(freeCamera, cameraSpeed)); + + add(Box.createVerticalStrut(10)); + add(status); + add(summary); + + add(Box.createVerticalStrut(10)); + add(variantHeading); + add(Box.createVerticalStrut(2)); + buildVariantSection(); + + add(Box.createVerticalStrut(10)); + add(button("Load from cache", "Build the scene at these coordinates and hand it to 117 HD", this::load)); + add(Box.createVerticalStrut(4)); + add(button("Back to the game", "Drop the cache scene and let the game's own scene render again", + tools::restoreGameScene)); + + regionIds.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + regionsChanged(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + regionsChanged(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + regionsChanged(); + } + }); + updateRegionNote(); + + setVariantObjects(List.of()); + } + + private void buildVariantSection() { + variantList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + variantList.setBackground(ColorScheme.DARKER_GRAY_COLOR); + variantList.setForeground(Color.LIGHT_GRAY); + variantList.setFont(FontManager.getRunescapeSmallFont()); + variantList.setCellRenderer(new VariantRenderer()); + variantList.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) + showFormsFor(variantList.getSelectedValue()); + }); + + variantScroll = new EditorScrollPane(variantList); + variantScroll.setAlignmentX(Component.LEFT_ALIGNMENT); + variantScroll.setPreferredSize(new Dimension(contentWidth(), LIST_HEIGHT)); + variantScroll.setMaximumSize(new Dimension(Integer.MAX_VALUE, LIST_HEIGHT)); + variantScroll.setBorder(BorderFactory.createLineBorder(ColorScheme.DARKER_GRAY_COLOR)); + add(variantScroll); + + add(Box.createVerticalStrut(6)); + add(formLabel); + add(dropdown(formChoice, "Which form this object takes, since the cache alone does not decide it", + this::chooseForm)); + + add(Box.createVerticalStrut(4)); + previewRow = sideBySide(nowPreview, nextPreview); + add(previewRow); + + add(Box.createVerticalStrut(4)); + goTo = button("Go to", "Fly to this object in the scene and ring it", this::goToNext); + add(goTo); + + add(Box.createVerticalStrut(4)); + applyForm = button("Apply transform", "Rebuild the scene with the chosen form in place", this::applyForm); + add(applyForm); + add(Box.createVerticalStrut(2)); + resetForm = button("Reset to default", "Put this object back to the form the game would pick", + this::resetForm); + add(resetForm); + + } + + private void reloadForPlane() { + if (!tools.hasScene()) + return; + setStatus("Rebuilding on plane " + plane.getValue() + "...", Color.LIGHT_GRAY); + tools.reload(); + } + + private void load() { + int[] wanted = wantedRegions(); + if (wanted.length == 0) { + setStatus("No region id to load", Color.GRAY); + return; + } + + getOutOfTheWay(); + + if (wanted.length > 1) { + int fit = SceneBuilder.regionsThatFit(wanted).length; + setStatus("Stitching " + fit + " regions...", Color.LIGHT_GRAY); + tools.loadStitched(wanted); + return; + } + + int region = wanted[0]; + setStatus("Loading region " + region + "...", Color.LIGHT_GRAY); + tools.load(worldXOf(region), worldYOf(region), (Integer) expandedChunks.getValue()); + } + + /** + * Puts the game view back before loading, where the map is sitting over it. + * + *

A map in a window of its own is left alone: there is nothing in the way, and closing it would + * mean opening it again for the next pick. + */ + private void getOutOfTheWay() { + if (mapHost != null && mapHost.isOpen() && !mapHost.isPoppedOut()) + mapHost.close(); + } + + private int[] wantedRegions() { + var found = new ArrayList(); + for (String part : regionIds.getText().split("[, ]+")) { + if (part.isEmpty()) + continue; + try { + int region = Integer.parseInt(part.trim()); + if (region >= 0 && region <= 0xFFFF) + found.add(region); + } catch (NumberFormatException ignored) { + } + } + + var regions = new int[found.size()]; + for (int i = 0; i < regions.length; i++) + regions[i] = found.get(i); + return regions; + } + + private void regionsChanged() { + updateRegionNote(); + int[] wanted = wantedRegions(); + expandedChunks.setEnabled(wanted.length <= 1); + if (mapHost != null) { + mapHost.setListed(wanted); + mapHost.refresh(); + } + } + + /** Ctrl clicking a region picks it, and ctrl clicking a picked one takes it back out */ + private void toggleRegion(int region) { + int[] wanted = wantedRegions(); + + var kept = new ArrayList(); + boolean removed = false; + for (int already : wanted) { + if (already == region) { + removed = true; + continue; + } + kept.add(already); + } + + if (removed) { + setRegions(kept); + setStatus("Took region " + region + " back out, " + kept.size() + " picked", Color.LIGHT_GRAY); + return; + } + + if (wanted.length >= SceneBuilder.MAX_STITCHED_REGIONS) { + setStatus( + SceneBuilder.MAX_STITCHED_REGIONS + " regions at a time is the most this picks up", + Color.GRAY + ); + return; + } + + kept.add(region); + setRegions(kept); + setStatus("Picked region " + region + ", " + kept.size() + " picked", Color.LIGHT_GRAY); + } + + /** Drops back to a single region, which is the mode everything else in the panel is written for */ + private void clearPickedRegions() { + int[] wanted = wantedRegions(); + regionIds.setText(wanted.length == 0 ? "" : String.valueOf(wanted[0])); + setStatus("Back to one region at a time", Color.LIGHT_GRAY); + } + + private void setRegions(java.util.List regions) { + var text = new StringBuilder(); + for (int region : regions) + text.append(text.length() == 0 ? "" : ", ").append(region); + regionIds.setText(text.toString()); + } + + private void updateRegionNote() { + int[] wanted = wantedRegions(); + if (wanted.length == 0) { + regionNote.setText("No region"); + regionNote.setToolTipText(null); + return; + } + + if (wanted.length > 1) { + int fit = SceneBuilder.regionsThatFit(wanted).length; + String text = fit + " regions laid out"; + if (wanted.length > fit) + text += ", " + (wanted.length - fit) + " will not fit"; + regionNote.setText(text); + regionNote.setForeground(wanted.length > fit ? Color.ORANGE.darker() : Color.GRAY); + regionNote.setToolTipText( + "Regions that adjoin in the world are laid against each other, and anything unrelated is " + + "set apart. Whether they all fit depends on their shape, not just how many there are: the " + + "scene is " + SceneBuilder.EXTENDED + " tiles across, so a pair side by side next to " + + "a pair stacked up needs more room than there is."); + return; + } + + int region = wanted[0]; + String text = (region >> 8) + ", " + (region & 0xFF) + + " at " + worldXOf(region) + ", " + worldYOf(region); + regionNote.setText(text); + regionNote.setForeground(Color.GRAY); + regionNote.setToolTipText("Region " + (region >> 8) + ", " + (region & 0xFF) + + ", centred on world tile " + worldXOf(region) + ", " + worldYOf(region)); + } + + private static int worldXOf(int region) { + return ((region >> 8) << 6) + REGION_SIZE / 2; + } + + private static int worldYOf(int region) { + return ((region & 0xFF) << 6) + REGION_SIZE / 2; + } + + public void setVariantObjects(List objects) { + SwingUtilities.invokeLater(() -> { + filling++; + try { + VariantObject previous = variantList.getSelectedValue(); + + variantModel.clear(); + for (VariantObject object : objects) + variantModel.addElement(object); + + boolean any = !objects.isEmpty(); + variantHeading.setVisible(any); + variantScroll.setVisible(any); + formLabel.setVisible(any); + formChoice.setVisible(any); + + if (previous != null) { + for (VariantObject object : objects) { + if (object.baseId == previous.baseId) { + variantList.setSelectedValue(object, true); + break; + } + } + } + } finally { + filling--; + } + showFormsFor(variantList.getSelectedValue()); + }); + } + + private void showFormsFor(@Nullable VariantObject object) { + filling++; + try { + formChoice.removeAllItems(); + goToIndex = 0; + + if (object == null) { + formOptions = new int[0]; + formChoice.setEnabled(false); + retitle(formLabel, "Form"); + return; + } + + formChoice.setEnabled(true); + int fallback = object.firstVisibleVariant(); + formChoice.addItem(fallback < 0 ? "Default" : "Default (" + fallback + ")"); + formChoice.addItem("Hidden"); + + var offered = new ArrayList(); + for (int i = 0; i < object.variantIds.length; i++) { + if (object.variantIds[i] == -1) + continue; + formChoice.addItem(i + ": " + object.variantLabel(i)); + offered.add(i); + } + formOptions = new int[offered.size()]; + for (int i = 0; i < formOptions.length; i++) + formOptions[i] = offered.get(i); + + retitle(formLabel, formOptions.length == object.variantIds.length + ? "Form" + : "Form — " + formOptions.length + " of " + object.variantIds.length); + + int choice = tools.getVariants().choiceFor(object.baseId); + if (choice == VariantOptions.HIDDEN) { + formChoice.setSelectedIndex(1); + } else { + int item = itemForForm(choice); + formChoice.setSelectedIndex(item < 0 ? 0 : item); + } + } finally { + filling--; + updatePreviews(); + } + } + + private void chooseForm() { + if (filling > 0) + return; + updatePreviews(); + } + + private int pendingChoice() { + int selected = formChoice.getSelectedIndex(); + if (selected <= 0) + return VariantOptions.DEFAULT; + if (selected == 1) + return VariantOptions.HIDDEN; + + int form = selected - FIRST_FORM_ITEM; + return form < formOptions.length ? formOptions[form] : VariantOptions.DEFAULT; + } + + private int itemForForm(int form) { + for (int i = 0; i < formOptions.length; i++) + if (formOptions[i] == form) + return FIRST_FORM_ITEM + i; + return -1; + } + + private static int objectFor(VariantObject object, int choice) { + if (choice == VariantOptions.HIDDEN) + return -1; + + int index = choice == VariantOptions.DEFAULT ? object.firstVisibleVariant() : choice; + if (index < 0 || index >= object.variantIds.length) + index = object.firstVisibleVariant(); + if (index < 0) + return -1; + return object.variantIds[index]; + } + + private void updatePreviews() { + if (previewRow == null) + return; + + VariantObject object = variantList.getSelectedValue(); + boolean any = object != null; + previewRow.setVisible(any); + goTo.setVisible(any); + applyForm.setVisible(any); + resetForm.setVisible(any); + if (!any) { + nowPreview.show(null, "", ""); + nextPreview.show(null, "", ""); + return; + } + + int applied = tools.getVariants().choiceFor(object.baseId); + int pending = pendingChoice(); + int appliedId = object.appliedId; + int pendingId = objectFor(object, pending); + + boolean changes = pending != applied && pendingId != appliedId; + applyForm.setEnabled(changes); + applyForm.setText(changes ? "Apply transform" : "Already this form"); + applyForm.setToolTipText( + changes + ? "Rebuild the scene with the chosen form in place" + : "The scene already has this object as " + (appliedId < 0 ? "nothing" : appliedId) + + ", so there is nothing to apply. Pick a different form." + ); + resetForm.setEnabled(applied != VariantOptions.DEFAULT); + + int copies = object.placements.size(); + goTo.setEnabled(copies > 0); + goTo.setText(copies > 1 ? "Go to next of " + copies : "Go to"); + goTo.setToolTipText( + copies == 0 + ? "This object is not standing anywhere in the scene, so there is nowhere to go" + : copies == 1 + ? "Fly to this object and ring it" + : "Fly to the next of the " + copies + " in the scene, coming back round to the first" + ); + + loadPreview(nowPreview, appliedId, "Now", null); + loadPreview(nextPreview, pendingId, "After", nowPreview); + } + + private void goToNext() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + String where = tools.goToPlacement(object, goToIndex); + if (where == null) { + setStatus("Nowhere to go: " + object.label() + " is not in the scene", Color.GRAY); + return; + } + goToIndex++; + if (!freeCamera.isSelected()) { + freeCamera.setSelected(true); + cameraSpeed.setEnabled(true); + } + setStatus("Looking at " + object.label() + ", " + where, Color.LIGHT_GRAY); + } + + private void loadPreview(ModelPreview preview, int objectId, String caption, @Nullable ModelPreview matchAngle) { + String label = objectId < 0 ? caption + ": nothing" : caption + ": " + objectId; + preview.show(null, label, "..."); + tools.previewObject(objectId, shape -> { + if (!label.equals(preview.getCaption())) + return; + preview.show(shape, label, objectId < 0 ? "Nothing" : "No model"); + if (matchAngle != null) + preview.matchAngleOf(matchAngle); + }); + } + + private void applyForm() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + int choice = pendingChoice(); + int applied = objectFor(object, choice); + tools.getVariants().setChoice(object.baseId, choice); + updatePreviews(); + setStatus( + "Rebuilding with " + object.label() + " as " + (applied < 0 ? "nothing" : applied) + "...", + Color.LIGHT_GRAY + ); + tools.reload(); + } + + private void resetForm() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + tools.getVariants().setChoice(object.baseId, VariantOptions.DEFAULT); + filling++; + try { + formChoice.setSelectedIndex(0); + } finally { + filling--; + } + updatePreviews(); + setStatus("Rebuilding with " + object.label() + " at its default...", Color.LIGHT_GRAY); + tools.reload(); + } + + public void setStatus(String text, Color color) { + SwingUtilities.invokeLater(() -> { + status.setText(text); + status.setToolTipText(text); + status.setForeground(color); + }); + } + + public void setSummary(String text) { + SwingUtilities.invokeLater(() -> { + summary.setText(text); + summary.setToolTipText(text); + }); + } + + + private static int contentWidth() { + return PANEL_WIDTH - 2 * BORDER_OFFSET; + } + + private static void retitle(JLabel label, String text) { + label.setMaximumSize(null); + label.setText(text); + label.setMaximumSize(label.getPreferredSize()); + } + + private static JLabel heading(String text) { + JLabel label = new JLabel(text); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(Color.LIGHT_GRAY); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setMaximumSize(label.getPreferredSize()); + return label; + } + + private static JLabel note(Color color) { + JLabel label = new JLabel(" "); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(color); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setMaximumSize(new Dimension(Integer.MAX_VALUE, 16)); + return label; + } + + private static JPanel labelled(String text, JComponent field, @Nullable Component after) { + JPanel panel = row(); + panel.add(heading(text)); + panel.add(Box.createHorizontalGlue()); + panel.add(field); + if (after != null) { + panel.add(Box.createHorizontalStrut(4)); + panel.add(after); + } + return panel; + } + + private static JTextField narrow(JTextField field, int width) { + field.setMaximumSize(new Dimension(width, ROW_HEIGHT)); + field.setPreferredSize(new Dimension(width, ROW_HEIGHT)); + return field; + } + + private static JPanel labelled(String text, JSpinner spinner, int width) { + return labelled(text, spinner, width, null); + } + + private static JPanel labelled(String text, JSpinner spinner, int width, @Nullable Component after) { + JPanel panel = row(); + panel.add(heading(text)); + panel.add(Box.createHorizontalGlue()); + panel.add(narrow(spinner, width)); + if (after != null) { + panel.add(Box.createHorizontalStrut(4)); + panel.add(after); + } + return panel; + } + + private JButton mapButton() { + JButton button = new JButton(new ImageIcon(createMapIcon())); + button.setToolTipText("Pick a region off the world map, or close it if it is already open"); + button.setMargin(new Insets(0, 0, 0, 0)); + var size = new Dimension(ICON_BUTTON_WIDTH, ROW_HEIGHT); + button.setPreferredSize(size); + button.setMaximumSize(size); + button.addActionListener(e -> toggleMap()); + return button; + } + + private static JPanel alongside(JCheckBox box, JSpinner spinner) { + JPanel panel = row(); + box.setMaximumSize(box.getPreferredSize()); + panel.add(box); + panel.add(Box.createHorizontalGlue()); + panel.add(narrow(spinner, SPINNER_WIDTH)); + return panel; + } + + private static JSpinner narrow(JSpinner spinner, int width) { + spinner.setMaximumSize(new Dimension(width, ROW_HEIGHT)); + spinner.setPreferredSize(new Dimension(width, ROW_HEIGHT)); + return spinner; + } + + private static void checkBox(JCheckBox box, String tooltip) { + box.setBackground(ColorScheme.DARK_GRAY_COLOR); + box.setForeground(Color.LIGHT_GRAY); + box.setAlignmentX(Component.LEFT_ALIGNMENT); + box.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + box.setToolTipText(tooltip); + } + + private static JPanel sideBySide(ModelPreview left, ModelPreview right) { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + panel.setBackground(ColorScheme.DARK_GRAY_COLOR); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, left.getPreferredSize().height)); + panel.add(left); + panel.add(Box.createHorizontalStrut(4)); + panel.add(right); + panel.add(Box.createHorizontalGlue()); + return panel; + } + + private static JPanel row() { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + panel.setBackground(ColorScheme.DARK_GRAY_COLOR); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + return panel; + } + + private static JButton button(String text, String tooltip, Runnable action) { + JButton button = new JButton(text); + button.setToolTipText(tooltip); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + button.addActionListener(e -> action.run()); + return button; + } + + private static JComboBox dropdown(JComboBox combo, String tooltip, Runnable action) { + combo.setFont(FontManager.getRunescapeSmallFont()); + combo.setAlignmentX(Component.LEFT_ALIGNMENT); + combo.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + combo.setToolTipText(tooltip); + combo.addActionListener(e -> action.run()); + return combo; + } + + private static JSpinner spinner(int value, int min, int max) { + JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, min, max, 1)); + var editor = new JSpinner.NumberEditor(spinner, "#"); + editor.getTextField().setHorizontalAlignment(JTextField.LEFT); + spinner.setEditor(editor); + + spinner.setMinimumSize(new Dimension(44, ROW_HEIGHT)); + spinner.setPreferredSize(new Dimension(60, ROW_HEIGHT)); + spinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + return spinner; + } + + private void toggleMap() { + if (mapHost != null && mapHost.isOpen()) { + mapHost.close(); + return; + } + + if (mapHost == null) { + mapHost = new MapHost( + tools.client(), + region -> regionIds.setText(String.valueOf(region)), + region -> { + regionIds.setText(String.valueOf(region)); + load(); + }, + this::coverageOf + ); + mapHost.setOnAdded(this::toggleRegion); + mapHost.setOnCleared(this::clearPickedRegions); + } + + int[] wanted = wantedRegions(); + mapHost.setListed(wanted); + mapHost.open(wanted.length == 0 ? LUMBRIDGE : wanted[0]); + } + + @Nullable + private int[] coverageOf(int region) { + // Picked regions are laid out side by side rather than where they sit in the world, and nothing is + // loaded around them, so the only true thing to show is which ones are picked + if (region < 0 || wantedRegions().length > 1) + return null; + return SceneBuilder.sceneTiles( + worldXOf(region), worldYOf(region), (Integer) expandedChunks.getValue()); + } + + public void closeMap() { + if (mapHost != null) + mapHost.close(); + } + + private static BufferedImage createMapIcon() { + BufferedImage image = new BufferedImage(14, 14, BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + + g.setColor(new Color(0xC8, 0xC8, 0xC8)); + g.fillRect(1, 1, 12, 12); + g.setColor(new Color(0xFF, 0xA0, 0x30)); + g.fillRect(5, 5, 4, 4); + + g.setColor(new Color(0x38, 0x38, 0x38)); + g.drawRect(1, 1, 12, 12); + g.drawLine(5, 2, 5, 12); + g.drawLine(9, 2, 9, 12); + g.drawLine(2, 5, 12, 5); + g.drawLine(2, 9, 12, 9); + + g.dispose(); + return image; + } + + public static BufferedImage createIcon() { + BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0xC0, 0xC0, 0xC0)); + g.fillOval(3, 1, 10, 10); + g.fillPolygon(new int[] { 5, 11, 8 }, new int[] { 9, 9, 15 }, 3); + g.setColor(ColorScheme.DARK_GRAY_COLOR); + g.fillOval(6, 4, 4, 4); + g.dispose(); + return image; + } + + private static final class VariantRenderer extends DefaultListCellRenderer { + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean selected, boolean focused + ) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (!(value instanceof VariantObject)) + return this; + + var object = (VariantObject) value; + setText(object.label() + (object.animated ? " [anim]" : "")); + setToolTipText(object.variantIds.length + " forms to choose between"); + setFont(FontManager.getRunescapeSmallFont()); + if (!selected) + setForeground(Color.LIGHT_GRAY); + return this; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java new file mode 100644 index 0000000..52f0bcb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java @@ -0,0 +1,92 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Dimension; +import java.awt.Graphics2D; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import net.runelite.client.ui.overlay.components.LineComponent; +import net.runelite.client.ui.overlay.components.PanelComponent; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; + +import static rs117.hd.utils.MathUtils.JAU_FINE_TO_RAD; + +/** + * RuneLite's Camera panel, for the camera the scene is actually drawn with. + * + *

The same four rows in the same order and the same units. Only where the numbers come from differs: the + * client's own camera stays over the player while this one is flown about, so reading it would describe a + * view nobody is looking through. 117 HD keeps what it was handed each frame, which is what was drawn. + */ +@Singleton +public class CameraOverlay extends Overlay { + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private final PanelComponent panel = new PanelComponent(); + private boolean added; + + public CameraOverlay() { + setPosition(OverlayPosition.TOP_LEFT); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + if (tools.getLoaded() == null || !devTools.isStandingIn() || !devTools.isActive("cameraPosition")) + return null; + + var position = plugin.cameraPosition; + panel.getChildren().clear(); + + // RuneLite prints x, then height, then northing, which is the order this is already kept in + panel.getChildren().add(LineComponent.builder() + .left("Camera") + .right(Math.round(position[0]) + ", " + Math.round(position[1]) + ", " + Math.round(position[2])) + .build()); + // Back into the whole units the client counts angles in, so these read like the original's + panel.getChildren().add(LineComponent.builder() + .left("Pitch") + .right(String.valueOf(Math.round(plugin.cameraOrientation[1] / JAU_FINE_TO_RAD))) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Yaw") + .right(String.valueOf(Math.round(plugin.cameraOrientation[0] / JAU_FINE_TO_RAD))) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Scale") + .right(String.valueOf(client.getScale())) + .build()); + + return panel.render(g); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java new file mode 100644 index 0000000..b5c3884 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.swing.AbstractButton; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.client.plugins.Plugin; +import net.runelite.client.plugins.PluginManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; + +/** + * Lets RuneLite's own scene tools keep working on a scene they know nothing about. + * + *

Their buttons are left alone and read rather than disabled, so pressing Walls still means walls. What + * is taken away is their drawing: every one of them reads the scene straight off the client and draws it + * through the client's camera, and neither is what is on screen while a cache scene is up. They would + * outline tiles where nothing stands and name objects belonging to wherever the player happens to be. + * + *

So their overlays are lifted out for as long as a cache scene is loaded and {@link SceneToolsOverlay} + * draws the same things from this scene instead. The buttons go on working as they always did; only what + * answers them changes. + */ +@Slf4j +@Singleton +public class DevToolBridge { + private static final String DEV_TOOLS_PACKAGE = "net.runelite.client.plugins.devtools."; + private static final String DEV_TOOLS_PLUGIN = DEV_TOOLS_PACKAGE + "DevToolsPlugin"; + + /** + * The ones there is nothing here for them to describe. + * + *

A cache scene is ground and scenery and nothing else: nobody is standing in it, nothing is moving + * through it, and it carries none of the collision the client walks on. These are switched off and + * greyed while it is up, since leaving them pressable would only ever answer about somewhere else. + * Everything that is not about the scene at all — the widget, variable, script and inventory + * inspectors, the shell and the rest — is left alone. + */ + private static final List UNANSWERABLE = List.of( + "players", + "npcs", + "groundItems", + "graphicsObjects", + "projectiles", + "interacting", + "worldEntities", + "lineOfSight", + "validMovement", + "movementFlags", + "zoneBorders", + "loadingLines", + "worldMapLocation", + "detachedCamera" + ); + + private static final String WHY_GREYED = + "Nothing for this to describe while a cache scene is loaded: it is ground and scenery only."; + + @Inject + private PluginManager pluginManager; + + @Inject + private OverlayManager overlayManager; + + /** Their overlays while they are lifted out, so the same ones can be put back */ + private final List lifted = new ArrayList<>(); + /** Which of the greyed ones were switched on, so they come back the way they were */ + private final List wasActive = new ArrayList<>(); + private final Map buttons = new HashMap<>(); + private final Map, Method> isActiveMethods = new HashMap<>(); + private final Map, Method> setActiveMethods = new HashMap<>(); + private boolean standingIn; + private boolean devToolsSearched; + private Plugin devToolsPlugin; + + /** Whether one of RuneLite's tools is switched on, by the name of its button's field. Called often + * (multiple overlays poll this every frame), so the plugin lookup and reflective method resolution + * below are both cached rather than redone on every call. */ + public boolean isActive(String name) { + Field field = button(name); + if (field == null) + return false; + + try { + Object button = field.get(find()); + Method isActive = isActiveMethod(button.getClass()); + if (isActive == null) + return false; + return (Boolean) isActive.invoke(button); + } catch (Exception ex) { + log.debug("Could not read RuneLite's {} tool", name, ex); + return false; + } + } + + @Nullable + private Method isActiveMethod(Class buttonClass) { + if (isActiveMethods.containsKey(buttonClass)) + return isActiveMethods.get(buttonClass); + Method found = null; + try { + found = buttonClass.getDeclaredMethod("isActive"); + found.setAccessible(true); + } catch (Exception ex) { + log.debug("Could not resolve isActive on {}", buttonClass, ex); + } + isActiveMethods.put(buttonClass, found); + return found; + } + + @Nullable + private Method setActiveMethod(Class buttonClass) { + if (setActiveMethods.containsKey(buttonClass)) + return setActiveMethods.get(buttonClass); + Method found = null; + try { + found = buttonClass.getDeclaredMethod("setActive", boolean.class); + found.setAccessible(true); + } catch (Exception ex) { + log.debug("Could not resolve setActive on {}", buttonClass, ex); + } + setActiveMethods.put(buttonClass, found); + return found; + } + + @Nullable + private Field button(String name) { + if (buttons.containsKey(name)) + return buttons.get(name); + + Field found = null; + Plugin devTools = find(); + if (devTools != null) { + try { + found = devTools.getClass().getDeclaredField(name); + found.setAccessible(true); + } catch (Exception ex) { + log.debug("RuneLite has no {} tool", name, ex); + } + } + buttons.put(name, found); + return found; + } + + /** Takes over the drawing, leaving the buttons where they are */ + public void standIn() { + if (standingIn) + return; + standingIn = true; + + // The predicate is what does the lifting, since there is no way to ask which overlays are in there + overlayManager.removeIf(overlay -> { + if (!overlay.getClass().getName().startsWith(DEV_TOOLS_PACKAGE)) + return false; + lifted.add(overlay); + return true; + }); + + SwingUtilities.invokeLater(() -> greyOut(true)); + } + + /** Hands the drawing back */ + public void standDown() { + if (!standingIn) + return; + standingIn = false; + + for (Overlay overlay : lifted) + overlayManager.add(overlay); + lifted.clear(); + + SwingUtilities.invokeLater(() -> greyOut(false)); + } + + private void greyOut(boolean grey) { + for (String name : UNANSWERABLE) { + Field field = button(name); + if (field == null) + continue; + + try { + Object button = field.get(find()); + if (!(button instanceof AbstractButton)) + continue; + + if (grey) { + if (isActive(name)) + wasActive.add(name); + setActive(button, false); + } else if (wasActive.contains(name)) { + setActive(button, true); + } + + ((AbstractButton) button).setEnabled(!grey); + ((AbstractButton) button).setToolTipText(grey ? WHY_GREYED : null); + } catch (Exception ex) { + log.debug("Could not grey RuneLite's {} tool", name, ex); + } + } + + if (!grey) + wasActive.clear(); + } + + private void setActive(Object button, boolean active) throws Exception { + Method setActive = setActiveMethod(button.getClass()); + if (setActive == null) + throw new NoSuchMethodException("setActive"); + setActive.invoke(button, active); + } + + public boolean isStandingIn() { + return standingIn; + } + + @Nullable + private Plugin find() { + if (devToolsSearched) + return devToolsPlugin; + devToolsSearched = true; + for (Plugin plugin : pluginManager.getPlugins()) + if (DEV_TOOLS_PLUGIN.equals(plugin.getClass().getName())) { + devToolsPlugin = plugin; + break; + } + return devToolsPlugin; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java new file mode 100644 index 0000000..ea3e90c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java @@ -0,0 +1,114 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import net.runelite.client.ui.overlay.components.LineComponent; +import net.runelite.client.ui.overlay.components.PanelComponent; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; +import rs117.hd.utils.HDUtils; + +import static net.runelite.api.Constants.CHUNK_SIZE; + +/** + * RuneLite's Location panel, for the scene that is on screen. + * + *

The same rows in the same order, read the same way. What they describe is the camera rather than the + * player, since a cache scene has no player in it: the player is still standing wherever the game left + * them, usually in another part of the world entirely, and reporting that while looking at somewhere else + * is how the original goes wrong here. + */ +@Singleton +public class LocationOverlay extends Overlay { + private static final int TILE_SIZE = 128; + + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private final PanelComponent panel = new PanelComponent(); + private boolean added; + + public LocationOverlay() { + setPosition(OverlayPosition.TOP_LEFT); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + var scene = tools.getLoaded(); + if (scene == null || !devTools.isStandingIn() || !devTools.isActive("location")) + return null; + + int localX = Math.round(plugin.cameraPosition[0]); + int localY = Math.round(plugin.cameraPosition[2]); + int sceneX = Math.floorDiv(localX, TILE_SIZE); + int sceneY = Math.floorDiv(localY, TILE_SIZE); + int plane = client.getPlane(); + int[] world = scene.isInstance() + ? HDUtils.sceneToWorld(scene, sceneX, sceneY, plane) + : new int[] { scene.getBaseX() + sceneX, scene.getBaseY() + sceneY, plane }; + + panel.getChildren().clear(); + if (scene.isInstance()) + panel.getChildren().add(LineComponent.builder().left("Instance").build()); + + panel.getChildren().add(LineComponent.builder() + .left("Local") + .right(localX + ", " + localY) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("World") + .right(world[0] + ", " + world[1] + ", " + world[2]) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Scene") + .right(sceneX + ", " + sceneY) + .build()); + + panel.getChildren().add(LineComponent.builder() + .left("Base") + .right(scene.getBaseX() + ", " + scene.getBaseY()) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Map regions") + .right(Arrays.stream(scene.getMapRegions()) + .mapToObj(String::valueOf) + .collect(Collectors.joining(", "))) + .build()); + + return panel.render(g); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java new file mode 100644 index 0000000..1257877 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java @@ -0,0 +1,284 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Polygon; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.api.Tile; +import net.runelite.api.TileObject; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayLayer; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; + +/** + * Draws what RuneLite's scene tools would draw, for the scene that is actually on screen. + * + *

Its buttons are RuneLite's own, read through {@link DevToolBridge}, so Walls still means walls and + * turning one off still turns it off. Only the two things RuneLite's own drawing cannot get right here are + * done differently: the tiles come from the cache scene rather than from the client, and the projection uses + * the camera the frame was drawn with rather than the client's, which stays wherever the player is standing + * while this one is flown about. + */ +@Singleton +public class SceneToolsOverlay extends Overlay { + private static final Color GAME_OBJECTS = Color.GREEN; + private static final Color WALLS = new Color(0x00, 0xB0, 0xFF); + private static final Color DECORATIONS = new Color(0xD0, 0x60, 0xFF); + private static final Color GROUND_OBJECTS = new Color(0xFF, 0xA0, 0x30); + private static final Color MAP_SQUARES = new Color(0xFF, 0xFF, 0x00, 0xA0); + private static final Color TILE_LOCATION = Color.WHITE; + /** Red, the same as RuneLite draws its tile flags in */ + private static final Color TILE_FLAGS = Color.RED; + + private static final int TILE_SIZE = 128; + private static final int REGION_TILES = 64; + /** How far out to bother drawing, since every tile has to be projected by hand */ + private static final int DRAW_RADIUS_TILES = 28; + + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private boolean added; + + public SceneToolsOverlay() { + setPosition(OverlayPosition.DYNAMIC); + setLayer(OverlayLayer.ABOVE_SCENE); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + var scene = tools.getLoaded(); + if (scene == null || !devTools.isStandingIn()) + return null; + + g.setFont(FontManager.getRunescapeSmallFont()); + + boolean gameObjects = devTools.isActive("gameObjects"); + boolean walls = devTools.isActive("walls"); + boolean decorations = devTools.isActive("decorations"); + boolean groundObjects = devTools.isActive("groundObjects"); + boolean tileLocation = devTools.isActive("tileLocation"); + boolean tileFlags = devTools.isActive("tileFlags"); + + if (gameObjects || walls || decorations || groundObjects || tileLocation || tileFlags) + drawTiles(g, scene, gameObjects, walls, decorations, groundObjects, tileLocation, tileFlags); + + if (devTools.isActive("mapSquares")) + drawMapSquares(g, scene); + + return null; + } + + private void drawTiles( + Graphics2D g, BuiltScene scene, + boolean gameObjects, boolean walls, boolean decorations, boolean groundObjects, + boolean tileLocation, boolean tileFlags + ) { + var tiles = scene.getExtendedTiles(); + int plane = Math.max(0, Math.min(MAX_Z - 1, client.getPlane())); + + int fromX = cameraTileX() - DRAW_RADIUS_TILES; + int toX = cameraTileX() + DRAW_RADIUS_TILES; + int fromY = cameraTileY() - DRAW_RADIUS_TILES; + int toY = cameraTileY() + DRAW_RADIUS_TILES; + + for (int x = Math.max(0, fromX); x <= Math.min(EXTENDED_SCENE_SIZE - 1, toX); x++) { + for (int y = Math.max(0, fromY); y <= Math.min(EXTENDED_SCENE_SIZE - 1, toY); y++) { + Tile tile = tiles[plane][x][y]; + if (tile == null) + continue; + + if (gameObjects) + for (var object : tile.getGameObjects()) + mark(g, scene, plane, x, y, object, GAME_OBJECTS); + if (walls) + mark(g, scene, plane, x, y, tile.getWallObject(), WALLS); + if (decorations) + mark(g, scene, plane, x, y, tile.getDecorativeObject(), DECORATIONS); + if (groundObjects) + mark(g, scene, plane, x, y, tile.getGroundObject(), GROUND_OBJECTS); + if (tileLocation) + label(g, scene, plane, x, y, (x - scene.getSceneOffset()) + ", " + (y - scene.getSceneOffset()), + TILE_LOCATION); + // The same settings byte RuneLite reads off the client, taken from this scene instead + if (tileFlags) + label(g, scene, plane, x, y, + String.valueOf(scene.getExtendedTileSettings()[plane][x][y]), TILE_FLAGS); + } + } + } + + private void mark( + Graphics2D g, BuiltScene scene, int plane, int x, int y, @Nullable TileObject object, Color color + ) { + if (object == null) + return; + + var poly = tilePoly(scene, plane, x, y); + if (poly == null) + return; + + g.setColor(color); + g.drawPolygon(poly); + label(g, scene, plane, x, y, String.valueOf(object.getId()), color); + } + + private void label(Graphics2D g, BuiltScene scene, int plane, int x, int y, String text, Color color) { + float[] middle = project( + (x - scene.getSceneOffset()) * TILE_SIZE + TILE_SIZE / 2, + (y - scene.getSceneOffset()) * TILE_SIZE + TILE_SIZE / 2, + heightAt(scene, plane, x, y) + ); + if (middle == null) + return; + + int width = g.getFontMetrics().stringWidth(text); + g.setColor(Color.BLACK); + g.drawString(text, middle[0] - width / 2f + 1, middle[1] + 1); + g.setColor(color); + g.drawString(text, middle[0] - width / 2f, middle[1]); + } + + private void drawMapSquares(Graphics2D g, BuiltScene scene) { + g.setColor(MAP_SQUARES); + int offset = scene.getSceneOffset(); + + // Where the regions fall is a property of the world, so the lines go wherever a region edge lands + for (int x = -offset; x <= EXTENDED_SCENE_SIZE - offset; x++) { + if (Math.floorMod(scene.getBaseX() + x, REGION_TILES) != 0) + continue; + drawSceneLine(g, scene, x, -offset, x, EXTENDED_SCENE_SIZE - offset); + } + for (int y = -offset; y <= EXTENDED_SCENE_SIZE - offset; y++) { + if (Math.floorMod(scene.getBaseY() + y, REGION_TILES) != 0) + continue; + drawSceneLine(g, scene, -offset, y, EXTENDED_SCENE_SIZE - offset, y); + } + } + + private void drawSceneLine(Graphics2D g, BuiltScene scene, int fromX, int fromY, int toX, int toY) { + int plane = Math.max(0, Math.min(MAX_Z - 1, client.getPlane())); + int steps = Math.max(Math.abs(toX - fromX), Math.abs(toY - fromY)); + float[] previous = null; + + for (int i = 0; i <= steps; i++) { + int x = fromX + (toX - fromX) * i / steps; + int y = fromY + (toY - fromY) * i / steps; + float[] point = project( + x * TILE_SIZE, y * TILE_SIZE, + heightAt(scene, plane, x + scene.getSceneOffset(), y + scene.getSceneOffset()) + ); + if (previous != null && point != null) + g.drawLine((int) previous[0], (int) previous[1], (int) point[0], (int) point[1]); + previous = point; + } + } + + private int cameraTileX() { + return (int) Math.floor(plugin.cameraPosition[0] / TILE_SIZE) + BuiltScene.SCENE_OFFSET; + } + + private int cameraTileY() { + return (int) Math.floor(plugin.cameraPosition[2] / TILE_SIZE) + BuiltScene.SCENE_OFFSET; + } + + private static int heightAt(BuiltScene scene, int plane, int x, int y) { + int[][][] heights = scene.getTileHeights(); + if (x < 0 || y < 0 || x >= heights[plane].length || y >= heights[plane][x].length) + return 0; + return heights[plane][x][y]; + } + + @Nullable + private Polygon tilePoly(BuiltScene scene, int plane, int x, int y) { + int offset = scene.getSceneOffset(); + int west = (x - offset) * TILE_SIZE; + int east = west + TILE_SIZE; + int south = (y - offset) * TILE_SIZE; + int north = south + TILE_SIZE; + + float[] sw = project(west, south, heightAt(scene, plane, x, y)); + float[] se = project(east, south, heightAt(scene, plane, x + 1, y)); + float[] ne = project(east, north, heightAt(scene, plane, x + 1, y + 1)); + float[] nw = project(west, north, heightAt(scene, plane, x, y + 1)); + if (sw == null || se == null || ne == null || nw == null) + return null; + + var poly = new Polygon(); + poly.addPoint((int) sw[0], (int) sw[1]); + poly.addPoint((int) se[0], (int) se[1]); + poly.addPoint((int) ne[0], (int) ne[1]); + poly.addPoint((int) nw[0], (int) nw[1]); + return poly; + } + + /** + * Local scene coordinates to the canvas, through the camera the scene was drawn with. + * + *

The client's own camera is no use here: it stays where the player is standing while this tool's + * camera is flown elsewhere, and everything would be placed from there instead of from what is on + * screen. 117 HD keeps what it was handed, which is what was actually drawn. + */ + @Nullable + private float[] project(int x, int y, int height) { + float dx = x - plugin.cameraPosition[0]; + float dy = y - plugin.cameraPosition[2]; + float dz = height - plugin.cameraPosition[1]; + + float yawSin = (float) Math.sin(plugin.cameraOrientation[0]); + float yawCos = (float) Math.cos(plugin.cameraOrientation[0]); + float pitchSin = (float) Math.sin(plugin.cameraOrientation[1]); + float pitchCos = (float) Math.cos(plugin.cameraOrientation[1]); + + float x1 = dx * yawCos + dy * yawSin; + float y1 = dy * yawCos - dx * yawSin; + float y2 = dz * pitchCos - y1 * pitchSin; + float z1 = y1 * pitchCos + dz * pitchSin; + if (z1 < 1) + return null; + + float scale = client.getScale(); + return new float[] { + x1 * scale / z1 + client.getViewportWidth() / 2f + client.getViewportXOffset(), + y2 * scale / z1 + client.getViewportHeight() / 2f + client.getViewportYOffset() + }; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java new file mode 100644 index 0000000..394c4f2 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java @@ -0,0 +1,120 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Polygon; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.api.Perspective; +import net.runelite.api.Point; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayLayer; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import rs117.hd.dev.sceneloader.scene.VariantObject; + +@Singleton +public class SelectionHighlight extends Overlay { + private static final Color OUTLINE = new Color(0x00E0FF); + private static final Color SHADE = new Color(0x2200E0FF, true); + private static final int TILE_SIZE = 128; + private static final long SHOWN_FOR_MILLIS = 8000; + + @Inject + private Client client; + + @Inject + private OverlayManager overlayManager; + + private boolean added; + + @Nullable + private volatile VariantObject.Placed target; + private volatile String label = ""; + private volatile long until; + + public SelectionHighlight() { + setPosition(OverlayPosition.DYNAMIC); + setLayer(OverlayLayer.ABOVE_SCENE); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + clear(); + overlayManager.remove(this); + } + + public void mark(VariantObject.Placed placed, String label) { + this.target = placed; + this.label = label; + this.until = System.currentTimeMillis() + SHOWN_FOR_MILLIS; + } + + public void clear() { + target = null; + } + + @Override + public Dimension render(Graphics2D g) { + var placed = target; + if (placed == null) + return null; + if (System.currentTimeMillis() > until) { + target = null; + return null; + } + + int halfX = placed.sizeX * TILE_SIZE / 2; + int halfY = placed.sizeY * TILE_SIZE / 2; + + Point southWest = project(placed.x - halfX, placed.z - halfY, placed.y); + Point southEast = project(placed.x + halfX, placed.z - halfY, placed.y); + Point northEast = project(placed.x + halfX, placed.z + halfY, placed.y); + Point northWest = project(placed.x - halfX, placed.z + halfY, placed.y); + if (southWest == null || southEast == null || northEast == null || northWest == null) + return null; + + var footprint = new Polygon(); + footprint.addPoint(southWest.getX(), southWest.getY()); + footprint.addPoint(southEast.getX(), southEast.getY()); + footprint.addPoint(northEast.getX(), northEast.getY()); + footprint.addPoint(northWest.getX(), northWest.getY()); + + g.setColor(SHADE); + g.fill(footprint); + g.setColor(OUTLINE); + g.setStroke(new BasicStroke(2)); + g.draw(footprint); + + if (!label.isEmpty()) { + int top = Math.min(Math.min(southWest.getY(), southEast.getY()), Math.min(northEast.getY(), northWest.getY())); + int middle = (southWest.getX() + northEast.getX()) / 2; + g.setFont(FontManager.getRunescapeSmallFont()); + int width = g.getFontMetrics().stringWidth(label); + g.setColor(Color.BLACK); + g.drawString(label, middle - width / 2 + 1, top - 5); + g.setColor(OUTLINE); + g.drawString(label, middle - width / 2, top - 6); + } + return null; + } + + @Nullable + private Point project(int x, int z, int height) { + return Perspective.localToCanvas(client, x, z, height); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java new file mode 100644 index 0000000..85c9bee --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java @@ -0,0 +1,218 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; + +import static rs117.hd.dev.sceneloader.map.MapProjection.REGION_SIZE; + + +class MapControls extends JPanel { + private static final int NARROW = 44; + private static final int WIDE = 58; + + private final RegionMapPanel map; + + private final JTextField worldX = field(WIDE, "The world tile under the mouse. Type one and press enter to go there."); + private final JTextField worldY = field(WIDE, "The world tile under the mouse. Type one and press enter to go there."); + private final JTextField regionId = field(WIDE, "The region under the mouse. Type one and press enter to go there."); + private final JTextField regionX = field(NARROW, "Which region across. Type one and press enter to go there."); + private final JTextField regionY = field(NARROW, "Which region up. Type one and press enter to go there."); + private final JTextField baseX = readOnly(WIDE, "The world tile the region starts at"); + private final JTextField baseY = readOnly(WIDE, "The world tile the region starts at"); + private final JTextField localX = readOnly(NARROW, "How far into the region, across"); + private final JTextField localY = readOnly(NARROW, "How far into the region, up"); + private final JComboBox plane = new JComboBox<>(new String[] { "0", "1", "2", "3" }); + private final JButton popOut = new JButton(); + private final JButton clearPicked = new JButton("Clear"); + private final MapWindow window; + + interface MapWindow { + void togglePopOut(); + + void close(); + + boolean isPoppedOut(); + } + + MapControls(RegionMapPanel map, MapWindow window) { + this.map = map; + this.window = window; + + setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4)); + setBackground(ColorScheme.DARK_GRAY_COLOR); + setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); + + add(label("X")); + add(worldX); + add(label("Y")); + add(worldY); + add(gap()); + + add(label("Region")); + add(regionId); + add(label("at")); + add(regionX); + add(label(",")); + add(regionY); + add(gap()); + + add(label("Base")); + add(baseX); + add(label(",")); + add(baseY); + add(gap()); + + add(label("Local")); + add(localX); + add(label(",")); + add(localY); + add(gap()); + + add(label("Plane")); + plane.setFont(FontManager.getRunescapeSmallFont()); + plane.setToolTipText("Which floor of the map to show"); + plane.addActionListener(e -> map.setPlane(plane.getSelectedIndex())); + add(plane); + add(gap()); + + popOut.setFont(FontManager.getRunescapeSmallFont()); + popOut.addActionListener(e -> { + window.togglePopOut(); + updatePopOut(); + }); + add(popOut); + + clearPicked.setFont(FontManager.getRunescapeSmallFont()); + clearPicked.setToolTipText("Forget the picked regions and go back to choosing one at a time"); + clearPicked.addActionListener(e -> map.clearPicked()); + add(clearPicked); + + var close = new JButton("Close"); + close.setFont(FontManager.getRunescapeSmallFont()); + close.setToolTipText("Put the game view back"); + close.addActionListener(e -> window.close()); + add(close); + + updatePopOut(); + + onEnter(worldX, this::goToWorld); + onEnter(worldY, this::goToWorld); + onEnter(regionId, this::goToRegionId); + onEnter(regionX, this::goToRegionCoords); + onEnter(regionY, this::goToRegionCoords); + + map.setPointerListener(this::follow); + map.setPickingListener(this::updatePicking); + updatePicking(); + } + + /** The button is only worth having while there is something picked to forget */ + private void updatePicking() { + clearPicked.setVisible(map.isPicking()); + } + + private void updatePopOut() { + boolean out = window.isPoppedOut(); + popOut.setText(out ? "Over game" : "Pop out"); + popOut.setToolTipText(out + ? "Put the map over the game view, where it has the most room" + : "Move the map into a window of its own, so the game can be seen behind it"); + } + + private void follow(int tileX, int tileY) { + int region = MapProjection.regionIdAt(tileX, tileY); + int rx = MapProjection.regionX(region); + int ry = MapProjection.regionY(region); + + set(worldX, tileX); + set(worldY, tileY); + set(regionId, region); + set(regionX, rx); + set(regionY, ry); + set(baseX, rx * REGION_SIZE); + set(baseY, ry * REGION_SIZE); + set(localX, tileX - rx * REGION_SIZE); + set(localY, tileY - ry * REGION_SIZE); + } + + private static void set(JTextField field, int value) { + if (field.isFocusOwner()) + return; + field.setText(Integer.toString(value)); + } + + private void goToWorld() { + Integer x = number(worldX); + Integer y = number(worldY); + if (x == null || y == null) + return; + map.goTo(x, y); + } + + private void goToRegionId() { + Integer id = number(regionId); + if (id != null) + map.select(id); + } + + private void goToRegionCoords() { + Integer x = number(regionX); + Integer y = number(regionY); + if (x == null || y == null || x < 0 || x > 0xFF || y < 0 || y > 0xFF) + return; + map.select(x << 8 | y); + } + + @Nullable + private static Integer number(JTextField field) { + try { + return Integer.parseInt(field.getText().trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + + private static void onEnter(JTextField field, Runnable action) { + field.addActionListener(e -> action.run()); + } + + private static JTextField field(int width, String tooltip) { + var field = new JTextField(); + field.setFont(FontManager.getRunescapeSmallFont()); + field.setToolTipText(tooltip); + field.setHorizontalAlignment(JTextField.CENTER); + field.setPreferredSize(new Dimension(width, 20)); + return field; + } + + private static JTextField readOnly(int width, String tooltip) { + var field = field(width, tooltip); + field.setEditable(false); + field.setFocusable(false); + field.setBackground(ColorScheme.DARKER_GRAY_COLOR); + field.setForeground(Color.LIGHT_GRAY); + return field; + } + + private static JLabel label(String text) { + var label = new JLabel(text); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(Color.LIGHT_GRAY); + return label; + } + + private static java.awt.Component gap() { + return Box.createHorizontalStrut(10); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java new file mode 100644 index 0000000..db290f4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java @@ -0,0 +1,248 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Window; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.function.IntConsumer; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; + +@Slf4j +public class MapHost implements MapControls.MapWindow { + private static final String CLIENT_PANEL = "net.runelite.client.ui.ClientPanel"; + private static final Dimension WINDOW_SIZE = new Dimension(960, 760); + + private final Client client; + private final IntConsumer onChosen; + private final IntConsumer onOpened; + @Nullable + private final RegionMapPanel.Coverage coverage; + + @Nullable + private JPanel content; + @Nullable + private RegionMapPanel map; + + @Nullable + private JDialog window; + + @Nullable + private Container gameHost; + @Nullable + private Component gameView; + + private boolean poppedOut; + + public MapHost( + Client client, IntConsumer onChosen, IntConsumer onOpened, + @Nullable RegionMapPanel.Coverage coverage + ) { + this.client = client; + this.onChosen = onChosen; + this.onOpened = onOpened; + this.coverage = coverage; + } + + public void setOnAdded(@Nullable IntConsumer onAdded) { + this.onAdded = onAdded; + if (map != null) + map.setOnAdded(onAdded); + } + + public void setOnCleared(@Nullable Runnable onCleared) { + this.onCleared = onCleared; + if (map != null) + map.setOnCleared(onCleared); + } + + public void setListed(int[] listedRegions) { + this.listed = listedRegions; + if (map != null) + map.setListed(listedRegions); + } + + @Nullable + private IntConsumer onAdded; + @Nullable + private Runnable onCleared; + private int[] listed = new int[0]; + + public void refresh() { + if (map != null) + map.setCoverage(coverage); + } + + public boolean isOpen() { + return content != null; + } + + public void open(int startRegion) { + assert SwingUtilities.isEventDispatchThread(); + + if (content != null) { + if (map != null) + map.select(startRegion); + if (window != null) + window.toFront(); + return; + } + + build(startRegion); + if (poppedOut || !embed()) + popOutWindow(); + } + + private void build(int startRegion) { + var status = new JLabel(" "); + status.setFont(FontManager.getRunescapeSmallFont()); + status.setForeground(Color.LIGHT_GRAY); + status.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8)); + + map = new RegionMapPanel(startRegion, onChosen, region -> { + onOpened.accept(region); + if (!poppedOut) + close(); + }, status); + map.setCoverage(coverage); + map.setOnAdded(onAdded); + map.setOnCleared(onCleared); + map.setListed(listed); + + content = new JPanel(new BorderLayout()); + content.setBackground(ColorScheme.DARK_GRAY_COLOR); + content.add(new MapControls(map, this), BorderLayout.NORTH); + content.add(map, BorderLayout.CENTER); + content.add(status, BorderLayout.SOUTH); + } + + @Override + public boolean isPoppedOut() { + return poppedOut; + } + + @Override + public void togglePopOut() { + if (content == null) + return; + + if (poppedOut) { + closeWindow(); + if (!embed()) + popOutWindow(); + } else { + restoreGameView(); + popOutWindow(); + } + } + + @Override + public void close() { + if (content == null) + return; + + closeWindow(); + restoreGameView(); + if (map != null) + map.shutDown(); + map = null; + content = null; + } + + + private boolean embed() { + Container host = findGameHost(); + if (host == null) { + log.debug("Could not find the game view to put the map over, so it opens in a window instead"); + return false; + } + + gameHost = host; + gameView = centreOf(host); + if (gameView == null) + return false; + + gameView.setVisible(false); + host.add(content, BorderLayout.CENTER); + host.revalidate(); + host.repaint(); + + poppedOut = false; + return true; + } + + private void restoreGameView() { + if (gameHost == null || gameView == null) + return; + + gameHost.remove(content); + ((BorderLayout) gameHost.getLayout()).addLayoutComponent(gameView, BorderLayout.CENTER); + gameView.setVisible(true); + gameHost.revalidate(); + gameHost.repaint(); + + gameHost = null; + gameView = null; + } + + @Nullable + private Container findGameHost() { + Component canvas = client.getCanvas(); + for (Container parent = canvas == null ? null : canvas.getParent(); + parent != null; + parent = parent.getParent()) { + if (CLIENT_PANEL.equals(parent.getClass().getName()) && parent.getLayout() instanceof BorderLayout) + return parent; + } + return null; + } + + @Nullable + private static Component centreOf(Container host) { + var layout = (BorderLayout) host.getLayout(); + return layout.getLayoutComponent(BorderLayout.CENTER); + } + + + private void popOutWindow() { + Window parent = SwingUtilities.getWindowAncestor(client.getCanvas()); + window = new JDialog(parent, "117 HD — pick a region", JDialog.ModalityType.MODELESS); + window.setContentPane(content); + window.setSize(WINDOW_SIZE); + window.setLocationRelativeTo(parent); + window.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + window.addWindowListener(new WindowAdapter() { + @Override + public void windowClosed(WindowEvent event) { + if (window != null) { + window = null; + close(); + } + } + }); + + poppedOut = true; + window.setVisible(true); + } + + private void closeWindow() { + if (window == null) + return; + var closing = window; + window = null; + closing.setContentPane(new JPanel()); + closing.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java new file mode 100644 index 0000000..dc38a9f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java @@ -0,0 +1,72 @@ +package rs117.hd.dev.sceneloader.map; + +public final class MapProjection { + public static final int TILE_SIZE = 256; + public static final int MIN_ZOOM = 4; + public static final int MAX_ZOOM = 11; + public static final int WORLD_TILE_PX = 32; + public static final int REGION_SIZE = 64; + public static final int REGION_PX = REGION_SIZE * WORLD_TILE_PX; + + private static final int VERTICAL_ORIGIN_PX = 364544; + private static final int WORLD_X_ORIGIN = 960; + private static final int WORLD_Y_ORIGIN = 6208; + + public static final int MIN_WORLD_X = WORLD_X_ORIGIN; + public static final int MAX_WORLD_X = 4224; + public static final int MIN_WORLD_Y = 1216; + public static final int MAX_WORLD_Y = 12608; + + private MapProjection() {} + + public static int pixelX(int worldX) { + return (worldX - WORLD_X_ORIGIN) * WORLD_TILE_PX; + } + + public static int pixelY(int worldY) { + return VERTICAL_ORIGIN_PX - (worldY - WORLD_Y_ORIGIN) * WORLD_TILE_PX; + } + + public static int worldX(double pixelX) { + return (int) Math.floor(pixelX / WORLD_TILE_PX) + WORLD_X_ORIGIN; + } + + public static int worldY(double pixelY) { + return (int) Math.floor((VERTICAL_ORIGIN_PX - pixelY) / WORLD_TILE_PX) + WORLD_Y_ORIGIN; + } + + public static int scale(int zoom) { + return 1 << (MAX_ZOOM - zoom); + } + + public static int regionPx(int zoom) { + return REGION_PX / scale(zoom); + } + + public static int regionIdAt(int worldX, int worldY) { + return (worldX / REGION_SIZE) << 8 | worldY / REGION_SIZE; + } + + public static int regionX(int regionId) { + return regionId >> 8 & 0xFF; + } + + public static int regionY(int regionId) { + return regionId & 0xFF; + } + + public static boolean isOnMap(int regionId) { + int worldX = regionX(regionId) * REGION_SIZE; + int worldY = regionY(regionId) * REGION_SIZE; + return worldX >= MIN_WORLD_X && worldX < MAX_WORLD_X + && worldY >= MIN_WORLD_Y && worldY < MAX_WORLD_Y; + } + + public static int tileIndex(double pixel, int zoom) { + return (int) Math.floor(pixel / scale(zoom) / TILE_SIZE); + } + + public static int flipTileY(int tileY, int zoom) { + return (1 << zoom) - 1 - tileY; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java new file mode 100644 index 0000000..601666b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java @@ -0,0 +1,240 @@ +package rs117.hd.dev.sceneloader.map; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.HdPlugin; + +@Slf4j +public class MapTileCache { + private static final String REPO = "Mark7625/osrs_map_tiles"; + private static final String BRANCH = "master"; + private static final String RAW_URL = "https://raw.githubusercontent.com/" + REPO + "/%s/%d/%d/%d/%d.png"; + private static final String COMMIT_URL = "https://api.github.com/repos/" + REPO + "/commits/" + BRANCH; + private static final String USER_AGENT = "117hd-dev-cache-scene"; + + private static final long RECHECK_MILLIS = 12 * 60 * 60 * 1000L; + private static final int CONNECT_TIMEOUT_MILLIS = 8000; + private static final int READ_TIMEOUT_MILLIS = 20000; + + private static final int IMAGES_IN_MEMORY = 160; + + private final Path root = HdPlugin.PLUGIN_DIR.resolve("map-tiles").toPath(); + private final ExecutorService downloads = Executors.newFixedThreadPool(4, runnable -> { + Thread thread = new Thread(runnable, "cache-scene-map-tiles"); + thread.setDaemon(true); + return thread; + }); + + private final Map images = new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > IMAGES_IN_MEMORY; + } + }; + + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Set missing = ConcurrentHashMap.newKeySet(); + + private volatile String commit; + + private final Runnable onLoaded; + + public MapTileCache(Runnable onLoaded) { + this.onLoaded = onLoaded; + } + + public void shutDown() { + downloads.shutdownNow(); + synchronized (images) { + images.clear(); + } + } + + @Nullable + public BufferedImage get(int plane, int zoom, int tileX, int tileY) { + long key = key(plane, zoom, tileX, tileY); + + BufferedImage image; + synchronized (images) { + image = images.get(key); + } + if (image != null || missing.contains(key)) + return image; + + if (pending.add(key)) + downloads.submit(() -> load(key, plane, zoom, tileX, tileY)); + return null; + } + + private void load(long key, int plane, int zoom, int tileX, int tileY) { + try { + String commit = commit(); + Path file = root.resolve(commit).resolve(plane + "/" + zoom + "/" + tileX + "/" + tileY + ".png"); + + byte[] bytes; + if (Files.isRegularFile(file)) { + bytes = Files.readAllBytes(file); + } else { + bytes = download(String.format(RAW_URL, commit, plane, zoom, tileX, tileY)); + if (bytes != null) { + Files.createDirectories(file.getParent()); + Path partial = file.resolveSibling(file.getFileName() + ".part"); + Files.write(partial, bytes); + Files.move(partial, file, java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } + } + + if (bytes == null) { + missing.add(key); + return; + } + + BufferedImage image = ImageIO.read(new java.io.ByteArrayInputStream(bytes)); + if (image == null) { + missing.add(key); + return; + } + + synchronized (images) { + images.put(key, image); + } + onLoaded.run(); + } catch (Exception ex) { + missing.add(key); + log.debug("Could not load map tile {}/{}/{}/{}", plane, zoom, tileX, tileY, ex); + } finally { + pending.remove(key); + } + } + + @Nullable + private byte[] download(String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", USER_AGENT); + connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS); + connection.setReadTimeout(READ_TIMEOUT_MILLIS); + try { + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) + return null; + try (InputStream in = connection.getInputStream()) { + return in.readAllBytes(); + } + } finally { + connection.disconnect(); + } + } + + private synchronized String commit() { + if (commit == null) { + try { + commit = resolveCommit(); + } catch (Exception ex) { + log.debug("Could not work out which map tiles are current, using whatever is cached", ex); + commit = BRANCH; + } + } + return commit; + } + + private String resolveCommit() throws IOException { + Path marker = root.resolve("version"); + String stored = null; + long checkedAt = 0; + if (Files.isRegularFile(marker)) { + String[] lines = Files.readString(marker, StandardCharsets.UTF_8).split("\n"); + stored = lines[0].trim(); + if (lines.length > 1) { + try { + checkedAt = Long.parseLong(lines[1].trim()); + } catch (NumberFormatException ignored) { + } + } + } + + boolean due = System.currentTimeMillis() - checkedAt > RECHECK_MILLIS; + if (stored != null && !due) + return stored; + + String current = fetchCommit(); + if (current == null) + return stored != null ? stored : BRANCH; + + if (!current.equals(stored)) { + log.debug("Map tiles have changed, fetching them again at {}", current); + deleteOldTiles(current); + } + + Files.createDirectories(root); + Files.writeString(marker, current + "\n" + System.currentTimeMillis(), StandardCharsets.UTF_8); + return current; + } + + @Nullable + private String fetchCommit() throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(COMMIT_URL).openConnection(); + connection.setRequestProperty("User-Agent", USER_AGENT); + connection.setRequestProperty("Accept", "application/vnd.github+json"); + connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS); + connection.setReadTimeout(READ_TIMEOUT_MILLIS); + try { + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) + return null; + try (var reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) { + var json = new Gson().fromJson(reader, JsonObject.class); + return json != null && json.has("sha") ? json.get("sha").getAsString() : null; + } + } finally { + connection.disconnect(); + } + } + + private void deleteOldTiles(String keep) { + if (!Files.isDirectory(root)) + return; + try (Stream entries = Files.list(root)) { + entries + .filter(Files::isDirectory) + .filter(path -> !path.getFileName().toString().equals(keep)) + .forEach(MapTileCache::deleteTree); + } catch (IOException ex) { + log.debug("Could not clear out the old map tiles", ex); + } + } + + private static void deleteTree(Path path) { + try (Stream tree = Files.walk(path)) { + tree.sorted(Comparator.reverseOrder()).forEach(entry -> { + try { + Files.deleteIfExists(entry); + } catch (IOException ignored) { + } + }); + } catch (IOException ex) { + log.debug("Could not delete {}", path, ex); + } + } + + private static long key(int plane, int zoom, int tileX, int tileY) { + return (long) plane << 56 | (long) zoom << 48 | (long) (tileX & 0xFFFFFF) << 24 | tileY & 0xFFFFFF; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java new file mode 100644 index 0000000..5916187 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java @@ -0,0 +1,487 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; +import java.util.function.IntConsumer; +import javax.annotation.Nullable; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import net.runelite.client.ui.ColorScheme; + +import static rs117.hd.dev.sceneloader.map.MapProjection.MAX_ZOOM; +import static rs117.hd.dev.sceneloader.map.MapProjection.MIN_ZOOM; +import static rs117.hd.dev.sceneloader.map.MapProjection.REGION_SIZE; +import static rs117.hd.dev.sceneloader.map.MapProjection.TILE_SIZE; + + +public class RegionMapPanel extends JPanel { + private static final int INITIAL_ZOOM = 6; + private static final int GRID_VISIBLE_PX = 24; + + private static final Color HOVER_FILL = new Color(0x33, 0xB5, 0xE5, 90); + private static final Color HOVER_LINE = new Color(0x33, 0xB5, 0xE5); + private static final Color CHOSEN_LINE = new Color(0xFF, 0xA0, 0x30); + private static final Color GRID_LINE = new Color(255, 255, 255, 40); + private static final Color COVERAGE_FILL = new Color(0xFF, 0xA0, 0x30, 36); + private static final Color COVERAGE_LINE = new Color(0xFF, 0xC8, 0x70, 190); + private static final Color BUILT_LINE = new Color(0x7C, 0xE8, 0x7C); + private static final BasicStroke COVERAGE_STROKE = new BasicStroke( + 2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 6, 4 }, 0); + private static final BasicStroke STROKE_1 = new BasicStroke(1); + private static final BasicStroke STROKE_2 = new BasicStroke(2); + + private static final Color LISTED_FILL = new Color(0x33, 0xE0, 0xFF, 0x33); + private static final Color LISTED_LINE = new Color(0x33, 0xE0, 0xFF); + + private final MapTileCache tiles; + private final IntConsumer onChosen; + private final IntConsumer onOpened; + private final JLabel status; + + private int plane; + private int zoom = INITIAL_ZOOM; + private double centreX, centreY; + + private int chosenRegion; + private int hoveredRegion = -1; + @Nullable + private IntConsumer onAdded; + @Nullable + private Runnable onCleared; + @Nullable + private Runnable pickingListener; + private int[] listedRegions = new int[0]; + private Point dragFrom; + + @Nullable + private PointerListener pointerListener; + + public interface PointerListener { + void moved(int worldX, int worldY); + } + + @Nullable + private Coverage coverage; + + public interface Coverage { + @Nullable + int[] tilesFor(int regionId); + } + + public void setOnAdded(@Nullable IntConsumer onAdded) { + this.onAdded = onAdded; + } + + public void setOnCleared(@Nullable Runnable onCleared) { + this.onCleared = onCleared; + } + + public void clearPicked() { + if (onCleared != null) + onCleared.run(); + } + + public void setListed(int[] listedRegions) { + this.listedRegions = listedRegions; + if (pickingListener != null) + pickingListener.run(); + describe(); + repaint(); + } + + public void setPickingListener(@Nullable Runnable pickingListener) { + this.pickingListener = pickingListener; + } + + /** Whether more than one region is picked, which is when the map stops being a single choice */ + public boolean isPicking() { + return listedRegions.length > 1; + } + + public void setCoverage(@Nullable Coverage coverage) { + this.coverage = coverage; + describe(); + repaint(); + } + + public RegionMapPanel(int startRegion, IntConsumer onChosen, IntConsumer onOpened, JLabel status) { + this.onChosen = onChosen; + this.onOpened = onOpened; + this.status = status; + // Where it opens looking, not what it has picked. Nothing is picked until something is clicked. + this.chosenRegion = -1; + this.tiles = new MapTileCache(this::repaintLater); + + centreOn(startRegion); + + setBackground(ColorScheme.DARKER_GRAY_COLOR); + setFocusable(true); + + var mouse = new MouseAdapter() { + @Override + public void mousePressed(MouseEvent event) { + dragFrom = event.getPoint(); + requestFocusInWindow(); + } + + @Override + public void mouseReleased(MouseEvent event) { + dragFrom = null; + } + + @Override + public void mouseDragged(MouseEvent event) { + if (dragFrom == null) + return; + int scale = MapProjection.scale(zoom); + centreX -= (double) (event.getX() - dragFrom.x) * scale; + centreY -= (double) (event.getY() - dragFrom.y) * scale; + dragFrom = event.getPoint(); + updatePointer(event.getPoint()); + repaint(); + } + + @Override + public void mouseMoved(MouseEvent event) { + updatePointer(event.getPoint()); + } + + @Override + public void mouseExited(MouseEvent event) { + hoveredRegion = -1; + describe(); + repaint(); + } + + @Override + public void mouseClicked(MouseEvent event) { + int region = regionAt(event.getPoint()); + if (region < 0) + return; + + if (event.isControlDown() && onAdded != null) { + onAdded.accept(region); + describe(); + repaint(); + return; + } + + // While several are picked the map is a list to edit, not a place to go, so an ordinary + // click would either be ignored or throw the picking away. It does nothing instead. + if (isPicking()) + return; + + chosenRegion = region; + onChosen.accept(region); + describe(); + repaint(); + + if (event.getClickCount() >= 2) + onOpened.accept(region); + } + + @Override + public void mouseWheelMoved(MouseWheelEvent event) { + zoomBy(-event.getWheelRotation(), event.getPoint()); + } + }; + addMouseListener(mouse); + addMouseMotionListener(mouse); + addMouseWheelListener(mouse); + } + + public void shutDown() { + tiles.shutDown(); + } + + public void setPlane(int plane) { + this.plane = plane; + repaint(); + } + + private void repaintLater() { + SwingUtilities.invokeLater(this::repaint); + } + + public void goTo(int worldX, int worldY) { + centreX = MapProjection.pixelX(worldX); + centreY = MapProjection.pixelY(worldY); + repaint(); + } + + public void select(int regionId) { + if (!MapProjection.isOnMap(regionId)) + return; + chosenRegion = regionId; + onChosen.accept(regionId); + describe(); + centreOn(regionId); + } + + public void centreOn(int regionId) { + centreX = MapProjection.pixelX(MapProjection.regionX(regionId) * REGION_SIZE + REGION_SIZE / 2); + centreY = MapProjection.pixelY(MapProjection.regionY(regionId) * REGION_SIZE + REGION_SIZE / 2); + repaint(); + } + + private void zoomBy(int steps, Point at) { + int wanted = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + steps)); + if (wanted == zoom) + return; + + double beforeX = pixelAtX(at.x); + double beforeY = pixelAtY(at.y); + zoom = wanted; + centreX += beforeX - pixelAtX(at.x); + centreY += beforeY - pixelAtY(at.y); + + updatePointer(at); + repaint(); + } + + private double pixelAtX(int screenX) { + return centreX + (screenX - getWidth() / 2.0) * MapProjection.scale(zoom); + } + + private double pixelAtY(int screenY) { + return centreY + (screenY - getHeight() / 2.0) * MapProjection.scale(zoom); + } + + public void setPointerListener(@Nullable PointerListener listener) { + this.pointerListener = listener; + } + + private void updatePointer(Point at) { + if (pointerListener != null) { + int worldX = MapProjection.worldX(pixelAtX(at.x)); + int worldY = MapProjection.worldY(pixelAtY(at.y)); + if (worldX >= 0 && worldY >= 0) + pointerListener.moved(worldX, worldY); + } + updateHover(at); + } + + private void updateHover(Point at) { + int region = regionAt(at); + if (region == hoveredRegion) + return; + hoveredRegion = region; + describe(); + repaint(); + } + + private int regionAt(Point at) { + int worldX = MapProjection.worldX(pixelAtX(at.x)); + int worldY = MapProjection.worldY(pixelAtY(at.y)); + if (worldX < 0 || worldY < 0) + return -1; + + int region = MapProjection.regionIdAt(worldX, worldY); + return MapProjection.isOnMap(region) ? region : -1; + } + + private void describe() { + if (status == null) + return; + + String hint; + if (onAdded == null) { + hint = "Drag to move, scroll to zoom, double click a region to load it"; + } else if (isPicking()) { + hint = "Ctrl click to pick a region or take one back, Clear to go back to one at a time"; + } else { + hint = "Drag to move, scroll to zoom, double click to load, ctrl click to pick several"; + } + String here = hoveredRegion < 0 + ? hint + : String.format( + "Region %d (%d, %d) at %d, %d", + hoveredRegion, + MapProjection.regionX(hoveredRegion), MapProjection.regionY(hoveredRegion), + MapProjection.regionX(hoveredRegion) * REGION_SIZE, + MapProjection.regionY(hoveredRegion) * REGION_SIZE + ); + if (hoveredRegion >= 0 && isPicking()) + here += " — " + listedRegions.length + " picked, ctrl click to " + + (isListed(hoveredRegion) ? "take it back" : "add it"); + status.setText(here + coverageNote()); + } + + /** + * What loading the region under the mouse would pull in. + * + *

It follows the pointer rather than whatever is chosen, so it reads as a preview of the region being + * considered. Pinned to the chosen one it painted a large overlay the moment the map opened, over a + * region nobody had picked, which looks like a selection that was never made. + */ + @Nullable + private int[] coverageTiles() { + if (coverage == null || hoveredRegion < 0) + return null; + return coverage.tilesFor(hoveredRegion); + } + + private String coverageNote() { + int[] tiles = coverageTiles(); + if (tiles == null) + return ""; + + int across = (tiles[2] >> 6) - (tiles[0] >> 6) + 1; + int up = (tiles[3] >> 6) - (tiles[1] >> 6) + 1; + return String.format( + " Loading %d builds %d x %d tiles, x %d to %d and y %d to %d, reading %d x %d regions (%d)", + hoveredRegion, + tiles[2] - tiles[0] + 1, tiles[3] - tiles[1] + 1, + tiles[0], tiles[2], tiles[1], tiles[3], + across, up, across * up + ); + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + var g = (Graphics2D) graphics.create(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); + drawTiles(g); + drawGrid(g); + drawCoverage(g); + for (int listed : listedRegions) + drawRegion(g, listed, LISTED_FILL, LISTED_LINE, 2); + if (!isPicking()) + drawRegion(g, chosenRegion, null, CHOSEN_LINE, 2); + if (hoveredRegion >= 0 && hoveredRegion != chosenRegion) + drawRegion(g, hoveredRegion, HOVER_FILL, HOVER_LINE, 1); + else if (hoveredRegion >= 0) + drawRegion(g, hoveredRegion, HOVER_FILL, CHOSEN_LINE, 2); + } finally { + g.dispose(); + } + } + + private void drawTiles(Graphics2D g) { + int scale = MapProjection.scale(zoom); + int onScreen = TILE_SIZE; + + int firstX = MapProjection.tileIndex(pixelAtX(0), zoom); + int lastX = MapProjection.tileIndex(pixelAtX(getWidth()), zoom); + int firstY = MapProjection.tileIndex(pixelAtY(0), zoom); + int lastY = MapProjection.tileIndex(pixelAtY(getHeight()), zoom); + + for (int tileX = firstX; tileX <= lastX; tileX++) { + for (int tileY = firstY; tileY <= lastY; tileY++) { + if (tileX < 0 || tileY < 0) + continue; + + BufferedImage image = tiles.get(plane, zoom, tileX, MapProjection.flipTileY(tileY, zoom)); + if (image == null) + continue; + + int screenX = screenXOf((double) tileX * TILE_SIZE * scale); + int screenY = screenYOf((double) tileY * TILE_SIZE * scale); + g.drawImage(image, screenX, screenY, onScreen, onScreen, null); + } + } + } + + private void drawCoverage(Graphics2D g) { + int[] tiles = coverageTiles(); + if (tiles == null) + return; + + fillTiles(g, + (tiles[0] >> 6) * REGION_SIZE, (tiles[1] >> 6) * REGION_SIZE, + ((tiles[2] >> 6) + 1) * REGION_SIZE - 1, ((tiles[3] >> 6) + 1) * REGION_SIZE - 1, + COVERAGE_FILL, COVERAGE_LINE, STROKE_1); + + fillTiles(g, tiles[0], tiles[1], tiles[2], tiles[3], null, BUILT_LINE, COVERAGE_STROKE); + } + + private void fillTiles( + Graphics2D g, int firstX, int firstY, int lastX, int lastY, + @Nullable Color fill, Color line, BasicStroke stroke + ) { + int left = screenXOf(MapProjection.pixelX(firstX)); + int right = screenXOf(MapProjection.pixelX(lastX + 1)); + int bottom = screenYOf(MapProjection.pixelY(firstY)); + int top = screenYOf(MapProjection.pixelY(lastY + 1)); + + if (fill != null) { + g.setColor(fill); + g.fillRect(left, top, right - left, bottom - top); + } + g.setColor(line); + g.setStroke(stroke); + g.drawRect(left, top, right - left, bottom - top); + } + + private void drawGrid(Graphics2D g) { + int regionPx = MapProjection.regionPx(zoom); + if (regionPx < GRID_VISIBLE_PX) + return; + + g.setColor(GRID_LINE); + g.setStroke(STROKE_1); + + int firstX = Math.floorDiv(MapProjection.worldX(pixelAtX(0)), REGION_SIZE); + int lastX = Math.floorDiv(MapProjection.worldX(pixelAtX(getWidth())), REGION_SIZE); + for (int x = firstX; x <= lastX + 1; x++) { + int screenX = screenXOf(MapProjection.pixelX(x * REGION_SIZE)); + g.drawLine(screenX, 0, screenX, getHeight()); + } + + int firstY = Math.floorDiv(MapProjection.worldY(pixelAtY(getHeight())), REGION_SIZE); + int lastY = Math.floorDiv(MapProjection.worldY(pixelAtY(0)), REGION_SIZE); + for (int y = firstY; y <= lastY + 1; y++) { + int screenY = screenYOf(MapProjection.pixelY(y * REGION_SIZE)); + g.drawLine(0, screenY, getWidth(), screenY); + } + } + + private boolean isListed(int region) { + for (int listed : listedRegions) + if (listed == region) + return true; + return false; + } + + private void drawRegion(Graphics2D g, int regionId, Color fill, Color line, int thickness) { + if (regionId < 0) + return; + + int worldX = MapProjection.regionX(regionId) * REGION_SIZE; + int worldY = MapProjection.regionY(regionId) * REGION_SIZE; + + int left = screenXOf(MapProjection.pixelX(worldX)); + int right = screenXOf(MapProjection.pixelX(worldX + REGION_SIZE)); + int bottom = screenYOf(MapProjection.pixelY(worldY)); + int top = screenYOf(MapProjection.pixelY(worldY + REGION_SIZE)); + + if (fill != null) { + g.setColor(fill); + g.fillRect(left, top, right - left, bottom - top); + } + g.setColor(line); + g.setStroke(thickness == 1 ? STROKE_1 : thickness == 2 ? STROKE_2 : new BasicStroke(thickness)); + g.drawRect(left, top, right - left, bottom - top); + } + + private int screenXOf(double pixelX) { + return (int) Math.round((pixelX - centreX) / MapProjection.scale(zoom) + getWidth() / 2.0); + } + + private int screenYOf(double pixelY) { + return (int) Math.round((pixelY - centreY) / MapProjection.scale(zoom) + getHeight() / 2.0); + } + +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java new file mode 100644 index 0000000..e5a5d9f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java @@ -0,0 +1,86 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.Animation; +import net.runelite.cache.definitions.SequenceDefinition; + +public class BuiltAnimation implements Animation { + private final SequenceDefinition sequence; + private final int duration; + + private int restartMode; + + public BuiltAnimation(SequenceDefinition sequence) { + this.sequence = sequence; + + int total = 0; + if (sequence.frameLengths != null) + for (int length : sequence.frameLengths) + total += length; + this.duration = total; + } + + public SequenceDefinition definition() { + return sequence; + } + + public int frameCount() { + return sequence.frameIDs == null ? 0 : sequence.frameIDs.length; + } + + public int frameLength(int frame) { + int[] lengths = sequence.frameLengths; + if (lengths == null || frame < 0 || frame >= lengths.length) + return 1; + return Math.max(1, lengths[frame]); + } + + @Override + public int getId() { + return sequence.getId(); + } + + @Override + public int getDuration() { + return duration; + } + + @Override + public int getNumFrames() { + return frameCount(); + } + + @Override + public int getRestartMode() { + return restartMode; + } + + @Override + public void setRestartMode(int restartMode) { + this.restartMode = restartMode; + } + + @Override + public int[] getFrameLengths() { + return sequence.frameLengths; + } + + @Override + public int getLeftHandItem() { + return sequence.leftHandItem; + } + + @Override + public int getRightHandItem() { + return sequence.rightHandItem; + } + + @Override + public int getFrameStep() { + return sequence.frameStep; + } + + @Override + public boolean isMayaAnim() { + return sequence.animMayaID != -1; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java new file mode 100644 index 0000000..9fbc7d1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java @@ -0,0 +1,69 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.DecorativeObject; +import net.runelite.api.Renderable; + +public class BuiltDecorativeObject extends BuiltTileObject implements DecorativeObject { + private Renderable renderable, renderable2; + private int xOffset, yOffset; + private final int xOffset2, yOffset2; + + public BuiltDecorativeObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable, Renderable renderable2, + int xOffset, int yOffset, int xOffset2, int yOffset2 + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + this.renderable2 = renderable2; + this.xOffset = xOffset; + this.yOffset = yOffset; + this.xOffset2 = xOffset2; + this.yOffset2 = yOffset2; + } + + public void displace(int displacement) { + if (xOffset != 0) + xOffset = xOffset < 0 ? -displacement : displacement; + if (yOffset != 0) + yOffset = yOffset < 0 ? -displacement : displacement; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + @Override + public Renderable getRenderable2() { + return renderable2; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } + + public void setRenderable2(Renderable renderable) { + renderable2 = renderable; + } + + @Override + public int getXOffset() { + return xOffset; + } + + @Override + public int getYOffset() { + return yOffset; + } + + @Override + public int getXOffset2() { + return xOffset2; + } + + @Override + public int getYOffset2() { + return yOffset2; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java new file mode 100644 index 0000000..66c7bbd --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java @@ -0,0 +1,225 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nullable; +import net.runelite.api.Animation; +import net.runelite.api.DynamicObject; +import net.runelite.api.Model; +import net.runelite.api.ObjectComposition; + +public class BuiltDynamicObject implements net.runelite.api.Renderable, DynamicObject { + public static final int CYCLE_MILLIS = 20; + + private final int objectId; + @Nullable + private final BuiltAnimation animation; + private final Model[] frames; + + private int frame; + private int cycleInFrame; + private int loops; + private int lastCycle = Integer.MIN_VALUE; + + private int modelHeight; + + public BuiltDynamicObject(int objectId, @Nullable BuiltAnimation animation, Model[] frames) { + this.objectId = objectId; + this.animation = animation; + this.frames = frames; + } + + public boolean posesDiffer() { + if (posesChecked) + return posesMove; + posesChecked = true; + + Model first = null; + for (Model model : frames) { + if (model == null) + continue; + if (first == null) { + first = model; + continue; + } + if (movedFrom(first, model)) { + posesMove = true; + break; + } + } + return posesMove; + } + + private boolean posesChecked; + private boolean posesMove; + + private static boolean movedFrom(Model a, Model b) { + if (a == b) + return false; + + float[] ax = a.getVerticesX(), bx = b.getVerticesX(); + float[] az = a.getVerticesZ(), bz = b.getVerticesZ(); + if (ax.length != bx.length) + return true; + for (int i = 0; i < ax.length; i++) + if (ax[i] != bx[i] || az[i] != bz[i]) + return true; + + byte[] at = a.getFaceTransparencies(), bt = b.getFaceTransparencies(); + if (at == null || bt == null) + return at != bt; + if (at.length != bt.length) + return true; + for (int i = 0; i < at.length; i++) + if (at[i] != bt[i]) + return true; + return false; + } + + public boolean hasModel() { + for (Model model : frames) + if (model != null) + return true; + return false; + } + + public Model modelAt(int cycle) { + advanceTo(cycle); + return getModel(); + } + + private void advanceTo(int cycle) { + if (animation == null || frames.length <= 1) + return; + + if (lastCycle == Integer.MIN_VALUE) { + lastCycle = cycle; + return; + } + + int elapsed = cycle - lastCycle; + lastCycle = cycle; + if (elapsed <= 0) + return; + + int frameCount = frames.length; + int frameStep = animation.getFrameStep(); + int duration = animation.getDuration(); + if (frameStep > 0 && duration > 0) + elapsed %= duration; + + if (frame >= frameCount) { + frame = 0; + cycleInFrame = 0; + } + + int spent = elapsed + cycleInFrame; + while (spent > animation.frameLength(frame)) { + spent -= animation.frameLength(frame); + frame++; + + if (frame >= frameCount) { + loops++; + frame -= frameStep; + if (frame < 0 || frame >= frameCount) + frame = 0; + } + } + cycleInFrame = spent; + } + + + @Override + public Model getModel() { + int at = Math.min(Math.max(frame, 0), frames.length - 1); + if (frames[at] != null) + return frames[at]; + + for (int away = 1; away < frames.length; away++) { + int before = at - away; + if (before >= 0 && frames[before] != null) + return frames[before]; + int after = at + away; + if (after < frames.length && frames[after] != null) + return frames[after]; + } + return null; + } + + @Override + public int getModelHeight() { + if (modelHeight == 0) { + Model model = getModel(); + modelHeight = model == null ? 0 : model.getModelHeight(); + } + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getRenderMode() { + return 0; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getAnimFrame() { + return frame; + } + + @Override + public int getAnimCycle() { + return cycleInFrame; + } + + @Nullable + @Override + public Model getModelZbuf() { + return animation == null ? getModel() : null; + } + + @Nullable + @Override + public Animation getAnimation() { + return animation; + } + + @Nullable + @Override + public ObjectComposition getRecordedObjectComposition() { + return null; + } + + public int getObjectId() { + return objectId; + } + + + @Override + public net.runelite.api.Node getNext() { + return null; + } + + @Override + public net.runelite.api.Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } + + @Override + public String toString() { + return "BuiltDynamicObject(" + objectId + + ", animation " + (animation == null ? "none" : animation.getId()) + + ", " + frames.length + " frames)"; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java new file mode 100644 index 0000000..3400145 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java @@ -0,0 +1,66 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.GameObject; +import net.runelite.api.Point; +import net.runelite.api.Renderable; + +public class BuiltGameObject extends BuiltTileObject implements GameObject { + private static final int ROTATION_UNIT = 512; + + private Renderable renderable; + private final int modelOrientation; + private final int minSceneX, minSceneY, maxSceneX, maxSceneY; + + public BuiltGameObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable, int modelOrientation, + int minSceneX, int minSceneY, int maxSceneX, int maxSceneY + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + this.modelOrientation = modelOrientation; + this.minSceneX = minSceneX; + this.minSceneY = minSceneY; + this.maxSceneX = maxSceneX; + this.maxSceneY = maxSceneY; + } + + @Override + public int sizeX() { + return maxSceneX - minSceneX + 1; + } + + @Override + public int sizeY() { + return maxSceneY - minSceneY + 1; + } + + @Override + public Point getSceneMinLocation() { + return new Point(minSceneX, minSceneY); + } + + @Override + public Point getSceneMaxLocation() { + return new Point(maxSceneX, maxSceneY); + } + + @Override + public int getOrientation() { + return getRotation() * ROTATION_UNIT + modelOrientation; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } + + @Override + public int getModelOrientation() { + return modelOrientation; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java new file mode 100644 index 0000000..c9c039e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java @@ -0,0 +1,24 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.GroundObject; +import net.runelite.api.Renderable; + +public class BuiltGroundObject extends BuiltTileObject implements GroundObject { + private Renderable renderable; + + public BuiltGroundObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, Renderable renderable + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java new file mode 100644 index 0000000..05c2451 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java @@ -0,0 +1,465 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nonnull; +import net.runelite.api.AABB; +import net.runelite.api.Model; +import net.runelite.api.Node; + +public class BuiltModel implements Model { + int verticesCount; + float[] verticesX, verticesY, verticesZ; + + int faceCount; + int[] faceIndices1, faceIndices2, faceIndices3; + + int[] faceColors1, faceColors2, faceColors3; + short[] unlitFaceColors; + + byte[] faceTransparencies; + byte transparency; + short[] faceTextures; + byte[] textureFaces; + int[] texIndices1, texIndices2, texIndices3; + + int[] vertexNormalsX, vertexNormalsY, vertexNormalsZ; + + byte[] faceRenderPriorities; + byte[] faceBias; + + int modelHeight, bottomY, xyzMag, radius, diameter; + private boolean boundsCalculated; + + private int sceneId, bufferOffset, uvBufferOffset; + + BuiltModel copyForContour() { + var copy = new BuiltModel(); + + copy.verticesCount = verticesCount; + copy.verticesX = verticesX; + copy.verticesY = new float[verticesCount]; + copy.verticesZ = verticesZ; + + copy.faceCount = faceCount; + copy.faceIndices1 = faceIndices1; + copy.faceIndices2 = faceIndices2; + copy.faceIndices3 = faceIndices3; + + copy.faceColors1 = faceColors1; + copy.faceColors2 = faceColors2; + copy.faceColors3 = faceColors3; + copy.unlitFaceColors = unlitFaceColors; + + copy.faceTransparencies = faceTransparencies; + copy.transparency = transparency; + copy.faceTextures = faceTextures; + copy.textureFaces = textureFaces; + copy.texIndices1 = texIndices1; + copy.texIndices2 = texIndices2; + copy.texIndices3 = texIndices3; + + copy.vertexNormalsX = vertexNormalsX; + copy.vertexNormalsY = vertexNormalsY; + copy.vertexNormalsZ = vertexNormalsZ; + + copy.faceRenderPriorities = faceRenderPriorities; + copy.faceBias = faceBias; + + return copy; + } + + /** Creates a renderable diagnostic copy without changing the cached mesh or its materials. */ + public BuiltModel withDiagnosticColors(int[] colors) { + if (colors.length != faceCount) + throw new IllegalArgumentException("Expected one diagnostic color per face"); + var copy = copyForContour(); + copy.verticesY = verticesY; + copy.faceColors1 = colors.clone(); + copy.faceColors2 = colors.clone(); + copy.faceColors3 = colors.clone(); + copy.unlitFaceColors = new short[faceCount]; + for (int face = 0; face < faceCount; face++) { + copy.unlitFaceColors[face] = (short) colors[face]; + if (faceColors3[face] == -2) + copy.faceColors3[face] = -2; + } + copy.faceTextures = null; + copy.textureFaces = null; + return copy; + } + + public BuiltModel withVertices(float[] x, float[] y, float[] z) { + var copy = copyForContour(); + copy.verticesX = x; + copy.verticesY = y; + copy.verticesZ = z; + return copy; + } + + BuiltModel withPose(float[] x, float[] y, float[] z, byte[] faceTransparencies) { + var copy = withVertices(x, y, z); + copy.faceTransparencies = faceTransparencies; + return copy; + } + + @Override + public int getVerticesCount() { + return verticesCount; + } + + @Override + public float[] getVerticesX() { + return verticesX; + } + + @Override + public float[] getVerticesY() { + return verticesY; + } + + @Override + public float[] getVerticesZ() { + return verticesZ; + } + + @Override + public int getFaceCount() { + return faceCount; + } + + @Override + public int[] getFaceIndices1() { + return faceIndices1; + } + + @Override + public int[] getFaceIndices2() { + return faceIndices2; + } + + @Override + public int[] getFaceIndices3() { + return faceIndices3; + } + + @Override + public byte[] getFaceTransparencies() { + return faceTransparencies; + } + + @Override + public short[] getFaceTextures() { + return faceTextures; + } + + @Override + public int[] getFaceColors1() { + return faceColors1; + } + + @Override + public int[] getFaceColors2() { + return faceColors2; + } + + @Override + public int[] getFaceColors3() { + return faceColors3; + } + + @Override + public short[] getUnlitFaceColors() { + return unlitFaceColors; + } + + @Override + public int getSceneId() { + return sceneId; + } + + @Override + public void setSceneId(int sceneId) { + this.sceneId = sceneId; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBottomY() { + calculateBoundsCylinder(); + return bottomY; + } + + @Override + public void calculateBoundsCylinder() { + if (boundsCalculated) + return; + boundsCalculated = true; + + modelHeight = 0; + bottomY = 0; + int magnitude = 0; + + for (int i = 0; i < verticesCount; i++) { + int x = (int) verticesX[i]; + int y = (int) verticesY[i]; + int z = (int) verticesZ[i]; + + if (-y > modelHeight) + modelHeight = -y; + if (y > bottomY) + bottomY = y; + + int squared = x * x + z * z; + if (squared > magnitude) + magnitude = squared; + } + + xyzMag = (int) (Math.sqrt(magnitude) + 0.99); + radius = (int) (Math.sqrt((double) xyzMag * xyzMag + (double) modelHeight * modelHeight) + 0.99); + diameter = radius + (int) (Math.sqrt((double) xyzMag * xyzMag + (double) bottomY * bottomY) + 0.99); + } + + @Override + public byte getTransparency() { + return transparency; + } + + @Override + public byte[] getFaceRenderPriorities() { + return faceRenderPriorities; + } + + @Override + public byte[] getFaceBias() { + return faceBias; + } + + @Override + public int getRadius() { + calculateBoundsCylinder(); + return radius; + } + + @Override + public int getDiameter() { + calculateBoundsCylinder(); + return diameter; + } + + @Override + public int getXYZMag() { + calculateBoundsCylinder(); + return xyzMag; + } + + @Override + @Deprecated + public void calculateExtreme(int orientation) {} + + @Nonnull + @Override + public AABB getAABB(int orientation) { + calculateBoundsCylinder(); + return new ModelAABB(xyzMag, modelHeight, bottomY); + } + + @Override + public boolean useBoundingBox() { + return false; + } + + @Override + public int[] getVertexNormalsX() { + return vertexNormalsX; + } + + @Override + public int[] getVertexNormalsY() { + return vertexNormalsY; + } + + @Override + public int[] getVertexNormalsZ() { + return vertexNormalsZ; + } + + @Override + public byte getOverrideAmount() { + return 0; + } + + @Override + public byte getOverrideHue() { + return 0; + } + + @Override + public byte getOverrideSaturation() { + return 0; + } + + @Override + public byte getOverrideLuminance() { + return 0; + } + + @Override + public byte[] getTextureFaces() { + return textureFaces; + } + + @Override + public int[] getTexIndices1() { + return texIndices1; + } + + @Override + public int[] getTexIndices2() { + return texIndices2; + } + + @Override + public int[] getTexIndices3() { + return texIndices3; + } + + @Override + public Model getUnskewedModel() { + return this; + } + + @Override + public void drawFrustum(int zero, int xRotate, int yRotate, int zRotate, int xCamera, int yCamera, int zCamera) { + } + + @Override + public void drawOrtho(int zero, int xRotate, int yRotate, int zRotate, int xCamera, int yCamera, int zCamera, int zoom) {} + + + @Override + public Model getModel() { + return this; + } + + @Override + public int getModelHeight() { + calculateBoundsCylinder(); + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getRenderMode() { + return RENDERMODE_DEFAULT; + } + + + @Override + public Node getNext() { + return null; + } + + @Override + public Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } + + + @Override + public Model rotateY90Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model rotateY180Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model rotateY270Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model translate(int x, int y, int z) { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model scale(int x, int y, int z) { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + private static final class ModelAABB implements AABB { + private final int extremeX, extremeY, extremeZ; + private final int centerY; + + ModelAABB(int xyzMag, int modelHeight, int bottomY) { + extremeX = extremeZ = xyzMag; + extremeY = modelHeight + bottomY >> 1; + centerY = bottomY - extremeY; + } + + @Override + public int getCenterX() { + return 0; + } + + @Override + public int getCenterY() { + return centerY; + } + + @Override + public int getCenterZ() { + return 0; + } + + @Override + public int getExtremeX() { + return extremeX; + } + + @Override + public int getExtremeY() { + return extremeY; + } + + @Override + public int getExtremeZ() { + return extremeZ; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java new file mode 100644 index 0000000..4722de3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java @@ -0,0 +1,359 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayDeque; +import net.runelite.api.GameObject; +import net.runelite.api.Model; +import net.runelite.api.Node; +import net.runelite.api.Scene; +import javax.annotation.Nullable; +import net.runelite.api.Tile; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; +import static net.runelite.api.Constants.SCENE_SIZE; + +public class BuiltScene implements Scene { + public static final int SCENE_OFFSET = (EXTENDED_SCENE_SIZE - SCENE_SIZE) / 2; + + private final int baseX, baseY; + private final int worldViewId; + + private final BuiltTile[][][] extendedTiles = new BuiltTile[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final Tile[][][] tiles = new Tile[MAX_Z][SCENE_SIZE][SCENE_SIZE]; + + private final int[][][] tileHeights = new int[MAX_Z][EXTENDED_SCENE_SIZE + 1][EXTENDED_SCENE_SIZE + 1]; + private final byte[][][] extendedTileSettings = new byte[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final short[][][] underlayIds = new short[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final short[][][] overlayIds = new short[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final byte[][][] tileShapes = new byte[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final int[][][] roofs = new int[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + + private final int[] mapRegions; + + private int drawDistance = 25; + private int minLevel; + private int roofRemovalMode; + + private int modelHeight; + + public BuiltScene(int baseX, int baseY, int worldViewId, int[] mapRegions) { + this.baseX = baseX; + this.baseY = baseY; + this.worldViewId = worldViewId; + this.mapRegions = mapRegions; + } + + public int getSceneOffset() { + return SCENE_OFFSET; + } + + public BuiltTile tile(int plane, int extendedX, int extendedY) { + BuiltTile tile = extendedTiles[plane][extendedX][extendedY]; + if (tile == null) { + tile = new BuiltTile(this, plane, extendedX, extendedY); + setTile(plane, extendedX, extendedY, tile); + } + return tile; + } + + public BuiltTile tileOrNull(int plane, int extendedX, int extendedY) { + return extendedTiles[plane][extendedX][extendedY]; + } + + public void setTile(int plane, int extendedX, int extendedY, BuiltTile tile) { + extendedTiles[plane][extendedX][extendedY] = tile; + + int sceneX = extendedX - SCENE_OFFSET; + int sceneY = extendedY - SCENE_OFFSET; + if (sceneX >= 0 && sceneX < SCENE_SIZE && sceneY >= 0 && sceneY < SCENE_SIZE) + tiles[plane][sceneX][sceneY] = tile; + } + + @Override + public Tile[][][] getTiles() { + return tiles; + } + + @Override + public Tile[][][] getExtendedTiles() { + return extendedTiles; + } + + @Override + public byte[][][] getExtendedTileSettings() { + return extendedTileSettings; + } + + @Override + public int getDrawDistance() { + return drawDistance; + } + + @Override + public void setDrawDistance(int drawDistance) { + this.drawDistance = drawDistance; + } + + @Override + public int getWorldViewId() { + return worldViewId; + } + + @Override + public int getMinLevel() { + return minLevel; + } + + @Override + public void setMinLevel(int minLevel) { + this.minLevel = minLevel; + } + + @Override + public void removeTile(Tile tile) { + if (!(tile instanceof BuiltTile)) + return; + BuiltTile cacheTile = (BuiltTile) tile; + setTile(cacheTile.getPlane(), cacheTile.getExtendedX(), cacheTile.getExtendedY(), null); + } + + @Override + public void removeGameObject(GameObject gameObject) { + for (int plane = 0; plane < MAX_Z; plane++) { + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) { + for (int y = 0; y < EXTENDED_SCENE_SIZE; y++) { + BuiltTile tile = extendedTiles[plane][x][y]; + if (tile == null) + continue; + GameObject[] objects = tile.getGameObjects(); + for (int i = 0; i < objects.length; i++) + if (objects[i] == gameObject) + objects[i] = null; + } + } + } + } + + private boolean isRoofed(int plane, int x, int y) { + return (extendedTileSettings[plane][x][y] & 4) != 0; + } + + @Override + public void buildRoofs() { + for (int plane = 0; plane < MAX_Z; plane++) + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) + java.util.Arrays.fill(roofs[plane][x], 0); + + int nextRoofId = 1; + for (int plane = MAX_Z - 1; plane >= 0; plane--) { + for (int y = 0; y < EXTENDED_SCENE_SIZE; y++) { + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) { + if (extendedTiles[plane][x][y] == null || roofs[plane][x][y] != 0 || !isRoofed(plane, x, y)) + continue; + floodRoof(plane, x, y, nextRoofId++); + } + } + } + } + + private void floodRoof(int startPlane, int startX, int startY, int roofId) { + var queue = new ArrayDeque(); + queue.add(new int[] { startPlane, startX, startY }); + + while (!queue.isEmpty()) { + int[] at = queue.poll(); + int plane = at[0], x = at[1], y = at[2]; + if (roofs[plane][x][y] != 0) + continue; + + if (isRoofed(plane, x, y)) { + for (int dx = -1; dx <= 1; dx++) { + for (int dy = -1; dy <= 1; dy++) { + if (dx == 0 && dy == 0) + continue; + int nx = x + dx; + int ny = y + dy; + if (nx < 0 || ny < 0 || nx >= EXTENDED_SCENE_SIZE || ny >= EXTENDED_SCENE_SIZE) + continue; + if (extendedTiles[plane][nx][ny] != null) + queue.add(new int[] { plane, nx, ny }); + } + } + } + + roofs[plane][x][y] = roofId; + + for (int above = plane + 1, distance = 1; above < MAX_Z; above++, distance++) { + if (roofs[above][x][y] != 0) + break; + roofs[above][x][y] = roofId | distance << 28; + } + } + } + + private final java.util.List dynamics = new java.util.ArrayList<>(); + + public static final class Dynamic { + public final net.runelite.api.TileObject tileObject; + public final BuiltDynamicObject renderable; + public final int orientation; + public final int x, y, z; + + public Dynamic( + net.runelite.api.TileObject tileObject, BuiltDynamicObject renderable, + int orientation, int x, int y, int z + ) { + this.tileObject = tileObject; + this.renderable = renderable; + this.orientation = orientation; + this.x = x; + this.y = y; + this.z = z; + } + } + + public void addDynamic(Dynamic dynamic) { + dynamics.add(dynamic); + } + + public java.util.List getDynamics() { + return dynamics; + } + + @Override + public int[][][] getRoofs() { + return roofs; + } + + @Override + public void setRoofRemovalMode(int flags) { + roofRemovalMode = flags; + } + + @Override + public int getRoofRemovalMode() { + return roofRemovalMode; + } + + @Override + public short[][][] getUnderlayIds() { + return underlayIds; + } + + @Override + public short[][][] getOverlayIds() { + return overlayIds; + } + + @Override + public byte[][][] getTileShapes() { + return tileShapes; + } + + @Override + public int[][][] getTileHeights() { + return tileHeights; + } + + @Override + public int getBaseX() { + return baseX; + } + + @Override + public int getBaseY() { + return baseY; + } + + public static final int CHUNKS_PER_SIDE = EXTENDED_SCENE_SIZE / 8; + + @Nullable + private int[][][] instanceTemplateChunks; + + public void setInstanceTemplateChunks(int[][][] instanceTemplateChunks) { + this.instanceTemplateChunks = instanceTemplateChunks; + } + + @Override + public boolean isInstance() { + return instanceTemplateChunks != null; + } + + @Nullable + @Override + public int[][][] getInstanceTemplateChunks() { + return instanceTemplateChunks; + } + + @Override + public int[] getMapRegions() { + return mapRegions; + } + + @Override + public byte getOverrideAmount() { + return 0; + } + + @Override + public byte getOverrideHue() { + return 0; + } + + @Override + public byte getOverrideSaturation() { + return 0; + } + + @Override + public byte getOverrideLuminance() { + return 0; + } + + @Override + public Model getSkybox() { + return null; + } + + + @Override + public Model getModel() { + return null; + } + + @Override + public int getModelHeight() { + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getRenderMode() { + return RENDERMODE_DEFAULT; + } + + + @Override + public Node getNext() { + return null; + } + + @Override + public Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java new file mode 100644 index 0000000..9ddbf3f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java @@ -0,0 +1,186 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; +import net.runelite.api.DecorativeObject; +import net.runelite.api.GameObject; +import net.runelite.api.GroundObject; +import net.runelite.api.ItemLayer; +import net.runelite.api.Point; +import net.runelite.api.SceneTileModel; +import net.runelite.api.SceneTilePaint; +import net.runelite.api.Tile; +import net.runelite.api.TileItem; +import net.runelite.api.WallObject; +import net.runelite.api.coords.LocalPoint; +import net.runelite.api.coords.WorldPoint; + +import static net.runelite.api.Perspective.LOCAL_TILE_SIZE; + +public class BuiltTile implements Tile { + public static final int MAX_GAME_OBJECTS = 5; + + private final BuiltScene scene; + private final int extendedX, extendedY; + private int plane; + private boolean onBridge; + + private SceneTilePaint paint; + private SceneTileModel model; + + private final GameObject[] gameObjects = new GameObject[MAX_GAME_OBJECTS]; + private WallObject wallObject; + private DecorativeObject decorativeObject; + private GroundObject groundObject; + + @Nullable + private BuiltTile bridge; + + public BuiltTile(BuiltScene scene, int plane, int extendedX, int extendedY) { + this.scene = scene; + this.plane = plane; + this.extendedX = extendedX; + this.extendedY = extendedY; + } + + public int getExtendedX() { + return extendedX; + } + + public int getExtendedY() { + return extendedY; + } + + public int getSceneX() { + return extendedX - scene.getSceneOffset(); + } + + public int getSceneY() { + return extendedY - scene.getSceneOffset(); + } + + @Override + public DecorativeObject getDecorativeObject() { + return decorativeObject; + } + + public void setDecorativeObject(DecorativeObject decorativeObject) { + this.decorativeObject = decorativeObject; + } + + @Override + public GameObject[] getGameObjects() { + return gameObjects; + } + + public int gameObjectCount() { + int count = 0; + for (GameObject object : gameObjects) + if (object != null) + count++; + return count; + } + + public boolean addGameObject(GameObject gameObject) { + for (int i = 0; i < gameObjects.length; i++) { + if (gameObjects[i] == null) { + gameObjects[i] = gameObject; + return true; + } + } + return false; + } + + @Override + public ItemLayer getItemLayer() { + return null; + } + + @Override + public GroundObject getGroundObject() { + return groundObject; + } + + @Override + public void setGroundObject(GroundObject groundObject) { + this.groundObject = groundObject; + } + + @Override + public WallObject getWallObject() { + return wallObject; + } + + public void setWallObject(WallObject wallObject) { + this.wallObject = wallObject; + } + + @Override + public SceneTilePaint getSceneTilePaint() { + return paint; + } + + @Override + public void setSceneTilePaint(SceneTilePaint paint) { + this.paint = paint; + } + + @Override + public SceneTileModel getSceneTileModel() { + return model; + } + + @Override + public void setSceneTileModel(SceneTileModel model) { + this.model = model; + } + + @Override + public WorldPoint getWorldLocation() { + return new WorldPoint(scene.getBaseX() + getSceneX(), scene.getBaseY() + getSceneY(), plane); + } + + @Override + public Point getSceneLocation() { + return new Point(getSceneX(), getSceneY()); + } + + @Override + public LocalPoint getLocalLocation() { + int half = LOCAL_TILE_SIZE / 2; + return new LocalPoint(getSceneX() * LOCAL_TILE_SIZE + half, getSceneY() * LOCAL_TILE_SIZE + half); + } + + @Override + public int getPlane() { + return plane; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + @Override + public int getRenderLevel() { + return plane + (onBridge ? 1 : 0) & 3; + } + + public void setOnBridge(boolean onBridge) { + this.onBridge = onBridge; + } + + @Override + public List getGroundItems() { + return Collections.emptyList(); + } + + @Override + public Tile getBridge() { + return bridge; + } + + public void setBridge(@Nullable BuiltTile bridge) { + this.bridge = bridge; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java new file mode 100644 index 0000000..8ccf4e1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java @@ -0,0 +1,370 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.SceneTileModel; + +public class BuiltTileModel implements SceneTileModel { + private static final int[][] SHAPE_VERTICES = { + { 1, 3, 5, 7 }, + { 1, 3, 5, 7 }, + { 1, 3, 5, 7 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 2, 6 }, + { 1, 3, 5, 7, 2, 8 }, + { 1, 3, 5, 7, 2, 8 }, + { 1, 3, 5, 7, 11, 12 }, + { 1, 3, 5, 7, 11, 12 }, + { 1, 3, 5, 7, 13, 14 } + }; + + private static final int[][] SHAPE_FACES = { + { 0, 1, 2, 3, 0, 0, 1, 3 }, + { 1, 1, 2, 3, 1, 0, 1, 3 }, + { 0, 1, 2, 3, 1, 0, 1, 3 }, + { 0, 0, 1, 2, 0, 0, 2, 4, 1, 0, 4, 3 }, + { 0, 0, 1, 4, 0, 0, 4, 3, 1, 1, 2, 4 }, + { 0, 0, 4, 3, 1, 0, 1, 2, 1, 0, 2, 4 }, + { 0, 1, 2, 4, 1, 0, 1, 4, 1, 0, 4, 3 }, + { 0, 4, 1, 2, 0, 4, 2, 5, 1, 0, 4, 5, 1, 0, 5, 3 }, + { 0, 4, 1, 2, 0, 4, 2, 3, 0, 4, 3, 5, 1, 0, 4, 5 }, + { 0, 0, 4, 5, 1, 4, 1, 2, 1, 4, 2, 3, 1, 4, 3, 5 }, + { 0, 0, 1, 5, 0, 1, 4, 5, 0, 1, 2, 4, 1, 0, 5, 3, 1, 5, 4, 3, 1, 4, 2, 3 }, + { 1, 0, 1, 5, 1, 1, 4, 5, 1, 1, 2, 4, 0, 0, 5, 3, 0, 5, 4, 3, 0, 4, 2, 3 }, + { 1, 0, 5, 4, 1, 0, 1, 5, 0, 0, 4, 3, 0, 4, 5, 3, 0, 5, 2, 3, 0, 1, 2, 5 } + }; + + private static final int UNIT = 128; + private static final int HALF = UNIT / 2; + private static final int QUARTER = UNIT / 4; + private static final int THREE_QUARTER = UNIT * 3 / 4; + + private final int shape; + private final int rotation; + private final int modelUnderlay; + private final int modelOverlay; + private final boolean flat; + + private final int[] vertexX; + private final int[] vertexY; + private final int[] vertexZ; + + private final int[] faceA; + private final int[] faceB; + private final int[] faceC; + + private final int[] triangleColorA; + private final int[] triangleColorB; + private final int[] triangleColorC; + private final int[] triangleTextureId; + + private int bufferOffset, uvBufferOffset, bufferLen; + + public BuiltTileModel( + int shape, int rotation, int texture, int tileX, int tileZ, + int swY, int seY, int neY, int nwY, + int swU, int seU, int neU, int nwU, + int swO, int seO, int neO, int nwO, + int modelUnderlay, int modelOverlay + ) { + this.shape = shape; + this.rotation = rotation; + this.modelUnderlay = modelUnderlay; + this.modelOverlay = modelOverlay; + this.flat = swY == seY && swY == neY && swY == nwY; + + int[] vertices = SHAPE_VERTICES[shape]; + int vertexCount = vertices.length; + vertexX = new int[vertexCount]; + vertexY = new int[vertexCount]; + vertexZ = new int[vertexCount]; + + int[] underlayColors = new int[vertexCount]; + int[] overlayColors = new int[vertexCount]; + + int baseX = tileX * UNIT; + int baseZ = tileZ * UNIT; + + for (int i = 0; i < vertexCount; i++) { + int vertex = vertices[i]; + if ((vertex & 1) == 0 && vertex <= 8) + vertex = (vertex - rotation - rotation - 1 & 7) + 1; + if (vertex > 8 && vertex <= 12) + vertex = (vertex - 9 - rotation & 3) + 9; + if (vertex > 12 && vertex <= 16) + vertex = (vertex - 13 - rotation & 3) + 13; + + int x, z, y, underlay, overlay; + switch (vertex) { + case 1: + x = baseX; + z = baseZ; + y = swY; + underlay = swU; + overlay = swO; + break; + case 2: + x = baseX + HALF; + z = baseZ; + y = swY + seY >> 1; + underlay = swU + seU >> 1; + overlay = swO + seO >> 1; + break; + case 3: + x = baseX + UNIT; + z = baseZ; + y = seY; + underlay = seU; + overlay = seO; + break; + case 4: + x = baseX + UNIT; + z = baseZ + HALF; + y = seY + neY >> 1; + underlay = seU + neU >> 1; + overlay = seO + neO >> 1; + break; + case 5: + x = baseX + UNIT; + z = baseZ + UNIT; + y = neY; + underlay = neU; + overlay = neO; + break; + case 6: + x = baseX + HALF; + z = baseZ + UNIT; + y = neY + nwY >> 1; + underlay = neU + nwU >> 1; + overlay = neO + nwO >> 1; + break; + case 7: + x = baseX; + z = baseZ + UNIT; + y = nwY; + underlay = nwU; + overlay = nwO; + break; + case 8: + x = baseX; + z = baseZ + HALF; + y = swY + nwY >> 1; + underlay = swU + nwU >> 1; + overlay = swO + nwO >> 1; + break; + case 9: + x = baseX + HALF; + z = baseZ + QUARTER; + y = swY + seY >> 1; + underlay = swU + seU >> 1; + overlay = swO + seO >> 1; + break; + case 10: + x = baseX + THREE_QUARTER; + z = baseZ + HALF; + y = seY + neY >> 1; + underlay = seU + neU >> 1; + overlay = seO + neO >> 1; + break; + case 11: + x = baseX + HALF; + z = baseZ + THREE_QUARTER; + y = neY + nwY >> 1; + underlay = neU + nwU >> 1; + overlay = neO + nwO >> 1; + break; + case 12: + x = baseX + QUARTER; + z = baseZ + HALF; + y = swY + nwY >> 1; + underlay = swU + nwU >> 1; + overlay = swO + nwO >> 1; + break; + case 13: + x = baseX + QUARTER; + z = baseZ + QUARTER; + y = swY; + underlay = swU; + overlay = swO; + break; + case 14: + x = baseX + THREE_QUARTER; + z = baseZ + QUARTER; + y = seY; + underlay = seU; + overlay = seO; + break; + case 15: + x = baseX + THREE_QUARTER; + z = baseZ + THREE_QUARTER; + y = neY; + underlay = neU; + overlay = neO; + break; + default: + x = baseX + QUARTER; + z = baseZ + THREE_QUARTER; + y = nwY; + underlay = nwU; + overlay = nwO; + break; + } + + vertexX[i] = x; + vertexY[i] = y; + vertexZ[i] = z; + underlayColors[i] = underlay; + overlayColors[i] = overlay; + } + + int[] faces = SHAPE_FACES[shape]; + int faceCount = faces.length / 4; + faceA = new int[faceCount]; + faceB = new int[faceCount]; + faceC = new int[faceCount]; + triangleColorA = new int[faceCount]; + triangleColorB = new int[faceCount]; + triangleColorC = new int[faceCount]; + triangleTextureId = texture != -1 ? new int[faceCount] : null; + + int f = 0; + for (int i = 0; i < faceCount; i++) { + int isOverlay = faces[f]; + int a = faces[f + 1]; + int b = faces[f + 2]; + int c = faces[f + 3]; + f += 4; + + if (a < 4) + a = a - rotation & 3; + if (b < 4) + b = b - rotation & 3; + if (c < 4) + c = c - rotation & 3; + + faceA[i] = a; + faceB[i] = b; + faceC[i] = c; + + if (isOverlay == 0) { + triangleColorA[i] = underlayColors[a]; + triangleColorB[i] = underlayColors[b]; + triangleColorC[i] = underlayColors[c]; + if (triangleTextureId != null) + triangleTextureId[i] = -1; + } else { + triangleColorA[i] = overlayColors[a]; + triangleColorB[i] = overlayColors[b]; + triangleColorC[i] = overlayColors[c]; + if (triangleTextureId != null) + triangleTextureId[i] = texture; + } + } + } + + @Override + public int getModelUnderlay() { + return modelUnderlay; + } + + @Override + public int getModelOverlay() { + return modelOverlay; + } + + @Override + public int getShape() { + return shape; + } + + @Override + public int getRotation() { + return rotation; + } + + @Override + public int[] getFaceX() { + return faceA; + } + + @Override + public int[] getFaceY() { + return faceB; + } + + @Override + public int[] getFaceZ() { + return faceC; + } + + @Override + public int[] getVertexX() { + return vertexX; + } + + @Override + public int[] getVertexY() { + return vertexY; + } + + @Override + public int[] getVertexZ() { + return vertexZ; + } + + @Override + public int[] getTriangleColorA() { + return triangleColorA; + } + + @Override + public int[] getTriangleColorB() { + return triangleColorB; + } + + @Override + public int[] getTriangleColorC() { + return triangleColorC; + } + + @Override + public int[] getTriangleTextureId() { + return triangleTextureId; + } + + @Override + public boolean isFlat() { + return flat; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBufferLen() { + return bufferLen; + } + + @Override + public void setBufferLen(int bufferLen) { + this.bufferLen = bufferLen; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java new file mode 100644 index 0000000..d9e9365 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java @@ -0,0 +1,158 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.Shape; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.runelite.api.Point; +import net.runelite.api.TileObject; +import net.runelite.api.WorldView; +import net.runelite.api.coords.LocalPoint; +import net.runelite.api.coords.WorldPoint; + +public abstract class BuiltTileObject implements TileObject { + public static final int HASH_ID_SHIFT = 20; + + protected final BuiltScene scene; + protected final long hash; + protected final int config; + protected final int x, y, z; + protected int plane; + + protected BuiltTileObject(BuiltScene scene, long hash, int config, int x, int y, int z, int plane) { + this.scene = scene; + this.hash = hash; + this.config = config; + this.x = x; + this.y = y; + this.z = z; + this.plane = plane; + } + + public int getConfig() { + return config; + } + + public int getType() { + return config & 0x3F; + } + + public int getRotation() { + return config >> 6 & 3; + } + + @Override + public long getHash() { + return hash; + } + + @Override + public int getId() { + return (int) (hash >>> HASH_ID_SHIFT & 0xFFFFFFFFL); + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } + + @Override + public int getZ() { + return z; + } + + @Override + public int getPlane() { + return plane; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + @Override + public WorldView getWorldView() { + return null; + } + + @Nonnull + @Override + public WorldPoint getWorldLocation() { + var local = getLocalLocation(); + return new WorldPoint( + scene.getBaseX() + local.getSceneX(), + scene.getBaseY() + local.getSceneY(), + plane + ); + } + + @Nonnull + @Override + public LocalPoint getLocalLocation() { + return new LocalPoint(x, y); + } + + + @Nullable + @Override + public Point getCanvasLocation() { + return null; + } + + @Nullable + @Override + public Point getCanvasLocation(int zOffset) { + return null; + } + + @Nullable + @Override + public Polygon getCanvasTilePoly() { + return null; + } + + @Nullable + @Override + public Point getCanvasTextLocation(Graphics2D graphics, String text, int zOffset) { + return null; + } + + @Nullable + @Override + public Point getMinimapLocation() { + return null; + } + + @Nullable + @Override + public Shape getClickbox() { + return null; + } + + @Nullable + @Override + public String getOpOverride(int index) { + return null; + } + + @Override + public boolean isOpShown(int index) { + return false; + } + + @Nullable + public Shape getConvexHull() { + return null; + } + + @Nullable + public Shape getConvexHull2() { + return null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java new file mode 100644 index 0000000..a1c6fdb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java @@ -0,0 +1,112 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.SceneTilePaint; + +public class BuiltTilePaint implements SceneTilePaint { + private final int rgb; + private int swColor, seColor, neColor, nwColor; + private int texture; + private final boolean flat; + + private int bufferOffset, uvBufferOffset, bufferLen; + + public BuiltTilePaint(int swColor, int seColor, int neColor, int nwColor, int texture, int rgb, boolean flat) { + this.swColor = swColor; + this.seColor = seColor; + this.neColor = neColor; + this.nwColor = nwColor; + this.texture = texture; + this.rgb = rgb; + this.flat = flat; + } + + @Override + public int getRBG() { + return rgb; + } + + @Override + public int getSwColor() { + return swColor; + } + + @Override + public void setSwColor(int color) { + swColor = color; + } + + @Override + public int getSeColor() { + return seColor; + } + + @Override + public void setSeColor(int color) { + seColor = color; + } + + @Override + public int getNwColor() { + return nwColor; + } + + @Override + public void setNwColor(int color) { + nwColor = color; + } + + @Override + public int getNeColor() { + return neColor; + } + + @Override + public void setNeColor(int color) { + neColor = color; + } + + @Override + public int getTexture() { + return texture; + } + + @Override + public void setTexture(int texture) { + this.texture = texture; + } + + @Override + public boolean isFlat() { + return flat; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBufferLen() { + return bufferLen; + } + + @Override + public void setBufferLen(int bufferLen) { + this.bufferLen = bufferLen; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java new file mode 100644 index 0000000..1c491fb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java @@ -0,0 +1,48 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.Renderable; +import net.runelite.api.WallObject; + +public class BuiltWallObject extends BuiltTileObject implements WallObject { + private Renderable renderable1, renderable2; + private final int orientationA, orientationB; + + public BuiltWallObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable1, Renderable renderable2, int orientationA, int orientationB + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable1 = renderable1; + this.renderable2 = renderable2; + this.orientationA = orientationA; + this.orientationB = orientationB; + } + + @Override + public int getOrientationA() { + return orientationA; + } + + @Override + public int getOrientationB() { + return orientationB; + } + + @Override + public Renderable getRenderable1() { + return renderable1; + } + + @Override + public Renderable getRenderable2() { + return renderable2; + } + + public void setRenderable1(Renderable renderable) { + renderable1 = renderable; + } + + public void setRenderable2(Renderable renderable) { + renderable2 = renderable; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java new file mode 100644 index 0000000..16260b4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java @@ -0,0 +1,445 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.cache.IndexType; +import net.runelite.cache.ObjectManager; +import net.runelite.cache.OverlayManager; +import net.runelite.cache.TextureManager; +import net.runelite.cache.UnderlayManager; +import net.runelite.cache.definitions.LocationsDefinition; +import net.runelite.cache.definitions.MapDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.definitions.OverlayDefinition; +import net.runelite.cache.definitions.TextureDefinition; +import net.runelite.cache.definitions.UnderlayDefinition; +import net.runelite.cache.ConfigType; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.FramemapDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.SequenceDefinition; +import net.runelite.cache.definitions.loaders.FrameLoader; +import net.runelite.cache.definitions.loaders.FramemapLoader; +import net.runelite.cache.definitions.loaders.LocationsLoader; +import net.runelite.cache.definitions.loaders.MapLoader; +import net.runelite.cache.definitions.loaders.ModelLoader; +import net.runelite.cache.definitions.loaders.SequenceLoader; +import net.runelite.cache.fs.Archive; +import net.runelite.cache.fs.ArchiveFiles; +import net.runelite.cache.fs.Index; +import net.runelite.cache.fs.Storage; +import net.runelite.cache.fs.Store; +import net.runelite.cache.region.Location; +import net.runelite.cache.region.Region; +import net.runelite.cache.util.Djb2; + +@Slf4j +public class Definitions implements Closeable { + private final Store store; + private final Index maps; + private final boolean mapsAreNamed; + private final Index models; + private final Index frameArchives; + private final Index framemapArchives; + + private final Map modelData; + + private final Map sequences = new HashMap<>(); + private final Map frameFiles; + private final Map framemaps; + private final Map frames; + + private final UnderlayManager underlays; + private final OverlayManager overlays; + private final ObjectManager objects; + private final TextureManager textures; + + private java.util.Set mapArchiveNames; + private final Map regions; + + public Definitions(Path cacheDirectory) throws IOException { + this(cacheDirectory, false); + } + + public Definitions(Path cacheDirectory, boolean limitPreviewCaches) throws IOException { + frameFiles = limitPreviewCaches ? limitedCache(64) : new HashMap<>(); + framemaps = limitPreviewCaches ? limitedCache(256) : new HashMap<>(); + frames = limitPreviewCaches ? limitedCache(512) : new HashMap<>(); + modelData = limitPreviewCaches ? limitedCache(1024) : new HashMap<>(); + regions = limitPreviewCaches ? limitedCache(128) : new HashMap<>(); + store = new Store(cacheDirectory.toFile()); + store.load(); + + maps = store.getIndex(IndexType.MAPS); + mapsAreNamed = maps.findArchiveByName("m50_50") != null; + models = store.getIndex(IndexType.MODELS); + frameArchives = store.getIndex(IndexType.ANIMATIONS); + framemapArchives = store.getIndex(IndexType.SKELETONS); + + underlays = new UnderlayManager(store); + underlays.load(); + overlays = new OverlayManager(store); + overlays.load(); + objects = new ObjectManager(store); + objects.load(); + textures = new TextureManager(store); + textures.load(); + + loadSequences(); + } + + public void clearPreviewCaches() { + regions.clear(); + modelData.clear(); + frameFiles.clear(); + framemaps.clear(); + frames.clear(); + } + + private static Map limitedCache(int capacity) { + return new java.util.LinkedHashMap(16, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > capacity; + } + }; + } + + private void loadSequences() throws IOException { + Archive archive = store.getIndex(IndexType.CONFIGS).getArchive(ConfigType.SEQUENCE.getId()); + if (archive == null) + return; + + ArchiveFiles files = archive.getFiles(store.getStorage().loadArchive(archive)); + SequenceLoader loader = new SequenceLoader().configureForRevision(archive.getRevision()); + for (var file : files.getFiles()) { + try { + sequences.put(file.getFileId(), loader.load(file.getFileId(), file.getContents())); + } catch (Exception ex) { + log.debug("Ignoring animation {}, which would not decode", file.getFileId(), ex); + } + } + } + + @Nullable + public SequenceDefinition sequence(int id) { + return sequences.get(id); + } + + @Nullable + public FrameDefinition frame(int packedFrameId) { + FrameDefinition cached = frames.get(packedFrameId); + if (cached != null || frames.containsKey(packedFrameId)) + return cached; + + FrameDefinition frame = null; + try { + frame = loadFrame(packedFrameId); + } catch (Exception ex) { + log.debug("Ignoring frame {}, which would not decode", packedFrameId, ex); + } + frames.put(packedFrameId, frame); + return frame; + } + + @Nullable + private FrameDefinition loadFrame(int packedFrameId) throws IOException { + int archiveId = packedFrameId >> 16; + int fileId = packedFrameId & 0xFFFF; + + ArchiveFiles files = frameFiles.get(archiveId); + if (files == null) { + if (frameFiles.containsKey(archiveId)) + return null; + + Archive archive = frameArchives.getArchive(archiveId); + files = archive == null + ? null + : archive.getFiles(store.getStorage().loadArchive(archive)); + frameFiles.put(archiveId, files); + if (files == null) + return null; + } + + var file = files.findFile(fileId); + if (file == null) + return null; + + byte[] data = file.getContents(); + if (data == null || data.length < 2) + return null; + + int framemapId = ((data[0] & 0xFF) << 8) | (data[1] & 0xFF); + FramemapDefinition framemap = framemap(framemapId); + if (framemap == null) + return null; + + FrameDefinition frame = new FrameLoader().load(framemap, fileId, data); + if (frame != null) { + frame.id = packedFrameId; + } + return frame; + } + + @Nullable + private FramemapDefinition framemap(int id) throws IOException { + FramemapDefinition cached = framemaps.get(id); + if (cached != null || framemaps.containsKey(id)) + return cached; + + FramemapDefinition framemap = null; + Archive archive = framemapArchives.getArchive(id); + if (archive != null) { + byte[] data = archive.decompress(store.getStorage().loadArchive(archive)); + if (data != null) + framemap = new FramemapLoader().load(id, data); + } + framemaps.put(id, framemap); + return framemap; + } + + public static Path findDefaultCache() throws IOException { + Path home = Paths.get(System.getProperty("user.home")); + Path[] candidates = { + home.resolve(".runelite").resolve("jagexcache").resolve("oldschool").resolve("LIVE"), + home.resolve("jagexcache").resolve("oldschool").resolve("LIVE") + }; + for (Path candidate : candidates) + if (Files.isRegularFile(candidate.resolve("main_file_cache.dat2"))) + return candidate; + throw new IOException("No OSRS cache found in " + home.resolve("jagexcache") + " or " + home.resolve(".runelite")); + } + + @Nullable + public Region region(int regionX, int regionY) { + int id = (regionX << 8) | regionY; + Region cached = regions.get(id); + if (cached != null) + return cached; + if (regions.containsKey(id)) + return null; + + Region region; + try { + region = load(regionX, regionY); + } catch (Exception ex) { + log.debug("Ignoring map square {},{}, which would not decode", regionX, regionY, ex); + region = null; + } + regions.put(id, region); + return region; + } + + @Nullable + private Region load(int regionX, int regionY) throws IOException { + byte[] terrain = archive("m" + regionX + "_" + regionY, (regionX << 8) | regionY, 0); + if (terrain == null) + return null; + + MapDefinition map = new MapLoader().load(regionX, regionY, terrain); + Region region = new Region(regionX, regionY); + region.loadTerrain(map); + + byte[] locations = archive("l" + regionX + "_" + regionY, (regionX << 8) | regionY, 1); + if (locations != null) { + LocationsDefinition locs = new LocationsLoader().load(regionX, regionY, locations); + region.loadLocations(locs); + } + + return region; + } + + @Nullable + private byte[] archive(String name, int regionId, int fileId) throws IOException { + Storage storage = store.getStorage(); + + if (mapsAreNamed) { + Archive named = maps.findArchiveByName(name); + return named == null ? null : named.decompress(storage.loadArchive(named)); + } + + Archive archive = maps.getArchive(regionId); + if (archive == null) + return null; + + var file = archive.getFiles(storage.loadArchive(archive)).findFile(fileId); + return file == null ? null : file.getContents(); + } + + private boolean hasMapArchive(String name, int regionId) { + if (!mapsAreNamed) + return maps.getArchive(regionId) != null; + if (mapArchiveNames == null) { + mapArchiveNames = new java.util.HashSet<>(); + for (Archive archive : maps.getArchives()) + mapArchiveNames.add(archive.getNameHash()); + } + return mapArchiveNames.contains(Djb2.hash(name)); + } + + public net.runelite.cache.region.Position findWaterPlacement( + String name, rs117.hd.scene.TileOverrideManager overrides, + rs117.hd.scene.ProceduralGenerator terrain, java.util.function.BooleanSupplier active + ) { + var priority = new java.util.LinkedHashSet(); + var rules = rs117.hd.scene.TileOverrideManager.OVERRIDES; + if (rules != null) { + for (var rule : rules) { + if (rule.waterType == null || !name.equals(rule.waterType.name) || rule.area == null || rule.area.aabbs == null) + continue; + for (var box : rule.area.aabbs) { + int minX = Math.max(0, box.minX >> 6), maxX = Math.min(255, box.maxX >> 6); + int minY = Math.max(0, box.minY >> 6), maxY = Math.min(255, box.maxY >> 6); + if ((long) (maxX - minX + 1) * (maxY - minY + 1) > 1024) + continue; + for (int x = minX; x <= maxX; x++) + for (int y = minY; y <= maxY; y++) + priority.add(x << 8 | y); + } + } + } + var regionsToSearch = java.util.stream.IntStream.concat(priority.stream().mapToInt(Integer::intValue), + java.util.stream.IntStream.range(0, 65536).filter(id -> !priority.contains(id))).iterator(); + while (regionsToSearch.hasNext() && active.getAsBoolean() && !Thread.currentThread().isInterrupted()) { + int id = regionsToSearch.nextInt(); + int x = id >> 8, y = id & 255; + String archiveName = "m" + x + "_" + y; + if (!hasMapArchive(archiveName, id)) + continue; + try { + byte[] data = archive(archiveName, id, 0); + if (data == null) + continue; + var region = new Region(x, y); + region.loadTerrain(new MapLoader().load(x, y, data)); + var position = findWaterTile(name, overrides, terrain, region, active); + if (position != null) + return position; + } catch (IOException | RuntimeException ex) { + log.trace("Could not inspect water in region {}", id, ex); + } + } + return null; + } + + private net.runelite.cache.region.Position findWaterTile( + String name, rs117.hd.scene.TileOverrideManager overrides, rs117.hd.scene.ProceduralGenerator terrain, + Region region, java.util.function.BooleanSupplier active + ) { + int[] position = new int[3]; + int[] ids = new int[2]; + for (int plane = 0; plane < 4 && active.getAsBoolean(); plane++) { + position[2] = plane; + for (int x = 0; x < 64; x++) { + position[0] = region.getBaseX() + x; + for (int y = 0; y < 64; y++) { + position[1] = region.getBaseY() + y; + int overlayId = region.getOverlayId(plane, x, y); + int underlayId = region.getUnderlayId(plane, x, y); + if (overlayId == 0 && underlayId == 0) + continue; + ids[0] = rs117.hd.scene.tile_overrides.TileOverride.OVERLAY_FLAG | overlayId; + ids[1] = underlayId; + var overlay = overlay(overlayId - 1); + var rule = overrides.getOverrideBeforeReplacements(position, ids); + var water = terrain.seasonalWaterType(rule, overlay == null ? -1 : overlay.getTexture()); + if (water != null && name.equals(water.name)) + return new net.runelite.cache.region.Position(position[0], position[1], plane); + } + } + } + return null; + } + + /** Searches decoded map locations without retaining terrain for every region. */ + @Nullable + public Location findObjectPlacement(int objectId, java.util.function.BooleanSupplier active) { + + for (int regionId = 0; regionId < 65536 && active.getAsBoolean() && !Thread.currentThread().isInterrupted(); regionId++) { + int x = regionId >> 8, y = regionId & 255; + String name = "l" + x + "_" + y; + if (!hasMapArchive(name, regionId)) + continue; + try { + byte[] data = archive(name, regionId, 1); + if (data == null) + continue; + for (var location : new LocationsLoader().load(x, y, data).getLocations()) + if (location.getId() == objectId) { + var pos = location.getPosition(); + return new Location(objectId, location.getType(), location.getOrientation(), + new net.runelite.cache.region.Position((x << 6) + pos.getX(), (y << 6) + pos.getY(), pos.getZ())); + } + } catch (IOException | RuntimeException ex) { + log.trace("Could not read object placements in region {}", regionId, ex); + } + } + return null; + } + + @Nullable + public ModelDefinition model(int id) throws IOException { + byte[] data = modelData.get(id); + if (data == null) { + if (modelData.containsKey(id)) + return null; + + Archive archive = models.getArchive(id); + data = archive == null ? null : archive.decompress(store.getStorage().loadArchive(archive)); + modelData.put(id, data); + if (data == null) + return null; + } + return new ModelLoader().load(id, data); + } + + @Nullable + public UnderlayDefinition underlay(int id) { + return underlays.provide(id); + } + + @Nullable + public OverlayDefinition overlay(int id) { + return overlays.provide(id); + } + + @Nullable + public java.util.Collection objects() { + return objects.getObjects(); + } + + public ObjectDefinition object(int id) { + return objects.getObject(id); + } + + @Nullable + public TextureDefinition texture(int id) { + return textures.findTexture(id); + } + + public List textures() { + return textures.getTextures(); + } + + public int textureColor(int id) { + TextureDefinition texture = texture(id); + return texture == null ? 0 : texture.missingColor; + } + + public Store getStore() { + return store; + } + + @Override + public void close() throws IOException { + store.close(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java new file mode 100644 index 0000000..419ebfd --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java @@ -0,0 +1,70 @@ +package rs117.hd.dev.sceneloader.scene; + +public final class HslPalette { + public static final double DEFAULT_BRIGHTNESS = 0.8; + + private static final int SIZE = 65536; + + private final int[] palette = new int[SIZE]; + + public HslPalette(double brightness) { + for (int hueSat = 0; hueSat < 512; hueSat++) { + double hue = (hueSat >> 3) / 64.0 + 0.0078125; + double saturation = (hueSat & 7) / 8.0 + 0.0625; + int index = hueSat * 128; + for (int luminance = 0; luminance < 128; luminance++) { + double lightness = luminance / 128.0; + double r = lightness; + double g = lightness; + double b = lightness; + if (saturation != 0) { + double high; + if (lightness < 0.5) { + high = lightness * (saturation + 1.0); + } else { + high = saturation + lightness - saturation * lightness; + } + double low = lightness * 2.0 - high; + + double redHue = hue + 1.0 / 3.0; + if (redHue > 1.0) + redHue--; + double blueHue = hue - 1.0 / 3.0; + if (blueHue < 0.0) + blueHue++; + + r = hueToChannel(redHue, high, low, lightness); + g = hueToChannel(hue, high, low, lightness); + b = hueToChannel(blueHue, high, low, lightness); + } + + int rgb = ((int) (r * 256.0) << 16) + ((int) (g * 256.0) << 8) + (int) (b * 256.0); + int adjusted = applyBrightness(rgb, brightness); + palette[index++] = adjusted == 0 ? 1 : adjusted; + } + } + } + + private static double hueToChannel(double hue, double high, double low, double fallback) { + if (hue * 6.0 < 1.0) + return (high - low) * 6.0 * hue + low; + if (hue * 2.0 < 1.0) + return high; + if (hue * 3.0 < 2.0) + return (high - low) * (2.0 / 3.0 - hue) * 6.0 + low; + return low; + } + + private static int applyBrightness(int rgb, double brightness) { + double r = Math.pow((rgb >> 16) / 256.0, brightness); + double g = Math.pow((rgb >> 8 & 0xFF) / 256.0, brightness); + double b = Math.pow((rgb & 0xFF) / 256.0, brightness); + return ((int) (r * 256.0) << 16) + ((int) (g * 256.0) << 8) + (int) (b * 256.0); + } + + public int toRgb(int packedHsl) { + if (packedHsl == -2) + return 0; + return palette[packedHsl & 0xFFFF]; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java new file mode 100644 index 0000000..a122095 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java @@ -0,0 +1,45 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.cache.definitions.ModelDefinition; + +final class ModelBounds { + final int minX, maxX; + final int minZ, maxZ; + final int maxY, modelHeight; + + private ModelBounds(int minX, int maxX, int minZ, int maxZ, int maxY, int modelHeight) { + this.minX = minX; + this.maxX = maxX; + this.minZ = minZ; + this.maxZ = maxZ; + this.maxY = maxY; + this.modelHeight = modelHeight; + } + + static ModelBounds of(ModelDefinition def) { + int minX = 999999, maxX = -999999; + int minZ = 99999, maxZ = -99999; + int maxY = 0, modelHeight = 0; + + for (int i = 0; i < def.vertexCount; i++) { + int x = def.vertexX[i]; + int y = def.vertexY[i]; + int z = def.vertexZ[i]; + + if (x < minX) + minX = x; + if (x > maxX) + maxX = x; + if (z < minZ) + minZ = z; + if (z > maxZ) + maxZ = z; + if (-y > modelHeight) + modelHeight = -y; + if (y > maxY) + maxY = y; + } + + return new ModelBounds(minX, maxX, minZ, maxZ, maxY, modelHeight); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java new file mode 100644 index 0000000..4b83068 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java @@ -0,0 +1,874 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import java.util.HashSet; +import java.util.Set; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.models.CircularAngle; +import net.runelite.cache.models.FaceNormal; +import net.runelite.cache.models.VertexNormal; + +public class ModelFactory { + private static final int LIGHT_X = -50; + private static final int LIGHT_Y = -10; + private static final int LIGHT_Z = -50; + private static final int AMBIENT_BASE = 64; + private static final int CONTRAST_BASE = 768; + + static final int LOC_OBJECT = 10; + private static final int DIAGONAL_ANGLE = 256; + private static final int DIAGONAL_OFFSET = 45; + private static final int TILE_SIZE = 128; + + private final Definitions defs; + + private final Map litModels = new HashMap<>(); + + public ModelFactory(Definitions defs) { + this.defs = defs; + } + + @Nullable + public BuiltModel model(ObjectDefinition object, int type, int rotation) throws IOException { + return model(object, type, rotation, null); + } + + @Nullable + public BuiltModel model(ObjectDefinition object, int type, int rotation, @Nullable FrameDefinition frame) + throws IOException { + long shape = object.getObjectTypes() == null + ? ((long) object.getId() << 10) + rotation + : ((long) object.getId() << 10) + ((long) type << 3) + rotation; + long key = shape << 33 | (frame == null ? 0 : (frame.id & 0xFFFFFFFFL) + 1); + + if (litModels.containsKey(key)) + return litModels.get(key); + + ModelDefinition built = build(object, type, rotation); + BuiltModel lit = null; + if (built != null) { + lit = light(built, object.getAmbient() + AMBIENT_BASE, object.getContrast() + CONTRAST_BASE); + if (frame != null) + lit = pose(lit, built, frame, rotation); + } + litModels.put(key, lit); + return lit; + } + + /** + * Moves a model into one of its animation's frames. + * + *

The frame is applied with the model turned back to the way it was built, and turned round again + * afterwards. An animation's transforms are written in the model's own directions, so applying them to + * a model that has already been turned to face the way the map wants turns the animation with it: a + * wheel put down facing the other way then turns the other way, which is the one thing about it anyone + * would notice. The client does the same thing either side of the frame for the same reason. + * + * @param rotation the rotation the map asked for, which the model has already been turned by + */ + private BuiltModel pose(BuiltModel lit, ModelDefinition def, FrameDefinition frame, int rotation) { + turnBack(def, rotation & 3); + applyFrame(def, frame); + turnForward(def, rotation & 3); + + return lit.withPose( + toFloats(def.vertexX, def.vertexCount), + toFloats(def.vertexY, def.vertexCount), + toFloats(def.vertexZ, def.vertexCount), + def.faceTransparencies + ); + } + + private static final int FADE_FACES = 5; + + private static final int SET_PIVOT = 0; + private static final int MOVE = 1; + private static final int TURN = 2; + private static final int SCALE = 3; + + private static final int[] SINE = new int[2048]; + private static final int[] COSINE = new int[2048]; + + static { + for (int i = 0; i < 2048; i++) { + SINE[i] = (int) (Math.sin(i * 0.0030679615) * 65536); + COSINE[i] = (int) (Math.cos(i * 0.0030679615) * 65536); + } + } + + /** Undoes the turn the map asked for, so an animation is applied the way it was written */ + private static void turnBack(ModelDefinition def, int rotation) { + switch (rotation) { + case 1: + def.rotate3(); + break; + case 2: + def.rotate2(); + break; + case 3: + def.rotate1(); + break; + default: + break; + } + } + + /** Puts it back the way the map wanted it */ + private static void turnForward(ModelDefinition def, int rotation) { + switch (rotation) { + case 1: + def.rotate1(); + break; + case 2: + def.rotate2(); + break; + case 3: + def.rotate3(); + break; + default: + break; + } + } + + /** + * Moves a model into a frame of an animation, if it is a model that can be animated at all. + * + *

Having groups of vertices to move is what makes a model animatable, and a model without them is + * left alone entirely, fades included. That is the game's own rule and not an optimisation standing in + * for one: {@code Model.method5839} does nothing at all unless the model has vertex groups, so a model + * carrying nothing but groups of faces to fade never fades. It reads like an oversight on their part and + * there is cache data written as though it fades, but what is on screen is what the game draws, and the + * game draws those faces at the colour they were built with. Fading them here instead takes away faces + * that are supposed to be there — for the altar ruins, the whole of the mist standing in the arch. + */ + public static void applyFrame(ModelDefinition def, FrameDefinition frame) { + def.computeAnimationTables(); + int[][] vertexGroups = def.getVertexGroups(); + if (vertexGroups == null) + return; + + int[][] faceGroups = null; + int pivotX = 0, pivotY = 0, pivotZ = 0; + + var framemap = frame.framemap; + for (int i = 0; i < frame.translatorCount; i++) { + int index = frame.indexFrameIds[i]; + if (index < 0 || index >= framemap.types.length) + continue; + + int type = framemap.types[index]; + int[] groups = framemap.frameMaps[index]; + int dx = frame.translator_x[i]; + int dy = frame.translator_y[i]; + int dz = frame.translator_z[i]; + + if (type == FADE_FACES) { + if (faceGroups == null) + faceGroups = faceGroups(def); + fadeFaces(def, faceGroups, groups, dx); + continue; + } + + switch (type) { + case SET_PIVOT: { + long sumX = 0, sumY = 0, sumZ = 0; + int counted = 0; + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + sumX += def.vertexX[vertex]; + sumY += def.vertexY[vertex]; + sumZ += def.vertexZ[vertex]; + counted++; + } + } + if (counted > 0) { + pivotX = (int) (sumX / counted) + dx; + pivotY = (int) (sumY / counted) + dy; + pivotZ = (int) (sumZ / counted) + dz; + } else { + pivotX = dx; + pivotY = dy; + pivotZ = dz; + } + break; + } + + case MOVE: + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + def.vertexX[vertex] += dx; + def.vertexY[vertex] += dy; + def.vertexZ[vertex] += dz; + } + } + break; + + case TURN: { + int aroundX = (dx & 0xFF) * 8; + int aroundY = (dy & 0xFF) * 8; + int aroundZ = (dz & 0xFF) * 8; + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + int x = def.vertexX[vertex] - pivotX; + int y = def.vertexY[vertex] - pivotY; + int z = def.vertexZ[vertex] - pivotZ; + + if (aroundZ != 0) { + int sin = SINE[aroundZ], cos = COSINE[aroundZ]; + int turned = x * cos + y * sin >> 16; + y = y * cos - x * sin >> 16; + x = turned; + } + if (aroundX != 0) { + int sin = SINE[aroundX], cos = COSINE[aroundX]; + int turned = y * cos - z * sin >> 16; + z = z * cos + y * sin >> 16; + y = turned; + } + if (aroundY != 0) { + int sin = SINE[aroundY], cos = COSINE[aroundY]; + int turned = z * sin + x * cos >> 16; + z = z * cos - x * sin >> 16; + x = turned; + } + + def.vertexX[vertex] = x + pivotX; + def.vertexY[vertex] = y + pivotY; + def.vertexZ[vertex] = z + pivotZ; + } + } + break; + } + + case SCALE: + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + def.vertexX[vertex] = (def.vertexX[vertex] - pivotX) * dx / 128 + pivotX; + def.vertexY[vertex] = (def.vertexY[vertex] - pivotY) * dy / 128 + pivotY; + def.vertexZ[vertex] = (def.vertexZ[vertex] - pivotZ) * dz / 128 + pivotZ; + } + } + break; + + default: + break; + } + } + } + + @Nullable + private static int[][] faceGroups(ModelDefinition def) { + int[] packed = def.packedTransparencyVertexGroups; + if (packed == null) + return null; + + if (def.faceTransparencies == null) { + def.faceTransparencies = new byte[def.faceCount]; + } + + int faces = Math.min(def.faceCount, packed.length); + int highest = 0; + int[] counts = new int[256]; + for (int face = 0; face < faces; face++) { + int group = packed[face] & 0xFF; + counts[group]++; + if (group > highest) + highest = group; + } + + var groups = new int[highest + 1][]; + for (int group = 0; group <= highest; group++) { + groups[group] = new int[counts[group]]; + counts[group] = 0; + } + for (int face = 0; face < faces; face++) { + int group = packed[face] & 0xFF; + groups[group][counts[group]++] = face; + } + return groups; + } + + private static void fadeFaces(ModelDefinition def, @Nullable int[][] faceGroups, int[] frameMap, int by) { + if (faceGroups == null) + return; + + for (int group : frameMap) { + if (group < 0 || group >= faceGroups.length) + continue; + for (int face : faceGroups[group]) { + int alpha = (def.faceTransparencies[face] & 0xFF) + by * 8; + def.faceTransparencies[face] = (byte) Math.max(0, Math.min(255, alpha)); + } + } + } + + @Nullable + public ModelDefinition unlitModel(ObjectDefinition object, int type, int rotation) throws IOException { + return build(object, type, rotation); + } + + @Nullable + private ModelDefinition build(ObjectDefinition object, int type, int rotation) throws IOException { + int[] modelIds = object.getObjectModels(); + int[] types = object.getObjectTypes(); + + ModelDefinition model; + if (types == null) { + if (type != LOC_OBJECT || modelIds == null || modelIds.length == 0) + return null; + + boolean mirrored = object.isRotated(); + if (modelIds.length == 1) { + model = defs.model(modelIds[0]); + if (model == null) + return null; + if (mirrored) + mirror(model); + } else { + var parts = new ModelDefinition[modelIds.length]; + for (int i = 0; i < modelIds.length; i++) { + parts[i] = defs.model(modelIds[i]); + if (parts[i] == null) + return null; + if (mirrored) + mirror(parts[i]); + } + model = merge(parts); + } + } else { + int index = -1; + for (int i = 0; i < types.length; i++) { + if (types[i] == type) { + index = i; + break; + } + } + if (index == -1 || modelIds == null || index >= modelIds.length) + return null; + + model = defs.model(modelIds[index]); + if (model == null) + return null; + if (object.isRotated() ^ rotation > 3) + mirror(model); + } + + if (type == 4 && rotation > 3) { + rotate(model, DIAGONAL_ANGLE); + model.move(DIAGONAL_OFFSET, 0, -DIAGONAL_OFFSET); + } + + switch (rotation & 3) { + case 1: + model.rotate1(); + break; + case 2: + model.rotate2(); + break; + case 3: + model.rotate3(); + break; + default: + break; + } + + if (object.getFullRecolor() != -1) { + for (int i = 0; i < model.faceCount; i++) + model.faceColors[i] = object.getFullRecolor(); + } else if (object.getRecolorToFind() != null) { + short[] find = object.getRecolorToFind(); + short[] replace = object.getRecolorToReplace(); + for (int i = 0; i < find.length; i++) + model.recolor(find[i], replace[i]); + } + + if (object.getRetextureToFind() != null) { + short[] find = object.getRetextureToFind(); + short[] replace = object.getTextureToReplace(); + for (int i = 0; i < find.length; i++) + model.retexture(find[i], replace[i]); + } + + if (object.getModelSizeX() != TILE_SIZE || object.getModelSizeHeight() != TILE_SIZE || object.getModelSizeY() != TILE_SIZE) + model.resize(object.getModelSizeX(), object.getModelSizeHeight(), object.getModelSizeY()); + + int offsetX = signed(object.getOffsetX()); + int offsetHeight = signed(object.getOffsetHeight()); + int offsetY = signed(object.getOffsetY()); + if (offsetX != 0 || offsetHeight != 0 || offsetY != 0) + model.move(offsetX, offsetHeight, offsetY); + + return model; + } + + private static int signed(int unsignedShort) { + return unsignedShort > Short.MAX_VALUE ? unsignedShort - 0x10000 : unsignedShort; + } + + private static void mirror(ModelDefinition model) { + for (int i = 0; i < model.vertexCount; i++) + model.vertexZ[i] = -model.vertexZ[i]; + for (int i = 0; i < model.faceCount; i++) { + int swap = model.faceIndices1[i]; + model.faceIndices1[i] = model.faceIndices3[i]; + model.faceIndices3[i] = swap; + } + model.vertexNormals = null; + model.faceNormals = null; + } + + private static void rotate(ModelDefinition model, int angle) { + int sin = CircularAngle.SINE[angle]; + int cos = CircularAngle.COSINE[angle]; + for (int i = 0; i < model.vertexCount; i++) { + int x = model.vertexX[i]; + int z = model.vertexZ[i]; + model.vertexX[i] = x * cos + z * sin >> 16; + model.vertexZ[i] = z * cos - x * sin >> 16; + } + model.vertexNormals = null; + model.faceNormals = null; + } + + public static ModelDefinition merge(ModelDefinition[] parts) { + var merged = new ModelDefinition(); + + int vertexTotal = 0, faceTotal = 0, textureFaceTotal = 0; + boolean anyRenderTypes = false, anyPriorities = false, anyTransparencies = false; + boolean anyFaceGroups = false, anyTextures = false, anyTextureCoords = false, anyZOffsets = false; + int sharedPriority = -1; + + for (ModelDefinition part : parts) { + if (part == null) + continue; + vertexTotal += part.vertexCount; + faceTotal += part.faceCount; + textureFaceTotal += part.numTextureFaces; + + if (part.faceRenderPriorities != null) { + anyPriorities = true; + } else { + if (sharedPriority == -1) + sharedPriority = part.priority; + if (sharedPriority != part.priority) + anyPriorities = true; + } + + anyRenderTypes |= part.faceRenderTypes != null; + anyTransparencies |= part.faceTransparencies != null; + anyFaceGroups |= part.packedTransparencyVertexGroups != null; + anyTextures |= part.faceTextures != null; + anyTextureCoords |= part.textureCoords != null; + anyZOffsets |= part.faceZOffsets != null; + } + + merged.vertexX = new int[vertexTotal]; + merged.vertexY = new int[vertexTotal]; + merged.vertexZ = new int[vertexTotal]; + merged.packedVertexGroups = new int[vertexTotal]; + merged.faceIndices1 = new int[faceTotal]; + merged.faceIndices2 = new int[faceTotal]; + merged.faceIndices3 = new int[faceTotal]; + merged.faceColors = new short[faceTotal]; + merged.priority = (byte) (sharedPriority == -1 ? 0 : sharedPriority); + + if (anyRenderTypes) + merged.faceRenderTypes = new byte[faceTotal]; + if (anyPriorities) + merged.faceRenderPriorities = new byte[faceTotal]; + if (anyTransparencies) + merged.faceTransparencies = new byte[faceTotal]; + if (anyFaceGroups) + merged.packedTransparencyVertexGroups = new int[faceTotal]; + if (anyTextures) + merged.faceTextures = new short[faceTotal]; + if (anyTextureCoords) + merged.textureCoords = new byte[faceTotal]; + if (anyZOffsets) + merged.faceZOffsets = new byte[faceTotal]; + + if (textureFaceTotal > 0) { + merged.textureRenderTypes = new byte[textureFaceTotal]; + merged.texIndices1 = new short[textureFaceTotal]; + merged.texIndices2 = new short[textureFaceTotal]; + merged.texIndices3 = new short[textureFaceTotal]; + } + + merged.vertexCount = 0; + merged.faceCount = 0; + merged.numTextureFaces = 0; + + for (ModelDefinition part : parts) { + if (part == null) + continue; + + int[] partGroups = groupOfVertex(part); + + for (int face = 0; face < part.faceCount; face++) { + int at = merged.faceCount; + + if (anyRenderTypes && part.faceRenderTypes != null) + merged.faceRenderTypes[at] = part.faceRenderTypes[face]; + if (anyPriorities) + merged.faceRenderPriorities[at] = part.faceRenderPriorities != null + ? part.faceRenderPriorities[face] + : part.priority; + if (anyTransparencies && part.faceTransparencies != null) + merged.faceTransparencies[at] = part.faceTransparencies[face]; + if (anyFaceGroups && part.packedTransparencyVertexGroups != null) + merged.packedTransparencyVertexGroups[at] = part.packedTransparencyVertexGroups[face]; + if (anyTextures) + merged.faceTextures[at] = part.faceTextures != null ? part.faceTextures[face] : -1; + if (anyTextureCoords) + merged.textureCoords[at] = part.textureCoords != null && part.textureCoords[face] != -1 + ? (byte) (part.textureCoords[face] + merged.numTextureFaces) + : -1; + if (anyZOffsets && part.faceZOffsets != null) + merged.faceZOffsets[at] = part.faceZOffsets[face]; + + merged.faceColors[at] = part.faceColors[face]; + merged.faceIndices1[at] = shareVertex(merged, part, partGroups, part.faceIndices1[face]); + merged.faceIndices2[at] = shareVertex(merged, part, partGroups, part.faceIndices2[face]); + merged.faceIndices3[at] = shareVertex(merged, part, partGroups, part.faceIndices3[face]); + merged.faceCount++; + } + + for (int triangle = 0; triangle < part.numTextureFaces; triangle++) { + int at = merged.numTextureFaces; + byte renderType = merged.textureRenderTypes[at] = part.textureRenderTypes[triangle]; + if (renderType == 0) { + merged.texIndices1[at] = (short) shareVertex(merged, part, partGroups, part.texIndices1[triangle]); + merged.texIndices2[at] = (short) shareVertex(merged, part, partGroups, part.texIndices2[triangle]); + merged.texIndices3[at] = (short) shareVertex(merged, part, partGroups, part.texIndices3[triangle]); + } + merged.numTextureFaces++; + } + } + + return merged; + } + + private static int shareVertex( + ModelDefinition merged, ModelDefinition part, @Nullable int[] partGroups, int vertex + ) { + int x = part.vertexX[vertex]; + int y = part.vertexY[vertex]; + int z = part.vertexZ[vertex]; + + for (int i = 0; i < merged.vertexCount; i++) + if (merged.vertexX[i] == x && merged.vertexY[i] == y && merged.vertexZ[i] == z) + return i; + + merged.vertexX[merged.vertexCount] = x; + merged.vertexY[merged.vertexCount] = y; + merged.vertexZ[merged.vertexCount] = z; + if (partGroups != null && vertex < partGroups.length) + merged.packedVertexGroups[merged.vertexCount] = partGroups[vertex]; + return merged.vertexCount++; + } + + @Nullable + private static int[] groupOfVertex(ModelDefinition part) { + if (part.packedVertexGroups != null) + return part.packedVertexGroups; + + int[][] groups = part.getVertexGroups(); + if (groups == null) + return null; + + var byVertex = new int[part.vertexCount]; + for (int group = 0; group < groups.length; group++) { + if (groups[group] == null) + continue; + for (int vertex : groups[group]) + if (vertex >= 0 && vertex < byVertex.length) + byVertex[vertex] = group; + } + return byVertex; + } + + public static BuiltModel light(ModelDefinition def, int ambient, int contrast) { + return light(def, ambient, contrast, null); + } + + public static BuiltModel light(ModelDefinition def, int ambient, int contrast, @Nullable VertexNormal[] mergedNormals) { + def.computeNormals(); + + int lightLength = (int) Math.sqrt((double) LIGHT_Z * LIGHT_Z + (double) LIGHT_X * LIGHT_X + (double) LIGHT_Y * LIGHT_Y); + int scaledContrast = lightLength * contrast >> 8; + + var model = new BuiltModel(); + model.faceColors1 = new int[def.faceCount]; + model.faceColors2 = new int[def.faceCount]; + model.faceColors3 = new int[def.faceCount]; + + if (def.numTextureFaces > 0 && def.textureCoords != null) + buildTextureTriangles(def, model); + + for (int face = 0; face < def.faceCount; face++) { + int renderType = def.faceRenderTypes == null ? 0 : def.faceRenderTypes[face]; + int alpha = def.faceTransparencies == null ? 0 : def.faceTransparencies[face]; + int texture = def.faceTextures == null ? -1 : def.faceTextures[face]; + + if (alpha == -2) + renderType = 3; + if (alpha == -1) + renderType = 2; + + if (texture == -1) { + if (renderType == 0) { + int color = def.faceColors[face] & 0xFFFF; + model.faceColors1[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices1[face], scaledContrast, ambient)); + model.faceColors2[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices2[face], scaledContrast, ambient)); + model.faceColors3[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices3[face], scaledContrast, ambient)); + } else if (renderType == 1) { + model.faceColors1[face] = shade(def.faceColors[face] & 0xFFFF, faceLight(def, face, scaledContrast, ambient)); + model.faceColors3[face] = -1; + } else if (renderType == 3) { + model.faceColors1[face] = 128; + model.faceColors3[face] = -1; + } else { + model.faceColors3[face] = -2; + } + } else if (renderType == 0) { + model.faceColors1[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices1[face], scaledContrast, ambient)); + model.faceColors2[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices2[face], scaledContrast, ambient)); + model.faceColors3[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices3[face], scaledContrast, ambient)); + } else if (renderType == 1) { + model.faceColors1[face] = clamp(faceLight(def, face, scaledContrast, ambient)); + model.faceColors3[face] = -1; + } else { + model.faceColors3[face] = -2; + } + } + + model.verticesCount = def.vertexCount; + model.verticesX = toFloats(def.vertexX, def.vertexCount); + model.verticesY = toFloats(def.vertexY, def.vertexCount); + model.verticesZ = toFloats(def.vertexZ, def.vertexCount); + + model.faceCount = def.faceCount; + model.faceIndices1 = def.faceIndices1; + model.faceIndices2 = def.faceIndices2; + model.faceIndices3 = def.faceIndices3; + + model.faceRenderPriorities = def.faceRenderPriorities; + model.faceTransparencies = def.faceTransparencies; + model.faceTextures = def.faceTextures; + model.faceBias = def.faceZOffsets; + model.unlitFaceColors = def.faceColors; + + storeVertexNormals(def, mergedNormals, model); + + return model; + } + + private static void buildTextureTriangles(ModelDefinition def, BuiltModel model) { + int[] remapped = new int[def.numTextureFaces]; + + for (int face = 0; face < def.faceCount; face++) + if (def.textureCoords[face] != -1) + remapped[def.textureCoords[face] & 0xFF]++; + + int kept = 0; + for (int i = 0; i < def.numTextureFaces; i++) + if (remapped[i] > 0 && def.textureRenderTypes[i] == 0) + kept++; + + model.texIndices1 = new int[kept]; + model.texIndices2 = new int[kept]; + model.texIndices3 = new int[kept]; + + int at = 0; + for (int i = 0; i < def.numTextureFaces; i++) { + if (remapped[i] > 0 && def.textureRenderTypes[i] == 0) { + model.texIndices1[at] = def.texIndices1[i] & 0xFFFF; + model.texIndices2[at] = def.texIndices2[i] & 0xFFFF; + model.texIndices3[at] = def.texIndices3[i] & 0xFFFF; + remapped[i] = at++; + } else { + remapped[i] = -1; + } + } + + model.textureFaces = new byte[def.faceCount]; + for (int face = 0; face < def.faceCount; face++) + model.textureFaces[face] = def.textureCoords[face] != -1 + ? (byte) remapped[def.textureCoords[face] & 0xFF] + : -1; + } + + private static void storeVertexNormals(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, BuiltModel model) { + if (def.vertexNormals == null) + return; + + model.vertexNormalsX = new int[def.vertexCount]; + model.vertexNormalsY = new int[def.vertexCount]; + model.vertexNormalsZ = new int[def.vertexCount]; + for (int i = 0; i < def.vertexCount; i++) { + VertexNormal normal = normalAt(def, mergedNormals, i); + if (normal == null) + continue; + model.vertexNormalsX[i] = normal.x; + model.vertexNormalsY[i] = normal.y; + model.vertexNormalsZ[i] = normal.z; + } + } + + @Nullable + static VertexNormal normalAt(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, int vertex) { + if (mergedNormals != null && mergedNormals[vertex] != null) + return mergedNormals[vertex]; + return def.vertexNormals[vertex]; + } + + private static int vertexLight(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, int vertex, int scaledContrast, int ambient) { + VertexNormal normal = normalAt(def, mergedNormals, vertex); + int divisor = scaledContrast * normal.magnitude; + if (divisor == 0) + return ambient; + return (LIGHT_Y * normal.y + LIGHT_Z * normal.z + LIGHT_X * normal.x) / divisor + ambient; + } + + private static int faceLight(ModelDefinition def, int face, int scaledContrast, int ambient) { + FaceNormal normal = def.faceNormals[face]; + int divisor = scaledContrast / 2 + scaledContrast; + if (divisor == 0) + return ambient; + return (LIGHT_Y * normal.y + LIGHT_Z * normal.z + LIGHT_X * normal.x) / divisor + ambient; + } + + private static int shade(int color, int light) { + return (color & 0xFF80) + clamp((color & 0x7F) * light >> 7); + } + + private static int clamp(int light) { + if (light < 2) + return 2; + return Math.min(light, 126); + } + + private static float[] toFloats(int[] values, int count) { + float[] floats = new float[count]; + for (int i = 0; i < count; i++) + floats[i] = values[i]; + return floats; + } + + public static void contourDefinition( + ModelDefinition def, int[][] heights, int localX, int baseHeight, int localY, int contouredGround + ) { + ModelBounds bounds = ModelBounds.of(def); + + int minX = bounds.minX + localX; + int maxX = bounds.maxX + localX; + int minZ = bounds.minZ + localY; + int maxZ = bounds.maxZ + localY; + + if (minX < 0 || (maxX + TILE_SIZE >> 7) >= heights.length || minZ < 0 || (maxZ + TILE_SIZE >> 7) >= heights[0].length) + return; + + int westTile = minX >> 7; + int eastTile = maxX + TILE_SIZE - 1 >> 7; + int southTile = minZ >> 7; + int northTile = maxZ + TILE_SIZE - 1 >> 7; + + if (heights[westTile][southTile] == baseHeight + && heights[eastTile][southTile] == baseHeight + && heights[westTile][northTile] == baseHeight + && heights[eastTile][northTile] == baseHeight) + return; + + for (int i = 0; i < def.vertexCount; i++) { + int vertexY = def.vertexY[i]; + int ground = groundAt(def.vertexX[i] + localX, def.vertexZ[i] + localY, heights); + + if (contouredGround > 0) { + int up = (-vertexY << 16) / Math.max(1, bounds.modelHeight); + if (up >= contouredGround) + continue; + def.vertexY[i] = (contouredGround - up) * (ground - baseHeight) / contouredGround + vertexY; + } else { + def.vertexY[i] = vertexY + ground - baseHeight; + } + } + + def.vertexNormals = null; + def.faceNormals = null; + } + + static int groundAt(int x, int z, int[][] heights) { + int fracX = x & TILE_SIZE - 1; + int fracZ = z & TILE_SIZE - 1; + int tileX = x >> 7; + int tileZ = z >> 7; + + int south = (TILE_SIZE - fracX) * heights[tileX][tileZ] + heights[tileX + 1][tileZ] * fracX >> 7; + int north = (TILE_SIZE - fracX) * heights[tileX][tileZ + 1] + heights[tileX + 1][tileZ + 1] * fracX >> 7; + return (TILE_SIZE - fracZ) * south + fracZ * north >> 7; + } + + public static BuiltModel contour( + BuiltModel model, int[][] heights, int localX, int baseHeight, int localY, int contouredGround + ) { + model.calculateBoundsCylinder(); + int reach = model.xyzMag; + + int minX = localX - reach; + int maxX = localX + reach; + int minY = localY - reach; + int maxY = localY + reach; + + if (minX < 0 || (maxX + TILE_SIZE >> 7) >= heights.length || minY < 0 || (maxY + TILE_SIZE >> 7) >= heights[0].length) + return model; + + int westTile = minX >> 7; + int eastTile = maxX + TILE_SIZE - 1 >> 7; + int southTile = minY >> 7; + int northTile = maxY + TILE_SIZE - 1 >> 7; + + if (heights[westTile][southTile] == baseHeight + && heights[eastTile][southTile] == baseHeight + && heights[westTile][northTile] == baseHeight + && heights[eastTile][northTile] == baseHeight) + return model; + + BuiltModel bent = model.copyForContour(); + + for (int i = 0; i < model.verticesCount; i++) { + int vertexY = (int) model.verticesY[i]; + + if (contouredGround > 0) { + int up = (-vertexY << 16) / Math.max(1, model.modelHeight); + if (up >= contouredGround) { + bent.verticesY[i] = model.verticesY[i]; + continue; + } + int ground = groundAt(model, heights, i, localX, localY); + bent.verticesY[i] = (contouredGround - up) * (ground - baseHeight) / contouredGround + vertexY; + } else { + int ground = groundAt(model, heights, i, localX, localY); + bent.verticesY[i] = vertexY + ground - baseHeight; + } + } + + return bent; + } + + private static int groundAt(BuiltModel model, int[][] heights, int vertex, int localX, int localY) { + return groundAt((int) model.verticesX[vertex] + localX, (int) model.verticesZ[vertex] + localY, heights); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java new file mode 100644 index 0000000..17a7712 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java @@ -0,0 +1,322 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.models.VertexNormal; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; + +public class NormalMerger { + private static final int TILE_SIZE = 128; + private static final int HALF_TILE = TILE_SIZE / 2; + + private static final int MIN_SHARED_TO_HIDE = 3; + private static final byte FACE_HIDDEN = 2; + + public enum Kind { + WALL_A, + WALL_B, + GAME, + GROUND + } + + public static final class Pending { + final ModelDefinition model; + final ObjectDefinition object; + final Kind kind; + final int plane; + final int extendedX, extendedY; + final int sizeX, sizeY; + final Consumer assign; + /** + * Which of the scene's regions put it down. + * + *

Normals are merged between neighbours so the light runs smoothly over a join, which is right + * for two things that really do stand next to each other. Regions laid side by side only touch by + * arrangement, so anything on one side of the join is lit by its own region alone. + */ + int region; + + final ModelBounds bounds; + VertexNormal[] merged; + final int[] marks; + boolean lit; + + public Pending( + ModelDefinition model, ObjectDefinition object, Kind kind, + int plane, int extendedX, int extendedY, int sizeX, int sizeY, + Consumer assign + ) { + this.model = model; + this.object = object; + this.kind = kind; + this.plane = plane; + this.extendedX = extendedX; + this.extendedY = extendedY; + this.sizeX = sizeX; + this.sizeY = sizeY; + this.assign = assign; + + model.computeNormals(); + this.bounds = ModelBounds.of(model); + this.marks = new int[model.vertexCount]; + } + } + + private final List pending = new ArrayList<>(); + private final Map> byTile = new HashMap<>(); + private int pass; + + public boolean isEmpty() { + return pending.isEmpty(); + } + + public void add(Pending entry) { + pending.add(entry); + for (int x = entry.extendedX; x < entry.extendedX + entry.sizeX; x++) + for (int y = entry.extendedY; y < entry.extendedY + entry.sizeY; y++) + if (x >= 0 && y >= 0 && x < EXTENDED_SCENE_SIZE && y < EXTENDED_SCENE_SIZE) + byTile.computeIfAbsent(key(entry.plane, x, y), k -> new ArrayList<>()).add(entry); + } + + public void run(int[][][] heights) { + pending.sort(Comparator + .comparingInt((Pending p) -> p.plane) + .thenComparingInt(p -> p.extendedX) + .thenComparingInt(p -> p.extendedY) + .thenComparingInt(p -> p.kind.ordinal())); + + for (Pending entry : pending) { + if (entry.lit) + continue; + + if (entry.kind == Kind.GROUND) { + mergeGroundNeighbours(entry, heights); + } else { + mergeNeighbours(entry, heights); + } + } + + for (Pending entry : pending) { + if (entry.kind != Kind.WALL_A) + continue; + Pending other = wallPartner(entry); + if (other != null) + merge(entry, other, 0, 0, 0, false); + } + + for (Pending entry : pending) + light(entry); + } + + private Pending wallPartner(Pending wall) { + for (Pending other : at(wall.plane, wall.extendedX, wall.extendedY)) + if (other.kind == Kind.WALL_B) + return other; + return null; + } + + private void mergeNeighbours(Pending entry, int[][][] heights) { + boolean sameTileRules = true; + int xStart = entry.extendedX; + int xEnd = entry.extendedX + entry.sizeX; + int yStart = entry.extendedY - 1; + int yEnd = entry.extendedY + entry.sizeY; + + int ownHeight = tileHeight(heights, entry.plane, entry.extendedX, entry.extendedY); + + for (int plane = entry.plane; plane <= entry.plane + 1; plane++) { + if (plane >= MAX_Z) + continue; + + for (int x = xStart; x <= xEnd; x++) { + if (x < 0 || x >= EXTENDED_SCENE_SIZE) + continue; + + for (int y = yStart; y <= yEnd; y++) { + if (y < 0 || y >= EXTENDED_SCENE_SIZE) + continue; + + if (sameTileRules && !(x >= xEnd || y >= yEnd || y < entry.extendedY && entry.extendedX != x)) + continue; + + int dy = tileHeight(heights, plane, x, y) - ownHeight; + + for (Pending other : at(plane, x, y)) { + if (other == entry || other.region != entry.region) + continue; + + if (other.kind == Kind.WALL_A || other.kind == Kind.WALL_B) { + merge( + entry, other, + (x - entry.extendedX) * TILE_SIZE + (1 - entry.sizeX) * HALF_TILE, + dy, + (y - entry.extendedY) * TILE_SIZE + (1 - entry.sizeY) * HALF_TILE, + sameTileRules + ); + } else if (other.kind == Kind.GAME) { + merge( + entry, other, + (other.extendedX - entry.extendedX) * TILE_SIZE + (other.sizeX - entry.sizeX) * HALF_TILE, + dy, + (other.extendedY - entry.extendedY) * TILE_SIZE + (other.sizeY - entry.sizeY) * HALF_TILE, + sameTileRules + ); + } + } + } + } + + xStart--; + sameTileRules = false; + } + } + + private void mergeGroundNeighbours(Pending entry, int[][][] heights) { + int xEnd = entry.extendedX + 1; + int yEnd = entry.extendedY + 1; + int ownHeight = tileHeight(heights, entry.plane, entry.extendedX, entry.extendedY); + + for (int x = entry.extendedX; x <= xEnd; x++) { + if (x < 0 || x >= EXTENDED_SCENE_SIZE) + continue; + + for (int y = entry.extendedY - 1; y <= yEnd; y++) { + if (y < 0 || y >= EXTENDED_SCENE_SIZE) + continue; + if (x < xEnd && y < yEnd) + continue; + + int dy = tileHeight(heights, entry.plane, x, y) - ownHeight; + for (Pending other : at(entry.plane, x, y)) { + if (other == entry || other.kind != Kind.GROUND || other.region != entry.region) + continue; + merge( + entry, other, + (x - entry.extendedX) * TILE_SIZE, dy, (y - entry.extendedY) * TILE_SIZE, + true + ); + } + } + } + } + + private void merge(Pending a, Pending b, int dx, int dy, int dz, boolean hideSharedFaces) { + pass++; + int shared = 0; + + for (int v = 0; v < a.model.vertexCount; v++) { + VertexNormal aNormal = a.model.vertexNormals[v]; + if (aNormal == null || aNormal.magnitude == 0) + continue; + + int y = a.model.vertexY[v] - dy; + if (y > b.bounds.maxY) + continue; + int x = a.model.vertexX[v] - dx; + if (x < b.bounds.minX || x > b.bounds.maxX) + continue; + int z = a.model.vertexZ[v] - dz; + if (z < b.bounds.minZ || z > b.bounds.maxZ) + continue; + + for (int w = 0; w < b.model.vertexCount; w++) { + VertexNormal bNormal = b.model.vertexNormals[w]; + if (bNormal == null || bNormal.magnitude == 0) + continue; + if (b.model.vertexX[w] != x || b.model.vertexZ[w] != z || b.model.vertexY[w] != y) + continue; + + if (a.merged == null) + a.merged = new VertexNormal[a.model.vertexCount]; + if (b.merged == null) + b.merged = new VertexNormal[b.model.vertexCount]; + + VertexNormal aMerged = a.merged[v]; + if (aMerged == null) + aMerged = a.merged[v] = copyOf(aNormal); + VertexNormal bMerged = b.merged[w]; + if (bMerged == null) + bMerged = b.merged[w] = copyOf(bNormal); + + aMerged.x += bNormal.x; + aMerged.y += bNormal.y; + aMerged.z += bNormal.z; + aMerged.magnitude += bNormal.magnitude; + + bMerged.x += aNormal.x; + bMerged.y += aNormal.y; + bMerged.z += aNormal.z; + bMerged.magnitude += aNormal.magnitude; + + shared++; + a.marks[v] = pass; + b.marks[w] = pass; + } + } + + if (shared < MIN_SHARED_TO_HIDE || !hideSharedFaces) + return; + + hideFullySharedFaces(a); + hideFullySharedFaces(b); + } + + private void hideFullySharedFaces(Pending entry) { + ModelDefinition model = entry.model; + for (int face = 0; face < model.faceCount; face++) { + if (entry.marks[model.faceIndices1[face]] != pass + || entry.marks[model.faceIndices2[face]] != pass + || entry.marks[model.faceIndices3[face]] != pass) + continue; + + if (model.faceRenderTypes == null) + model.faceRenderTypes = new byte[model.faceCount]; + model.faceRenderTypes[face] = FACE_HIDDEN; + } + } + + private void light(Pending entry) { + if (entry.lit) + return; + entry.lit = true; + + BuiltModel model = ModelFactory.light( + entry.model, + entry.object.getAmbient() + 64, + entry.object.getContrast() + 768, + entry.merged + ); + entry.assign.accept(model); + } + + private List at(int plane, int x, int y) { + List found = byTile.get(key(plane, x, y)); + return found == null ? java.util.Collections.emptyList() : found; + } + + private static int tileHeight(int[][][] heights, int plane, int x, int y) { + int[][] plan = heights[plane]; + return plan[x + 1][y + 1] + plan[x][y] + plan[x + 1][y] + plan[x][y + 1] >> 2; + } + + private static VertexNormal copyOf(VertexNormal normal) { + var copy = new VertexNormal(); + copy.x = normal.x; + copy.y = normal.y; + copy.z = normal.z; + copy.magnitude = normal.magnitude; + return copy; + } + + private static int key(int plane, int x, int y) { + return (plane * EXTENDED_SCENE_SIZE + x) * EXTENDED_SCENE_SIZE + y; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java new file mode 100644 index 0000000..dfa76e1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java @@ -0,0 +1,656 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import javax.annotation.Nullable; +import net.runelite.api.Model; +import net.runelite.api.Renderable; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static rs117.hd.dev.sceneloader.scene.SceneBuilder.OFFSET; + +public class ObjectPlacer { + private static final int TILE_SIZE = 128; + private static final int HALF_TILE = TILE_SIZE / 2; + + private static final int MAX_OBJECTS_PER_TILE = 5; + + private static final int WALL = 0; + private static final int WALL_CORNER_A = 1; + private static final int WALL_JOINT = 2; + private static final int WALL_CORNER_B = 3; + private static final int DECOR_AGAINST_WALL = 4; + private static final int DECOR_OFFSET_WALL = 5; + private static final int DECOR_DIAGONAL = 6; + private static final int DECOR_DIAGONAL_OPPOSITE = 7; + private static final int DECOR_DIAGONAL_BOTH = 8; + private static final int WALL_DIAGONAL = 9; + private static final int OBJECT = 10; + private static final int OBJECT_DIAGONAL = 11; + private static final int ROOF_FIRST = 12; + private static final int GROUND_DECORATION = 22; + + private static final int[] WALL_OFFSET_X = { 1, 0, -1, 0 }; + private static final int[] WALL_OFFSET_Y = { 0, -1, 0, 1 }; + private static final int[] CORNER_OFFSET_X = { 1, -1, -1, 1 }; + private static final int[] CORNER_OFFSET_Y = { -1, -1, 1, 1 }; + + private static final int NO_DISPLACEMENT = 16; + private static final int ASSUMED_WALL_DISPLACEMENT = 16; + private static final int ASSUMED_OBJECT_DISPLACEMENT = 8; + + private static final int HASH_TYPE_LOC = 2; + private static final long HASH_NOT_A_DOOR = 0x80000L; + private static final int DIAGONAL_MODEL_ORIENTATION = 256; + private static final int CONFIG_SUPPORTS_ITEMS = 256; + + + private static final int WALL_SHADOW = 50; + private static final int MAX_OBJECT_SHADOW = 30; + private static final int DEFAULT_OBJECT_SHADOW = 15; + + private final Definitions defs; + private final ModelFactory models; + + public ObjectPlacer(Definitions defs, ModelFactory models) { + this.defs = defs; + this.models = models; + } + + public void place(SceneBuilder.Work work, int plane, int sceneX, int sceneY, int id, int rotation, int type) + throws IOException { + ObjectDefinition object = defs.object(id); + if (object == null) + return; + + ObjectDefinition modelObject = object; + BuiltAnimation animation = null; + FrameDefinition[] animationFrames = null; + boolean decidedAtRuntime = object.getConfigChangeDest() != null || object.getAnimationID() != -1; + + if (decidedAtRuntime) { + VariantOptions.Resolution resolution = work.variants.record(object, variantDefs(object)); + if (resolution.hidden) + return; + if (resolution.modelObjectId != -1) { + modelObject = defs.object(resolution.modelObjectId); + if (modelObject == null) + return; + } + + animation = animationFor(object); + if (animation != null) { + animationFrames = framesOf(animation); + if (animationFrames == null) + animation = null; + } + } + + BuiltScene scene = work.scene; + int[][] heights = work.heights[plane]; + + int sizeX = object.getSizeX(); + int sizeY = object.getSizeY(); + if (rotation == 1 || rotation == 3) { + int swap = sizeX; + sizeX = sizeY; + sizeY = swap; + } + + int extendedX = OFFSET + sceneX; + int extendedY = OFFSET + sceneY; + + int sampleWestX, sampleEastX; + if (sceneX + sizeX <= work.maxTile) { + sampleWestX = OFFSET + sceneX + (sizeX >> 1); + sampleEastX = OFFSET + sceneX + (sizeX + 1 >> 1); + } else { + sampleWestX = extendedX; + sampleEastX = extendedX + 1; + } + int sampleSouthY, sampleNorthY; + if (sceneY + sizeY <= work.maxTile) { + sampleSouthY = OFFSET + sceneY + (sizeY >> 1); + sampleNorthY = OFFSET + sceneY + (sizeY + 1 >> 1); + } else { + sampleSouthY = extendedY; + sampleNorthY = extendedY + 1; + } + int height = heights[sampleWestX][sampleSouthY] + heights[sampleWestX][sampleNorthY] + + heights[sampleEastX][sampleSouthY] + heights[sampleEastX][sampleNorthY] >> 2; + + int contourX = (sizeX << 6) + (extendedX << 7); + int contourY = (sizeY << 6) + (extendedY << 7); + + boolean interactableWall = object.getWallOrDoor() != 0 + && sceneX >= 0 && sceneX < 128 && sceneY >= 0 && sceneY < 128; + long hash = hash(plane, sceneX, sceneY, HASH_TYPE_LOC, !interactableWall, id, scene.getWorldViewId()); + + int config = (rotation << 6) + type; + if (object.getSupportsItems() == 1) + config += CONFIG_SUPPORTS_ITEMS; + + boolean smoothSeams = !decidedAtRuntime && modelObject.isMergeNormals(); + + var at = new Placement(work, object, modelObject, animation, animationFrames, + smoothSeams, plane, sceneX, sceneY, + extendedX, extendedY, height, contourX, contourY, rotation, type, hash, config, sizeX, sizeY); + + if (decidedAtRuntime) + work.variants.noteLocation( + object.getId(), + at.sceneX * TILE_SIZE + sizeX * HALF_TILE, at.height, at.sceneY * TILE_SIZE + sizeY * HALF_TILE, + plane, sizeX, sizeY + ); + + if (type == GROUND_DECORATION) { + placeGroundDecoration(at); + } else if (type >= ROOF_FIRST) { + addGameObject(at, model(at, type, rotation), 1, 1, 0); + } else if (type == OBJECT || type == OBJECT_DIAGONAL) { + placeObject(at); + } else if (type == WALL) { + placeWall(at); + } else if (type == WALL_CORNER_A || type == WALL_CORNER_B) { + placeWallCorner(at); + } else if (type == WALL_JOINT) { + placeWallJoint(at); + } else if (type == WALL_DIAGONAL) { + placeDiagonalWall(at); + } else if (type >= DECOR_AGAINST_WALL && type <= DECOR_DIAGONAL_BOTH) { + placeDecoration(at); + } + } + + private void placeGroundDecoration(Placement at) throws IOException { + Slot slot = model(at, GROUND_DECORATION, at.rotation); + if (slot.missing()) + return; + + var object = new BuiltGroundObject( + at.work.scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + slot.ready + ); + tileFor(at).setGroundObject(object); + noteDynamic(at, object, slot.ready, object.getX(), object.getZ(), object.getY()); + defer(at, slot, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable); + } + + private void placeObject(Placement at) throws IOException { + Slot slot = model(at, OBJECT, at.rotation); + int modelOrientation = at.type == OBJECT_DIAGONAL ? DIAGONAL_MODEL_ORIENTATION : 0; + + if (addGameObject(at, slot, at.sizeX, at.sizeY, modelOrientation) && at.object.isShadow()) + castObjectShadow(at, slot); + } + + private void placeWall(Placement at) throws IOException { + addWallObject(at, model(at, WALL, at.rotation), Slot.NONE, 1 << at.rotation, 0); + + if (at.object.isShadow()) + castWallShadow(at, true); + displaceDecoration(at, at.object.getDecorDisplacement() + 1); + } + + private void placeWallCorner(Placement at) throws IOException { + addWallObject(at, model(at, at.type, at.rotation), Slot.NONE, 16 << at.rotation, 0); + + if (at.object.isShadow()) + castWallShadow(at, false); + } + + private void placeWallJoint(Placement at) throws IOException { + int otherRotation = at.rotation + 1 & 3; + addWallObject( + at, + model(at, WALL_JOINT, at.rotation + 4), + model(at, WALL_JOINT, otherRotation), + 1 << at.rotation, 1 << otherRotation + ); + displaceDecoration(at, at.object.getDecorDisplacement() + 1); + } + + private void placeDiagonalWall(Placement at) throws IOException { + addGameObject(at, model(at, WALL_DIAGONAL, at.rotation), 1, 1, 0); + displaceDecoration(at, at.object.getDecorDisplacement() / 2 + 1); + } + + private void placeDecoration(Placement at) throws IOException { + int rotation = at.rotation; + + switch (at.type) { + case DECOR_AGAINST_WALL: + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation), Slot.NONE, + WALL_OFFSET_X[rotation], WALL_OFFSET_Y[rotation], 0, 0); + break; + + case DECOR_OFFSET_WALL: { + int displacement = ASSUMED_WALL_DISPLACEMENT; + var wall = tileFor(at).getWallObject(); + if (wall != null) { + var wallDef = defs.object(wall.getId()); + if (wallDef != null) + displacement = wallDef.getDecorDisplacement(); + } + displacement++; + + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation), Slot.NONE, + WALL_OFFSET_X[rotation] * displacement, WALL_OFFSET_Y[rotation] * displacement, 0, 0); + break; + } + + case DECOR_DIAGONAL: { + int displacement = objectDisplacement(at) + 1; + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation + 4), Slot.NONE, + CORNER_OFFSET_X[rotation] * displacement, CORNER_OFFSET_Y[rotation] * displacement, 0, 0); + break; + } + + case DECOR_DIAGONAL_OPPOSITE: { + int otherRotation = rotation + 2 & 3; + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, otherRotation + 4), Slot.NONE, + CORNER_OFFSET_X[otherRotation], CORNER_OFFSET_Y[otherRotation], 0, 0); + break; + } + + case DECOR_DIAGONAL_BOTH: { + int displacement = objectDisplacement(at) + 1; + int otherRotation = rotation + 2 & 3; + addDecorativeObject( + at, + model(at, DECOR_AGAINST_WALL, rotation + 4), + model(at, DECOR_AGAINST_WALL, otherRotation + 4), + CORNER_OFFSET_X[rotation] * displacement, CORNER_OFFSET_Y[rotation] * displacement, + CORNER_OFFSET_X[otherRotation], CORNER_OFFSET_Y[otherRotation] + ); + break; + } + + default: + break; + } + } + + private int objectDisplacement(Placement at) { + int displacement = ASSUMED_OBJECT_DISPLACEMENT; + for (var object : tileFor(at).getGameObjects()) { + if (object == null) + continue; + var objectDef = defs.object(object.getId()); + if (objectDef != null) + displacement = objectDef.getDecorDisplacement() / 2; + break; + } + return displacement; + } + + private void displaceDecoration(Placement at, int displacement) { + if (at.object.getDecorDisplacement() == NO_DISPLACEMENT) + return; + var decoration = tileFor(at).getDecorativeObject(); + if (decoration instanceof BuiltDecorativeObject) + ((BuiltDecorativeObject) decoration).displace(displacement); + } + + private Slot model(Placement at, int modelType, int modelRotation) throws IOException { + int contour = at.work.hillskew ? at.modelObject.getContouredGround() : -1; + + if (at.smoothSeams) { + ModelDefinition unlit = models.unlitModel(at.modelObject, modelType, modelRotation); + if (unlit == null) + return Slot.NONE; + if (contour >= 0) + ModelFactory.contourDefinition(unlit, at.work.heights[at.plane], at.contourX, at.height, at.contourY, contour); + return Slot.deferred(unlit); + } + + if (at.animation != null) + return animated(at, modelType, modelRotation, contour); + + BuiltModel model = models.model(at.modelObject, modelType, modelRotation); + if (model == null) + return Slot.NONE; + return Slot.ready(contoured(at, model, contour)); + } + + private Slot animated(Placement at, int modelType, int modelRotation, int contour) throws IOException { + FrameDefinition[] frames = at.animationFrames; + assert frames != null && at.animation != null; + + var models = new Model[frames.length]; + boolean any = false; + for (int i = 0; i < frames.length; i++) { + BuiltModel posed = this.models.model(at.modelObject, modelType, modelRotation, frames[i]); + if (posed == null) + continue; + models[i] = contoured(at, posed, contour); + any = true; + } + if (!any) + return Slot.NONE; + + return Slot.ready(new BuiltDynamicObject(at.object.getId(), at.animation, models)); + } + + private BuiltModel contoured(Placement at, BuiltModel model, int contour) { + if (contour < 0) + return model; + return ModelFactory.contour( + model, at.work.heights[at.plane], at.contourX, at.height, at.contourY, contour + ); + } + + private void noteDynamic( + Placement at, net.runelite.api.TileObject owner, @Nullable Renderable renderable, int x, int y, int z + ) { + if (!(renderable instanceof BuiltDynamicObject)) + return; + var dynamic = (BuiltDynamicObject) renderable; + if (!dynamic.hasModel()) + return; + at.work.scene.addDynamic(new BuiltScene.Dynamic(owner, dynamic, 0, x, y, z)); + } + + private void defer( + Placement at, Slot slot, NormalMerger.Kind kind, int sizeX, int sizeY, java.util.function.Consumer assign + ) { + if (slot.deferred == null) + return; + var pending = new NormalMerger.Pending( + slot.deferred, at.modelObject, kind, at.plane, at.extendedX, at.extendedY, sizeX, sizeY, assign + ); + pending.region = at.work.region; + at.work.merger.add(pending); + } + + private BuiltTile tileFor(Placement at) { + return at.work.scene.tile(at.plane, at.extendedX, at.extendedY); + } + + private void ensureColumn(BuiltScene scene, int plane, int x, int y) { + for (int below = plane; below >= 0; below--) + scene.tile(below, x, y); + } + + private boolean addGameObject(Placement at, Slot slot, int sizeX, int sizeY, int modelOrientation) { + if (slot.missing()) + return true; + + BuiltScene scene = at.work.scene; + + for (int x = at.extendedX; x < at.extendedX + sizeX; x++) { + for (int y = at.extendedY; y < at.extendedY + sizeY; y++) { + if (x < 0 || y < 0 || x >= EXTENDED_SCENE_SIZE || y >= EXTENDED_SCENE_SIZE) + return false; + BuiltTile tile = scene.tileOrNull(at.plane, x, y); + if (tile != null && tile.gameObjectCount() >= MAX_OBJECTS_PER_TILE) + return false; + } + } + + var object = new BuiltGameObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + sizeX * HALF_TILE, + at.sceneY * TILE_SIZE + sizeY * HALF_TILE, + at.height, at.plane, + slot.ready, modelOrientation, + at.sceneX, at.sceneY, at.sceneX + sizeX - 1, at.sceneY + sizeY - 1 + ); + + for (int x = at.extendedX; x < at.extendedX + sizeX; x++) { + for (int y = at.extendedY; y < at.extendedY + sizeY; y++) { + ensureColumn(scene, at.plane, x, y); + scene.tile(at.plane, x, y).addGameObject(object); + } + } + + noteDynamic(at, object, slot.ready, object.getX(), object.getZ(), object.getY()); + defer(at, slot, NormalMerger.Kind.GAME, sizeX, sizeY, object::setRenderable); + return true; + } + + private void addWallObject(Placement at, Slot first, Slot second, int orientationA, int orientationB) { + if (first.missing() && second.missing()) + return; + + BuiltScene scene = at.work.scene; + ensureColumn(scene, at.plane, at.extendedX, at.extendedY); + + var object = new BuiltWallObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + first.ready, second.ready, orientationA, orientationB + ); + scene.tile(at.plane, at.extendedX, at.extendedY).setWallObject(object); + + noteDynamic(at, object, first.ready, object.getX(), object.getZ(), object.getY()); + noteDynamic(at, object, second.ready, object.getX(), object.getZ(), object.getY()); + defer(at, first, NormalMerger.Kind.WALL_A, 1, 1, object::setRenderable1); + defer(at, second, NormalMerger.Kind.WALL_B, 1, 1, object::setRenderable2); + } + + private void addDecorativeObject( + Placement at, Slot first, Slot second, + int xOffset, int yOffset, int xOffset2, int yOffset2 + ) { + if (first.missing()) + return; + + BuiltScene scene = at.work.scene; + ensureColumn(scene, at.plane, at.extendedX, at.extendedY); + + var object = new BuiltDecorativeObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + first.ready, second.ready, xOffset, yOffset, xOffset2, yOffset2 + ); + scene.tile(at.plane, at.extendedX, at.extendedY).setDecorativeObject(object); + + noteDynamic(at, object, first.ready, object.getX(), object.getZ(), object.getY()); + noteDynamic(at, object, second.ready, object.getX(), object.getZ(), object.getY()); + defer(at, first, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable); + defer(at, second, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable2); + } + + private void castWallShadow(Placement at, boolean straight) { + byte[][] shadow = at.work.shadow[at.plane]; + int x = at.extendedX; + int y = at.extendedY; + + if (straight) { + switch (at.rotation) { + case 0: + shadow[x][y] = WALL_SHADOW; + shadow[x][y + 1] = WALL_SHADOW; + break; + case 1: + shadow[x][y + 1] = WALL_SHADOW; + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + case 2: + shadow[x + 1][y] = WALL_SHADOW; + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + default: + shadow[x][y] = WALL_SHADOW; + shadow[x + 1][y] = WALL_SHADOW; + break; + } + } else { + switch (at.rotation) { + case 0: + shadow[x][y + 1] = WALL_SHADOW; + break; + case 1: + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + case 2: + shadow[x + 1][y] = WALL_SHADOW; + break; + default: + shadow[x][y] = WALL_SHADOW; + break; + } + } + } + + private void castObjectShadow(Placement at, Slot slot) { + int amount = DEFAULT_OBJECT_SHADOW; + if (slot.ready instanceof BuiltModel) { + var model = (BuiltModel) slot.ready; + model.calculateBoundsCylinder(); + amount = Math.min(model.xyzMag / 4, MAX_OBJECT_SHADOW); + } + + byte[][] shadow = at.work.shadow[at.plane]; + for (int dx = 0; dx <= at.sizeX; dx++) { + for (int dy = 0; dy <= at.sizeY; dy++) { + int x = at.extendedX + dx; + int y = at.extendedY + dy; + if (x < 0 || y < 0 || x >= shadow.length || y >= shadow[0].length) + continue; + if (amount > shadow[x][y]) + shadow[x][y] = (byte) amount; + } + } + } + + public static long hash(int plane, int sceneX, int sceneY, int type, boolean notADoor, int id, int worldViewId) { + long hash = (sceneX & 127L) + | (sceneY & 127L) << 7 + | (plane & 3L) << 14 + | (type & 7L) << 16 + | (id & 0xFFFFFFFFL) << 20 + | (worldViewId & 4095L) << 52; + if (notADoor) + hash |= HASH_NOT_A_DOOR; + return hash; + } + + private static final class Slot { + static final Slot NONE = new Slot(null, null); + + @Nullable + final Renderable ready; + @Nullable + final ModelDefinition deferred; + + private Slot(@Nullable Renderable ready, @Nullable ModelDefinition deferred) { + this.ready = ready; + this.deferred = deferred; + } + + static Slot ready(Renderable renderable) { + return new Slot(renderable, null); + } + + static Slot deferred(ModelDefinition model) { + return new Slot(null, model); + } + + boolean missing() { + return ready == null && deferred == null; + } + } + + /** + * The animation an object plays, which is always the one the id itself names. + * + *

A transform only decides which object supplies the model. The animation stays with the one that + * was placed on the map, even when that one has no model of its own: the game reads the animation once + * when it spawns the object and then transforms afresh every frame purely to find the model to pose. + * Taking it from the transformed object instead leaves anything whose animation lives on the parent + * standing still, which for a model animated by fading its faces also means it never becomes see + * through. + */ + @Nullable + private BuiltAnimation animationFor(ObjectDefinition object) { + int animationId = object.getAnimationID(); + if (animationId == -1) + return null; + + var sequence = defs.sequence(animationId); + if (sequence == null || sequence.frameIDs == null || sequence.frameIDs.length == 0) + return null; + + return new BuiltAnimation(sequence); + } + + @Nullable + private FrameDefinition[] framesOf(BuiltAnimation animation) { + int[] frameIds = animation.definition().frameIDs; + var frames = new FrameDefinition[frameIds.length]; + for (int i = 0; i < frameIds.length; i++) { + frames[i] = defs.frame(frameIds[i]); + if (frames[i] == null) + return null; + } + return frames; + } + + @Nullable + private ObjectDefinition[] variantDefs(ObjectDefinition object) { + int[] variants = object.getConfigChangeDest(); + if (variants == null) + return null; + + var defsForVariants = new ObjectDefinition[variants.length]; + for (int i = 0; i < variants.length; i++) + if (variants[i] != -1) + defsForVariants[i] = defs.object(variants[i]); + return defsForVariants; + } + + private static final class Placement { + final SceneBuilder.Work work; + final ObjectDefinition object; + final ObjectDefinition modelObject; + @Nullable + final BuiltAnimation animation; + @Nullable + final FrameDefinition[] animationFrames; + final boolean smoothSeams; + final int plane; + final int sceneX, sceneY; + final int extendedX, extendedY; + final int height; + final int contourX, contourY; + final int rotation, type; + final long hash; + final int config; + final int sizeX, sizeY; + + Placement( + SceneBuilder.Work work, ObjectDefinition object, ObjectDefinition modelObject, + @Nullable BuiltAnimation animation, @Nullable FrameDefinition[] animationFrames, + boolean smoothSeams, int plane, + int sceneX, int sceneY, int extendedX, int extendedY, + int height, int contourX, int contourY, + int rotation, int type, long hash, int config, int sizeX, int sizeY + ) { + this.work = work; + this.object = object; + this.modelObject = modelObject; + this.animation = animation; + this.animationFrames = animationFrames; + this.smoothSeams = smoothSeams; + this.plane = plane; + this.sceneX = sceneX; + this.sceneY = sceneY; + this.extendedX = extendedX; + this.extendedY = extendedY; + this.height = height; + this.contourX = contourX; + this.contourY = contourY; + this.rotation = rotation; + this.type = type; + this.hash = hash; + this.config = config; + this.sizeX = sizeX; + this.sizeY = sizeY; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java new file mode 100644 index 0000000..6e313e1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java @@ -0,0 +1,974 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.definitions.OverlayDefinition; +import net.runelite.cache.definitions.UnderlayDefinition; +import net.runelite.cache.region.Location; +import net.runelite.cache.region.Position; +import net.runelite.cache.region.Region; +import rs117.hd.dev.sceneloader.ModelPreview; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; +import static net.runelite.api.Constants.SCENE_SIZE; +import static rs117.hd.dev.sceneloader.scene.ModelFactory.LOC_OBJECT; + +public class SceneBuilder { + public static final int EXTENDED = EXTENDED_SCENE_SIZE; + public static final int OFFSET = BuiltScene.SCENE_OFFSET; + private static final int HEIGHT_GRID = EXTENDED + 1; + + public static final int NO_COLOR = 12345678; + private static final int HIDDEN_OVERLAY = 0xFF00FF; + + private static final int LIGHT_X = -50; + private static final int LIGHT_Y = -10; + private static final int LIGHT_Z = -50; + private static final int LIGHT_MAGNITUDE = (int) Math.sqrt(5100.0) * 768 >> 8; + private static final int AMBIENT_LIGHT = 96; + + private static final int BLUR_RADIUS = 5; + + private static final int BLANK_SHADOW = 127; + + private static final int BASE_CHUNK_OFFSET = 6; + private static final int BLANK_FILL_CHUNK_LIMIT = 800; + + private final Definitions defs; + private final HslPalette palette; + private final ObjectPlacer placer; + private final ModelFactory factory; + + public SceneBuilder(Definitions defs) { + this(defs, new HslPalette(HslPalette.DEFAULT_BRIGHTNESS)); + } + + public SceneBuilder(Definitions defs, HslPalette palette) { + this.defs = defs; + this.palette = palette; + this.factory = new ModelFactory(defs); + this.placer = new ObjectPlacer(defs, factory); + } + + @Nullable + public ModelPreview.Shape preview(int objectId, int type) throws IOException { + ObjectDefinition object = defs.object(objectId); + if (object == null) + return null; + + int[] types = object.getObjectTypes(); + if (type < 0) + type = types == null || types.length == 0 ? LOC_OBJECT : types[0]; + + BuiltModel model = factory.model(object, type, 0); + if (model == null || model.getFaceCount() == 0) + return null; + + int faceCount = model.getFaceCount(); + int[] colors1 = model.getFaceColors1(); + int[] colors2 = model.getFaceColors2(); + int[] colors3 = model.getFaceColors3(); + short[] textures = model.getFaceTextures(); + byte[] transparencies = model.getFaceTransparencies(); + + var faceColors = new int[faceCount]; + for (int f = 0; f < faceCount; f++) { + if (colors3[f] == -2 || transparencies != null && (transparencies[f] & 0xFF) == 0xFF) { + faceColors[f] = -1; + continue; + } + + int texture = textures == null ? -1 : textures[f]; + if (texture != -1) { + faceColors[f] = palette.toRgb(defs.textureColor(texture)); + } else if (colors3[f] == -1) { + faceColors[f] = palette.toRgb(colors1[f]); + } else { + int a = palette.toRgb(colors1[f]); + int b = palette.toRgb(colors2[f]); + int c = palette.toRgb(colors3[f]); + faceColors[f] = + (((a >> 16 & 0xFF) + (b >> 16 & 0xFF) + (c >> 16 & 0xFF)) / 3) << 16 | + (((a >> 8 & 0xFF) + (b >> 8 & 0xFF) + (c >> 8 & 0xFF)) / 3) << 8 | + ((a & 0xFF) + (b & 0xFF) + (c & 0xFF)) / 3; + } + } + + return new ModelPreview.Shape(model, faceColors); + } + + public BuiltScene build(int worldX, int worldY) throws IOException { + return build(worldX, worldY, 0, 0, new VariantOptions()); + } + + public BuiltScene build(int worldX, int worldY, int expandedChunks, int worldViewId) throws IOException { + return build(worldX, worldY, expandedChunks, worldViewId, new VariantOptions()); + } + + private static int baseOf(int worldTile) { + return ((worldTile >> 3) - BASE_CHUNK_OFFSET) * 8; + } + + public static int[] sceneTiles(int worldX, int worldY, int expandedChunks) { + int baseX = baseOf(worldX); + int baseY = baseOf(worldY); + int minTile = -expandedChunks * 8; + int maxTile = SCENE_SIZE + expandedChunks * 8; + return new int[] { + baseX + minTile, + baseY + minTile, + baseX + maxTile - 1, + baseY + maxTile - 1, + }; + } + + public static int[] regionBlock(int worldX, int worldY, int expandedChunks) { + int[] tiles = sceneTiles(worldX, worldY, expandedChunks); + return new int[] { tiles[0] >> 6, tiles[1] >> 6, tiles[2] >> 6, tiles[3] >> 6 }; + } + + public BuiltScene build( + int worldX, int worldY, int expandedChunks, int worldViewId, VariantOptions variants + ) throws IOException { + return build(worldX, worldY, expandedChunks, worldViewId, variants, location -> true); + } + + public BuiltScene buildPreview(int worldX, int worldY, int worldViewId, java.util.function.Predicate includeObjects) + throws IOException { + return build(worldX, worldY, 0, worldViewId, new VariantOptions(), includeObjects); + } + + private BuiltScene build(int worldX, int worldY, int expandedChunks, int worldViewId, VariantOptions variants, + java.util.function.Predicate includeObjects) throws IOException { + variants.startBuild(); + + int baseX = baseOf(worldX); + int baseY = baseOf(worldY); + + int minTile = -expandedChunks * 8; + int maxTile = SCENE_SIZE + expandedChunks * 8; + + List regions = new ArrayList<>(); + List origins = new ArrayList<>(); + List regionIds = new ArrayList<>(); + + int[] block = regionBlock(worldX, worldY, expandedChunks); + int firstRegionX = block[0]; + int firstRegionY = block[1]; + int lastRegionX = block[2]; + int lastRegionY = block[3]; + + for (int regionX = firstRegionX; regionX <= lastRegionX; regionX++) { + for (int regionY = firstRegionY; regionY <= lastRegionY; regionY++) { + regions.add(defs.region(regionX, regionY)); + origins.add(new int[] { (regionX << 6) - baseX, (regionY << 6) - baseY }); + regionIds.add(regionX << 8 | regionY); + } + } + + return assemble( + regions, origins, regionIds, baseX, baseY, worldViewId, variants, minTile, maxTile, + (worldY >> 3) < BLANK_FILL_CHUNK_LIMIT, true, includeObjects, null, null + ); + } + + /** + * How much space to leave between regions that are not neighbours, in tiles. + * + *

Taken off the far side of the region itself rather than added between them. That keeps every + * region on the same sixty four tile pitch, so two that really do adjoin in the world can still be laid + * against each other and drawn whole, while anything unrelated is set apart by this much. A whole + * number of chunks, because a region says where it really is through the instance template, which names + * a whole chunk at a time. + */ + public static final int REGION_GAP = 8; + + /** + * How many regions fit across the scene. + * + *

Three rather than the two that whole regions would allow. A region is sixty four tiles and the + * scene a hundred and eighty four, so three of them only fit if the last gives up the eight tiles it + * cannot have: two at full width and one clipped comes to exactly the scene. + */ + public static final int REGIONS_PER_SIDE = (EXTENDED + REGION_GAP) / Region.X; + + /** + * How many regions may be picked at once. + * + *

Fewer than the nine the scene has room for. Nine is a lot of ground to build and most of them end + * up giving away their edges to make space, so this is held lower on purpose. Raising it to + * {@code REGIONS_PER_SIDE * REGIONS_PER_SIDE} is all that is needed to fill the grid. + */ + public static final int MAX_STITCHED_REGIONS = 5; + + /** One region in a stitched scene: where it was put, and whether its neighbours there are the real ones */ + private static final class Stitched { + final int id; + final int originX, originY; + /** How much ground it covers, before anything beside it is taken into account */ + /** How many of its sixty four tiles are drawn, which is fewer where something unrelated is next to it */ + final int drawnX, drawnY; + /** Which run of adjoining regions it belongs to, so lighting runs across one but not between two */ + final int group; + + Stitched(int id, int originX, int originY, int drawnX, int drawnY, int group) { + this.id = id; + this.originX = originX; + this.originY = originY; + this.drawnX = drawnX; + this.drawnY = drawnY; + this.group = group; + } + } + + public BuiltScene buildStitched(int[] wantedRegions, int worldViewId, VariantOptions variants) + throws IOException { + variants.startBuild(); + + int minTile = -OFFSET; + int maxTile = SCENE_SIZE + OFFSET; + List placed = layOut(wantedRegions); + if (placed.isEmpty()) + return build(3222, 3218, 0, worldViewId, variants); + + List regions = new ArrayList<>(); + List origins = new ArrayList<>(); + List regionIds = new ArrayList<>(); + var drawn = new ArrayList(); + var groups = new ArrayList(); + + for (Stitched entry : placed) { + regions.add(defs.region(entry.id >> 8, entry.id & 0xFF)); + origins.add(new int[] { entry.originX, entry.originY }); + regionIds.add(entry.id); + drawn.add(new int[] { entry.drawnX, entry.drawnY }); + groups.add(entry.group); + } + + int[] first = origins.get(0); + Region firstRegion = regions.get(0); + int baseX = (placed.get(0).id >> 8 << 6) - first[0]; + int baseY = ((placed.get(0).id & 0xFF) << 6) - first[1]; + if (firstRegion != null) { + baseX = firstRegion.getBaseX() - first[0]; + baseY = firstRegion.getBaseY() - first[1]; + } + + BuiltScene scene = assemble( + regions, origins, regionIds, baseX, baseY, worldViewId, variants, minTile, maxTile, + true, true, location -> true, drawn, groups); + scene.setInstanceTemplateChunks(templateChunks(regionIds, origins)); + return scene; + } + + /** + * Works out where each picked region goes. + * + *

Regions that adjoin each other in the world are gathered into one group and laid out at their true + * offsets, so the group reads as one continuous piece of map. Groups are then packed into the scene with + * a gap between them, since there is nothing continuous about two places that merely got picked + * together. Everything lands on a chunk boundary, which the instance template needs. + * + *

Anything that will not fit is left out rather than overlapped. + */ + /** + * Which of the picked regions will actually fit, in the order they would be laid out. + * + *

Worth asking before building, since whether they fit depends on their shape and not just how many + * there are. Two regions side by side next to two more stacked one above the other needs a hundred and + * ninety two tiles whichever way round it is put, and the scene is a hundred and eighty four. + */ + public static int[] regionsThatFit(int[] wantedRegions) { + var placed = layOut(wantedRegions); + var fitting = new int[placed.size()]; + for (int i = 0; i < fitting.length; i++) + fitting[i] = placed.get(i).id; + return fitting; + } + + private static List layOut(int[] wantedRegions) { + int minTile = -OFFSET; + int span = EXTENDED; + var picked = new ArrayList(); + for (int id : wantedRegions) + if (!picked.contains(id) && picked.size() < MAX_STITCHED_REGIONS) + picked.add(id); + + var pending = new ArrayDeque(groupNeighbours(picked)); + var groups = new ArrayList(); + var offsets = new ArrayList(); + + // Packed left to right, starting a new row when a group will not fit on this one. A group that + // will not fit anywhere is broken up and its regions placed one at a time: they lose the join + // between them, which is a shame, but it beats not showing them at all. A pair side by side next + // to a pair stacked up needs a hundred and ninety two tiles and the scene has a hundred and + // eighty four, so without this the second pair would simply be missing. + int cursorX = 0, cursorY = 0, rowHeight = 0, widest = 0; + while (!pending.isEmpty()) { + int[] group = pending.poll(); + // What it must have: every region at full pitch but the last, which can give up its far edge + int width = group[2] * Region.X - REGION_GAP; + int height = group[3] * Region.Y - REGION_GAP; + + int wrapX = cursorX, wrapY = cursorY, wrapRow = rowHeight; + if (wrapX > 0 && wrapX + width > span) { + wrapX = 0; + wrapY += wrapRow; + wrapRow = 0; + } + + if (width > span || wrapY + height > span) { + var apart = members(picked, group); + if (apart.size() > 1) + for (int i = apart.size() - 1; i >= 0; i--) + pending.addFirst(new int[] { apart.get(i) >> 8, apart.get(i) & 0xFF, 1, 1 }); + continue; + } + + cursorX = wrapX; + cursorY = wrapY; + rowHeight = wrapRow; + + groups.add(group); + offsets.add(new int[] { cursorX, cursorY }); + widest = Math.max(widest, cursorX + width); + rowHeight = Math.max(rowHeight, group[3] * Region.Y); + // On to the next cell, so whatever follows starts a whole region along + cursorX += group[2] * Region.X; + } + int tall = Math.min(cursorY + rowHeight, span); + widest = Math.min(widest, span); + + int leftPad = alignToChunk(minTile + (span - widest) / 2); + int topPad = alignToChunk(minTile + (span - tall) / 2); + + var placed = new ArrayList(); + for (int i = 0; i < groups.size(); i++) { + int[] group = groups.get(i); + int[] offset = offsets.get(i); + int groupX = leftPad + offset[0]; + // Packed downwards, but the scene counts upwards, so the rows are read back the other way + int groupY = topPad + tall - offset[1] - group[3] * Region.Y; + + for (int id : members(picked, group)) { + placed.add(new Stitched( + id, + groupX + ((id >> 8) - group[0]) * Region.X, + groupY + ((id & 0xFF) - group[1]) * Region.Y, + Region.X, Region.Y, i + )); + } + } + return joinUp(placed, minTile + span); + } + + /** + * Works out how much of each region to draw, once everything has been placed. + * + *

A region gives up the far eight tiles of itself to make a space, unless what sits there is the + * region that really does adjoin it, in which case the two are drawn whole and meet seamlessly. Being + * neighbours in the world is not enough on its own: a group that had to be broken up to fit has its + * regions scattered about, and two halves of a pair sitting apart do not share a join. So it is asked + * of the layout rather than of the picking. + * + *

A region with nothing beyond it is drawn whole as well, since there is nothing to be apart from, + * except where the scene runs out first and it is clipped to what is left. + */ + private static List joinUp(List placed, int lastTile) { + var measured = new ArrayList(placed.size()); + for (Stitched entry : placed) { + int drawnX = Region.X, drawnY = Region.Y; + + for (Stitched other : placed) { + boolean east = other.originX == entry.originX + Region.X && other.originY == entry.originY; + boolean north = other.originY == entry.originY + Region.Y && other.originX == entry.originX; + if (east && other.id != entry.id + (1 << 8)) + drawnX = Region.X - REGION_GAP; + if (north && other.id != entry.id + 1) + drawnY = Region.Y - REGION_GAP; + } + + drawnX = Math.min(drawnX, lastTile - entry.originX); + drawnY = Math.min(drawnY, lastTile - entry.originY); + measured.add(new Stitched(entry.id, entry.originX, entry.originY, drawnX, drawnY, entry.group)); + } + return measured; + } + + /** + * Gathers the picked regions into groups that adjoin in the world. + * + * @return one entry per group: its lowest region x and y, then how many regions it spans each way + */ + private static List groupNeighbours(List picked) { + var groups = new ArrayList(); + var taken = new ArrayList(); + + for (int id : picked) { + if (taken.contains(id)) + continue; + + var queue = new ArrayDeque(); + queue.add(id); + taken.add(id); + int minX = id >> 8, maxX = minX, minY = id & 0xFF, maxY = minY; + + while (!queue.isEmpty()) { + int at = queue.poll(); + minX = Math.min(minX, at >> 8); + maxX = Math.max(maxX, at >> 8); + minY = Math.min(minY, at & 0xFF); + maxY = Math.max(maxY, at & 0xFF); + + for (int side : new int[] { 1 << 8, -(1 << 8), 1, -1 }) { + int next = at + side; + if (picked.contains(next) && !taken.contains(next)) { + taken.add(next); + queue.add(next); + } + } + } + + // No more of a group than the scene has room for, since the rest could not be drawn anyway + maxX = Math.min(maxX, minX + REGIONS_PER_SIDE - 1); + maxY = Math.min(maxY, minY + REGIONS_PER_SIDE - 1); + groups.add(new int[] { minX, minY, maxX - minX + 1, maxY - minY + 1 }); + } + return groups; + } + + /** The picked regions inside a group's bounds, bottom row first */ + private static List members(List picked, int[] group) { + var found = new ArrayList(); + for (int id : picked) { + int regionX = id >> 8, regionY = id & 0xFF; + if (regionX >= group[0] && regionX < group[0] + group[2] + && regionY >= group[1] && regionY < group[1] + group[3]) + found.add(id); + } + return found; + } + + /** The nearest chunk boundary at or before a scene tile, counted from the extended scene's own corner */ + private static int alignToChunk(int sceneTile) { + return Math.floorDiv(sceneTile + OFFSET, 8) * 8 - OFFSET; + } + + private static int[][][] templateChunks(List regionIds, List origins) { + int side = BuiltScene.CHUNKS_PER_SIDE; + var chunks = new int[MAX_Z][side][side]; + for (int[][] plane : chunks) + for (int[] column : plane) + java.util.Arrays.fill(column, -1); + + int chunksPerRegion = Region.X / 8; + for (int i = 0; i < regionIds.size(); i++) { + int id = regionIds.get(i); + int regionChunkX = (id >> 8) * chunksPerRegion; + int regionChunkY = (id & 0xFF) * chunksPerRegion; + int[] origin = origins.get(i); + + for (int plane = 0; plane < MAX_Z; plane++) { + for (int cx = 0; cx < chunksPerRegion; cx++) { + for (int cy = 0; cy < chunksPerRegion; cy++) { + int sceneChunkX = (origin[0] + OFFSET) / 8 + cx; + int sceneChunkY = (origin[1] + OFFSET) / 8 + cy; + if (sceneChunkX < 0 || sceneChunkY < 0 || sceneChunkX >= side || sceneChunkY >= side) + continue; + + chunks[plane][sceneChunkX][sceneChunkY] = + plane << 24 | (regionChunkX + cx) << 14 | (regionChunkY + cy) << 3; + } + } + } + } + return chunks; + } + + private BuiltScene assemble( + List regions, List origins, List regionIds, + int baseX, int baseY, int worldViewId, VariantOptions variants, + int minTile, int maxTile, boolean fillBlanks, boolean hillskew, java.util.function.Predicate includeObjects, + @Nullable List drawn, @Nullable List groups + ) throws IOException { + int[] mapRegions = new int[regionIds.size()]; + for (int i = 0; i < mapRegions.length; i++) + mapRegions[i] = regionIds.get(i); + + Work work = new Work(new BuiltScene(baseX, baseY, worldViewId, mapRegions), minTile, maxTile, variants); + work.hillskew = hillskew; + work.isolateRegions = drawn != null; + + for (int i = 0; i < regions.size(); i++) { + Region region = regions.get(i); + if (region == null) + continue; + int[] size = drawn == null ? null : drawn.get(i); + readTerrain( + work, region, origins.get(i)[0], origins.get(i)[1], + size == null ? Region.X : size[0], size == null ? Region.Y : size[1] + ); + } + if (fillBlanks) + for (int i = 0; i < regions.size(); i++) + if (regions.get(i) == null) + blank(work, origins.get(i)[0], origins.get(i)[1]); + + for (int i = 0; i < regions.size(); i++) { + Region region = regions.get(i); + if (region == null) + continue; + work.region = groups == null ? 0 : groups.get(i); + int[] size = drawn == null ? null : drawn.get(i); + placeObjects( + work, region, origins.get(i)[0], origins.get(i)[1], + size == null ? Region.X : size[0], size == null ? Region.Y : size[1], includeObjects + ); + } + + if (!work.merger.isEmpty()) + work.merger.run(work.heights); + + shade(work); + linkBridges(work); + work.scene.buildRoofs(); + + return work.scene; + } + + /** + * Reads one region's terrain into the scene at the place it has been given. + * + *

A tile is drawn between its own corner and the next one along, so the tiles down a region's far + * side read a corner belonging to whatever lies beyond. Where that really is the next region, the + * ground is continuous and the corner holds the one height both of them want, so there is nothing to + * do. Where it is a region from somewhere else entirely, or empty scene, those tiles would be stretched + * from one landscape to the other, which is the wall that appears along such a join. Since the two + * cannot both own the corner, that one row of tiles is left undrawn instead. + * + *

The heights are read either way, one row past the region, so the row behind an undrawn one has a + * corner of its own to sit flat against rather than dropping away to nothing. + * + * @param joinedEast whether the region that really adjoins it to the east is in the scene beside it + * @param joinedNorth the same to the north + */ + private void readTerrain( + Work work, Region region, int originX, int originY, int drawnX, int drawnY + ) { + int edge = work.isolateRegions ? 1 : 0; + boolean joinedEast = drawnX >= Region.X; + boolean joinedNorth = drawnY >= Region.Y; + + for (int plane = 0; plane < MAX_Z; plane++) { + for (int localX = 0; localX < Region.X + edge; localX++) { + int sceneX = originX + localX; + if (sceneX < work.minTile || sceneX >= work.maxTile) + continue; + int x = OFFSET + sceneX; + int sampleX = Math.min(localX, Region.X - 1); + + for (int localY = 0; localY < Region.Y + edge; localY++) { + int sceneY = originY + localY; + if (sceneY < work.minTile || sceneY >= work.maxTile) + continue; + int y = OFFSET + sceneY; + int sampleY = Math.min(localY, Region.Y - 1); + + // Never over a real neighbour's own corner, which it has already read or will read + if (localX < Region.X && localY < Region.Y + || !(joinedEast && localX >= Region.X) + && !(joinedNorth && localY >= Region.Y)) + work.heights[plane][x][y] = region.getTileHeight(plane, sampleX, sampleY); + + if (localX >= drawnX || localY >= drawnY) + continue; + + work.settings[plane][x][y] = region.getTileSetting(plane, localX, localY); + work.underlayIds[plane][x][y] = (short) region.getUnderlayId(plane, localX, localY); + work.overlayIds[plane][x][y] = (short) region.getOverlayId(plane, localX, localY); + work.shapes[plane][x][y] = region.getOverlayPath(plane, localX, localY); + work.rotations[plane][x][y] = region.getOverlayRotation(plane, localX, localY); + } + } + } + } + + private void blank(Work work, int originX, int originY) { + int width = Region.X; + int height = Region.Y; + for (int sceneY = originY; sceneY <= originY + height; sceneY++) { + for (int sceneX = originX; sceneX <= originX + width; sceneX++) { + if (sceneX < work.minTile || sceneX >= work.maxTile || sceneY < work.minTile || sceneY >= work.maxTile) + continue; + + int x = OFFSET + sceneX; + int y = OFFSET + sceneY; + work.shadow[0][x][y] = BLANK_SHADOW; + + if (sceneX == originX && sceneX > 0) + work.heights[0][x][y] = work.heights[0][x - 1][y]; + if (sceneX == originX + width && sceneX < EXTENDED - 1) + work.heights[0][x][y] = work.heights[0][x + 1][y]; + if (sceneY == originY && sceneY > 0) + work.heights[0][x][y] = work.heights[0][x][y - 1]; + if (sceneY == originY + height && sceneY < EXTENDED - 1) + work.heights[0][x][y] = work.heights[0][x][y + 1]; + } + } + } + + /** + * Puts down everything the region has, so long as there is ground under it. + * + *

A region that has given up its far edge to make space keeps its locations there all the same, and + * a wall or a tree standing over the gap with nothing beneath it reads as a fault rather than a gap. + * So the same edge is kept off both. + */ + private void placeObjects(Work work, Region region, int originX, int originY, int drawnX, int drawnY, java.util.function.Predicate includeObjects) + throws IOException { + for (Location location : region.getLocations()) { + if (!includeObjects.test(location)) + continue; + Position position = location.getPosition(); + int localX = position.getX() - region.getBaseX(); + int localY = position.getY() - region.getBaseY(); + if (localX < 0 || localY < 0 || localX >= drawnX || localY >= drawnY) + continue; + + int sceneX = localX + originX; + int sceneY = localY + originY; + int plane = position.getZ(); + + if (sceneX <= work.minTile || sceneY <= work.minTile || sceneX >= work.maxTile - 1 || sceneY >= work.maxTile - 1) + continue; + if (plane < 0 || plane >= MAX_Z) + continue; + + placer.place(work, plane, sceneX, sceneY, location.getId(), location.getOrientation(), location.getType()); + } + } + + private void light(Work work, int plane) { + byte[][] shadow = work.shadow[plane]; + int[][] heights = work.heights[plane]; + + for (int y = 1; y < EXTENDED - 1; y++) { + for (int x = 1; x < EXTENDED - 1; x++) { + int slopeX = heights[x + 1][y] - heights[x - 1][y]; + int slopeY = heights[x][y + 1] - heights[x][y - 1]; + int length = (int) Math.sqrt(slopeX * slopeX + slopeY * slopeY + 65536); + + int normalX = (slopeX << 8) / length; + int normalY = 65536 / length; + int normalZ = (slopeY << 8) / length; + + int lit = (normalY * LIGHT_Y + normalX * LIGHT_X + normalZ * LIGHT_Z) / LIGHT_MAGNITUDE + AMBIENT_LIGHT; + int shaded = (shadow[x][y] >> 1) + + (shadow[x + 1][y] >> 3) + + (shadow[x][y - 1] >> 2) + + (shadow[x][y + 1] >> 3) + + (shadow[x - 1][y] >> 2); + + work.lightness[x][y] = lit - shaded; + } + } + } + + private void shade(Work work) { + for (int plane = 0; plane < MAX_Z; plane++) { + light(work, plane); + + int[] hues = new int[EXTENDED]; + int[] saturations = new int[EXTENDED]; + int[] lightnesses = new int[EXTENDED]; + int[] multipliers = new int[EXTENDED]; + int[] counts = new int[EXTENDED]; + + for (int x = -BLUR_RADIUS; x < EXTENDED + BLUR_RADIUS; x++) { + for (int y = 0; y < EXTENDED; y++) { + int entering = x + BLUR_RADIUS; + if (entering >= 0 && entering < EXTENDED) { + UnderlayDefinition underlay = underlayAt(work, plane, entering, y); + if (underlay != null) { + hues[y] += underlay.getHue(); + saturations[y] += underlay.getSaturation(); + lightnesses[y] += underlay.getLightness(); + multipliers[y] += underlay.getHueMultiplier(); + counts[y]++; + } + } + + int leaving = x - BLUR_RADIUS; + if (leaving >= 0 && leaving < EXTENDED) { + UnderlayDefinition underlay = underlayAt(work, plane, leaving, y); + if (underlay != null) { + hues[y] -= underlay.getHue(); + saturations[y] -= underlay.getSaturation(); + lightnesses[y] -= underlay.getLightness(); + multipliers[y] -= underlay.getHueMultiplier(); + counts[y]--; + } + } + } + + if (x < 1 || x >= EXTENDED - 1) + continue; + + int hue = 0, saturation = 0, lightness = 0, multiplier = 0, count = 0; + for (int y = -BLUR_RADIUS; y < EXTENDED + BLUR_RADIUS; y++) { + int entering = y + BLUR_RADIUS; + if (entering >= 0 && entering < EXTENDED) { + hue += hues[entering]; + saturation += saturations[entering]; + lightness += lightnesses[entering]; + multiplier += multipliers[entering]; + count += counts[entering]; + } + + int leaving = y - BLUR_RADIUS; + if (leaving >= 0 && leaving < EXTENDED) { + hue -= hues[leaving]; + saturation -= saturations[leaving]; + lightness -= lightnesses[leaving]; + multiplier -= multipliers[leaving]; + count -= counts[leaving]; + } + + if (y < 1 || y >= EXTENDED - 1) + continue; + + emit(work, plane, x, y, hue, saturation, lightness, multiplier, count); + } + } + } + } + + @Nullable + private UnderlayDefinition underlayAt(Work work, int plane, int x, int y) { + int id = work.underlayIds[plane][x][y] & 0x7FFF; + return id > 0 ? defs.underlay(id - 1) : null; + } + + private void emit(Work work, int plane, int x, int y, int hue, int saturation, int lightness, int multiplier, int count) { + int underlayId = work.underlayIds[plane][x][y] & 0x7FFF; + int overlayId = work.overlayIds[plane][x][y] & 0x7FFF; + if (underlayId == 0 && overlayId == 0) + return; + + int[][] heights = work.heights[plane]; + int southWestY = heights[x][y]; + int southEastY = heights[x + 1][y]; + int northEastY = heights[x + 1][y + 1]; + int northWestY = heights[x][y + 1]; + + int southWestLight = work.lightness[x][y]; + int southEastLight = work.lightness[x + 1][y]; + int northEastLight = work.lightness[x + 1][y + 1]; + int northWestLight = work.lightness[x][y + 1]; + + int underlayHsl = -1; + if (underlayId > 0 && count > 0 && multiplier > 0) + underlayHsl = packHsl(hue * 256 / multiplier, saturation / count, lightness / count); + + int underlayRgb = underlayHsl == -1 ? 0 : palette.toRgb(shadeUnderlay(underlayHsl, AMBIENT_LIGHT)); + + if (overlayId == 0) { + addTile( + work, plane, x, y, 0, 0, -1, + southWestY, southEastY, northEastY, northWestY, + shadeUnderlay(underlayHsl, southWestLight), + shadeUnderlay(underlayHsl, southEastLight), + shadeUnderlay(underlayHsl, northEastLight), + shadeUnderlay(underlayHsl, northWestLight), + 0, 0, 0, 0, + underlayRgb, 0 + ); + return; + } + + int shape = work.shapes[plane][x][y] + 1; + int rotation = work.rotations[plane][x][y]; + + OverlayDefinition overlay = defs.overlay(overlayId - 1); + int texture = overlay == null ? -1 : overlay.getTexture(); + + int overlayHsl; + int flatHsl; + if (texture >= 0) { + flatHsl = defs.textureColor(texture); + overlayHsl = -1; + } else if (overlay == null || overlay.getRgbColor() == HIDDEN_OVERLAY) { + overlayHsl = -2; + flatHsl = -2; + texture = -1; + } else { + overlayHsl = packHsl(overlay.getHue(), overlay.getSaturation(), overlay.getLightness()); + flatHsl = overlayHsl; + } + + int overlayRgb = flatHsl == -2 ? 0 : palette.toRgb(shadeOverlay(flatHsl, AMBIENT_LIGHT)); + if (overlay != null && overlay.getSecondaryRgbColor() != -1) { + int secondary = packHsl(overlay.getOtherHue(), overlay.getOtherSaturation(), overlay.getOtherLightness()); + overlayRgb = palette.toRgb(shadeOverlay(secondary, AMBIENT_LIGHT)); + } + + addTile( + work, plane, x, y, shape, rotation, texture, + southWestY, southEastY, northEastY, northWestY, + shadeUnderlay(underlayHsl, southWestLight), + shadeUnderlay(underlayHsl, southEastLight), + shadeUnderlay(underlayHsl, northEastLight), + shadeUnderlay(underlayHsl, northWestLight), + shadeOverlay(overlayHsl, southWestLight), + shadeOverlay(overlayHsl, southEastLight), + shadeOverlay(overlayHsl, northEastLight), + shadeOverlay(overlayHsl, northWestLight), + underlayRgb, overlayRgb + ); + } + + private void addTile( + Work work, int plane, int x, int y, int shape, int rotation, int texture, + int southWestY, int southEastY, int northEastY, int northWestY, + int southWestU, int southEastU, int northEastU, int northWestU, + int southWestO, int southEastO, int northEastO, int northWestO, + int underlayRgb, int overlayRgb + ) { + for (int below = plane; below >= 0; below--) + work.scene.tile(below, x, y); + + BuiltTile tile = work.scene.tile(plane, x, y); + + if (shape == 0) { + tile.setSceneTilePaint(new BuiltTilePaint( + southWestU, southEastU, northEastU, northWestU, -1, underlayRgb, false)); + } else if (shape == 1) { + boolean flat = southWestY == southEastY && southWestY == northEastY && southWestY == northWestY; + tile.setSceneTilePaint(new BuiltTilePaint( + southWestO, southEastO, northEastO, northWestO, texture, overlayRgb, flat)); + } else { + tile.setSceneTileModel(new BuiltTileModel( + shape, rotation, texture, x - OFFSET, y - OFFSET, + southWestY, southEastY, northEastY, northWestY, + southWestU, southEastU, northEastU, northWestU, + southWestO, southEastO, northEastO, northWestO, + underlayRgb, Math.max(1, overlayRgb) + )); + } + } + + private void linkBridges(Work work) { + for (int x = 0; x < EXTENDED; x++) { + for (int y = 0; y < EXTENDED; y++) { + if ((work.settings[1][x][y] & 2) != 2) + continue; + + BuiltScene scene = work.scene; + BuiltTile under = scene.tileOrNull(0, x, y); + + for (int plane = 0; plane < MAX_Z - 1; plane++) { + BuiltTile above = scene.tileOrNull(plane + 1, x, y); + scene.setTile(plane, x, y, above); + if (above != null) + above.setPlane(plane); + } + scene.setTile(MAX_Z - 1, x, y, null); + + if (under != null) + under.setPlane(MAX_Z - 1); + + for (int plane = 0; plane < MAX_Z; plane++) { + BuiltTile tile = scene.tileOrNull(plane, x, y); + if (tile != null) + tile.setOnBridge(true); + } + if (under != null) + under.setOnBridge(true); + + scene.tile(0, x, y).setBridge(under); + } + } + } + + public static int packHsl(int hue, int saturation, int lightness) { + if (lightness > 179) + saturation /= 2; + if (lightness > 192) + saturation /= 2; + if (lightness > 217) + saturation /= 2; + if (lightness > 243) + saturation /= 2; + return (hue / 4 << 10) + (saturation / 32 << 7) + lightness / 2; + } + + public static int shadeUnderlay(int hsl, int light) { + if (hsl == -1) + return NO_COLOR; + return applyLight(hsl, light); + } + + public static int shadeOverlay(int hsl, int light) { + if (hsl == -2) + return NO_COLOR; + if (hsl == -1) + return clampLight(light); + return applyLight(hsl, light); + } + + private static int applyLight(int hsl, int light) { + return (hsl & 0xFF80) + clampLight((hsl & 0x7F) * light / 128); + } + + private static int clampLight(int light) { + if (light < 2) + return 2; + return Math.min(light, 126); + } + + static final class Work { + final BuiltScene scene; + final int minTile, maxTile; + + final int[][][] heights; + final byte[][][] settings; + final short[][][] underlayIds; + final short[][][] overlayIds; + final byte[][][] shapes; + + final byte[][][] rotations = new byte[MAX_Z][EXTENDED][EXTENDED]; + final byte[][][] shadow = new byte[MAX_Z][HEIGHT_GRID][HEIGHT_GRID]; + final int[][] lightness = new int[HEIGHT_GRID][HEIGHT_GRID]; + final NormalMerger merger = new NormalMerger(); + final VariantOptions variants; + /** + * Whether models are bent to follow the ground they stand on. + * + *

Off for regions laid side by side. Bending reaches across tile corners, and the corner where + * two regions meet belongs to both of them while the ground either side of it does not, so anything + * standing near the join gets stretched between two unrelated landscapes. + */ + boolean hillskew = true; + /** Which region's locations are being placed, so their lighting does not reach into another's */ + int region; + /** Whether the regions are unrelated places laid side by side rather than real neighbours */ + boolean isolateRegions; + + Work(BuiltScene scene, int minTile, int maxTile, VariantOptions variants) { + this.scene = scene; + this.minTile = minTile; + this.maxTile = maxTile; + this.variants = variants; + heights = scene.getTileHeights(); + settings = scene.getExtendedTileSettings(); + underlayIds = scene.getUnderlayIds(); + overlayIds = scene.getOverlayIds(); + shapes = scene.getTileShapes(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java new file mode 100644 index 0000000..dacf09c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java @@ -0,0 +1,77 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nullable; + +public class VariantObject { + public static final class Placed { + public final int x, y, z; + public final int plane; + public final int sizeX, sizeY; + + public Placed(int x, int y, int z, int plane, int sizeX, int sizeY) { + this.x = x; + this.y = y; + this.z = z; + this.plane = plane; + this.sizeX = sizeX; + this.sizeY = sizeY; + } + } + + public final java.util.List placements = new java.util.ArrayList<>(); + + public final int baseId; + public final String name; + public int count; + public int appliedId = -1; + + public final boolean animated; + public final int animationId; + public final int[] variantIds; + public final String[] variantNames; + + @Nullable + public String gameval; + @Nullable + public String[] variantGamevals; + + VariantObject(int baseId, String name, int animationId, int[] variantIds, String[] variantNames) { + this.baseId = baseId; + this.name = name; + this.animationId = animationId; + this.animated = animationId != -1; + this.variantIds = variantIds; + this.variantNames = variantNames; + } + + public boolean hasVariants() { + return variantIds.length > 0; + } + + public int firstVisibleVariant() { + for (int i = 0; i < variantIds.length; i++) + if (variantIds[i] != -1) + return i; + return -1; + } + + @Nullable + public String variantLabel(int index) { + if (index < 0 || index >= variantNames.length) + return null; + String gameval = variantGamevals == null || index >= variantGamevals.length ? null : variantGamevals[index]; + return gameval == null ? variantNames[index] : gameval + " (" + variantIds[index] + ")"; + } + + public String label() { + String shown = name == null || name.isEmpty() || "null".equals(name) ? gameval : name; + if (shown == null || shown.isEmpty()) + shown = "Object"; + return shown + " (" + baseId + ") x" + count; + } + + @Override + public String toString() { + return label(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java new file mode 100644 index 0000000..c451151 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java @@ -0,0 +1,106 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nullable; +import net.runelite.cache.definitions.ObjectDefinition; + +public class VariantOptions { + public static final int HIDDEN = -1; + public static final int DEFAULT = -2; + + private final Map choices = new ConcurrentHashMap<>(); + private final Map found = new LinkedHashMap<>(); + + public int choiceFor(int baseId) { + return choices.getOrDefault(baseId, DEFAULT); + } + + public void setChoice(int baseId, int choice) { + choices.put(baseId, choice); + } + + public synchronized List getFound() { + var sorted = new ArrayList(); + for (VariantObject entry : found.values()) + if (entry.hasVariants()) + sorted.add(entry); + sorted.sort((a, b) -> b.count - a.count); + return sorted; + } + + synchronized void noteLocation(int baseId, int x, int y, int z, int plane, int sizeX, int sizeY) { + VariantObject entry = found.get(baseId); + if (entry != null) + entry.placements.add(new VariantObject.Placed(x, y, z, plane, sizeX, sizeY)); + } + + synchronized void startBuild() { + found.clear(); + } + + synchronized Resolution record(ObjectDefinition object, @Nullable ObjectDefinition[] variantDefs) { + int baseId = object.getId(); + VariantObject entry = found.get(baseId); + + if (entry == null) { + int[] variantIds = object.getConfigChangeDest() == null ? new int[0] : object.getConfigChangeDest(); + var names = new String[variantIds.length]; + for (int i = 0; i < variantIds.length; i++) { + if (variantIds[i] == -1) { + names[i] = "Nothing"; + } else { + ObjectDefinition def = variantDefs == null ? null : variantDefs[i]; + String name = def == null ? null : def.getName(); + boolean unnamed = name == null || name.isEmpty() || "null".equals(name); + names[i] = (unnamed ? "Form" : name) + " (" + variantIds[i] + ")"; + } + } + entry = new VariantObject(baseId, object.getName(), object.getAnimationID(), variantIds, names); + found.put(baseId, entry); + } + entry.count++; + + int choice = choiceFor(baseId); + if (choice == HIDDEN) { + entry.appliedId = -1; + return Resolution.HIDE; + } + + if (!entry.hasVariants()) { + entry.appliedId = baseId; + return Resolution.OWN_MODELS; + } + + int index = choice == DEFAULT ? entry.firstVisibleVariant() : choice; + if (index < 0 || index >= entry.variantIds.length) + index = entry.firstVisibleVariant(); + if (index < 0 || entry.variantIds[index] == -1) { + entry.appliedId = -1; + return Resolution.HIDE; + } + + entry.appliedId = entry.variantIds[index]; + return Resolution.variant(entry.appliedId); + } + + static final class Resolution { + static final Resolution HIDE = new Resolution(true, -1); + static final Resolution OWN_MODELS = new Resolution(false, -1); + + final boolean hidden; + final int modelObjectId; + + private Resolution(boolean hidden, int modelObjectId) { + this.hidden = hidden; + this.modelObjectId = modelObjectId; + } + + static Resolution variant(int objectId) { + return new Resolution(false, objectId); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java new file mode 100644 index 0000000..3abc7bc --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.awt.event.KeyEvent; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public final class FlyCamera { + private static final int ANGLE_UNITS = 16384; + private static final float RADIANS_PER_UNIT = (float) (2 * Math.PI / ANGLE_UNITS); + private static final int QUARTER_TURN = ANGLE_UNITS / 4; + + private static final float CLIENT_FRAMES_PER_SECOND = 50; + + private static final int NORMAL_SPEED = 12; + private static final int SLOW_SPEED = 6; + private static final int SPEED_FRACTION = 16; + private static final float SPEED_GAINED_PER_FRAME = 1 / 8f; + private static final float SPEED_KEPT_PER_FRAME = 0.9f; + + private static final float MIN_PITCH = 1 * RADIANS_PER_UNIT; + private static final float MAX_PITCH = 4160 * RADIANS_PER_UNIT; + + private static final int YAW_TURN_UNITS = 24 << 3; + private static final int PITCH_TURN_UNITS = 12 << 3; + private static final float TURN_GAP_CLOSED_PER_FRAME = 0.5f; + + private static final float DRAG_UNITS_PER_PIXEL = 8; + + private static final float MAX_STEP_SECONDS = 0.1f; + + private static final float VIEWING_DISTANCE = 6 * 128; + private static final float AIM_ABOVE_GROUND = 128; + + private final float[] position = new float[3]; + private float yaw, pitch = 1024 * RADIANS_PER_UNIT; + private float speed = 1; + + private final Set heldKeys = ConcurrentHashMap.newKeySet(); + + private float travelSpeed; + private int travelHeading = -1; + private int travelVertical; + private float yawSpeed, pitchSpeed; + + public float[] getPosition() { + return position; + } + + public float getYaw() { + return yaw; + } + + public float getPitch() { + return pitch; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + public void placeAt(float x, float y, float z, float yaw, float pitch) { + position[0] = x; + position[1] = y; + position[2] = z; + this.yaw = yaw; + this.pitch = clampPitch(pitch); + stop(); + } + + public void goTo(float x, float y, float z) { + float level = (float) Math.cos(pitch); + float forwardX = -(float) Math.sin(yaw) * level; + float forwardZ = (float) Math.cos(yaw) * level; + float forwardY = (float) Math.sin(pitch); + + float aimY = y - AIM_ABOVE_GROUND; + position[0] = x - forwardX * VIEWING_DISTANCE; + position[1] = aimY - forwardY * VIEWING_DISTANCE; + position[2] = z - forwardZ * VIEWING_DISTANCE; + stop(); + } + + private void stop() { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + yawSpeed = 0; + pitchSpeed = 0; + } + + public void keyPressed(int keyCode) { + heldKeys.add(keyCode); + } + + public void keyReleased(int keyCode) { + heldKeys.remove(keyCode); + } + + public void releaseEverything() { + heldKeys.clear(); + stop(); + } + + public void drag(int dx, int dy) { + turnUnits(-dx * DRAG_UNITS_PER_PIXEL, dy * DRAG_UNITS_PER_PIXEL); + } + + public void step(float seconds) { + if (seconds <= 0) + return; + + float frames = Math.min(seconds, MAX_STEP_SECONDS) * CLIENT_FRAMES_PER_SECOND; + turnWithKeys(frames); + travel(frames); + } + + + private void turnWithKeys(float frames) { + int wantedYaw = heldKeys.contains(KeyEvent.VK_LEFT) ? -YAW_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_RIGHT) ? YAW_TURN_UNITS : 0; + int wantedPitch = heldKeys.contains(KeyEvent.VK_UP) ? PITCH_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_DOWN) ? -PITCH_TURN_UNITS : 0; + + float closed = 1 - (float) Math.pow(1 - TURN_GAP_CLOSED_PER_FRAME, frames); + yawSpeed += (wantedYaw - yawSpeed) * closed; + pitchSpeed += (wantedPitch - pitchSpeed) * closed; + + turnUnits(yawSpeed / 2 * frames, pitchSpeed / 2 * frames); + } + + private void travel(float frames) { + int heading = headingOf(heldKeys); + int vertical = verticalOf(heldKeys); + + float wanted = 0; + if (heading >= 0 || vertical != 0) { + int perFrame = heldKeys.contains(KeyEvent.VK_CONTROL) ? SLOW_SPEED : NORMAL_SPEED; + wanted = perFrame * speed * SPEED_FRACTION; + travelHeading = heading; + travelVertical = vertical; + } + + if (travelSpeed < wanted) { + travelSpeed = Math.min(wanted, travelSpeed + wanted * SPEED_GAINED_PER_FRAME * frames); + } else if (travelSpeed > wanted) { + travelSpeed *= (float) Math.pow(SPEED_KEPT_PER_FRAME, frames); + if (travelSpeed < 1) { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + } + if (travelSpeed <= 0) + return; + + float distance = travelSpeed / SPEED_FRACTION * frames; + if (travelHeading >= 0) { + float angle = (travelHeading - yaw / RADIANS_PER_UNIT) * RADIANS_PER_UNIT; + position[0] += distance * (float) Math.sin(angle); + position[2] += distance * (float) Math.cos(angle); + } + position[1] += travelVertical * distance; + } + + static int headingOf(Set held) { + int heading = -1; + if (held.contains(KeyEvent.VK_W)) { + heading = 0; + } else if (held.contains(KeyEvent.VK_S)) { + heading = QUARTER_TURN * 2; + } + + if (held.contains(KeyEvent.VK_A)) { + heading = heading == 0 ? QUARTER_TURN * 7 / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 5 / 2 + : QUARTER_TURN * 3; + } else if (held.contains(KeyEvent.VK_D)) { + heading = heading == 0 ? QUARTER_TURN / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 3 / 2 + : QUARTER_TURN; + } + return heading; + } + + static int verticalOf(Set held) { + boolean up = held.contains(KeyEvent.VK_R) || held.contains(KeyEvent.VK_E) + || held.contains(KeyEvent.VK_SPACE); + boolean down = held.contains(KeyEvent.VK_F) || held.contains(KeyEvent.VK_Q) + || held.contains(KeyEvent.VK_SHIFT); + if (up == down) + return 0; + return up ? -1 : 1; + } + + private void turnUnits(float yawUnits, float pitchUnits) { + if (yawUnits == 0 && pitchUnits == 0) + return; + yaw += yawUnits * RADIANS_PER_UNIT; + pitch = clampPitch(pitch + pitchUnits * RADIANS_PER_UNIT); + } + + private static float clampPitch(float pitch) { + return Math.max(MIN_PITCH, Math.min(MAX_PITCH, pitch)); + } + + public static boolean isCameraKey(int keyCode) { + switch (keyCode) { + case KeyEvent.VK_W: + case KeyEvent.VK_A: + case KeyEvent.VK_S: + case KeyEvent.VK_D: + case KeyEvent.VK_Q: + case KeyEvent.VK_E: + case KeyEvent.VK_R: + case KeyEvent.VK_F: + case KeyEvent.VK_SPACE: + case KeyEvent.VK_SHIFT: + case KeyEvent.VK_CONTROL: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_UP: + case KeyEvent.VK_DOWN: + return true; + default: + return false; + } + } + + public String describe() { + return String.format( + "%.0f, %.0f, %.0f yaw %.0f° pitch %.0f°", + position[0], position[1], position[2], + Math.toDegrees(yaw) % 360, Math.toDegrees(pitch) + ); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java new file mode 100644 index 0000000..6a05083 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java @@ -0,0 +1,639 @@ +package rs117.hd.dev.sceneloader.standalone; + +import com.google.gson.Gson; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.name.Names; +import java.awt.Canvas; +import java.awt.Image; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Consumer; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.Projection; +import net.runelite.api.WorldView; +import net.runelite.api.events.BeforeRender; +import net.runelite.api.events.ClientTick; +import net.runelite.api.events.GameStateChanged; +import net.runelite.api.events.GameTick; +import net.runelite.api.hooks.DrawCallbacks; +import net.runelite.client.callback.ClientThread; +import net.runelite.client.callback.RenderCallbackManager; +import net.runelite.client.chat.ChatMessageManager; +import net.runelite.client.config.ConfigManager; +import net.runelite.client.events.ConfigChanged; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.input.KeyManager; +import net.runelite.client.input.MouseManager; +import net.runelite.client.plugins.Plugin; +import net.runelite.client.plugins.PluginManager; +import net.runelite.client.ui.ClientUI; +import net.runelite.client.ui.DrawManager; +import net.runelite.client.ui.components.colorpicker.ColorPickerManager; +import net.runelite.client.ui.overlay.OverlayManager; +import rs117.hd.HdPlugin; +import rs117.hd.HdPluginConfig; +import rs117.hd.overlays.FrameTimer; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.renderer.Renderer; +import rs117.hd.renderer.zone.ZoneRenderer; + +import static net.runelite.api.Constants.MAX_Z; +import static rs117.hd.renderer.zone.SceneManager.NUM_ZONES; +import rs117.hd.dev.sceneloader.standalone.client.CacheTextureProvider; +import rs117.hd.dev.sceneloader.standalone.client.Fake; +import rs117.hd.dev.sceneloader.standalone.client.FakeClient; +import rs117.hd.dev.sceneloader.standalone.client.FakeObjects; + +@Slf4j +public final class HdRuntime { + private final Canvas canvas; + private final Definitions defs; + private final Textures textures; + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + var thread = new Thread(runnable, "117 HD standalone"); + thread.setDaemon(true); + return thread; + }); + + private final FakeClient clientState; + private final Client client; + private final InlineClientThread clientThread = new InlineClientThread(); + private final EventBus eventBus = new EventBus(); + private final PreviewDrawManager drawManager = new PreviewDrawManager(); + private final HdSettings settings; + + private Injector injector; + private HdPlugin plugin; + + @Nullable + private BuiltScene scene; + @Nullable + private Renderer handedTo; + + private int level; + private boolean planesBelow = true; + private boolean showRoofs; + private Set roofIds = Set.of(); + + public HdRuntime(Canvas canvas, Definitions defs, Textures textures, HdSettings settings) { + this.canvas = canvas; + this.defs = defs; + this.textures = textures; + this.settings = settings; + + var provider = new CacheTextureProvider(defs, textures); + clientState = new FakeClient(canvas, provider.asProvider(), new FakeObjects(defs)); + client = Fake.of(Client.class, clientState); + } + + public HdPlugin getPlugin() { + return plugin; + } + + public rs117.hd.scene.GamevalManager.Handle openGamevals() { + return injector.getInstance(rs117.hd.scene.GamevalManager.class).obtainHandle(); + } + + public Gson getGson() { + return rs117.hd.utils.GsonUtils.wrap(injector.getInstance(Gson.class)); + } + + public FrameTimer frameTimer() { + return injector.getInstance(FrameTimer.class); + } + + public void nextFrameTo(Consumer whenDrawn) { + drawManager.previewFrame = whenDrawn; + } + + /** Preview captures run on the renderer thread. Replace a request if its draw was skipped. */ + private static final class PreviewDrawManager extends DrawManager { + private Consumer previewFrame; + + @Override + public void processDrawComplete(java.util.function.Supplier capture) { + var listener = previewFrame; + previewFrame = null; + if (listener != null) + requestNextFrameListener(listener); + super.processDrawComplete(capture); + } + } + + public boolean isReady() { + return plugin != null && plugin.renderer != null && clientThread.watchedFinished(); + } + + public void setLevels(int level, boolean planesBelow, boolean showRoofs) { + this.level = Math.max(0, Math.min(MAX_Z - 1, level)); + this.planesBelow = planesBelow; + this.showRoofs = showRoofs; + } + + public void start() throws Exception { + Thread owner = Thread.currentThread(); + clientState.ownedBy(owner); + clientThread.ownedBy(owner); + + plugin = previewSkyEnabled ? new HdPlugin() { + @Override public void drawUi(int overlayColor) { + if (previewWireframe) + polygonMode(org.lwjgl.opengl.GL11.GL_FILL); + super.drawUi(overlayColor); + } + } : new HdPlugin(); + injector = Guice.createInjector(new Bindings()); + injector.injectMembers(plugin); + + var injectorField = Plugin.class.getDeclaredField("injector"); + injectorField.setAccessible(true); + injectorField.set(plugin, injector); + + eventBus.register(plugin); + settings.whenChanged(this::settingChanged); + + var startUp = HdPlugin.class.getDeclaredMethod("startUp"); + startUp.setAccessible(true); + clientThread.watchNext(); + startUp.invoke(plugin); + + eventBus.post(gameStateChanged(GameState.LOGGED_IN)); + } + + private void settingChanged(String key) { + var event = new ConfigChanged(); + event.setGroup(HdPluginConfig.CONFIG_GROUP); + event.setKey(key); + eventBus.post(event); + } + + public void stop() { + if (plugin == null) + return; + try { + var shutDown = HdPlugin.class.getDeclaredMethod("shutDown"); + shutDown.setAccessible(true); + shutDown.invoke(plugin); + } catch (Exception ex) { + log.warn("Could not stop the plugin cleanly", ex); + } + executor.shutdownNow(); + } + + public void setScene(@Nullable BuiltScene scene) { + this.scene = scene; + handedTo = null; + roofIds = scene == null ? Set.of() : roofIdsOf(scene); + clientState.setScene(scene); + } + + /** Swap out the top-level renderer's scene so its terrain buffers can be released. */ + public void releasePreviewScene(BuiltScene empty) { + nextFrameTo(null); + setPreviewModel(null, null, null); + setPreviewOverride(null, null); + setScene(empty); + if (isReady()) { + var renderer = plugin.renderer; + handOver(renderer, empty); + handedTo = renderer; + } + } + + private final PreviewTerrain previewTerrain = new PreviewTerrain(); + private rs117.hd.scene.water_types.WaterType[] previewWaterTypes; + + private static final class PreviewTerrain extends rs117.hd.scene.ProceduralGenerator { + volatile rs117.hd.scene.water_types.WaterType water; + String sourceName; + + @Override public rs117.hd.scene.water_types.WaterType seasonalWaterType( + rs117.hd.scene.tile_overrides.TileOverride override, int textureId + ) { + var original = super.seasonalWaterType(override, textureId); + var selected = water; + return selected == null || original == null || original == rs117.hd.scene.water_types.WaterType.NONE + || (sourceName != null && !sourceName.equals(original.name)) ? original : selected; + } + } + + public rs117.hd.scene.TileOverrideManager tileOverrides() { + return injector.getInstance(rs117.hd.scene.TileOverrideManager.class); + } + + public rs117.hd.scene.ProceduralGenerator terrain() { return previewTerrain; } + + public void setPreviewWater(String json, String sourceName) { + var manager = injector.getInstance(rs117.hd.scene.WaterTypeManager.class); + // The existing uniform buffer retains this array. Reuse a water slot + // while the Definitions scene is active so drafts also work before saving. + if (previewWaterTypes != null) { + if (previewWaterTypes == rs117.hd.scene.WaterTypeManager.WATER_TYPES) + manager.uboWaterTypes.update(); + previewWaterTypes = null; + } + previewTerrain.water = null; + if (json == null) + return; + var selected = getGson().fromJson(json, rs117.hd.scene.water_types.WaterType.class); + var types = rs117.hd.scene.WaterTypeManager.WATER_TYPES; + if (types.length < 2) + throw new IllegalStateException("Water types are unavailable"); + // Keep the slot stable when switching definitions so existing terrain vertices stay valid. + int index = 1; + if (sourceName != null) { + for (int i = 1; i < types.length; i++) { + if (sourceName.equals(types[i].name)) { + index = i; + break; + } + } + } + var materials = injector.getInstance(rs117.hd.scene.MaterialManager.class); + selected.normalize(index, materials.getMaterial("WATER_NORMAL_MAP_1")); + previewWaterTypes = types; + var original = types[index]; + types[index] = selected; + try { + manager.uboWaterTypes.update(); + } finally { + types[index] = original; + } + previewTerrain.sourceName = sourceName; + previewTerrain.water = selected; + } + + public void isolatePreviewWater(BuiltScene scene, String sourceName) { + var overrides = tileOverrides(); + var tiles = scene.getExtendedTiles(); + int[] position = new int[3]; + int[] ids = new int[2]; + for (int plane = 0; plane < tiles.length; plane++) { + position[2] = plane; + for (int x = 0; x < tiles[plane].length; x++) { + position[0] = scene.getBaseX() + x - BuiltScene.SCENE_OFFSET; + for (int y = 0; y < tiles[plane][x].length; y++) { + var tile = tiles[plane][x][y]; + if (tile == null) + continue; + position[1] = scene.getBaseY() + y - BuiltScene.SCENE_OFFSET; + ids[0] = rs117.hd.scene.tile_overrides.TileOverride.OVERLAY_FLAG | scene.getOverlayIds()[plane][x][y]; + ids[1] = scene.getUnderlayIds()[plane][x][y]; + var paint = tile.getSceneTilePaint(); + var model = tile.getSceneTileModel(); + var rule = overrides.getOverrideBeforeReplacements(position, ids); + boolean keep = matchesPreviewWater(rule, paint == null ? -1 : paint.getTexture(), sourceName); + if (!keep && model != null && model.getTriangleTextureId() != null) + for (int texture : model.getTriangleTextureId()) + if (matchesPreviewWater(rs117.hd.scene.tile_overrides.TileOverride.NONE, texture, sourceName)) { + keep = true; + break; + } + if (!keep) + scene.removeTile(tile); + } + } + } + } + + private boolean matchesPreviewWater(rs117.hd.scene.tile_overrides.TileOverride rule, int texture, String name) { + var water = previewTerrain.seasonalWaterType(rule, texture); + return water != null && water != rs117.hd.scene.water_types.WaterType.NONE && (name == null || name.equals(water.name)); + } + + public boolean previewWaterNeedsRefresh() { + return previewWaterTypes != rs117.hd.scene.WaterTypeManager.WATER_TYPES; + } + + private final PreviewOverrides previewOverrides = new PreviewOverrides(); + + private static final class PreviewOverrides extends rs117.hd.scene.ModelOverrideManager { + private Integer uuid; + private rs117.hd.scene.model_overrides.ModelOverride override; + + @Override + public rs117.hd.scene.model_overrides.ModelOverride getOverride(int id, int[] worldPos) { + if (uuid != null && uuid == rs117.hd.utils.ModelHash.getUuidWithoutSubType(id)) + return override; + return super.getOverride(id, worldPos); + } + } + + /** Overrides only the inspected entity, leaving normal scene lookup intact. */ + private final PreviewSky previewSky = new PreviewSky(); + private boolean previewSkyEnabled; + private boolean previewWireframe; + + public void setPreviewSky(int color) { + previewSkyEnabled = true; + previewSky.showSky = false; + previewSky.neutralColor = color; + } + + private static final class PreviewSky extends rs117.hd.renderer.SkyRenderer { + boolean showSky; + int neutralColor; + @Override public boolean shouldRender(boolean hasVanillaSkybox) { + return showSky && super.shouldRender(hasVanillaSkybox); + } + @Override public void clear(boolean hasVanillaSkybox) { + super.clear(hasVanillaSkybox); + if (!showSky) { + org.lwjgl.opengl.GL11.glClearColor((neutralColor >> 16 & 255) / 255f, (neutralColor >> 8 & 255) / 255f, + (neutralColor & 255) / 255f, 1); + org.lwjgl.opengl.GL11.glClear(org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT); + } + } + } + + public void setPreviewPass(boolean showSky, boolean wireframe) { + previewSky.showSky = showSky; + previewWireframe = wireframe; + } + + public void setPreviewOverride(Integer uuid, rs117.hd.scene.model_overrides.ModelOverride override) { + previewOverrides.uuid = uuid; + previewOverrides.override = override; + } + + private PreviewModel preview; + + private static final class PreviewModel { + final net.runelite.api.TileObject tile; + final net.runelite.api.Renderable renderable; + final net.runelite.api.Model model; + + PreviewModel(net.runelite.api.TileObject tile, net.runelite.api.Renderable renderable, net.runelite.api.Model model) { + this.tile = tile; + this.renderable = renderable; + this.model = model; + } + } + + /** Installs a cache preview model on the renderer thread. */ + public void setPreviewModel(net.runelite.api.TileObject tile, net.runelite.api.Renderable renderable, net.runelite.api.Model model) { + preview = model == null ? null : new PreviewModel(tile, renderable, model); + } + + public void frame(float[] cameraPosition, float yaw, float pitch) { + frame(cameraPosition, yaw, pitch, false); + } + + /** Draws the inspected model in the editor's empty preview scene. */ + public void frameModelPreview(float[] cameraPosition, float yaw, float pitch) { + frame(cameraPosition, yaw, pitch, true); + } + + private void frame(float[] cameraPosition, float yaw, float pitch, boolean modelOnly) { + clientThread.runPending(); + clientState.sizeUi(Math.max(1, canvas.getWidth()), Math.max(1, canvas.getHeight())); + clientState.setCamera(cameraPosition, yaw, pitch, level); + clientState.tick(); + + eventBus.post(new ClientTick()); + eventBus.post(new BeforeRender()); + + if (!isReady()) + return; + + Renderer renderer = plugin.renderer; + var scene = this.scene; + if (scene == null) { + renderer.draw(0); + return; + } + + if (handedTo != renderer) { + handOver(renderer, scene); + handedTo = renderer; + } + + if (clientState.getGameCycle() % 30 == 0) + eventBus.post(new GameTick()); + + Projection projection = renderer instanceof ZoneRenderer ? ((ZoneRenderer) renderer).sceneCamera : null; + int minLevel = planesBelow ? 0 : level; + var hiddenRoofs = showRoofs ? Set.of() : roofIds; + + renderer.preSceneDraw( + scene, null, + cameraPosition[0], cameraPosition[1], cameraPosition[2], pitch, yaw, + minLevel, level, MAX_Z - 1, hiddenRoofs + ); + + if (plugin.sceneViewport != null) { + if (!modelOnly) + drawDynamics(renderer, projection, scene, minLevel, hiddenRoofs); + if (preview != null && projection != null) + renderer.drawDynamic(-1, projection, scene, preview.tile, preview.renderable, preview.model, preview.tile instanceof net.runelite.api.GameObject ? ((net.runelite.api.GameObject) preview.tile).getOrientation() : 0, + preview.tile.getX(), preview.tile.getZ(), preview.tile.getY()); + + if (!modelOnly) { + for (int zx = 0; zx < NUM_ZONES; zx++) + for (int zz = 0; zz < NUM_ZONES; zz++) + renderer.drawZoneOpaque(projection, scene, zx, zz); + } + renderer.drawPass(projection, scene, DrawCallbacks.PASS_OPAQUE); + + renderer.drawPass(projection, scene, DrawCallbacks.PRE_PASS_ALPHA); + if (modelOnly) { + if (preview != null && projection != null) { + // Transparent preview faces are stored in the model's zone. + int zoneOffset = BuiltScene.SCENE_OFFSET >> 3; + int zx = (preview.tile.getX() >> 10) + zoneOffset; + int zz = (preview.tile.getY() >> 10) + zoneOffset; + PreviewZoneAccess.drawAlpha((ZoneRenderer) renderer, projection, scene, preview.tile.getPlane(), zx, zz); + } + } else { + int[] order = zonesFurthestFirst(cameraPosition); + for (int at = minLevel; at < MAX_Z; at++) + for (int zone : order) + renderer.drawZoneAlpha(projection, scene, at, zone >> 8, zone & 0xFF); + } + renderer.drawPass(projection, scene, DrawCallbacks.PASS_ALPHA); + + renderer.postSceneDraw(scene); + } + + if (previewWireframe) + polygonMode(org.lwjgl.opengl.GL11.GL_LINE); + try { + renderer.draw(0); + } finally { + if (previewWireframe) + polygonMode(org.lwjgl.opengl.GL11.GL_FILL); + } + } + + private static void polygonMode(int mode) { + org.lwjgl.opengl.GL11.glPolygonMode(org.lwjgl.opengl.GL11.GL_FRONT_AND_BACK, mode); + } + + private void handOver(Renderer renderer, BuiltScene scene) { + WorldView worldView = client.getTopLevelWorldView(); + if (renderer instanceof ZoneRenderer) { + var previous = ((ZoneRenderer) renderer).getSceneContext(); + // An empty preview scene can otherwise seed the next terrain build with a zero-sized buffer. + if (previous != null && previous.vertexTerrainNormals != null && previous.vertexTerrainNormals.length == 0) + previous.vertexTerrainNormals = null; + } + renderer.loadScene(worldView, scene); + renderer.swapScene(scene); + + for (int x = 0; x < NUM_ZONES; x++) + for (int z = 0; z < NUM_ZONES; z++) + renderer.invalidateZone(scene, x, z); + + log.debug("Handed over a scene at {}, {}", scene.getBaseX(), scene.getBaseY()); + } + + private void drawDynamics( + Renderer renderer, @Nullable Projection projection, BuiltScene scene, + int minLevel, Set hiddenRoofs + ) { + if (projection == null || scene.getDynamics().isEmpty()) + return; + + int cycle = clientState.getGameCycle(); + int[][][] roofs = scene.getRoofs(); + + for (var dynamic : scene.getDynamics()) { + if (!isShown(dynamic, roofs, minLevel, hiddenRoofs)) + continue; + + var model = dynamic.renderable.modelAt(cycle); + if (model == null) + continue; + renderer.drawDynamic( + -1, projection, scene, dynamic.tileObject, dynamic.renderable, model, + dynamic.orientation, dynamic.x, dynamic.y, dynamic.z + ); + } + } + + private boolean isShown(BuiltScene.Dynamic dynamic, int[][][] roofs, int minLevel, Set hiddenRoofs) { + int objectLevel = dynamic.tileObject.getPlane(); + if (objectLevel < minLevel) + return false; + if (objectLevel <= level || objectLevel >= MAX_Z || hiddenRoofs.isEmpty()) + return true; + + int tileX = (dynamic.x >> 7) + BuiltScene.SCENE_OFFSET; + int tileZ = (dynamic.z >> 7) + BuiltScene.SCENE_OFFSET; + var plan = roofs[objectLevel]; + if (tileX < 0 || tileX >= plan.length || tileZ < 0 || tileZ >= plan[tileX].length) + return true; + + int roofId = plan[tileX][tileZ]; + return roofId == 0 || !hiddenRoofs.contains(roofId); + } + + private int[] zoneOrder; + private long[] zoneDistance; + + private float sortedCameraX = Float.NaN; + private float sortedCameraZ = Float.NaN; + + private int[] zonesFurthestFirst(float[] cameraPosition) { + if (zoneOrder != null && cameraPosition[0] == sortedCameraX && cameraPosition[2] == sortedCameraZ) + return zoneOrder; + sortedCameraX = cameraPosition[0]; + sortedCameraZ = cameraPosition[2]; + int count = NUM_ZONES * NUM_ZONES; + if (zoneOrder == null) { + zoneOrder = new int[count]; + zoneDistance = new long[count]; + } + + int offset = BuiltScene.SCENE_OFFSET; + for (int zx = 0, at = 0; zx < NUM_ZONES; zx++) { + for (int zz = 0; zz < NUM_ZONES; zz++, at++) { + float x = (zx * 8 - offset) * 128 + 512; + float z = (zz * 8 - offset) * 128 + 512; + float dx = x - cameraPosition[0]; + float dz = z - cameraPosition[2]; + zoneOrder[at] = zx << 8 | zz; + zoneDistance[at] = (long) (dx * dx + dz * dz); + } + } + + for (int i = 1; i < count; i++) { + int zone = zoneOrder[i]; + long distance = zoneDistance[i]; + int j = i - 1; + while (j >= 0 && zoneDistance[j] < distance) { + zoneOrder[j + 1] = zoneOrder[j]; + zoneDistance[j + 1] = zoneDistance[j]; + j--; + } + zoneOrder[j + 1] = zone; + zoneDistance[j + 1] = distance; + } + return zoneOrder; + } + + private static Set roofIdsOf(BuiltScene scene) { + var ids = new HashSet(); + for (int[][] plane : scene.getRoofs()) + for (int[] column : plane) + for (int roofId : column) + if (roofId > 0) + ids.add(roofId); + return ids; + } + + private static GameStateChanged gameStateChanged(GameState state) { + var event = new GameStateChanged(); + event.setGameState(state); + return event; + } + + private final class Bindings extends AbstractModule { + @Override + protected void configure() { + bind(HdPlugin.class).toInstance(plugin); + bind(Client.class).toInstance(client); + bind(rs117.hd.scene.ModelOverrideManager.class).toInstance(previewOverrides); + if (previewSkyEnabled) + bind(rs117.hd.scene.ProceduralGenerator.class).toInstance(previewTerrain); + if (previewSkyEnabled) + bind(rs117.hd.renderer.SkyRenderer.class).toInstance(previewSky); + + bindConstant().annotatedWith(Names.named("developerMode")).to(true); + bindConstant().annotatedWith(Names.named("safeMode")).to(false); + bindConstant().annotatedWith(Names.named("disableTelemetry")).to(true); + bindConstant().annotatedWith(Names.named("insecureWriteCredentials")).to(false); + bind(ClientThread.class).toInstance(clientThread); + bind(EventBus.class).toInstance(eventBus); + bind(DrawManager.class).toInstance(drawManager); + bind(RenderCallbackManager.class).toInstance(new RenderCallbackManager()); + bind(HdPluginConfig.class).toInstance(settings.asConfig()); + bind(Gson.class).toInstance(new Gson()); + bind(ScheduledExecutorService.class).toInstance(executor); + + bind(ConfigManager.class).toInstance(nothing(ConfigManager.class)); + bind(ClientUI.class).toInstance(nothing(ClientUI.class)); + + var plugins = nothing(PluginManager.class); + org.mockito.Mockito.when(plugins.isPluginEnabled(org.mockito.ArgumentMatchers.any())).thenReturn(true); + bind(PluginManager.class).toInstance(plugins); + bind(OverlayManager.class).toInstance(nothing(OverlayManager.class)); + bind(KeyManager.class).toInstance(nothing(KeyManager.class)); + bind(MouseManager.class).toInstance(nothing(MouseManager.class)); + bind(ColorPickerManager.class).toInstance(nothing(ColorPickerManager.class)); + bind(ChatMessageManager.class).toInstance(nothing(ChatMessageManager.class)); + } + } + + private static T nothing(Class type) { + return org.mockito.Mockito.mock(type); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java new file mode 100644 index 0000000..76f3df0 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java @@ -0,0 +1,104 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.HdPluginConfig; +import rs117.hd.dev.sceneloader.standalone.client.Fake; + +@Slf4j +public final class HdSettings { + private final Map values = new ConcurrentHashMap<>(); + private final HdPluginConfig config; + + @Nullable + private volatile Consumer listener; + + public HdSettings() { + config = (HdPluginConfig) Proxy.newProxyInstance( + HdPluginConfig.class.getClassLoader(), + new Class[] { HdPluginConfig.class }, + this::answer + ); + } + + public HdPluginConfig asConfig() { + return config; + } + + public void whenChanged(Consumer listener) { + this.listener = listener; + } + + public void set(String name, String value) { + values.put(name, value); + } + + public void change(String name, String key, String value) { + values.put(name, value); + var told = listener; + if (told != null) + told.accept(key); + } + + private Object answer(Object proxy, Method method, Object[] args) throws Throwable { + String asked = values.get(method.getName()); + if (asked != null && method.getParameterCount() == 0) { + Object value = read(method.getReturnType(), asked); + if (value != null) + return value; + log.warn("Could not read {} as a {}", asked, method.getReturnType().getSimpleName()); + } + + if (method.isDefault()) + return Fake.callDefault(proxy, method, args); + + switch (method.getName()) { + case "toString": + if (method.getParameterCount() == 0) + return "HdPluginConfig(defaults)"; + break; + case "equals": + if (method.getParameterCount() == 1) + return proxy == args[0]; + break; + case "hashCode": + if (method.getParameterCount() == 0) + return System.identityHashCode(proxy); + break; + default: + break; + } + + return Fake.blank(method.getReturnType()); + } + + @Nullable + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Object read(Class wanted, String value) { + try { + if (wanted.isEnum()) + return Enum.valueOf((Class) wanted, value.toUpperCase()); + if (wanted == boolean.class || wanted == Boolean.class) + return Boolean.parseBoolean(value); + if (wanted == int.class || wanted == Integer.class) + return Integer.parseInt(value); + if (wanted == long.class || wanted == Long.class) + return Long.parseLong(value); + if (wanted == float.class || wanted == Float.class) + return Float.parseFloat(value); + if (wanted == double.class || wanted == Double.class) + return Double.parseDouble(value); + if (wanted == String.class) + return value; + } catch (IllegalArgumentException ex) { + return null; + } + return null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java new file mode 100644 index 0000000..5618b24 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java @@ -0,0 +1,106 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; +import lombok.extern.slf4j.Slf4j; +import net.runelite.client.callback.ClientThread; + +@Slf4j +public final class InlineClientThread extends ClientThread { + private final List pending = new ArrayList<>(); + private volatile Thread owner; + + private boolean watching; + private volatile boolean watchedFinished; + + public void ownedBy(Thread owner) { + this.owner = owner; + } + + public void watchNext() { + watching = true; + watchedFinished = false; + } + + public boolean watchedFinished() { + return watchedFinished; + } + + @Override + public void invoke(Runnable runnable) { + invoke(() -> { + runnable.run(); + return true; + }); + } + + @Override + public void invoke(BooleanSupplier work) { + BooleanSupplier watched = watch(work); + if (Thread.currentThread() != owner) { + invokeLater(watched); + return; + } + if (!watched.getAsBoolean()) + invokeLater(watched); + } + + private BooleanSupplier watch(BooleanSupplier work) { + if (!watching) + return work; + watching = false; + return () -> { + boolean finished = work.getAsBoolean(); + if (finished) + watchedFinished = true; + return finished; + }; + } + + @Override + public void invokeLater(Runnable runnable) { + invokeLater(() -> { + runnable.run(); + return true; + }); + } + + @Override + public void invokeLater(BooleanSupplier work) { + synchronized (pending) { + pending.add(work); + } + } + + @Override + public void invokeAtTickEnd(Runnable runnable) { + invokeLater(runnable); + } + + public void runPending() { + List due; + synchronized (pending) { + if (pending.isEmpty()) + return; + due = new ArrayList<>(pending); + pending.clear(); + } + + var again = new ArrayList(); + for (BooleanSupplier work : due) { + try { + if (!work.getAsBoolean()) + again.add(work); + } catch (Throwable ex) { + log.warn("Something the plugin put off went wrong", ex); + } + } + + if (!again.isEmpty()) { + synchronized (pending) { + pending.addAll(again); + } + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/PreviewZoneAccess.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/PreviewZoneAccess.java new file mode 100644 index 0000000..f282dae --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/PreviewZoneAccess.java @@ -0,0 +1,72 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import net.runelite.api.Projection; +import net.runelite.api.Scene; +import rs117.hd.renderer.zone.SceneManager; +import rs117.hd.renderer.zone.WorldViewContext; +import rs117.hd.renderer.zone.Zone; +import rs117.hd.renderer.zone.ZoneRenderer; + +/** Keeps the editor's isolated alpha pass on the existing RLHD renderer. */ +final class PreviewZoneAccess { + private static final Field SCENE_MANAGER = field(ZoneRenderer.class, "sceneManager"); + private static final Field ZONES = field(WorldViewContext.class, "zones"); + private static final Field ALPHA_MODELS = field(Zone.class, "alphaModels"); + private static final Method IS_TEMP = method(Zone.AlphaModel.class, "isTemp"); + // Reused across calls instead of allocating a new list every frame; always drained before returning, + // and rendering happens on a single thread, so there's no overlap between calls. + private static final List hidden = new ArrayList<>(); + + static void drawAlpha(ZoneRenderer renderer, Projection projection, Scene scene, int level, int x, int z) { + try { + var context = ((SceneManager) SCENE_MANAGER.get(renderer)).getContext(scene); + if (context == null) + return; + var zone = ((Zone[][]) ZONES.get(context))[x][z]; + @SuppressWarnings("unchecked") + var models = (List) ALPHA_MODELS.get(zone); + boolean hasWater = zone.hasWater; + try { + for (var iterator = models.iterator(); iterator.hasNext();) { + var model = iterator.next(); + if (!(boolean) IS_TEMP.invoke(model)) { + hidden.add(model); + iterator.remove(); + } + } + zone.hasWater = false; + renderer.drawZoneAlpha(projection, scene, level, x, z); + } finally { + models.addAll(hidden); + hidden.clear(); + zone.hasWater = hasWater; + } + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not isolate the preview zone", e); + } + } + + private static Field field(Class owner, String name) { + try { + var field = owner.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not access " + name, e); + } + } + + private static Method method(Class owner, String name) { + try { + var method = owner.getDeclaredMethod(name); + method.setAccessible(true); + return method; + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Could not access " + name, e); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java new file mode 100644 index 0000000..d30b286 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java @@ -0,0 +1,95 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.cache.SpriteManager; +import net.runelite.cache.definitions.SpriteDefinition; +import net.runelite.cache.definitions.TextureDefinition; +import net.runelite.cache.definitions.providers.SpriteProvider; +import rs117.hd.dev.sceneloader.scene.Definitions; + +@Slf4j +public final class Textures { + public static final int SIZE = 128; + + private final Definitions defs; + private final SpriteManager sprites; + private final Map> atBrightness = new LinkedHashMap>(4, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry> eldest) { + return size() > 2; + } + }; + + public Textures(Definitions defs) throws IOException { + this.defs = defs; + sprites = new SpriteManager(defs.getStore()); + sprites.load(); + } + + @Nullable + public synchronized int[] get(int textureId, double brightness) { + var byId = atBrightness.computeIfAbsent(brightness, b -> new LinkedHashMap<>()); + int[] cached = byId.get(textureId); + if (cached != null || byId.containsKey(textureId)) + return cached; + + int[] built = null; + try { + built = build(textureId, brightness); + } catch (Exception | Error ex) { + log.debug("Ignoring texture {}, which would not build", textureId, ex); + } + byId.put(textureId, built); + return built; + } + + @Nullable + private int[] build(int textureId, double brightness) { + TextureDefinition texture = defs.texture(textureId); + if (texture == null) + return null; + + var lender = new Lender(); + try { + texture.method2680(brightness, SIZE, lender); + return texture.pixels == null ? null : texture.pixels.clone(); + } finally { + lender.putBack(); + texture.pixels = null; + } + } + + public List ids() { + var ids = new ArrayList(); + for (var texture : defs.textures()) + ids.add(texture.getId()); + return ids; + } + + private final class Lender implements SpriteProvider { + private final List lent = new ArrayList<>(); + private final List palettes = new ArrayList<>(); + + @Override + public SpriteDefinition provide(int spriteId, int frameId) { + SpriteDefinition sprite = sprites.findSprite(spriteId, frameId); + if (sprite != null && sprite.palette != null) { + lent.add(sprite); + palettes.add(sprite.palette.clone()); + } + return sprite; + } + + void putBack() { + for (int i = 0; i < lent.size(); i++) { + int[] was = palettes.get(i); + System.arraycopy(was, 0, lent.get(i).palette, 0, was.length); + } + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java new file mode 100644 index 0000000..6899161 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java @@ -0,0 +1,97 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import javax.annotation.Nullable; +import net.runelite.api.Texture; +import net.runelite.api.TextureProvider; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.HslPalette; +import rs117.hd.dev.sceneloader.standalone.Textures; + +public final class CacheTextureProvider { + private final Definitions defs; + private final Textures textures; + + private final Texture[] byId; + private double brightness = HslPalette.DEFAULT_BRIGHTNESS; + + public CacheTextureProvider(Definitions defs, Textures textures) { + this.defs = defs; + this.textures = textures; + + int highest = 0; + for (int id : textures.ids()) + highest = Math.max(highest, id); + + byId = new Texture[highest + 1]; + for (int id : textures.ids()) + byId[id] = Fake.of(Texture.class, new OneTexture(id)); + } + + public TextureProvider asProvider() { + return Fake.of(TextureProvider.class, this); + } + + public double getBrightness() { + return brightness; + } + + public void setBrightness(double brightness) { + this.brightness = brightness; + } + + public Texture[] getTextures() { + return byId; + } + + @Nullable + public int[] load(int id) { + return textures.get(id, brightness); + } + + public int getDefaultColor(int id) { + return defs.textureColor(id); + } + + private final class OneTexture { + private final int id; + private float u, v; + + OneTexture(int id) { + this.id = id; + } + + public int[] getPixels() { + return load(id); + } + + public int getAnimationDirection() { + var definition = defs.texture(id); + return definition == null ? 0 : definition.animationDirection; + } + + public int getAnimationSpeed() { + var definition = defs.texture(id); + return definition == null ? 0 : definition.animationSpeed; + } + + public boolean isLoaded() { + return true; + } + + public float getU() { + return u; + } + + public void setU(float u) { + this.u = u; + } + + public float getV() { + return v; + } + + public void setV(float v) { + this.v = v; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java new file mode 100644 index 0000000..82c7f81 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java @@ -0,0 +1,137 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.lang.invoke.MethodHandles; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +public final class Fake { + private Fake() {} + + @SuppressWarnings("unchecked") + public static T of(Class wanted, Object answers) { + var byName = new HashMap(); + for (Method method : answers.getClass().getMethods()) + if (method.getDeclaringClass() != Object.class) + byName.putIfAbsent(key(method), method); + + return (T) Proxy.newProxyInstance( + wanted.getClassLoader(), + new Class[] { wanted }, + new Answers(wanted, answers, byName) + ); + } + + private static String key(Method method) { + return method.getName() + "/" + method.getParameterCount(); + } + + private static final class Answers implements InvocationHandler { + private final Class wanted; + private final Object answers; + private final Map byName; + // Resolved per interface Method, so hot accessors (called every frame by the renderer) skip + // rebuilding the name/arity string key and re-hashing it on every single call. + private final Map resolved = new HashMap<>(); + + Answers(Class wanted, Object answers, Map byName) { + this.wanted = wanted; + this.answers = answers; + this.byName = byName; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "equals": + if (method.getParameterCount() == 1) + return proxy == args[0]; + break; + case "hashCode": + if (method.getParameterCount() == 0) + return System.identityHashCode(proxy); + break; + case "toString": + if (method.getParameterCount() == 0) + return "Fake" + wanted.getSimpleName(); + break; + default: + break; + } + + Method mine; + if (resolved.containsKey(method)) { + mine = resolved.get(method); + } else { + mine = byName.get(key(method)); + resolved.put(method, mine); + } + if (mine != null) { + try { + return asKindOf(method.getReturnType(), mine.invoke(answers, args)); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + } + + if (method.isDefault()) + return callDefault(proxy, method, args); + + return blank(method.getReturnType()); + } + } + + public static Object callDefault(Object proxy, Method method, Object[] args) throws Throwable { + Class owner = method.getDeclaringClass(); + return MethodHandles + .privateLookupIn(owner, MethodHandles.lookup()) + .unreflectSpecial(method, owner) + .bindTo(proxy) + .invokeWithArguments(args == null ? new Object[0] : args); + } + + private static Object asKindOf(Class wanted, Object answer) { + if (!(answer instanceof Number) || !wanted.isPrimitive()) + return answer; + + Number number = (Number) answer; + if (wanted == float.class) + return number.floatValue(); + if (wanted == double.class) + return number.doubleValue(); + if (wanted == long.class) + return number.longValue(); + if (wanted == int.class) + return number.intValue(); + if (wanted == short.class) + return number.shortValue(); + if (wanted == byte.class) + return number.byteValue(); + return answer; + } + + public static Object blank(Class type) { + if (!type.isPrimitive()) + return null; + if (type == boolean.class) + return false; + if (type == void.class) + return null; + if (type == char.class) + return (char) 0; + if (type == byte.class) + return (byte) 0; + if (type == short.class) + return (short) 0; + if (type == int.class) + return 0; + if (type == long.class) + return 0L; + if (type == float.class) + return 0f; + return 0d; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java new file mode 100644 index 0000000..23f386f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java @@ -0,0 +1,301 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.awt.Canvas; +import java.awt.Dimension; +import java.util.Collections; +import java.util.Iterator; +import javax.annotation.Nullable; +import net.runelite.api.BufferProvider; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.IndexedObjectSet; +import net.runelite.api.Point; +import net.runelite.api.Scene; +import net.runelite.api.TextureProvider; +import net.runelite.api.WorldView; +import net.runelite.api.hooks.DrawCallbacks; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +public final class FakeClient { + public static final int ZOOM = 512; + + private final Canvas canvas; + private final TextureProvider textureProvider; + private final FakeObjects objects; + + private final FakeWorldView topLevel = new FakeWorldView(); + private final WorldView worldView = Fake.of(WorldView.class, topLevel); + + private int[] uiPixels = new int[0]; + private int uiWidth, uiHeight; + private final BufferProvider bufferProvider = Fake.of(BufferProvider.class, new Object() { + public int[] getPixels() { + return uiPixels; + } + + public int getWidth() { + return uiWidth; + } + + public int getHeight() { + return uiHeight; + } + }); + + private Thread clientThread; + private DrawCallbacks drawCallbacks; + private GameState gameState = GameState.LOGGED_IN; + private int gpuFlags; + private int gameCycle; + + private final float[] camera = new float[3]; + private float cameraPitch, cameraYaw; + private int plane; + + public FakeClient(Canvas canvas, TextureProvider textureProvider, FakeObjects objects) { + this.canvas = canvas; + this.textureProvider = textureProvider; + this.objects = objects; + } + + public void ownedBy(Thread thread) { + clientThread = thread; + } + + public void setScene(@Nullable BuiltScene scene) { + topLevel.scene = scene; + } + + public void setCamera(float[] position, float yaw, float pitch, int plane) { + System.arraycopy(position, 0, camera, 0, 3); + cameraYaw = yaw; + cameraPitch = pitch; + this.plane = plane; + topLevel.plane = plane; + } + + public void tick() { + gameCycle++; + } + + public void sizeUi(int width, int height) { + if (uiWidth == width && uiHeight == height) + return; + uiWidth = width; + uiHeight = height; + uiPixels = new int[Math.max(1, width * height)]; + } + + public DrawCallbacks getDrawCallbacks() { + return drawCallbacks; + } + + public Canvas getCanvas() { + return canvas; + } + + public int getCanvasWidth() { + return Math.max(1, canvas.getWidth()); + } + + public int getCanvasHeight() { + return Math.max(1, canvas.getHeight()); + } + + public boolean isResized() { + return true; + } + + public boolean isStretchedEnabled() { + return false; + } + + public Dimension getStretchedDimensions() { + return new Dimension(getCanvasWidth(), getCanvasHeight()); + } + + public int getViewportWidth() { + return getCanvasWidth(); + } + + public int getViewportHeight() { + return getCanvasHeight(); + } + + public int getViewportXOffset() { + return 0; + } + + public int getViewportYOffset() { + return 0; + } + + public int getCenterX() { + return getCanvasWidth() / 2; + } + + public int getCenterY() { + return getCanvasHeight() / 2; + } + + public int getScale() { + return ZOOM; + } + + public int get3dZoom() { + return ZOOM; + } + + public int getRasterizer3D_clipNegativeMidX() { + return -getCenterX(); + } + + public int getRasterizer3D_clipNegativeMidY() { + return -getCenterY(); + } + + public int getRasterizer3D_clipMidX2() { + return getCanvasWidth() - getCenterX(); + } + + public int getRasterizer3D_clipMidY2() { + return getCanvasHeight() - getCenterY(); + } + + public BufferProvider getBufferProvider() { + return bufferProvider; + } + + public TextureProvider getTextureProvider() { + return textureProvider; + } + + public boolean isClientThread() { + return Thread.currentThread() == clientThread; + } + + public GameState getGameState() { + return gameState; + } + + public void setGameState(GameState gameState) { + this.gameState = gameState; + } + + public int getGameCycle() { + return gameCycle; + } + + public WorldView getTopLevelWorldView() { + return worldView; + } + + public WorldView getWorldView(int id) { + return id == WorldView.TOPLEVEL || id == -1 ? worldView : null; + } + + public Scene getScene() { + return topLevel.scene; + } + + public int getPlane() { + return plane; + } + + public int[] getMapRegions() { + return topLevel.scene == null ? new int[0] : topLevel.scene.getMapRegions(); + } + + public int getCameraX() { + return (int) camera[0]; + } + + public int getCameraY() { + return (int) camera[1]; + } + + public int getCameraZ() { + return (int) camera[2]; + } + + public float getCameraFocalPointX() { + return camera[0]; + } + + public float getCameraFocalPointY() { + return camera[1]; + } + + public float getCameraFocalPointZ() { + return camera[2]; + } + + public float getCameraFpX() { + return camera[0]; + } + + public float getCameraFpY() { + return camera[1]; + } + + public float getCameraFpZ() { + return camera[2]; + } + + public float getCameraFpPitch() { + return cameraPitch; + } + + public float getCameraFpYaw() { + return cameraYaw; + } + + public int getCameraYaw() { + return (int) (cameraYaw / (2 * Math.PI) * 2048) & 2047; + } + + public int getCameraPitch() { + return (int) (cameraPitch / (2 * Math.PI) * 2048); + } + + public void setDrawCallbacks(DrawCallbacks drawCallbacks) { + this.drawCallbacks = drawCallbacks; + } + + public void setGpuFlags(int gpuFlags) { + this.gpuFlags = gpuFlags; + } + + public int getGpuFlags() { + return gpuFlags; + } + + public Point getMouseCanvasPosition() { + return new Point(-1, -1); + } + + @Nullable + public net.runelite.api.ObjectComposition getObjectDefinition(int id) { + return objects.get(id); + } + + public int getSkyboxColor() { + return 0; + } + + public java.util.List getDBTableRows(int table) { + return java.util.List.of(); + } + + public static final IndexedObjectSet NOBODY = new IndexedObjectSet<>() { + @Override + public Object byIndex(int index) { + return null; + } + + @Override + public Iterator iterator() { + return Collections.emptyIterator(); + } + }; +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java new file mode 100644 index 0000000..2a20f04 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java @@ -0,0 +1,83 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import net.runelite.api.ObjectComposition; +import rs117.hd.dev.sceneloader.scene.Definitions; + +public final class FakeObjects { + private final Definitions defs; + private final Map byId = new HashMap<>(); + + public FakeObjects(Definitions defs) { + this.defs = defs; + } + + @Nullable + public ObjectComposition get(int id) { + ObjectComposition cached = byId.get(id); + if (cached != null || byId.containsKey(id)) + return cached; + + var definition = defs.object(id); + ObjectComposition composition = definition == null ? null : Fake.of(ObjectComposition.class, new OneObject(id)); + byId.put(id, composition); + return composition; + } + + private final class OneObject { + private final int id; + + OneObject(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public String getName() { + var definition = defs.object(id); + return definition == null ? "null" : definition.getName(); + } + + public int getSizeX() { + var definition = defs.object(id); + return definition == null ? 1 : definition.getSizeX(); + } + + public int getSizeY() { + var definition = defs.object(id); + return definition == null ? 1 : definition.getSizeY(); + } + + public int getVarbitId() { + var definition = defs.object(id); + return definition == null ? -1 : definition.getVarbitID(); + } + + public int getVarPlayerId() { + var definition = defs.object(id); + return definition == null ? -1 : definition.getVarpID(); + } + + @Nullable + public int[] getImpostorIds() { + var definition = defs.object(id); + return definition == null ? null : definition.getConfigChangeDest(); + } + + @Nullable + public ObjectComposition getImpostor() { + int[] forms = getImpostorIds(); + if (forms == null) + return null; + + for (int form : forms) + if (form != -1) + return FakeObjects.this.get(form); + return null; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java new file mode 100644 index 0000000..f9fe21b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java @@ -0,0 +1,60 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import javax.annotation.Nullable; +import net.runelite.api.IndexedObjectSet; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; + +public final class FakeWorldView { + @Nullable + BuiltScene scene; + int plane; + + public int getId() { + return WorldView.TOPLEVEL; + } + + public boolean isTopLevel() { + return true; + } + + @Nullable + public Scene getScene() { + return scene; + } + + public int getPlane() { + return plane; + } + + public int getSizeX() { + return EXTENDED_SCENE_SIZE; + } + + public int getSizeY() { + return EXTENDED_SCENE_SIZE; + } + + public int getBaseX() { + return scene == null ? 0 : scene.getBaseX(); + } + + public int getBaseY() { + return scene == null ? 0 : scene.getBaseY(); + } + + public IndexedObjectSet players() { + return FakeClient.NOBODY; + } + + public IndexedObjectSet npcs() { + return FakeClient.NOBODY; + } + + public IndexedObjectSet worldEntities() { + return FakeClient.NOBODY; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java new file mode 100644 index 0000000..9df249e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java @@ -0,0 +1,457 @@ +package rs117.hd.dev.sceneloader.standalone.headless; + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Dimension; +import java.awt.GraphicsEnvironment; +import java.io.BufferedWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.annotation.Nullable; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantOptions; +import rs117.hd.overlays.FrameTimings; +import rs117.hd.overlays.Timer; + +import static net.runelite.api.Perspective.LOCAL_TILE_SIZE; +import rs117.hd.dev.sceneloader.standalone.FlyCamera; +import rs117.hd.dev.sceneloader.standalone.HdRuntime; +import rs117.hd.dev.sceneloader.standalone.HdSettings; +import rs117.hd.dev.sceneloader.standalone.Textures; + +@Slf4j +public final class HdBenchmark { + private static final String USAGE = + "Usage: HdBenchmark [--x 3222] [--y 3218] [--chunks 0] [--region 12850] [--plane 0] [--roofs]\n" + + " [--cache ] [--width 1280] [--height 800] [--config name=value,...]\n" + + " [--out ] [--warmup 3] [--spin 12] [--hold 3]\n" + + " [--above 2400] [--pitch 50] [--hidden] [--name