From e60add30c5b2cb9253bb467eb96a7ec3e795e561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20Przemys=C5=82aw=20Pluta?= Date: Wed, 10 Feb 2021 17:16:37 +0100 Subject: [PATCH] Migrate CRLF file endings to LF --- .gitattributes | 38 +- .gitignore | 276 +++++++------- editor/build.gradle | 100 ++--- .../com/bartlomiejpluta/base/editor/App.kt | 68 ++-- .../editor/command/context/UndoableContext.kt | 4 +- .../editor/command/context/UndoableScope.kt | 8 +- .../base/editor/command/model/base/Command.kt | 8 +- .../command/model/base/SimpleCommand.kt | 40 +- .../editor/command/model/base/Undoable.kt | 12 +- .../command/model/map/CreateLayerCommand.kt | 44 +-- .../command/model/map/MoveLayerCommand.kt | 42 +-- .../command/model/map/RemoveLayerCommand.kt | 48 +-- .../command/model/map/RenameLayerCommand.kt | 44 +-- .../command/service/DefaultUndoRedoService.kt | 242 ++++++------ .../editor/command/service/UndoRedoService.kt | 50 +-- .../base/editor/common/serial/Deserializer.kt | 12 +- .../base/editor/common/serial/Serializer.kt | 14 +- .../editor/event/RedrawMapRequestEvent.kt | 12 +- .../editor/main/controller/MainController.kt | 116 +++--- .../base/editor/main/view/MainMenuView.kt | 78 ++-- .../base/editor/main/view/MainView.kt | 66 ++-- .../base/editor/map/canvas/MapCanvas.kt | 194 +++++----- .../base/editor/map/canvas/MapPainter.kt | 186 +++++----- .../editor/map/canvas/MapPaintingTrace.kt | 110 +++--- .../base/editor/map/component/MapPane.kt | 104 +++--- .../base/editor/map/model/brush/Brush.kt | 194 +++++----- .../base/editor/map/model/brush/BrushMode.kt | 10 +- .../base/editor/map/model/layer/Layer.kt | 22 +- .../base/editor/map/model/layer/TileLayer.kt | 60 +-- .../base/editor/map/model/map/GameMap.kt | 108 +++--- .../base/editor/map/serial/MapDeserializer.kt | 10 +- .../base/editor/map/serial/MapSerializer.kt | 10 +- .../map/serial/ProtobufMapDeserializer.kt | 102 ++--- .../map/serial/ProtobufMapSerializer.kt | 66 ++-- .../base/editor/map/view/MapFragment.kt | 72 ++-- .../base/editor/map/view/MapLayersView.kt | 188 +++++----- .../editor/map/view/MapSettingsFragment.kt | 164 ++++---- .../base/editor/map/view/MapStatusBarView.kt | 66 ++-- .../base/editor/map/view/MapToolbarView.kt | 208 +++++------ .../base/editor/map/view/MapView.kt | 126 +++---- .../base/editor/map/viewmodel/BrushVM.kt | 56 +-- .../editor/map/viewmodel/EditorStateVM.kt | 54 +-- .../base/editor/map/viewmodel/GameMapVM.kt | 78 ++-- .../project/manager/DefaultProjectManager.kt | 62 ++-- .../editor/project/manager/ProjectManager.kt | 16 +- .../base/editor/project/model/Project.kt | 28 +- .../project/serial/ProjectDeserializer.kt | 10 +- .../project/serial/ProjectSerializer.kt | 10 +- .../serial/ProtobufProjectDeserializer.kt | 34 +- .../serial/ProtobufProjectSerializer.kt | 30 +- .../project/view/ProjectSettingsFragment.kt | 190 +++++----- .../editor/project/viewmodel/ProjectVM.kt | 22 +- .../base/editor/render/input/MapMouseEvent.kt | 34 +- .../render/input/MapMouseEventHandler.kt | 8 +- .../base/editor/render/model/Renderable.kt | 12 +- .../editor/resource/uid/manager/UIDManager.kt | 14 +- .../uid/manager/UUIDBasedUIDManager.kt | 50 +-- .../editor/resource/uid/model/UIDTarget.kt | 8 +- .../editor/tileset/canvas/TileSetCanvas.kt | 136 +++---- .../editor/tileset/canvas/TileSetSelection.kt | 158 ++++---- .../editor/tileset/component/TileSetPane.kt | 82 ++-- .../base/editor/tileset/model/Tile.kt | 108 +++--- .../base/editor/tileset/model/TileSet.kt | 124 +++---- .../base/editor/tileset/view/TileSetView.kt | 36 +- editor/src/main/resources/application.yml | 4 +- engine/build.gradle | 0 .../base/core/engine/DefaultGameEngine.java | 222 +++++------ .../base/core/engine/GameEngine.java | 10 +- .../base/core/error/AppException.java | 44 +-- .../base/core/gc/Cleanable.java | 10 +- .../gc/DefaultOffHeapGarbageCollector.java | 44 +-- .../base/core/gc/Disposable.java | 10 +- .../base/core/gc/OffHeapGarbageCollector.java | 10 +- .../core/gl/object/material/Material.java | 166 ++++----- .../base/core/gl/object/mesh/Mesh.java | 188 +++++----- .../object/texture/DefaultTextureManager.java | 78 ++-- .../base/core/gl/object/texture/Texture.java | 132 +++---- .../gl/object/texture/TextureManager.java | 14 +- .../base/core/gl/render/DefaultRenderer.java | 124 +++---- .../base/core/gl/render/Renderable.java | 16 +- .../base/core/gl/render/Renderer.java | 18 +- .../core/gl/shader/constant/UniformName.java | 24 +- .../shader/manager/DefaultShaderManager.java | 298 +++++++-------- .../core/gl/shader/manager/ShaderManager.java | 88 ++--- .../core/gl/shader/program/ShaderProgram.java | 350 +++++++++--------- .../base/core/gl/shader/uniform/Uniform.java | 18 +- .../base/core/image/DefaultImageManager.java | 78 ++-- .../base/core/image/Image.java | 38 +- .../base/core/image/ImageManager.java | 0 .../base/core/logic/GameLogic.java | 28 +- .../base/core/logic/Updatable.java | 10 +- .../base/core/profiling/fps/FPSMonitor.java | 14 +- .../core/profiling/fps/LogFPSMonitor.java | 126 +++---- .../time/annotation/MeasureExecutionTime.java | 22 +- .../time/aspect/ExecutionTimeAspect.java | 76 ++-- .../base/core/thread/ThreadManager.java | 20 +- .../base/core/time/ChronoMeter.java | 40 +- .../bartlomiejpluta/base/core/ui/Window.java | 238 ++++++------ .../base/core/ui/WindowManager.java | 20 +- .../base/core/util/math/MathUtil.java | 64 ++-- .../core/util/mesh/DefaultMeshManager.java | 86 ++--- .../base/core/util/mesh/MeshManager.java | 16 +- .../base/core/util/res/ResourcesManager.java | 70 ++-- .../world/animation/AnimationableObject.java | 66 ++-- .../base/core/world/animation/Animator.java | 10 +- .../core/world/animation/DefaultAnimator.java | 36 +- .../base/core/world/camera/Camera.java | 44 +-- .../base/core/world/map/GameMap.java | 272 +++++++------- .../base/core/world/map/ImageLayer.java | 116 +++--- .../base/core/world/map/Layer.java | 16 +- .../base/core/world/map/ObjectLayer.java | 146 ++++---- .../base/core/world/map/PassageAbility.java | 20 +- .../base/core/world/map/TileLayer.java | 92 ++--- .../base/core/world/movement/Direction.java | 48 +-- .../core/world/movement/MovableObject.java | 162 ++++---- .../base/core/world/movement/Movement.java | 98 ++--- .../core/world/object/PositionableObject.java | 156 ++++---- .../core/world/object/RenderableObject.java | 130 +++---- .../manager/DefaultTileSetManager.java | 84 ++--- .../world/tileset/manager/TileSetManager.java | 16 +- .../base/core/world/tileset/model/Tile.java | 38 +- .../core/world/tileset/model/TileSet.java | 78 ++-- engine/src/main/resources/shaders/default.fs | 44 +-- engine/src/main/resources/shaders/default.vs | 30 +- game/build.gradle | 110 +++--- .../com/bartlomiejpluta/base/game/App.java | 0 .../base/game/logic/DefaultGameLogic.java | 129 ++++--- .../config/EntitySpriteConfiguration.java | 56 +-- .../entity/manager/DefaultEntityManager.java | 76 ++-- .../world/entity/manager/EntityManager.java | 20 +- .../base/game/world/entity/model/Entity.java | 158 ++++---- game/src/main/resources/application.yml | 58 +-- gradle.properties | 0 gradle/wrapper/gradle-wrapper.jar | Bin gradle/wrapper/gradle-wrapper.properties | 0 gradlew | 0 gradlew.bat | 0 proto/build.gradle | 88 ++--- proto/src/main/proto/map.proto | 44 +-- proto/src/main/proto/project.proto | 14 +- settings.gradle | 0 141 files changed, 4973 insertions(+), 4978 deletions(-) mode change 100755 => 100644 .gitattributes mode change 100755 => 100644 .gitignore mode change 100755 => 100644 editor/build.gradle mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/App.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableContext.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableScope.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Command.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/SimpleCommand.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Undoable.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/CreateLayerCommand.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/MoveLayerCommand.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RemoveLayerCommand.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RenameLayerCommand.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/DefaultUndoRedoService.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/UndoRedoService.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Deserializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Serializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/event/RedrawMapRequestEvent.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/controller/MainController.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainMenuView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapCanvas.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPainter.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPaintingTrace.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/component/MapPane.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/Brush.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/BrushMode.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/Layer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/TileLayer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/map/GameMap.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapDeserializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapSerializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapDeserializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapSerializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapFragment.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapLayersView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapSettingsFragment.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapStatusBarView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapToolbarView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapView.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/BrushVM.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/EditorStateVM.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/GameMapVM.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/DefaultProjectManager.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/ProjectManager.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/model/Project.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectDeserializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectSerializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectDeserializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectSerializer.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/view/ProjectSettingsFragment.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/viewmodel/ProjectVM.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEvent.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEventHandler.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/model/Renderable.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UIDManager.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UUIDBasedUIDManager.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/model/UIDTarget.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetCanvas.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetSelection.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/component/TileSetPane.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/Tile.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/TileSet.kt mode change 100755 => 100644 editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/view/TileSetView.kt mode change 100755 => 100644 editor/src/main/resources/application.yml mode change 100755 => 100644 engine/build.gradle mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/engine/DefaultGameEngine.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/engine/GameEngine.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/error/AppException.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gc/Cleanable.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gc/DefaultOffHeapGarbageCollector.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gc/Disposable.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gc/OffHeapGarbageCollector.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/material/Material.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/mesh/Mesh.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/DefaultTextureManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/Texture.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/TextureManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/DefaultRenderer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderable.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/constant/UniformName.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/DefaultShaderManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/ShaderManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/program/ShaderProgram.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/uniform/Uniform.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/image/DefaultImageManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/image/Image.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/image/ImageManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/logic/GameLogic.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/logic/Updatable.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/profiling/fps/FPSMonitor.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/profiling/fps/LogFPSMonitor.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/annotation/MeasureExecutionTime.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/aspect/ExecutionTimeAspect.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/thread/ThreadManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/time/ChronoMeter.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/ui/Window.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/ui/WindowManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/util/math/MathUtil.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/DefaultMeshManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/MeshManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/util/res/ResourcesManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/AnimationableObject.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/Animator.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/DefaultAnimator.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/camera/Camera.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/GameMap.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ImageLayer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/Layer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ObjectLayer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/PassageAbility.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/map/TileLayer.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Direction.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/MovableObject.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Movement.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/object/PositionableObject.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/object/RenderableObject.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/DefaultTileSetManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/TileSetManager.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/Tile.java mode change 100755 => 100644 engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/TileSet.java mode change 100755 => 100644 engine/src/main/resources/shaders/default.fs mode change 100755 => 100644 engine/src/main/resources/shaders/default.vs mode change 100755 => 100644 game/build.gradle mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/App.java mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/logic/DefaultGameLogic.java mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/world/entity/config/EntitySpriteConfiguration.java mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/DefaultEntityManager.java mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/EntityManager.java mode change 100755 => 100644 game/src/main/java/com/bartlomiejpluta/base/game/world/entity/model/Entity.java mode change 100755 => 100644 game/src/main/resources/application.yml mode change 100755 => 100644 gradle.properties mode change 100755 => 100644 gradle/wrapper/gradle-wrapper.jar mode change 100755 => 100644 gradle/wrapper/gradle-wrapper.properties mode change 100755 => 100644 gradlew mode change 100755 => 100644 gradlew.bat mode change 100755 => 100644 proto/build.gradle mode change 100755 => 100644 proto/src/main/proto/map.proto mode change 100755 => 100644 proto/src/main/proto/project.proto mode change 100755 => 100644 settings.gradle diff --git a/.gitattributes b/.gitattributes old mode 100755 new mode 100644 index 70042da9..a5b91850 --- a/.gitattributes +++ b/.gitattributes @@ -1,19 +1,19 @@ -# -# https://help.github.com/articles/dealing-with-line-endings/ -# -# These are explicitly windows files and should use crlf -*.bat text eol=crlf - -# The rest of project files should use lf -*.gradle text eol=lf -*.kt text eol=lf -*.yml text eol=lf -*.java text eol=lf -*.fs text eol=lf -*.vs text eol=lf -*.properties text eol=lf -*.proto text eol=lf -gradlew text eol=lf - -# Binary files -*.jar binary +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + +# The rest of project files should use lf +*.gradle text eol=lf +*.kt text eol=lf +*.yml text eol=lf +*.java text eol=lf +*.fs text eol=lf +*.vs text eol=lf +*.properties text eol=lf +*.proto text eol=lf +gradlew text eol=lf + +# Binary files +*.jar binary diff --git a/.gitignore b/.gitignore old mode 100755 new mode 100644 index 3e3bf619..b29633bd --- a/.gitignore +++ b/.gitignore @@ -1,138 +1,138 @@ - -# Created by https://www.toptal.com/developers/gitignore/api/java,gradle,intellij -# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,intellij - -### Intellij ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff -.idea/ -# Gradle -.idea/**/gradle.xml -.idea/**/libraries - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/artifacts -# .idea/compiler.xml -# .idea/jarRepositories.xml -# .idea/modules.xml -# .idea/*.iml -# .idea/modules -# *.iml -# *.ipr - -# CMake -cmake-build-*/ - -# Mongo Explorer plugin -.idea/**/mongoSettings.xml - -# File-based project format -*.iws - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -# Editor-based Rest Client -.idea/httpRequests - -# Android studio 3.1+ serialized cache file -.idea/caches/build_file_checksums.ser - -### Intellij Patch ### -# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 - -# *.iml -# modules.xml -# .idea/misc.xml -# *.ipr - -# Sonarlint plugin -# https://plugins.jetbrains.com/plugin/7973-sonarlint -.idea/**/sonarlint/ - -# SonarQube Plugin -# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin -.idea/**/sonarIssues.xml - -# Markdown Navigator plugin -# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced -.idea/**/markdown-navigator.xml -.idea/**/markdown-navigator-enh.xml -.idea/**/markdown-navigator/ - -# Cache file creation bug -# See https://youtrack.jetbrains.com/issue/JBR-2257 -.idea/$CACHE_FILE$ - -# CodeStream plugin -# https://plugins.jetbrains.com/plugin/12206-codestream -.idea/codestream.xml - -### Java ### -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -### Gradle ### -.gradle -build/ - -# Ignore Gradle GUI config -gradle-app.setting - -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar - -# Cache of project -.gradletasknamecache - -# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 -# gradle/wrapper/gradle-wrapper.properties - -### Gradle Patch ### -**/build/ - -### Textures and other resources ### -*.png - -# End of https://www.toptal.com/developers/gitignore/api/java,gradle,intellij + +# Created by https://www.toptal.com/developers/gitignore/api/java,gradle,intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/ +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### Gradle ### +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +### Textures and other resources ### +*.png + +# End of https://www.toptal.com/developers/gitignore/api/java,gradle,intellij diff --git a/editor/build.gradle b/editor/build.gradle old mode 100755 new mode 100644 index 56847ff4..5d2913bf --- a/editor/build.gradle +++ b/editor/build.gradle @@ -1,50 +1,50 @@ -plugins { - id 'org.jetbrains.kotlin.jvm' version '1.4.10' - id 'org.openjfx.javafxplugin' version '0.0.8' - id 'org.springframework.boot' version "$springBootVersion" - id 'io.spring.dependency-management' version "$springDependencyManagementVersion" - id 'idea' -} - -group 'com.bartlomiejpluta.base' -version 'unspecified' - -repositories { - mavenCentral() - maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } -} - -sourceSets { - main.kotlin.srcDirs += 'src/main/kotlin' -} - -javafx { - version = "11.0.2" - modules = ['javafx.controls', 'javafx.graphics'] -} - - - -compileKotlin { - kotlinOptions.jvmTarget = "14" -} - -compileTestKotlin { - kotlinOptions.jvmTarget = "14" -} - -dependencies { - implementation project(":proto") - implementation "org.jetbrains.kotlin:kotlin-stdlib" - implementation "no.tornado:tornadofx:${tornadoFxVersion}" - implementation platform("org.kordamp.ikonli:ikonli-bom:${ikonliVersion}") - implementation 'org.kordamp.ikonli:ikonli-javafx' - implementation 'org.kordamp.ikonli:ikonli-fontawesome-pack' - - // Spring - implementation 'org.springframework.boot:spring-boot-starter' -} - -build { - dependsOn(":proto:build") -} +plugins { + id 'org.jetbrains.kotlin.jvm' version '1.4.10' + id 'org.openjfx.javafxplugin' version '0.0.8' + id 'org.springframework.boot' version "$springBootVersion" + id 'io.spring.dependency-management' version "$springDependencyManagementVersion" + id 'idea' +} + +group 'com.bartlomiejpluta.base' +version 'unspecified' + +repositories { + mavenCentral() + maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } +} + +sourceSets { + main.kotlin.srcDirs += 'src/main/kotlin' +} + +javafx { + version = "11.0.2" + modules = ['javafx.controls', 'javafx.graphics'] +} + + + +compileKotlin { + kotlinOptions.jvmTarget = "14" +} + +compileTestKotlin { + kotlinOptions.jvmTarget = "14" +} + +dependencies { + implementation project(":proto") + implementation "org.jetbrains.kotlin:kotlin-stdlib" + implementation "no.tornado:tornadofx:${tornadoFxVersion}" + implementation platform("org.kordamp.ikonli:ikonli-bom:${ikonliVersion}") + implementation 'org.kordamp.ikonli:ikonli-javafx' + implementation 'org.kordamp.ikonli:ikonli-fontawesome-pack' + + // Spring + implementation 'org.springframework.boot:spring-boot-starter' +} + +build { + dependsOn(":proto:build") +} diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/App.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/App.kt old mode 100755 new mode 100644 index 223668fa..94a24af2 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/App.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/App.kt @@ -1,35 +1,35 @@ -package com.bartlomiejpluta.base.editor - -import com.bartlomiejpluta.base.editor.main.view.MainView -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.context.ConfigurableApplicationContext -import tornadofx.App -import tornadofx.DIContainer -import tornadofx.FX -import tornadofx.launch -import kotlin.reflect.KClass - -@SpringBootApplication -open class EditorApp : App(MainView::class) { - private lateinit var context: ConfigurableApplicationContext - - override fun init() { - this.context = SpringApplication.run(this.javaClass) - context.autowireCapableBeanFactory.autowireBean(this) - - FX.dicontainer = object : DIContainer { - override fun getInstance(type: KClass): T = context.getBean(type.java) - override fun getInstance(type: KClass, name: String): T = context.getBean(name, type.java) - } - } - - override fun stop() { - super.stop() - context.close() - } -} - -fun main(args: Array) { - launch(args) +package com.bartlomiejpluta.base.editor + +import com.bartlomiejpluta.base.editor.main.view.MainView +import org.springframework.boot.SpringApplication +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.context.ConfigurableApplicationContext +import tornadofx.App +import tornadofx.DIContainer +import tornadofx.FX +import tornadofx.launch +import kotlin.reflect.KClass + +@SpringBootApplication +open class EditorApp : App(MainView::class) { + private lateinit var context: ConfigurableApplicationContext + + override fun init() { + this.context = SpringApplication.run(this.javaClass) + context.autowireCapableBeanFactory.autowireBean(this) + + FX.dicontainer = object : DIContainer { + override fun getInstance(type: KClass): T = context.getBean(type.java) + override fun getInstance(type: KClass, name: String): T = context.getBean(name, type.java) + } + } + + override fun stop() { + super.stop() + context.close() + } +} + +fun main(args: Array) { + launch(args) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableContext.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableContext.kt old mode 100755 new mode 100644 index 14621919..5c1f212b --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableContext.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableContext.kt @@ -1,3 +1,3 @@ -package com.bartlomiejpluta.base.editor.command.context - +package com.bartlomiejpluta.base.editor.command.context + interface UndoableContext \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableScope.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableScope.kt old mode 100755 new mode 100644 index 0187dc35..a6c260a5 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableScope.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/context/UndoableScope.kt @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.editor.command.context - -import tornadofx.Scope - +package com.bartlomiejpluta.base.editor.command.context + +import tornadofx.Scope + class UndoableScope : UndoableContext, Scope() \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Command.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Command.kt old mode 100755 new mode 100644 index 2ff58153..0c4c4160 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Command.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Command.kt @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.editor.command.model.base - -interface Command { - fun execute() +package com.bartlomiejpluta.base.editor.command.model.base + +interface Command { + fun execute() } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/SimpleCommand.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/SimpleCommand.kt old mode 100755 new mode 100644 index 4b7bd981..02ea3420 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/SimpleCommand.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/SimpleCommand.kt @@ -1,21 +1,21 @@ -package com.bartlomiejpluta.base.editor.command.model.base - -class SimpleCommand( - override val commandName: String, - private val formerValue: T, - private val value: T, - private val execute: (T) -> Unit -) : Undoable, Command { - - override fun undo() { - execute(formerValue) - } - - override fun redo() { - execute() - } - - override fun execute() { - execute(value) - } +package com.bartlomiejpluta.base.editor.command.model.base + +class SimpleCommand( + override val commandName: String, + private val formerValue: T, + private val value: T, + private val execute: (T) -> Unit +) : Undoable, Command { + + override fun undo() { + execute(formerValue) + } + + override fun redo() { + execute() + } + + override fun execute() { + execute(value) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Undoable.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Undoable.kt old mode 100755 new mode 100644 index 30c4e169..2d4ebb73 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Undoable.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/base/Undoable.kt @@ -1,7 +1,7 @@ -package com.bartlomiejpluta.base.editor.command.model.base - -interface Undoable { - fun undo() - fun redo() - val commandName: String +package com.bartlomiejpluta.base.editor.command.model.base + +interface Undoable { + fun undo() + fun redo() + val commandName: String } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/CreateLayerCommand.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/CreateLayerCommand.kt old mode 100755 new mode 100644 index 54bd24f9..77be84ab --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/CreateLayerCommand.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/CreateLayerCommand.kt @@ -1,23 +1,23 @@ -package com.bartlomiejpluta.base.editor.command.model.map - -import com.bartlomiejpluta.base.editor.command.model.base.Command -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap - -class CreateLayerCommand(private val map: GameMap, private val layer: Layer): Undoable, Command { - - override fun execute() { - map.layers += layer - } - - override fun undo() { - map.layers -= layer - } - - override fun redo() { - execute() - } - - override val commandName = "Create map layer" +package com.bartlomiejpluta.base.editor.command.model.map + +import com.bartlomiejpluta.base.editor.command.model.base.Command +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap + +class CreateLayerCommand(private val map: GameMap, private val layer: Layer): Undoable, Command { + + override fun execute() { + map.layers += layer + } + + override fun undo() { + map.layers -= layer + } + + override fun redo() { + execute() + } + + override val commandName = "Create map layer" } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/MoveLayerCommand.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/MoveLayerCommand.kt old mode 100755 new mode 100644 index 4aa4b807..7d4d6449 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/MoveLayerCommand.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/MoveLayerCommand.kt @@ -1,22 +1,22 @@ -package com.bartlomiejpluta.base.editor.command.model.map - -import com.bartlomiejpluta.base.editor.command.model.base.Command -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import com.bartlomiejpluta.base.editor.map.model.map.GameMap -import tornadofx.swap - -class MoveLayerCommand(private val map: GameMap, private val currentIndex: Int, private val newIndex: Int) : Undoable, Command { - override fun execute() { - map.layers.swap(currentIndex, newIndex) - } - - override fun undo() { - map.layers.swap(newIndex, currentIndex) - } - - override fun redo() { - execute() - } - - override val commandName = "Move layer" +package com.bartlomiejpluta.base.editor.command.model.map + +import com.bartlomiejpluta.base.editor.command.model.base.Command +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import com.bartlomiejpluta.base.editor.map.model.map.GameMap +import tornadofx.swap + +class MoveLayerCommand(private val map: GameMap, private val currentIndex: Int, private val newIndex: Int) : Undoable, Command { + override fun execute() { + map.layers.swap(currentIndex, newIndex) + } + + override fun undo() { + map.layers.swap(newIndex, currentIndex) + } + + override fun redo() { + execute() + } + + override val commandName = "Move layer" } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RemoveLayerCommand.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RemoveLayerCommand.kt old mode 100755 new mode 100644 index 846576a5..0f73e28d --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RemoveLayerCommand.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RemoveLayerCommand.kt @@ -1,25 +1,25 @@ -package com.bartlomiejpluta.base.editor.command.model.map - -import com.bartlomiejpluta.base.editor.command.model.base.Command -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap - -class RemoveLayerCommand(private val map: GameMap, private val layerIndex: Int) : Undoable, Command { - private var layer: Layer? = null - - override fun execute() { - layer = map.layers.removeAt(layerIndex) - } - - override fun undo() { - map.layers.add(layerIndex, layer) - layer = null - } - - override fun redo() { - execute() - } - - override val commandName = "Remove layer" +package com.bartlomiejpluta.base.editor.command.model.map + +import com.bartlomiejpluta.base.editor.command.model.base.Command +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap + +class RemoveLayerCommand(private val map: GameMap, private val layerIndex: Int) : Undoable, Command { + private var layer: Layer? = null + + override fun execute() { + layer = map.layers.removeAt(layerIndex) + } + + override fun undo() { + map.layers.add(layerIndex, layer) + layer = null + } + + override fun redo() { + execute() + } + + override val commandName = "Remove layer" } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RenameLayerCommand.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RenameLayerCommand.kt old mode 100755 new mode 100644 index 07340a0e..20abed51 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RenameLayerCommand.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/model/map/RenameLayerCommand.kt @@ -1,23 +1,23 @@ -package com.bartlomiejpluta.base.editor.command.model.map - -import com.bartlomiejpluta.base.editor.command.model.base.Command -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import com.bartlomiejpluta.base.editor.map.model.layer.Layer - -class RenameLayerCommand(private val layer: Layer, private val newName: String) : Undoable, Command { - private val formerName = layer.name - - override fun execute() { - layer.name = newName - } - - override fun undo() { - layer.name = formerName - } - - override fun redo() { - execute() - } - - override val commandName = "Rename layer" +package com.bartlomiejpluta.base.editor.command.model.map + +import com.bartlomiejpluta.base.editor.command.model.base.Command +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import com.bartlomiejpluta.base.editor.map.model.layer.Layer + +class RenameLayerCommand(private val layer: Layer, private val newName: String) : Undoable, Command { + private val formerName = layer.name + + override fun execute() { + layer.name = newName + } + + override fun undo() { + layer.name = formerName + } + + override fun redo() { + execute() + } + + override val commandName = "Rename layer" } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/DefaultUndoRedoService.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/DefaultUndoRedoService.kt old mode 100755 new mode 100644 index b879bc9e..aa9a7d8a --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/DefaultUndoRedoService.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/DefaultUndoRedoService.kt @@ -1,122 +1,122 @@ -package com.bartlomiejpluta.base.editor.command.service - -import com.bartlomiejpluta.base.editor.command.context.UndoableContext -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Component -import java.lang.Integer.toHexString -import java.util.* - -@Component -class DefaultUndoRedoService : UndoRedoService { - private val undo: Deque> = ArrayDeque() - private val redo: Deque> = ArrayDeque() - - var sizeMax = 30 - set(value) { - if (value >= 0) { - for (i in 0 until undo.size - value) { - undo.removeLast() - } - - field = value - } - } - - override fun push(undoable: Undoable) { - push(undoable, GLOBAL_CONTEXT) - } - - override fun push(undoable: Undoable, context: UndoableContext) { - if (undo.size == sizeMax) { - log.debug("The max size of [undo] stack has been reached. Removing the last item...") - undo.removeLast() - } - - log.debug("Pushing item to [undo] stack: ${undoable.commandName} (ctx: ${toHexString(context.hashCode())})") - undo.push(undoable to context) - redo.clear() - } - - override fun undo() { - if (undo.isNotEmpty()) { - undo.pop().let { - log.debug("Performing undo: ${it.first.commandName}") - it.first.undo() - redo.push(it) - } - } - } - - override fun undo(context: UndoableContext) { - if (undo.isNotEmpty()) { - undo.firstOrNull { it.second === context }?.let { - log.debug("Performing contextual (ctx: ${toHexString(context.hashCode())}) undo: ${it.first.commandName}") - undo.remove(it) - it.first.undo() - redo.push(it) - } - } - } - - override fun redo() { - if (redo.isNotEmpty()) { - redo.pop().let { - log.debug("Performing redo: ${it.first.commandName}") - it.first.redo() - undo.push(it) - } - } - } - - override fun redo(context: UndoableContext) { - if (redo.isNotEmpty()) { - redo.firstOrNull { it.second === context }?.let { - log.debug("Performing contextual (ctx: ${toHexString(context.hashCode())}) redo: ${it.first.commandName}") - redo.remove(it) - it.first.redo() - undo.push(it) - } - } - } - - override fun clear() { - log.debug("Clearing [undo] and [redo] stacks") - undo.clear() - redo.clear() - } - - override fun clear(context: UndoableContext) { - log.debug("Clearing [undo] and [redo] stacks (ctx: ${toHexString(context.hashCode())})") - undo.removeIf { it.second == context } - redo.removeIf { it.second == context } - } - - override val lastUndoable: Undoable? - get() = undo.first?.first - - override val lastRedoable: Undoable? - get() = redo.first?.first - - override val undoCommandName: String - get() = undo.first?.first?.commandName ?: "" - - override val redoCommandName: String - get() = redo.first?.first?.commandName ?: "" - - override fun lastUndoable(context: UndoableContext) = undo.firstOrNull { it.second === context }?.first - - override fun lastRedoable(context: UndoableContext) = redo.firstOrNull { it.second === context }?.first - - override fun undoCommandName(context: UndoableContext) = - undo.firstOrNull { it.second === context }?.first?.commandName ?: "" - - override fun redoCommandName(context: UndoableContext) = - redo.firstOrNull { it.second === context }?.first?.commandName ?: "" - - - companion object { - private val log = LoggerFactory.getLogger(DefaultUndoRedoService::class.java) - private val GLOBAL_CONTEXT = object : UndoableContext {} - } +package com.bartlomiejpluta.base.editor.command.service + +import com.bartlomiejpluta.base.editor.command.context.UndoableContext +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Component +import java.lang.Integer.toHexString +import java.util.* + +@Component +class DefaultUndoRedoService : UndoRedoService { + private val undo: Deque> = ArrayDeque() + private val redo: Deque> = ArrayDeque() + + var sizeMax = 30 + set(value) { + if (value >= 0) { + for (i in 0 until undo.size - value) { + undo.removeLast() + } + + field = value + } + } + + override fun push(undoable: Undoable) { + push(undoable, GLOBAL_CONTEXT) + } + + override fun push(undoable: Undoable, context: UndoableContext) { + if (undo.size == sizeMax) { + log.debug("The max size of [undo] stack has been reached. Removing the last item...") + undo.removeLast() + } + + log.debug("Pushing item to [undo] stack: ${undoable.commandName} (ctx: ${toHexString(context.hashCode())})") + undo.push(undoable to context) + redo.clear() + } + + override fun undo() { + if (undo.isNotEmpty()) { + undo.pop().let { + log.debug("Performing undo: ${it.first.commandName}") + it.first.undo() + redo.push(it) + } + } + } + + override fun undo(context: UndoableContext) { + if (undo.isNotEmpty()) { + undo.firstOrNull { it.second === context }?.let { + log.debug("Performing contextual (ctx: ${toHexString(context.hashCode())}) undo: ${it.first.commandName}") + undo.remove(it) + it.first.undo() + redo.push(it) + } + } + } + + override fun redo() { + if (redo.isNotEmpty()) { + redo.pop().let { + log.debug("Performing redo: ${it.first.commandName}") + it.first.redo() + undo.push(it) + } + } + } + + override fun redo(context: UndoableContext) { + if (redo.isNotEmpty()) { + redo.firstOrNull { it.second === context }?.let { + log.debug("Performing contextual (ctx: ${toHexString(context.hashCode())}) redo: ${it.first.commandName}") + redo.remove(it) + it.first.redo() + undo.push(it) + } + } + } + + override fun clear() { + log.debug("Clearing [undo] and [redo] stacks") + undo.clear() + redo.clear() + } + + override fun clear(context: UndoableContext) { + log.debug("Clearing [undo] and [redo] stacks (ctx: ${toHexString(context.hashCode())})") + undo.removeIf { it.second == context } + redo.removeIf { it.second == context } + } + + override val lastUndoable: Undoable? + get() = undo.first?.first + + override val lastRedoable: Undoable? + get() = redo.first?.first + + override val undoCommandName: String + get() = undo.first?.first?.commandName ?: "" + + override val redoCommandName: String + get() = redo.first?.first?.commandName ?: "" + + override fun lastUndoable(context: UndoableContext) = undo.firstOrNull { it.second === context }?.first + + override fun lastRedoable(context: UndoableContext) = redo.firstOrNull { it.second === context }?.first + + override fun undoCommandName(context: UndoableContext) = + undo.firstOrNull { it.second === context }?.first?.commandName ?: "" + + override fun redoCommandName(context: UndoableContext) = + redo.firstOrNull { it.second === context }?.first?.commandName ?: "" + + + companion object { + private val log = LoggerFactory.getLogger(DefaultUndoRedoService::class.java) + private val GLOBAL_CONTEXT = object : UndoableContext {} + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/UndoRedoService.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/UndoRedoService.kt old mode 100755 new mode 100644 index bf7d50d4..3f5e5013 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/UndoRedoService.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/command/service/UndoRedoService.kt @@ -1,26 +1,26 @@ -package com.bartlomiejpluta.base.editor.command.service - -import com.bartlomiejpluta.base.editor.command.context.UndoableContext -import com.bartlomiejpluta.base.editor.command.model.base.Undoable - -interface UndoRedoService { - fun push(undoable: Undoable) - fun undo() - fun redo() - fun clear() - - fun push(undoable: Undoable, context: UndoableContext) - fun undo(context: UndoableContext) - fun redo(context: UndoableContext) - fun clear(context: UndoableContext) - - val lastUndoable: Undoable? - val lastRedoable: Undoable? - val undoCommandName: String - val redoCommandName: String - - fun lastUndoable(context: UndoableContext): Undoable? - fun lastRedoable(context: UndoableContext): Undoable? - fun undoCommandName(context: UndoableContext): String - fun redoCommandName(context: UndoableContext): String +package com.bartlomiejpluta.base.editor.command.service + +import com.bartlomiejpluta.base.editor.command.context.UndoableContext +import com.bartlomiejpluta.base.editor.command.model.base.Undoable + +interface UndoRedoService { + fun push(undoable: Undoable) + fun undo() + fun redo() + fun clear() + + fun push(undoable: Undoable, context: UndoableContext) + fun undo(context: UndoableContext) + fun redo(context: UndoableContext) + fun clear(context: UndoableContext) + + val lastUndoable: Undoable? + val lastRedoable: Undoable? + val undoCommandName: String + val redoCommandName: String + + fun lastUndoable(context: UndoableContext): Undoable? + fun lastRedoable(context: UndoableContext): Undoable? + fun undoCommandName(context: UndoableContext): String + fun redoCommandName(context: UndoableContext): String } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Deserializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Deserializer.kt old mode 100755 new mode 100644 index dafb4827..9a4b951c --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Deserializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Deserializer.kt @@ -1,7 +1,7 @@ -package com.bartlomiejpluta.base.editor.common.serial - -import java.io.InputStream - -interface Deserializer { - fun deserialize(input: InputStream): T +package com.bartlomiejpluta.base.editor.common.serial + +import java.io.InputStream + +interface Deserializer { + fun deserialize(input: InputStream): T } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Serializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Serializer.kt old mode 100755 new mode 100644 index 123d699b..346b3433 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Serializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/common/serial/Serializer.kt @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.editor.common.serial - -import java.io.InputStream -import java.io.OutputStream - -interface Serializer { - fun serialize(item: T, output: OutputStream) +package com.bartlomiejpluta.base.editor.common.serial + +import java.io.InputStream +import java.io.OutputStream + +interface Serializer { + fun serialize(item: T, output: OutputStream) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/event/RedrawMapRequestEvent.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/event/RedrawMapRequestEvent.kt old mode 100755 new mode 100644 index 1e63929f..b3d11e83 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/event/RedrawMapRequestEvent.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/event/RedrawMapRequestEvent.kt @@ -1,7 +1,7 @@ -package com.bartlomiejpluta.base.editor.event - -import tornadofx.EventBus.RunOn.ApplicationThread -import tornadofx.EventBus.RunOn.BackgroundThread -import tornadofx.FXEvent - +package com.bartlomiejpluta.base.editor.event + +import tornadofx.EventBus.RunOn.ApplicationThread +import tornadofx.EventBus.RunOn.BackgroundThread +import tornadofx.FXEvent + object RedrawMapRequestEvent : FXEvent(ApplicationThread) \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/controller/MainController.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/controller/MainController.kt old mode 100755 new mode 100644 index 8a1daad0..248a5cfe --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/controller/MainController.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/controller/MainController.kt @@ -1,59 +1,59 @@ -package com.bartlomiejpluta.base.editor.main.controller - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.map.model.map.GameMap -import com.bartlomiejpluta.base.editor.map.view.MapSettingsFragment -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import com.bartlomiejpluta.base.editor.project.manager.ProjectManager -import com.bartlomiejpluta.base.editor.project.model.Project -import com.bartlomiejpluta.base.editor.project.view.ProjectSettingsFragment -import com.bartlomiejpluta.base.editor.project.viewmodel.ProjectVM -import com.bartlomiejpluta.base.editor.tileset.model.TileSet -import javafx.beans.property.SimpleObjectProperty -import javafx.stage.FileChooser -import org.springframework.stereotype.Component -import tornadofx.* -import kotlin.collections.set - -@Component -class MainController : Controller() { - // In the future it'll be pulled from TileSetService or something like that - private val tileset = TileSet(resources.image("/textures/tileset.png"), 160, 8) - private val projectManager: ProjectManager by di() - - val openProject = SimpleObjectProperty() - val openMaps = observableMapOf() - - fun createEmptyProject() { - val project = Project() - val vm = ProjectVM(project) - - setInScope(vm) - val modal = find().apply { openModal(block = true, resizable = false) } - - if(modal.result) { - openProject.value = project - projectManager.saveProject(project) - } - } - - fun createEmptyMap() { - val map = GameMap(tileset) - val scope = UndoableScope() - val vm = GameMapVM(map) - setInScope(vm, scope) - - val modal = find(scope).apply { openModal(block = true, resizable = false) } - - if (modal.result) { - openMaps[scope] = map - } - } - - fun loadProject() { - chooseFile( - title = "Load Project", - filters = arrayOf(FileChooser.ExtensionFilter("BASE Editor Project (*.bep)", "*.bep")), - ).getOrNull(0)?.let { openProject.value = projectManager.openProject(it) } - } +package com.bartlomiejpluta.base.editor.main.controller + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.map.model.map.GameMap +import com.bartlomiejpluta.base.editor.map.view.MapSettingsFragment +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import com.bartlomiejpluta.base.editor.project.manager.ProjectManager +import com.bartlomiejpluta.base.editor.project.model.Project +import com.bartlomiejpluta.base.editor.project.view.ProjectSettingsFragment +import com.bartlomiejpluta.base.editor.project.viewmodel.ProjectVM +import com.bartlomiejpluta.base.editor.tileset.model.TileSet +import javafx.beans.property.SimpleObjectProperty +import javafx.stage.FileChooser +import org.springframework.stereotype.Component +import tornadofx.* +import kotlin.collections.set + +@Component +class MainController : Controller() { + // In the future it'll be pulled from TileSetService or something like that + private val tileset = TileSet(resources.image("/textures/tileset.png"), 160, 8) + private val projectManager: ProjectManager by di() + + val openProject = SimpleObjectProperty() + val openMaps = observableMapOf() + + fun createEmptyProject() { + val project = Project() + val vm = ProjectVM(project) + + setInScope(vm) + val modal = find().apply { openModal(block = true, resizable = false) } + + if(modal.result) { + openProject.value = project + projectManager.saveProject(project) + } + } + + fun createEmptyMap() { + val map = GameMap(tileset) + val scope = UndoableScope() + val vm = GameMapVM(map) + setInScope(vm, scope) + + val modal = find(scope).apply { openModal(block = true, resizable = false) } + + if (modal.result) { + openMaps[scope] = map + } + } + + fun loadProject() { + chooseFile( + title = "Load Project", + filters = arrayOf(FileChooser.ExtensionFilter("BASE Editor Project (*.bep)", "*.bep")), + ).getOrNull(0)?.let { openProject.value = projectManager.openProject(it) } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainMenuView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainMenuView.kt old mode 100755 new mode 100644 index daf7d569..ee35d9af --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainMenuView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainMenuView.kt @@ -1,40 +1,40 @@ -package com.bartlomiejpluta.base.editor.main.view - -import com.bartlomiejpluta.base.editor.main.controller.MainController -import tornadofx.* - -class MainMenuView : View() { - private val mainController: MainController by di() - - override val root = menubar { - menu("File") { - menu("New") { - item("Project...") { - action { - mainController.createEmptyProject() - } - } - - item("Map...") { - enableWhen(mainController.openProject.isNotNull) - action { - mainController.createEmptyMap() - } - } - } - - menu("Open") { - item("Project...") { - action { - mainController.loadProject() - } - } - } - } - - menu("Edit") { - item("Undo") - item("Redo") - } - } +package com.bartlomiejpluta.base.editor.main.view + +import com.bartlomiejpluta.base.editor.main.controller.MainController +import tornadofx.* + +class MainMenuView : View() { + private val mainController: MainController by di() + + override val root = menubar { + menu("File") { + menu("New") { + item("Project...") { + action { + mainController.createEmptyProject() + } + } + + item("Map...") { + enableWhen(mainController.openProject.isNotNull) + action { + mainController.createEmptyMap() + } + } + } + + menu("Open") { + item("Project...") { + action { + mainController.loadProject() + } + } + } + } + + menu("Edit") { + item("Undo") + item("Redo") + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainView.kt old mode 100755 new mode 100644 index 29ce7dab..a49718b2 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/main/view/MainView.kt @@ -1,34 +1,34 @@ -package com.bartlomiejpluta.base.editor.main.view - -import com.bartlomiejpluta.base.editor.main.controller.MainController -import com.bartlomiejpluta.base.editor.map.view.MapFragment -import javafx.scene.control.Tab -import tornadofx.* - - -class MainView : View("BASE Game Editor") { - private val mainController: MainController by di() - - private val mainMenuView = find() - - init { - mainController.openProject.addListener { _, _, project -> - val projectName = project?.let { " :: ${it.name} (${it.sourceDirectory.absolutePath})" } ?: "" - title = "BASE Game Editor$projectName" - } - } - - override val root = borderpane { - top = mainMenuView.root - - center = tabpane { - tabs.bind(mainController.openMaps) { scope, map -> - Tab().apply { - textProperty().bindBidirectional(map.nameProperty) - content = find(scope).root - setOnClosed { mainController.openMaps.remove(scope) } - } - } - } - } +package com.bartlomiejpluta.base.editor.main.view + +import com.bartlomiejpluta.base.editor.main.controller.MainController +import com.bartlomiejpluta.base.editor.map.view.MapFragment +import javafx.scene.control.Tab +import tornadofx.* + + +class MainView : View("BASE Game Editor") { + private val mainController: MainController by di() + + private val mainMenuView = find() + + init { + mainController.openProject.addListener { _, _, project -> + val projectName = project?.let { " :: ${it.name} (${it.sourceDirectory.absolutePath})" } ?: "" + title = "BASE Game Editor$projectName" + } + } + + override val root = borderpane { + top = mainMenuView.root + + center = tabpane { + tabs.bind(mainController.openMaps) { scope, map -> + Tab().apply { + textProperty().bindBidirectional(map.nameProperty) + content = find(scope).root + setOnClosed { mainController.openMaps.remove(scope) } + } + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapCanvas.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapCanvas.kt old mode 100755 new mode 100644 index 34bed6fb..22970525 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapCanvas.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapCanvas.kt @@ -1,98 +1,98 @@ -package com.bartlomiejpluta.base.editor.map.canvas - -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer -import com.bartlomiejpluta.base.editor.render.model.Renderable -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.canvas.GraphicsContext -import javafx.scene.paint.Color - - -class MapCanvas(val map: GameMapVM, private val editorStateVM: EditorStateVM, private val painter: MapPainter) : Renderable { - var tileSet = map.tileSet - private var tileWidth = map.tileWidth - private var tileHeight = map.tileHeight - - - override fun render(gc: GraphicsContext) { - gc.clearRect(0.0, 0.0, gc.canvas.width, gc.canvas.height) - - renderBackground(gc) - renderUnderlyingLayers(gc) - renderCover(gc) - renderSelectedLayer(gc) - renderGrid(gc) - painter.render(gc) - } - - private fun renderSelectedLayer(gc: GraphicsContext) { - map.layers.getOrNull(editorStateVM.selectedLayer) ?. let { dispatchLayerRender(gc, it) } - } - - private fun renderCover(gc: GraphicsContext) { - if(!editorStateVM.coverUnderlyingLayers) { - return - } - - gc.fill = Color.color(0.0, 0.0, 0.0, 0.4) - gc.fillRect(0.0, 0.0, map.width, map.height) - } - - private fun renderUnderlyingLayers(gc: GraphicsContext) { - for(layer in map.layers.dropLast(if(editorStateVM.selectedLayer < 0) 0 else map.layers.size - editorStateVM.selectedLayer)) { - dispatchLayerRender(gc, layer) - } - } - - private fun dispatchLayerRender(gc: GraphicsContext, layer: Layer) { - when (layer) { - is TileLayer -> renderTileLayer(gc, layer) - } - } - - private fun renderBackground(gc: GraphicsContext) { - for (row in 0 until map.rows) { - for (column in 0 until map.columns) { - gc.fill = if ((row + column) % 2 == 0) BACKGROUND_COLOR1 else BACKGROUND_COLOR2 - gc.fillRect(column * tileWidth, row * tileHeight, tileWidth, tileHeight) - } - } - } - - private fun renderTileLayer(gc: GraphicsContext, tileLayer: TileLayer) { - for ((row, columns) in tileLayer.layer.withIndex()) { - for ((column, tile) in columns.withIndex()) { - if (tile != null) { - gc.drawImage(tile.image, column * tile.image.width, row * tile.image.height) - } - } - } - } - - private fun renderGrid(gc: GraphicsContext) { - if(!editorStateVM.showGrid) { - return - } - - gc.lineWidth = 1.5 - - gc.strokeLine(0.0, 0.0, map.width, 0.0) - gc.strokeLine(0.0, 0.0, 0.0, map.height) - gc.strokeLine(map.width, 0.0, map.width, map.height) - gc.strokeLine(0.0, map.height, map.width, map.height) - - for (row in 0 until map.rows) { - gc.strokeLine(0.0, row * tileHeight, map.width, row * tileHeight) - } - - for (column in 0 until map.columns) { - gc.strokeLine(column * tileWidth, 0.0, column * tileWidth, map.height) - } - } - - companion object { - private val BACKGROUND_COLOR1 = Color.color(1.0, 1.0, 1.0, 1.0) - private val BACKGROUND_COLOR2 = Color.color(0.8, 0.8, 0.8, 1.0) - } +package com.bartlomiejpluta.base.editor.map.canvas + +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer +import com.bartlomiejpluta.base.editor.render.model.Renderable +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.canvas.GraphicsContext +import javafx.scene.paint.Color + + +class MapCanvas(val map: GameMapVM, private val editorStateVM: EditorStateVM, private val painter: MapPainter) : Renderable { + var tileSet = map.tileSet + private var tileWidth = map.tileWidth + private var tileHeight = map.tileHeight + + + override fun render(gc: GraphicsContext) { + gc.clearRect(0.0, 0.0, gc.canvas.width, gc.canvas.height) + + renderBackground(gc) + renderUnderlyingLayers(gc) + renderCover(gc) + renderSelectedLayer(gc) + renderGrid(gc) + painter.render(gc) + } + + private fun renderSelectedLayer(gc: GraphicsContext) { + map.layers.getOrNull(editorStateVM.selectedLayer) ?. let { dispatchLayerRender(gc, it) } + } + + private fun renderCover(gc: GraphicsContext) { + if(!editorStateVM.coverUnderlyingLayers) { + return + } + + gc.fill = Color.color(0.0, 0.0, 0.0, 0.4) + gc.fillRect(0.0, 0.0, map.width, map.height) + } + + private fun renderUnderlyingLayers(gc: GraphicsContext) { + for(layer in map.layers.dropLast(if(editorStateVM.selectedLayer < 0) 0 else map.layers.size - editorStateVM.selectedLayer)) { + dispatchLayerRender(gc, layer) + } + } + + private fun dispatchLayerRender(gc: GraphicsContext, layer: Layer) { + when (layer) { + is TileLayer -> renderTileLayer(gc, layer) + } + } + + private fun renderBackground(gc: GraphicsContext) { + for (row in 0 until map.rows) { + for (column in 0 until map.columns) { + gc.fill = if ((row + column) % 2 == 0) BACKGROUND_COLOR1 else BACKGROUND_COLOR2 + gc.fillRect(column * tileWidth, row * tileHeight, tileWidth, tileHeight) + } + } + } + + private fun renderTileLayer(gc: GraphicsContext, tileLayer: TileLayer) { + for ((row, columns) in tileLayer.layer.withIndex()) { + for ((column, tile) in columns.withIndex()) { + if (tile != null) { + gc.drawImage(tile.image, column * tile.image.width, row * tile.image.height) + } + } + } + } + + private fun renderGrid(gc: GraphicsContext) { + if(!editorStateVM.showGrid) { + return + } + + gc.lineWidth = 1.5 + + gc.strokeLine(0.0, 0.0, map.width, 0.0) + gc.strokeLine(0.0, 0.0, 0.0, map.height) + gc.strokeLine(map.width, 0.0, map.width, map.height) + gc.strokeLine(0.0, map.height, map.width, map.height) + + for (row in 0 until map.rows) { + gc.strokeLine(0.0, row * tileHeight, map.width, row * tileHeight) + } + + for (column in 0 until map.columns) { + gc.strokeLine(column * tileWidth, 0.0, column * tileWidth, map.height) + } + } + + companion object { + private val BACKGROUND_COLOR1 = Color.color(1.0, 1.0, 1.0, 1.0) + private val BACKGROUND_COLOR2 = Color.color(0.8, 0.8, 0.8, 1.0) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPainter.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPainter.kt old mode 100755 new mode 100644 index de8d931d..b3eb6f1a --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPainter.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPainter.kt @@ -1,94 +1,94 @@ -package com.bartlomiejpluta.base.editor.map.canvas - -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent -import com.bartlomiejpluta.base.editor.render.input.MapMouseEventHandler -import com.bartlomiejpluta.base.editor.render.model.Renderable -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.canvas.GraphicsContext -import javafx.scene.input.MouseButton -import javafx.scene.input.MouseEvent -import javafx.scene.paint.Color - -class MapPainter( - private val mapVM: GameMapVM, - private val brushVM: BrushVM, - private val editorStateVM: EditorStateVM, - private val paintingCallback: (MapPaintingTrace) -> Unit -) : Renderable, MapMouseEventHandler { - private val tileWidth = mapVM.tileSet.tileWidth.toDouble() - private val tileHeight = mapVM.tileSet.tileHeight.toDouble() - - private var currentTrace: MapPaintingTrace? = null - - override fun render(gc: GraphicsContext) { - val alpha = gc.globalAlpha - gc.globalAlpha = 0.4 - - brushVM.forEach { row, column, centerRow, centerColumn, tile -> - renderTile(gc, row, column, centerRow, centerColumn, tile) - } - - gc.globalAlpha = alpha - } - - private fun renderTile(gc: GraphicsContext, row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) { - val x = tileWidth * (editorStateVM.cursorColumn - centerColumn + column) - val y = tileHeight * (editorStateVM.cursorRow - centerRow + row) - - when { - tile != null -> renderPaintingBrushTile(gc, tile, x, y) - else -> renderEraserTile(gc, x, y) - } - } - - private fun renderPaintingBrushTile(gc: GraphicsContext, tile: Tile, x: Double, y: Double) = - gc.drawImage(tile.image, x, y) - - private fun renderEraserTile(gc: GraphicsContext, x: Double, y: Double) { - gc.fill = Color.WHITE - gc.fillRect(x, y, tileWidth, tileHeight) - } - - override fun handleMouseInput(event: MapMouseEvent) { - editorStateVM.cursorRowProperty.value = event.row - editorStateVM.cursorColumnProperty.value = event.column - - when (event.type) { - MouseEvent.MOUSE_PRESSED -> beginTrace(event) - MouseEvent.MOUSE_DRAGGED -> proceedTrace(event) - MouseEvent.MOUSE_RELEASED -> commitTrace(event) - } - } - - private fun beginTrace(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY && editorStateVM.selectedLayer >= 0) { - currentTrace = MapPaintingTrace(mapVM, "Paint trace").apply { - brushVM.forEach { row, column, centerRow, centerColumn, tile -> - paint(editorStateVM.selectedLayer, editorStateVM.cursorRow - centerRow + row, editorStateVM.cursorColumn - centerColumn + column, tile) - } - } - } - } - - private fun proceedTrace(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY) { - currentTrace?.apply { - brushVM.forEach { row, column, centerRow, centerColumn, tile -> - paint(editorStateVM.selectedLayer, editorStateVM.cursorRow - centerRow + row, editorStateVM.cursorColumn - centerColumn + column, tile) - } - } - } - } - - private fun commitTrace(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY) { - currentTrace?.let { - paintingCallback(it) - currentTrace = null - } - } - } +package com.bartlomiejpluta.base.editor.map.canvas + +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent +import com.bartlomiejpluta.base.editor.render.input.MapMouseEventHandler +import com.bartlomiejpluta.base.editor.render.model.Renderable +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.canvas.GraphicsContext +import javafx.scene.input.MouseButton +import javafx.scene.input.MouseEvent +import javafx.scene.paint.Color + +class MapPainter( + private val mapVM: GameMapVM, + private val brushVM: BrushVM, + private val editorStateVM: EditorStateVM, + private val paintingCallback: (MapPaintingTrace) -> Unit +) : Renderable, MapMouseEventHandler { + private val tileWidth = mapVM.tileSet.tileWidth.toDouble() + private val tileHeight = mapVM.tileSet.tileHeight.toDouble() + + private var currentTrace: MapPaintingTrace? = null + + override fun render(gc: GraphicsContext) { + val alpha = gc.globalAlpha + gc.globalAlpha = 0.4 + + brushVM.forEach { row, column, centerRow, centerColumn, tile -> + renderTile(gc, row, column, centerRow, centerColumn, tile) + } + + gc.globalAlpha = alpha + } + + private fun renderTile(gc: GraphicsContext, row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) { + val x = tileWidth * (editorStateVM.cursorColumn - centerColumn + column) + val y = tileHeight * (editorStateVM.cursorRow - centerRow + row) + + when { + tile != null -> renderPaintingBrushTile(gc, tile, x, y) + else -> renderEraserTile(gc, x, y) + } + } + + private fun renderPaintingBrushTile(gc: GraphicsContext, tile: Tile, x: Double, y: Double) = + gc.drawImage(tile.image, x, y) + + private fun renderEraserTile(gc: GraphicsContext, x: Double, y: Double) { + gc.fill = Color.WHITE + gc.fillRect(x, y, tileWidth, tileHeight) + } + + override fun handleMouseInput(event: MapMouseEvent) { + editorStateVM.cursorRowProperty.value = event.row + editorStateVM.cursorColumnProperty.value = event.column + + when (event.type) { + MouseEvent.MOUSE_PRESSED -> beginTrace(event) + MouseEvent.MOUSE_DRAGGED -> proceedTrace(event) + MouseEvent.MOUSE_RELEASED -> commitTrace(event) + } + } + + private fun beginTrace(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY && editorStateVM.selectedLayer >= 0) { + currentTrace = MapPaintingTrace(mapVM, "Paint trace").apply { + brushVM.forEach { row, column, centerRow, centerColumn, tile -> + paint(editorStateVM.selectedLayer, editorStateVM.cursorRow - centerRow + row, editorStateVM.cursorColumn - centerColumn + column, tile) + } + } + } + } + + private fun proceedTrace(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY) { + currentTrace?.apply { + brushVM.forEach { row, column, centerRow, centerColumn, tile -> + paint(editorStateVM.selectedLayer, editorStateVM.cursorRow - centerRow + row, editorStateVM.cursorColumn - centerColumn + column, tile) + } + } + } + } + + private fun commitTrace(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY) { + currentTrace?.let { + paintingCallback(it) + currentTrace = null + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPaintingTrace.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPaintingTrace.kt old mode 100755 new mode 100644 index a2452ae8..e3614581 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPaintingTrace.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/canvas/MapPaintingTrace.kt @@ -1,56 +1,56 @@ -package com.bartlomiejpluta.base.editor.map.canvas - -import com.bartlomiejpluta.base.editor.command.model.base.Undoable -import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM - - -data class MapPaintingTrace(val map: GameMapVM, override val commandName: String) : Undoable { - private val trace = mutableListOf() - - fun paint(layerIndex: Int, row: Int, column: Int, tile: Tile?) { - if (row >= map.rows || column >= map.columns || row < 0 || column < 0 || layerIndex < 0) { - return - } - - val layer = (map.layers[layerIndex] as TileLayer).layer - val formerTile = layer[row][column] - - if (trace.isEmpty()) { - trace += Element(layerIndex, row, column, formerTile, tile) - layer[row][column] = tile - return - } - - val tileAlreadyPainted = - trace.find { it.layerIndex == layerIndex && it.row == row && it.column == column } != null - - if (!tileAlreadyPainted) { - trace += Element(layerIndex, row, column, formerTile, tile) - layer[row][column] = tile - } - } - - override fun undo() { - trace.forEach { - (map.layers[it.layerIndex] as TileLayer).layer[it.row][it.column] = it.formerTile - } - } - - override fun redo() { - trace.forEach { - (map.layers[it.layerIndex] as TileLayer).layer[it.row][it.column] = it.tile - } - } - - companion object { - private data class Element( - val layerIndex: Int, - val row: Int, - val column: Int, - val formerTile: Tile?, - val tile: Tile? - ) - } +package com.bartlomiejpluta.base.editor.map.canvas + +import com.bartlomiejpluta.base.editor.command.model.base.Undoable +import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM + + +data class MapPaintingTrace(val map: GameMapVM, override val commandName: String) : Undoable { + private val trace = mutableListOf() + + fun paint(layerIndex: Int, row: Int, column: Int, tile: Tile?) { + if (row >= map.rows || column >= map.columns || row < 0 || column < 0 || layerIndex < 0) { + return + } + + val layer = (map.layers[layerIndex] as TileLayer).layer + val formerTile = layer[row][column] + + if (trace.isEmpty()) { + trace += Element(layerIndex, row, column, formerTile, tile) + layer[row][column] = tile + return + } + + val tileAlreadyPainted = + trace.find { it.layerIndex == layerIndex && it.row == row && it.column == column } != null + + if (!tileAlreadyPainted) { + trace += Element(layerIndex, row, column, formerTile, tile) + layer[row][column] = tile + } + } + + override fun undo() { + trace.forEach { + (map.layers[it.layerIndex] as TileLayer).layer[it.row][it.column] = it.formerTile + } + } + + override fun redo() { + trace.forEach { + (map.layers[it.layerIndex] as TileLayer).layer[it.row][it.column] = it.tile + } + } + + companion object { + private data class Element( + val layerIndex: Int, + val row: Int, + val column: Int, + val formerTile: Tile?, + val tile: Tile? + ) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/component/MapPane.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/component/MapPane.kt old mode 100755 new mode 100644 index 9fee9d14..314c94e1 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/component/MapPane.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/component/MapPane.kt @@ -1,53 +1,53 @@ -package com.bartlomiejpluta.base.editor.map.component - -import com.bartlomiejpluta.base.editor.map.canvas.MapCanvas -import com.bartlomiejpluta.base.editor.map.canvas.MapPainter -import com.bartlomiejpluta.base.editor.map.canvas.MapPaintingTrace -import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.event.EventHandler -import javafx.scene.canvas.Canvas -import javafx.scene.input.MouseEvent - -class MapPane( - private val mapVM: GameMapVM, - brushVM: BrushVM, - editorStateVM: EditorStateVM, - paintingCallback: (MapPaintingTrace) -> Unit -) : Canvas(), EventHandler { - private val painter = MapPainter(mapVM, brushVM, editorStateVM, paintingCallback) - private val mapCanvas = MapCanvas(mapVM, editorStateVM, painter) - - init { - onMouseMoved = this - onMouseDragged = this - onMousePressed = this - onMouseReleased = this - - widthProperty().bind(mapVM.widthProperty) - heightProperty().bind(mapVM.heightProperty) - - mapVM.item.rowsProperty.addListener { _, _, _ -> render() } - mapVM.item.columnsProperty.addListener { _, _, _ -> render() } - - editorStateVM.showGridProperty.addListener { _, _, _ -> render() } - editorStateVM.selectedLayerProperty.addListener { _, _, _ -> render() } - editorStateVM.coverUnderlyingLayersProperty.addListener { _, _, _ -> render() } - - render() - } - - fun render() { - mapCanvas.render(graphicsContext2D) - } - - override fun handle(event: MouseEvent?) { - if (event != null) { - painter.handleMouseInput(MapMouseEvent.of(event, mapVM.tileSet)) - } - - mapCanvas.render(graphicsContext2D) - } +package com.bartlomiejpluta.base.editor.map.component + +import com.bartlomiejpluta.base.editor.map.canvas.MapCanvas +import com.bartlomiejpluta.base.editor.map.canvas.MapPainter +import com.bartlomiejpluta.base.editor.map.canvas.MapPaintingTrace +import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.event.EventHandler +import javafx.scene.canvas.Canvas +import javafx.scene.input.MouseEvent + +class MapPane( + private val mapVM: GameMapVM, + brushVM: BrushVM, + editorStateVM: EditorStateVM, + paintingCallback: (MapPaintingTrace) -> Unit +) : Canvas(), EventHandler { + private val painter = MapPainter(mapVM, brushVM, editorStateVM, paintingCallback) + private val mapCanvas = MapCanvas(mapVM, editorStateVM, painter) + + init { + onMouseMoved = this + onMouseDragged = this + onMousePressed = this + onMouseReleased = this + + widthProperty().bind(mapVM.widthProperty) + heightProperty().bind(mapVM.heightProperty) + + mapVM.item.rowsProperty.addListener { _, _, _ -> render() } + mapVM.item.columnsProperty.addListener { _, _, _ -> render() } + + editorStateVM.showGridProperty.addListener { _, _, _ -> render() } + editorStateVM.selectedLayerProperty.addListener { _, _, _ -> render() } + editorStateVM.coverUnderlyingLayersProperty.addListener { _, _, _ -> render() } + + render() + } + + fun render() { + mapCanvas.render(graphicsContext2D) + } + + override fun handle(event: MouseEvent?) { + if (event != null) { + painter.handleMouseInput(MapMouseEvent.of(event, mapVM.tileSet)) + } + + mapCanvas.render(graphicsContext2D) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/Brush.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/Brush.kt old mode 100755 new mode 100644 index c9f2fb80..cd6994e3 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/Brush.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/Brush.kt @@ -1,97 +1,97 @@ -package com.bartlomiejpluta.base.editor.map.model.brush - -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import javafx.beans.property.SimpleIntegerProperty -import javafx.beans.property.SimpleObjectProperty -import javafx.collections.ObservableList -import tornadofx.asObservable -import tornadofx.getValue -import tornadofx.observableListOf -import tornadofx.setValue - -class Brush { - val brush: ObservableList - - val rowsProperty = SimpleIntegerProperty(0) - var rows by rowsProperty - private set - - val columnsProperty = SimpleIntegerProperty(0) - var columns by columnsProperty - private set - - val rangeProperty = SimpleIntegerProperty(1) - var range by rangeProperty - private set - - val modeProperty = SimpleObjectProperty(BrushMode.PAINTING_MODE) - var mode by modeProperty - private set - - private constructor(brushArray: Array>) { - rowsProperty.value = brushArray.size - - brush = observableListOf() - - brushArray.forEach { brush.addAll(it) } - - if (rowsProperty.value > 0) { - columns = brush.size / rowsProperty.value - } - } - - private constructor(brush: List, rows: Int, columns: Int) { - this.rows = rows - this.columns = columns - - this.brush = brush.asObservable() - } - - fun forEach(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { - return when { - range > 1 || mode == BrushMode.ERASING_MODE -> forEachInRangedBrush(consumer) - else -> forEachInRegularBrush(consumer) - } - } - - private fun forEachInRangedBrush(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { - val center = range / 2 - - (0 until range).forEach { row -> - (0 until range).forEach { column -> - consumer(row, column, center, center, getTileByMode(brush[0])) - } - } - } - - private fun getTileByMode(tile: Tile) = when (mode) { - BrushMode.PAINTING_MODE -> tile - BrushMode.ERASING_MODE -> null - } - - private fun forEachInRegularBrush(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { - val centerRow = rows / 2 - val centerColumn = columns / 2 - - brush.forEachIndexed { id, tile -> - consumer(id / columns, id % columns, centerRow, centerColumn, getTileByMode(tile)) - } - } - - private fun clone() = Brush(brush, rows, columns).apply { - this.range = this@Brush.range - this.mode = this@Brush.mode - } - - fun withRange(range: Int) = clone().apply { - this.range = range - } - - fun withMode(mode: BrushMode) = clone().apply { - this.mode = mode - } - - companion object { - fun of(brushArray: Array>) = Brush(brushArray) - } -} +package com.bartlomiejpluta.base.editor.map.model.brush + +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import javafx.beans.property.SimpleIntegerProperty +import javafx.beans.property.SimpleObjectProperty +import javafx.collections.ObservableList +import tornadofx.asObservable +import tornadofx.getValue +import tornadofx.observableListOf +import tornadofx.setValue + +class Brush { + val brush: ObservableList + + val rowsProperty = SimpleIntegerProperty(0) + var rows by rowsProperty + private set + + val columnsProperty = SimpleIntegerProperty(0) + var columns by columnsProperty + private set + + val rangeProperty = SimpleIntegerProperty(1) + var range by rangeProperty + private set + + val modeProperty = SimpleObjectProperty(BrushMode.PAINTING_MODE) + var mode by modeProperty + private set + + private constructor(brushArray: Array>) { + rowsProperty.value = brushArray.size + + brush = observableListOf() + + brushArray.forEach { brush.addAll(it) } + + if (rowsProperty.value > 0) { + columns = brush.size / rowsProperty.value + } + } + + private constructor(brush: List, rows: Int, columns: Int) { + this.rows = rows + this.columns = columns + + this.brush = brush.asObservable() + } + + fun forEach(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { + return when { + range > 1 || mode == BrushMode.ERASING_MODE -> forEachInRangedBrush(consumer) + else -> forEachInRegularBrush(consumer) + } + } + + private fun forEachInRangedBrush(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { + val center = range / 2 + + (0 until range).forEach { row -> + (0 until range).forEach { column -> + consumer(row, column, center, center, getTileByMode(brush[0])) + } + } + } + + private fun getTileByMode(tile: Tile) = when (mode) { + BrushMode.PAINTING_MODE -> tile + BrushMode.ERASING_MODE -> null + } + + private fun forEachInRegularBrush(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) { + val centerRow = rows / 2 + val centerColumn = columns / 2 + + brush.forEachIndexed { id, tile -> + consumer(id / columns, id % columns, centerRow, centerColumn, getTileByMode(tile)) + } + } + + private fun clone() = Brush(brush, rows, columns).apply { + this.range = this@Brush.range + this.mode = this@Brush.mode + } + + fun withRange(range: Int) = clone().apply { + this.range = range + } + + fun withMode(mode: BrushMode) = clone().apply { + this.mode = mode + } + + companion object { + fun of(brushArray: Array>) = Brush(brushArray) + } +} diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/BrushMode.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/BrushMode.kt old mode 100755 new mode 100644 index 57b20257..6177c07a --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/BrushMode.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/brush/BrushMode.kt @@ -1,6 +1,6 @@ -package com.bartlomiejpluta.base.editor.map.model.brush - -enum class BrushMode { - PAINTING_MODE, - ERASING_MODE +package com.bartlomiejpluta.base.editor.map.model.brush + +enum class BrushMode { + PAINTING_MODE, + ERASING_MODE } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/Layer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/Layer.kt old mode 100755 new mode 100644 index 09011cf0..30d320cc --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/Layer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/Layer.kt @@ -1,12 +1,12 @@ -package com.bartlomiejpluta.base.editor.map.model.layer - -import javafx.beans.property.StringProperty - -interface Layer { - var name: String - val nameProperty: StringProperty - - fun resize(rows: Int, columns: Int) - - fun clone(): Layer +package com.bartlomiejpluta.base.editor.map.model.layer + +import javafx.beans.property.StringProperty + +interface Layer { + var name: String + val nameProperty: StringProperty + + fun resize(rows: Int, columns: Int) + + fun clone(): Layer } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/TileLayer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/TileLayer.kt old mode 100755 new mode 100644 index d62c70eb..273eb3fe --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/TileLayer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/layer/TileLayer.kt @@ -1,31 +1,31 @@ -package com.bartlomiejpluta.base.editor.map.model.layer - -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import javafx.beans.property.SimpleStringProperty -import tornadofx.getValue -import tornadofx.setValue - -class TileLayer( - name: String, - rows: Int, - columns: Int, - layer: Array> = Array(rows) { Array(columns) { null } } -) : Layer { - var layer = layer - private set - - override val nameProperty = SimpleStringProperty(name) - override var name: String by nameProperty - - override fun resize(rows: Int, columns: Int) { - layer = Array(rows) { row -> - Array(columns) { column -> - layer.getOrNull(row)?.getOrNull(column) - } - } - } - - override fun clone() = TileLayer(name, 0, 0).apply { - layer = this@TileLayer.layer - } +package com.bartlomiejpluta.base.editor.map.model.layer + +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import javafx.beans.property.SimpleStringProperty +import tornadofx.getValue +import tornadofx.setValue + +class TileLayer( + name: String, + rows: Int, + columns: Int, + layer: Array> = Array(rows) { Array(columns) { null } } +) : Layer { + var layer = layer + private set + + override val nameProperty = SimpleStringProperty(name) + override var name: String by nameProperty + + override fun resize(rows: Int, columns: Int) { + layer = Array(rows) { row -> + Array(columns) { column -> + layer.getOrNull(row)?.getOrNull(column) + } + } + } + + override fun clone() = TileLayer(name, 0, 0).apply { + layer = this@TileLayer.layer + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/map/GameMap.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/map/GameMap.kt old mode 100755 new mode 100644 index ea1def88..59618e0a --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/map/GameMap.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/model/map/GameMap.kt @@ -1,54 +1,54 @@ -package com.bartlomiejpluta.base.editor.map.model.map - -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.tileset.model.TileSet -import javafx.beans.property.SimpleDoubleProperty -import javafx.beans.property.SimpleIntegerProperty -import javafx.beans.property.SimpleStringProperty -import tornadofx.getValue -import tornadofx.observableListOf -import tornadofx.setValue - - -class GameMap(val tileSet: TileSet) { - val layers = observableListOf() - - val nameProperty = SimpleStringProperty() - var name by nameProperty - - val tileWidth = tileSet.tileWidth.toDouble() - val tileHeight = tileSet.tileHeight.toDouble() - - val rowsProperty = SimpleIntegerProperty(INITIAL_ROWS) - var rows by rowsProperty - - val columnsProperty = SimpleIntegerProperty(INITIAL_COLUMNS) - var columns by columnsProperty - - val widthProperty = SimpleDoubleProperty(INITIAL_COLUMNS * tileWidth) - var width by widthProperty - private set - - val heightProperty = SimpleDoubleProperty(INITIAL_ROWS * tileHeight) - var height by heightProperty - private set - - init { - rowsProperty.addListener { _, _, newValue -> - val newRows = newValue.toInt() - height = newRows * tileWidth - layers.forEach { it.resize(newRows, columns) } - } - - columnsProperty.addListener { _, _, newValue -> - val newColumns = newValue.toInt() - width = newColumns * tileWidth - layers.forEach { it.resize(rows, newColumns) } - } - } - - companion object { - private const val INITIAL_ROWS = 20 - private const val INITIAL_COLUMNS = 20 - } -} +package com.bartlomiejpluta.base.editor.map.model.map + +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.tileset.model.TileSet +import javafx.beans.property.SimpleDoubleProperty +import javafx.beans.property.SimpleIntegerProperty +import javafx.beans.property.SimpleStringProperty +import tornadofx.getValue +import tornadofx.observableListOf +import tornadofx.setValue + + +class GameMap(val tileSet: TileSet) { + val layers = observableListOf() + + val nameProperty = SimpleStringProperty() + var name by nameProperty + + val tileWidth = tileSet.tileWidth.toDouble() + val tileHeight = tileSet.tileHeight.toDouble() + + val rowsProperty = SimpleIntegerProperty(INITIAL_ROWS) + var rows by rowsProperty + + val columnsProperty = SimpleIntegerProperty(INITIAL_COLUMNS) + var columns by columnsProperty + + val widthProperty = SimpleDoubleProperty(INITIAL_COLUMNS * tileWidth) + var width by widthProperty + private set + + val heightProperty = SimpleDoubleProperty(INITIAL_ROWS * tileHeight) + var height by heightProperty + private set + + init { + rowsProperty.addListener { _, _, newValue -> + val newRows = newValue.toInt() + height = newRows * tileWidth + layers.forEach { it.resize(newRows, columns) } + } + + columnsProperty.addListener { _, _, newValue -> + val newColumns = newValue.toInt() + width = newColumns * tileWidth + layers.forEach { it.resize(rows, newColumns) } + } + } + + companion object { + private const val INITIAL_ROWS = 20 + private const val INITIAL_COLUMNS = 20 + } +} diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapDeserializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapDeserializer.kt old mode 100755 new mode 100644 index e2618f47..d58f1823 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapDeserializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapDeserializer.kt @@ -1,6 +1,6 @@ -package com.bartlomiejpluta.base.editor.map.serial - -import com.bartlomiejpluta.base.editor.common.serial.Deserializer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap - +package com.bartlomiejpluta.base.editor.map.serial + +import com.bartlomiejpluta.base.editor.common.serial.Deserializer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap + interface MapDeserializer : Deserializer \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapSerializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapSerializer.kt old mode 100755 new mode 100644 index 2190d62a..2b8c3af8 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapSerializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/MapSerializer.kt @@ -1,6 +1,6 @@ -package com.bartlomiejpluta.base.editor.map.serial - -import com.bartlomiejpluta.base.editor.common.serial.Serializer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap - +package com.bartlomiejpluta.base.editor.map.serial + +import com.bartlomiejpluta.base.editor.common.serial.Serializer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap + interface MapSerializer : Serializer \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapDeserializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapDeserializer.kt old mode 100755 new mode 100644 index 00c503ae..0f60a96c --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapDeserializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapDeserializer.kt @@ -1,52 +1,52 @@ -package com.bartlomiejpluta.base.editor.map.serial - -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import com.bartlomiejpluta.base.editor.tileset.model.TileSet -import com.bartlomiejpluta.base.proto.GameMapProto -import org.springframework.stereotype.Component -import tornadofx.ResourceLookup -import java.io.InputStream - -@Component -class ProtobufMapDeserializer : MapDeserializer { - private val resources = ResourceLookup(this) - private val tileset = TileSet(resources.image("/textures/tileset.png"), 160, 8) - - override fun deserialize(input: InputStream): GameMap { - val map = GameMap(tileset) - val proto = GameMapProto.GameMap.parseFrom(input) - map.name = proto.name - map.rows = proto.rows - map.columns = proto.columns - - proto.layersList.forEach { - map.layers.add(deserializeLayer(map.rows, map.columns, tileset, it)) - } - - return map - } - - private fun deserializeLayer(rows: Int, columns: Int, tileSet: TileSet, proto: GameMapProto.Layer): Layer { - return when { - proto.hasTileLayer() -> deserializeTileLayer(rows, columns, tileSet, proto) - - else -> throw IllegalStateException("Not supported layer type") - } - } - - private fun deserializeTileLayer(rows: Int, columns: Int, tileSet: TileSet, proto: GameMapProto.Layer): Layer { - val layer: Array> = Array(rows) { Array(columns) { null } } - - proto.tileLayer.tilesList.forEachIndexed { index, tile -> - layer[index / columns][index % columns] = when(tile) { - 0 -> null - else -> tileSet.getTile(tile-1) - } - } - - return TileLayer(proto.name, rows, columns, layer) - } +package com.bartlomiejpluta.base.editor.map.serial + +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import com.bartlomiejpluta.base.editor.tileset.model.TileSet +import com.bartlomiejpluta.base.proto.GameMapProto +import org.springframework.stereotype.Component +import tornadofx.ResourceLookup +import java.io.InputStream + +@Component +class ProtobufMapDeserializer : MapDeserializer { + private val resources = ResourceLookup(this) + private val tileset = TileSet(resources.image("/textures/tileset.png"), 160, 8) + + override fun deserialize(input: InputStream): GameMap { + val map = GameMap(tileset) + val proto = GameMapProto.GameMap.parseFrom(input) + map.name = proto.name + map.rows = proto.rows + map.columns = proto.columns + + proto.layersList.forEach { + map.layers.add(deserializeLayer(map.rows, map.columns, tileset, it)) + } + + return map + } + + private fun deserializeLayer(rows: Int, columns: Int, tileSet: TileSet, proto: GameMapProto.Layer): Layer { + return when { + proto.hasTileLayer() -> deserializeTileLayer(rows, columns, tileSet, proto) + + else -> throw IllegalStateException("Not supported layer type") + } + } + + private fun deserializeTileLayer(rows: Int, columns: Int, tileSet: TileSet, proto: GameMapProto.Layer): Layer { + val layer: Array> = Array(rows) { Array(columns) { null } } + + proto.tileLayer.tilesList.forEachIndexed { index, tile -> + layer[index / columns][index % columns] = when(tile) { + 0 -> null + else -> tileSet.getTile(tile-1) + } + } + + return TileLayer(proto.name, rows, columns, layer) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapSerializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapSerializer.kt old mode 100755 new mode 100644 index 12d411a8..a08a89c4 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapSerializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/serial/ProtobufMapSerializer.kt @@ -1,34 +1,34 @@ -package com.bartlomiejpluta.base.editor.map.serial - -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap -import com.bartlomiejpluta.base.proto.GameMapProto -import org.springframework.stereotype.Component -import java.io.OutputStream - -@Component -class ProtobufMapSerializer : MapSerializer { - - override fun serialize(item: GameMap, output: OutputStream) { - val protoMap = GameMapProto.GameMap.newBuilder() - protoMap.name = item.name - protoMap.rows = item.rows - protoMap.columns = item.columns - - item.layers.forEach { layer -> protoMap.addLayers(serializeLayer(layer)) } - - protoMap.build().writeTo(output) - } - - private fun serializeLayer(layer: Layer): GameMapProto.Layer { - return when (layer) { - is TileLayer -> layer.layer.flatMap { it.asIterable() } - .fold(GameMapProto.TileLayer.newBuilder()) { acc, tile -> acc.addTiles((tile?.id?.plus(1)) ?: 0) } - .build() - .let { GameMapProto.Layer.newBuilder().setName(layer.name).setTileLayer(it).build() } - - else -> throw IllegalStateException("Not supported layer type") - } - } +package com.bartlomiejpluta.base.editor.map.serial + +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap +import com.bartlomiejpluta.base.proto.GameMapProto +import org.springframework.stereotype.Component +import java.io.OutputStream + +@Component +class ProtobufMapSerializer : MapSerializer { + + override fun serialize(item: GameMap, output: OutputStream) { + val protoMap = GameMapProto.GameMap.newBuilder() + protoMap.name = item.name + protoMap.rows = item.rows + protoMap.columns = item.columns + + item.layers.forEach { layer -> protoMap.addLayers(serializeLayer(layer)) } + + protoMap.build().writeTo(output) + } + + private fun serializeLayer(layer: Layer): GameMapProto.Layer { + return when (layer) { + is TileLayer -> layer.layer.flatMap { it.asIterable() } + .fold(GameMapProto.TileLayer.newBuilder()) { acc, tile -> acc.addTiles((tile?.id?.plus(1)) ?: 0) } + .build() + .let { GameMapProto.Layer.newBuilder().setName(layer.name).setTileLayer(it).build() } + + else -> throw IllegalStateException("Not supported layer type") + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapFragment.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapFragment.kt old mode 100755 new mode 100644 index 41aeec11..ba531d50 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapFragment.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapFragment.kt @@ -1,36 +1,36 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.tileset.view.TileSetView -import tornadofx.* - - -class MapFragment : Fragment() { - override val scope = super.scope as UndoableScope - - private val mapView = find() - private val layersView = find() - private val tileSetView = find() - private val toolbarView = find() - private val statusBarView = find() - - override val root = borderpane { - top = toolbarView.root - - center = mapView.root - - right = drawer(multiselect = true) { - item("Layers", expanded = true) { - this += layersView.root - } - - item("Tile Set", expanded = true) { - this += tileSetView.root.apply { - maxHeightProperty().bind(this@item.heightProperty()) - } - } - } - - bottom = statusBarView.root - } -} +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.tileset.view.TileSetView +import tornadofx.* + + +class MapFragment : Fragment() { + override val scope = super.scope as UndoableScope + + private val mapView = find() + private val layersView = find() + private val tileSetView = find() + private val toolbarView = find() + private val statusBarView = find() + + override val root = borderpane { + top = toolbarView.root + + center = mapView.root + + right = drawer(multiselect = true) { + item("Layers", expanded = true) { + this += layersView.root + } + + item("Tile Set", expanded = true) { + this += tileSetView.root.apply { + maxHeightProperty().bind(this@item.heightProperty()) + } + } + } + + bottom = statusBarView.root + } +} diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapLayersView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapLayersView.kt old mode 100755 new mode 100644 index 968bfdb5..85bea7b0 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapLayersView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapLayersView.kt @@ -1,95 +1,95 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.command.model.map.CreateLayerCommand -import com.bartlomiejpluta.base.editor.command.model.map.MoveLayerCommand -import com.bartlomiejpluta.base.editor.command.model.map.RemoveLayerCommand -import com.bartlomiejpluta.base.editor.command.model.map.RenameLayerCommand -import com.bartlomiejpluta.base.editor.command.service.UndoRedoService -import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.control.TableView -import org.kordamp.ikonli.javafx.FontIcon -import tornadofx.* - -class MapLayersView : View() { - private val undoRedoService: UndoRedoService by di() - - override val scope = super.scope as UndoableScope - - private val mapVM = find() - - private val editorStateVM = find() - - private var layersPane = TableView(mapVM.layers).apply { - column("Layer Name", Layer::nameProperty).makeEditable().setOnEditCommit { - val command = RenameLayerCommand(it.rowValue, it.newValue) - command.execute() - undoRedoService.push(command, scope) - } - - editorStateVM.selectedLayerProperty.bind(selectionModel.selectedIndexProperty()) - } - - override val root = borderpane { - center = layersPane - - bottom = toolbar { - button(graphic = FontIcon("fa-plus")) { - action { - val tileLayer = TileLayer("Layer ${mapVM.layers.size + 1}", mapVM.rows, mapVM.columns) - val command = CreateLayerCommand(mapVM.item, tileLayer) - command.execute() - layersPane.selectionModel.select(mapVM.layers.size - 1) - undoRedoService.push(command, scope) - } - } - - button(graphic = FontIcon("fa-chevron-up")) { - enableWhen(editorStateVM.selectedLayerProperty.greaterThan(0)) - action { - val newIndex = editorStateVM.selectedLayer - 1 - val command = MoveLayerCommand(mapVM.item, editorStateVM.selectedLayer, newIndex) - command.execute() - layersPane.selectionModel.select(newIndex) - fire(RedrawMapRequestEvent) - undoRedoService.push(command, scope) - } - } - - button(graphic = FontIcon("fa-chevron-down")) { - enableWhen( - editorStateVM.selectedLayerProperty.lessThan(mapVM.layers.sizeProperty().minus(1)) - .and(editorStateVM.selectedLayerProperty.greaterThanOrEqualTo(0)) - ) - action { - val newIndex = editorStateVM.selectedLayer + 1 - val command = MoveLayerCommand(mapVM.item, editorStateVM.selectedLayer, newIndex) - command.execute() - layersPane.selectionModel.select(newIndex) - fire(RedrawMapRequestEvent) - undoRedoService.push(command, scope) - } - } - - button(graphic = FontIcon("fa-trash")) { - enableWhen(editorStateVM.selectedLayerProperty.greaterThanOrEqualTo(0)) - action { - var index = editorStateVM.selectedLayer - val command = RemoveLayerCommand(mapVM.item, index) - command.execute() - - if (--index >= 0) { - layersPane.selectionModel.select(index) - } - - fire(RedrawMapRequestEvent) - undoRedoService.push(command, scope) - } - } - } - } +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.command.model.map.CreateLayerCommand +import com.bartlomiejpluta.base.editor.command.model.map.MoveLayerCommand +import com.bartlomiejpluta.base.editor.command.model.map.RemoveLayerCommand +import com.bartlomiejpluta.base.editor.command.model.map.RenameLayerCommand +import com.bartlomiejpluta.base.editor.command.service.UndoRedoService +import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.layer.TileLayer +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.control.TableView +import org.kordamp.ikonli.javafx.FontIcon +import tornadofx.* + +class MapLayersView : View() { + private val undoRedoService: UndoRedoService by di() + + override val scope = super.scope as UndoableScope + + private val mapVM = find() + + private val editorStateVM = find() + + private var layersPane = TableView(mapVM.layers).apply { + column("Layer Name", Layer::nameProperty).makeEditable().setOnEditCommit { + val command = RenameLayerCommand(it.rowValue, it.newValue) + command.execute() + undoRedoService.push(command, scope) + } + + editorStateVM.selectedLayerProperty.bind(selectionModel.selectedIndexProperty()) + } + + override val root = borderpane { + center = layersPane + + bottom = toolbar { + button(graphic = FontIcon("fa-plus")) { + action { + val tileLayer = TileLayer("Layer ${mapVM.layers.size + 1}", mapVM.rows, mapVM.columns) + val command = CreateLayerCommand(mapVM.item, tileLayer) + command.execute() + layersPane.selectionModel.select(mapVM.layers.size - 1) + undoRedoService.push(command, scope) + } + } + + button(graphic = FontIcon("fa-chevron-up")) { + enableWhen(editorStateVM.selectedLayerProperty.greaterThan(0)) + action { + val newIndex = editorStateVM.selectedLayer - 1 + val command = MoveLayerCommand(mapVM.item, editorStateVM.selectedLayer, newIndex) + command.execute() + layersPane.selectionModel.select(newIndex) + fire(RedrawMapRequestEvent) + undoRedoService.push(command, scope) + } + } + + button(graphic = FontIcon("fa-chevron-down")) { + enableWhen( + editorStateVM.selectedLayerProperty.lessThan(mapVM.layers.sizeProperty().minus(1)) + .and(editorStateVM.selectedLayerProperty.greaterThanOrEqualTo(0)) + ) + action { + val newIndex = editorStateVM.selectedLayer + 1 + val command = MoveLayerCommand(mapVM.item, editorStateVM.selectedLayer, newIndex) + command.execute() + layersPane.selectionModel.select(newIndex) + fire(RedrawMapRequestEvent) + undoRedoService.push(command, scope) + } + } + + button(graphic = FontIcon("fa-trash")) { + enableWhen(editorStateVM.selectedLayerProperty.greaterThanOrEqualTo(0)) + action { + var index = editorStateVM.selectedLayer + val command = RemoveLayerCommand(mapVM.item, index) + command.execute() + + if (--index >= 0) { + layersPane.selectionModel.select(index) + } + + fire(RedrawMapRequestEvent) + undoRedoService.push(command, scope) + } + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapSettingsFragment.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapSettingsFragment.kt old mode 100755 new mode 100644 index c3067800..1001376d --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapSettingsFragment.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapSettingsFragment.kt @@ -1,83 +1,83 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.command.service.UndoRedoService -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import org.kordamp.ikonli.javafx.FontIcon -import tornadofx.* - -class MapSettingsFragment : Fragment("Map Settings") { - override val scope = super.scope as UndoableScope - private val undoRedoService: UndoRedoService by di() - - private val mapVM = find() - - var result = false - private set - - override val root = form { - icon = FontIcon("fa-map-o") - - fieldset("Map Settings") { - field("Map name") { - textfield(mapVM.nameProperty) { - required() - whenDocked { requestFocus() } - } - } - - field("Rows") { - - textfield(mapVM.rowsProperty) { - stripNonInteger() - required() - validator { - when (it?.toIntOrNull()) { - in 1..50 -> null - in 50..100 -> warning("The map sizes over 50 can impact game performance") - else -> error("The map size must be between 1 and 100") - } - } - } - } - - field("Columns") { - textfield(mapVM.columnsProperty) { - stripNonInteger() - required() - validator { - when (it?.toIntOrNull()) { - in 1..50 -> null - in 50..100 -> warning("The map sizes over 50 can impact game performance") - else -> error("The map size must be between 1 and 100") - } - } - } - } - - label("Warning: Submitting the form will clear related undo/redo stacks!") - } - - buttonbar { - button("Ok") { - shortcut("Enter") - - action { - mapVM.commit { - result = true - undoRedoService.clear(scope) - close() - } - } - } - - button("Reset") { - action { mapVM.rollback() } - } - - button("Cancel") { - action { close() } - } - } - } +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.command.service.UndoRedoService +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import org.kordamp.ikonli.javafx.FontIcon +import tornadofx.* + +class MapSettingsFragment : Fragment("Map Settings") { + override val scope = super.scope as UndoableScope + private val undoRedoService: UndoRedoService by di() + + private val mapVM = find() + + var result = false + private set + + override val root = form { + icon = FontIcon("fa-map-o") + + fieldset("Map Settings") { + field("Map name") { + textfield(mapVM.nameProperty) { + required() + whenDocked { requestFocus() } + } + } + + field("Rows") { + + textfield(mapVM.rowsProperty) { + stripNonInteger() + required() + validator { + when (it?.toIntOrNull()) { + in 1..50 -> null + in 50..100 -> warning("The map sizes over 50 can impact game performance") + else -> error("The map size must be between 1 and 100") + } + } + } + } + + field("Columns") { + textfield(mapVM.columnsProperty) { + stripNonInteger() + required() + validator { + when (it?.toIntOrNull()) { + in 1..50 -> null + in 50..100 -> warning("The map sizes over 50 can impact game performance") + else -> error("The map size must be between 1 and 100") + } + } + } + } + + label("Warning: Submitting the form will clear related undo/redo stacks!") + } + + buttonbar { + button("Ok") { + shortcut("Enter") + + action { + mapVM.commit { + result = true + undoRedoService.clear(scope) + close() + } + } + } + + button("Reset") { + action { mapVM.rollback() } + } + + button("Cancel") { + action { close() } + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapStatusBarView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapStatusBarView.kt old mode 100755 new mode 100644 index 598f04b2..85617de1 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapStatusBarView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapStatusBarView.kt @@ -1,34 +1,34 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import javafx.beans.binding.Bindings -import org.kordamp.ikonli.javafx.FontIcon -import tornadofx.* - -class MapStatusBarView : View() { - - private val editorStateVM = find() - - override val root = hbox { - spacing = 50.0 - paddingAll = 5.0 - - hbox { - this += FontIcon("fa-search-minus") - - slider(0.5..5.0) { - bind(editorStateVM.zoomProperty) - } - - this += FontIcon("fa-search-plus") - } - - label( - Bindings.format( - "Cursor: %d, %d", - editorStateVM.cursorColumnProperty.add(1), - editorStateVM.cursorRowProperty.add(1) - ) - ) - } +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import javafx.beans.binding.Bindings +import org.kordamp.ikonli.javafx.FontIcon +import tornadofx.* + +class MapStatusBarView : View() { + + private val editorStateVM = find() + + override val root = hbox { + spacing = 50.0 + paddingAll = 5.0 + + hbox { + this += FontIcon("fa-search-minus") + + slider(0.5..5.0) { + bind(editorStateVM.zoomProperty) + } + + this += FontIcon("fa-search-plus") + } + + label( + Bindings.format( + "Cursor: %d, %d", + editorStateVM.cursorColumnProperty.add(1), + editorStateVM.cursorRowProperty.add(1) + ) + ) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapToolbarView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapToolbarView.kt old mode 100755 new mode 100644 index d4d60011..347de2bb --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapToolbarView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapToolbarView.kt @@ -1,105 +1,105 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.command.service.UndoRedoService -import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent -import com.bartlomiejpluta.base.editor.map.model.brush.BrushMode -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.control.ToggleGroup -import org.kordamp.ikonli.javafx.FontIcon -import tornadofx.* - -class MapToolbarView : View() { - private val undoRedoService: UndoRedoService by di() - - override val scope = super.scope as UndoableScope - - private val mapVM = find() - private val brushVM = find() - private val editorStateVM = find() - - private val brushMode = ToggleGroup().apply { - brushVM.itemProperty.addListener { _, _, brush -> - selectedValueProperty().value = brush.mode - } - } - - override val root = toolbar { - button(graphic = FontIcon("fa-undo")) { - shortcut("Ctrl+Z") - action { - undoRedoService.undo(scope) - fire(RedrawMapRequestEvent) - } - } - - button(graphic = FontIcon("fa-repeat")) { - shortcut("Ctrl+Shift+Z") - action { - undoRedoService.redo(scope) - fire(RedrawMapRequestEvent) - } - } - - togglebutton { - graphic = FontIcon("fa-window-restore") - - action { - editorStateVM.coverUnderlyingLayers = isSelected - } - } - - togglebutton { - graphic = FontIcon("fa-th") - - action { - editorStateVM.showGrid = isSelected - } - } - - togglebutton(value = BrushMode.PAINTING_MODE, group = brushMode) { - graphic = FontIcon("fa-paint-brush") - - action { - brushVM.item = brushVM.withMode(BrushMode.PAINTING_MODE) - brushVM.commit() - } - } - - togglebutton(value = BrushMode.ERASING_MODE, group = brushMode) { - graphic = FontIcon("fa-eraser") - - action { - brushVM.item = brushVM.withMode(BrushMode.ERASING_MODE) - brushVM.commit() - } - } - - this += FontIcon("fa-paint-brush").apply { iconSize = 10 } - - slider(1..5) { - majorTickUnit = 1.0 - isSnapToTicks = true - minorTickCount = 0 - - valueProperty().addListener { _, _, newValue -> - brushVM.item = brushVM.withRange(newValue.toInt()) - brushVM.commit() - } - - brushVM.itemProperty.addListener { _, _, brush -> - value = brush.range.toDouble() - } - } - - this += FontIcon("fa-paint-brush").apply { iconSize = 15 } - - button(graphic = FontIcon("fa-sliders")) { - action { - find().openModal(block = true, resizable = false) - } - } - } +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.command.service.UndoRedoService +import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent +import com.bartlomiejpluta.base.editor.map.model.brush.BrushMode +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.control.ToggleGroup +import org.kordamp.ikonli.javafx.FontIcon +import tornadofx.* + +class MapToolbarView : View() { + private val undoRedoService: UndoRedoService by di() + + override val scope = super.scope as UndoableScope + + private val mapVM = find() + private val brushVM = find() + private val editorStateVM = find() + + private val brushMode = ToggleGroup().apply { + brushVM.itemProperty.addListener { _, _, brush -> + selectedValueProperty().value = brush.mode + } + } + + override val root = toolbar { + button(graphic = FontIcon("fa-undo")) { + shortcut("Ctrl+Z") + action { + undoRedoService.undo(scope) + fire(RedrawMapRequestEvent) + } + } + + button(graphic = FontIcon("fa-repeat")) { + shortcut("Ctrl+Shift+Z") + action { + undoRedoService.redo(scope) + fire(RedrawMapRequestEvent) + } + } + + togglebutton { + graphic = FontIcon("fa-window-restore") + + action { + editorStateVM.coverUnderlyingLayers = isSelected + } + } + + togglebutton { + graphic = FontIcon("fa-th") + + action { + editorStateVM.showGrid = isSelected + } + } + + togglebutton(value = BrushMode.PAINTING_MODE, group = brushMode) { + graphic = FontIcon("fa-paint-brush") + + action { + brushVM.item = brushVM.withMode(BrushMode.PAINTING_MODE) + brushVM.commit() + } + } + + togglebutton(value = BrushMode.ERASING_MODE, group = brushMode) { + graphic = FontIcon("fa-eraser") + + action { + brushVM.item = brushVM.withMode(BrushMode.ERASING_MODE) + brushVM.commit() + } + } + + this += FontIcon("fa-paint-brush").apply { iconSize = 10 } + + slider(1..5) { + majorTickUnit = 1.0 + isSnapToTicks = true + minorTickCount = 0 + + valueProperty().addListener { _, _, newValue -> + brushVM.item = brushVM.withRange(newValue.toInt()) + brushVM.commit() + } + + brushVM.itemProperty.addListener { _, _, brush -> + value = brush.range.toDouble() + } + } + + this += FontIcon("fa-paint-brush").apply { iconSize = 15 } + + button(graphic = FontIcon("fa-sliders")) { + action { + find().openModal(block = true, resizable = false) + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapView.kt old mode 100755 new mode 100644 index e5d18ab0..8c6264ec --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/view/MapView.kt @@ -1,64 +1,64 @@ -package com.bartlomiejpluta.base.editor.map.view - -import com.bartlomiejpluta.base.editor.command.context.UndoableScope -import com.bartlomiejpluta.base.editor.command.service.UndoRedoService -import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent -import com.bartlomiejpluta.base.editor.map.component.MapPane -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.input.MouseButton -import javafx.scene.input.MouseEvent -import javafx.scene.transform.Scale -import tornadofx.View -import tornadofx.group -import tornadofx.plusAssign -import tornadofx.scrollpane - - -class MapView : View() { - private val undoRedoService: UndoRedoService by di() - - override val scope = super.scope as UndoableScope - - private val mapVM = find() - - private val brushVM = find() - - private val editorStateVM = find() - - private val mapPane = MapPane(mapVM, brushVM, editorStateVM) { undoRedoService.push(it, scope) } - - private val zoom = Scale(1.0, 1.0, 0.0, 0.0).apply { - xProperty().bind(editorStateVM.zoomProperty) - yProperty().bind(editorStateVM.zoomProperty) - } - - init { - brushVM.item = mapVM.tileSet.baseBrush - brushVM.commit() - - subscribe { mapPane.render() } - } - - override val root = scrollpane { - prefWidth = 640.0 - prefHeight = 480.0 - isPannable = true - - group { - - // Let the ScrollPane.viewRect only pan on middle button. - addEventHandler(MouseEvent.ANY) { - if (it.button != MouseButton.MIDDLE) { - it.consume() - } - } - - group { - this += mapPane - transforms += zoom - } - } - } +package com.bartlomiejpluta.base.editor.map.view + +import com.bartlomiejpluta.base.editor.command.context.UndoableScope +import com.bartlomiejpluta.base.editor.command.service.UndoRedoService +import com.bartlomiejpluta.base.editor.event.RedrawMapRequestEvent +import com.bartlomiejpluta.base.editor.map.component.MapPane +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.EditorStateVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.input.MouseButton +import javafx.scene.input.MouseEvent +import javafx.scene.transform.Scale +import tornadofx.View +import tornadofx.group +import tornadofx.plusAssign +import tornadofx.scrollpane + + +class MapView : View() { + private val undoRedoService: UndoRedoService by di() + + override val scope = super.scope as UndoableScope + + private val mapVM = find() + + private val brushVM = find() + + private val editorStateVM = find() + + private val mapPane = MapPane(mapVM, brushVM, editorStateVM) { undoRedoService.push(it, scope) } + + private val zoom = Scale(1.0, 1.0, 0.0, 0.0).apply { + xProperty().bind(editorStateVM.zoomProperty) + yProperty().bind(editorStateVM.zoomProperty) + } + + init { + brushVM.item = mapVM.tileSet.baseBrush + brushVM.commit() + + subscribe { mapPane.render() } + } + + override val root = scrollpane { + prefWidth = 640.0 + prefHeight = 480.0 + isPannable = true + + group { + + // Let the ScrollPane.viewRect only pan on middle button. + addEventHandler(MouseEvent.ANY) { + if (it.button != MouseButton.MIDDLE) { + it.consume() + } + } + + group { + this += mapPane + transforms += zoom + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/BrushVM.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/BrushVM.kt old mode 100755 new mode 100644 index ea8b10c3..ad64e843 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/BrushVM.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/BrushVM.kt @@ -1,29 +1,29 @@ -package com.bartlomiejpluta.base.editor.map.viewmodel - -import com.bartlomiejpluta.base.editor.map.model.brush.Brush -import com.bartlomiejpluta.base.editor.map.model.brush.BrushMode -import com.bartlomiejpluta.base.editor.tileset.model.Tile -import tornadofx.ItemViewModel -import tornadofx.getValue - -class BrushVM : ItemViewModel(Brush.of(arrayOf(arrayOf()))) { - val brush = bind(Brush::brush) - - val rowsProperty = bind(Brush::rowsProperty) - val rows by rowsProperty - - val columnsProperty = bind(Brush::columnsProperty) - val columns by columnsProperty - - val rangeProperty = bind(Brush::rangeProperty) - val range by rangeProperty - - val modeProperty = bind(Brush::modeProperty) - val mode by modeProperty - - fun forEach(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) = item.forEach(consumer) - - fun withRange(range: Int) = item.withRange(range) - - fun withMode(mode: BrushMode) = item.withMode(mode) +package com.bartlomiejpluta.base.editor.map.viewmodel + +import com.bartlomiejpluta.base.editor.map.model.brush.Brush +import com.bartlomiejpluta.base.editor.map.model.brush.BrushMode +import com.bartlomiejpluta.base.editor.tileset.model.Tile +import tornadofx.ItemViewModel +import tornadofx.getValue + +class BrushVM : ItemViewModel(Brush.of(arrayOf(arrayOf()))) { + val brush = bind(Brush::brush) + + val rowsProperty = bind(Brush::rowsProperty) + val rows by rowsProperty + + val columnsProperty = bind(Brush::columnsProperty) + val columns by columnsProperty + + val rangeProperty = bind(Brush::rangeProperty) + val range by rangeProperty + + val modeProperty = bind(Brush::modeProperty) + val mode by modeProperty + + fun forEach(consumer: (row: Int, column: Int, centerRow: Int, centerColumn: Int, tile: Tile?) -> Unit) = item.forEach(consumer) + + fun withRange(range: Int) = item.withRange(range) + + fun withMode(mode: BrushMode) = item.withMode(mode) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/EditorStateVM.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/EditorStateVM.kt old mode 100755 new mode 100644 index fed090f7..bc1fa45b --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/EditorStateVM.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/EditorStateVM.kt @@ -1,28 +1,28 @@ -package com.bartlomiejpluta.base.editor.map.viewmodel - -import javafx.beans.property.SimpleBooleanProperty -import javafx.beans.property.SimpleDoubleProperty -import javafx.beans.property.SimpleIntegerProperty -import tornadofx.ViewModel -import tornadofx.getValue -import tornadofx.setValue - -class EditorStateVM : ViewModel() { - val selectedLayerProperty = SimpleIntegerProperty(0) - var selectedLayer by selectedLayerProperty - - val showGridProperty = SimpleBooleanProperty(true) - var showGrid by showGridProperty - - val coverUnderlyingLayersProperty = SimpleBooleanProperty(true) - var coverUnderlyingLayers by coverUnderlyingLayersProperty - - val zoomProperty = SimpleDoubleProperty(1.0) - var zoom by zoomProperty - - val cursorRowProperty = SimpleIntegerProperty(-1) - val cursorRow by cursorRowProperty - - val cursorColumnProperty = SimpleIntegerProperty(-1) - val cursorColumn by cursorColumnProperty +package com.bartlomiejpluta.base.editor.map.viewmodel + +import javafx.beans.property.SimpleBooleanProperty +import javafx.beans.property.SimpleDoubleProperty +import javafx.beans.property.SimpleIntegerProperty +import tornadofx.ViewModel +import tornadofx.getValue +import tornadofx.setValue + +class EditorStateVM : ViewModel() { + val selectedLayerProperty = SimpleIntegerProperty(0) + var selectedLayer by selectedLayerProperty + + val showGridProperty = SimpleBooleanProperty(true) + var showGrid by showGridProperty + + val coverUnderlyingLayersProperty = SimpleBooleanProperty(true) + var coverUnderlyingLayers by coverUnderlyingLayersProperty + + val zoomProperty = SimpleDoubleProperty(1.0) + var zoom by zoomProperty + + val cursorRowProperty = SimpleIntegerProperty(-1) + val cursorRow by cursorRowProperty + + val cursorColumnProperty = SimpleIntegerProperty(-1) + val cursorColumn by cursorColumnProperty } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/GameMapVM.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/GameMapVM.kt old mode 100755 new mode 100644 index 45db0cb8..d205bbf9 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/GameMapVM.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/map/viewmodel/GameMapVM.kt @@ -1,39 +1,39 @@ -package com.bartlomiejpluta.base.editor.map.viewmodel - -import com.bartlomiejpluta.base.editor.map.model.layer.Layer -import com.bartlomiejpluta.base.editor.map.model.map.GameMap -import javafx.beans.property.SimpleListProperty -import tornadofx.ItemViewModel -import tornadofx.getValue -import tornadofx.setValue - -class GameMapVM(map: GameMap) : ItemViewModel(map) { - val layers: SimpleListProperty = bind(GameMap::layers) - - val nameProperty = bind(GameMap::nameProperty) - var name by nameProperty - - val tileSetProperty = bind(GameMap::tileSet) - val tileSet by tileSetProperty - - val rowsProperty = bind(GameMap::rowsProperty) - var rows by rowsProperty - - val columnsProperty = bind(GameMap::columnsProperty) - var columns by columnsProperty - - val tileWidthProperty = bind(GameMap::tileWidth) - val tileWidth by tileWidthProperty - - val tileHeightProperty = bind(GameMap::tileHeight) - val tileHeight by tileHeightProperty - - val widthProperty = bind(GameMap::widthProperty) - val width by widthProperty - - val heightProperty = bind(GameMap::heightProperty) - val height by heightProperty -} - - - +package com.bartlomiejpluta.base.editor.map.viewmodel + +import com.bartlomiejpluta.base.editor.map.model.layer.Layer +import com.bartlomiejpluta.base.editor.map.model.map.GameMap +import javafx.beans.property.SimpleListProperty +import tornadofx.ItemViewModel +import tornadofx.getValue +import tornadofx.setValue + +class GameMapVM(map: GameMap) : ItemViewModel(map) { + val layers: SimpleListProperty = bind(GameMap::layers) + + val nameProperty = bind(GameMap::nameProperty) + var name by nameProperty + + val tileSetProperty = bind(GameMap::tileSet) + val tileSet by tileSetProperty + + val rowsProperty = bind(GameMap::rowsProperty) + var rows by rowsProperty + + val columnsProperty = bind(GameMap::columnsProperty) + var columns by columnsProperty + + val tileWidthProperty = bind(GameMap::tileWidth) + val tileWidth by tileWidthProperty + + val tileHeightProperty = bind(GameMap::tileHeight) + val tileHeight by tileHeightProperty + + val widthProperty = bind(GameMap::widthProperty) + val width by widthProperty + + val heightProperty = bind(GameMap::heightProperty) + val height by heightProperty +} + + + diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/DefaultProjectManager.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/DefaultProjectManager.kt old mode 100755 new mode 100644 index 50a82c43..b0f2c40d --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/DefaultProjectManager.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/DefaultProjectManager.kt @@ -1,32 +1,32 @@ -package com.bartlomiejpluta.base.editor.project.manager - -import com.bartlomiejpluta.base.editor.project.model.Project -import com.bartlomiejpluta.base.editor.project.serial.ProjectDeserializer -import com.bartlomiejpluta.base.editor.project.serial.ProjectSerializer -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Component -import java.io.File -import java.io.FileInputStream -import java.io.FileOutputStream - -@Component -class DefaultProjectManager : ProjectManager { - - @Autowired - private lateinit var projectSerializer: ProjectSerializer - - @Autowired - private lateinit var projectDeserializer: ProjectDeserializer - - override fun saveProject(project: Project) { - project.sourceDirectory.mkdirs() - - FileOutputStream(File(project.sourceDirectory, "project.bep")).use { - projectSerializer.serialize(project, it) - } - } - - override fun openProject(file: File) = FileInputStream(file) - .use { projectDeserializer.deserialize(it) } - .apply { sourceDirectoryProperty.value = file.parentFile } +package com.bartlomiejpluta.base.editor.project.manager + +import com.bartlomiejpluta.base.editor.project.model.Project +import com.bartlomiejpluta.base.editor.project.serial.ProjectDeserializer +import com.bartlomiejpluta.base.editor.project.serial.ProjectSerializer +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Component +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream + +@Component +class DefaultProjectManager : ProjectManager { + + @Autowired + private lateinit var projectSerializer: ProjectSerializer + + @Autowired + private lateinit var projectDeserializer: ProjectDeserializer + + override fun saveProject(project: Project) { + project.sourceDirectory.mkdirs() + + FileOutputStream(File(project.sourceDirectory, "project.bep")).use { + projectSerializer.serialize(project, it) + } + } + + override fun openProject(file: File) = FileInputStream(file) + .use { projectDeserializer.deserialize(it) } + .apply { sourceDirectoryProperty.value = file.parentFile } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/ProjectManager.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/ProjectManager.kt old mode 100755 new mode 100644 index 6c6cc8a8..1e122c80 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/ProjectManager.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/manager/ProjectManager.kt @@ -1,9 +1,9 @@ -package com.bartlomiejpluta.base.editor.project.manager - -import com.bartlomiejpluta.base.editor.project.model.Project -import java.io.File - -interface ProjectManager { - fun saveProject(project: Project) - fun openProject(file: File): Project +package com.bartlomiejpluta.base.editor.project.manager + +import com.bartlomiejpluta.base.editor.project.model.Project +import java.io.File + +interface ProjectManager { + fun saveProject(project: Project) + fun openProject(file: File): Project } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/model/Project.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/model/Project.kt old mode 100755 new mode 100644 index 5f5ca03d..4dadc9fe --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/model/Project.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/model/Project.kt @@ -1,14 +1,14 @@ -package com.bartlomiejpluta.base.editor.project.model - -import javafx.beans.property.SimpleObjectProperty -import javafx.beans.property.SimpleStringProperty -import tornadofx.* -import java.io.File - -class Project { - val nameProperty = SimpleStringProperty() - var name by nameProperty - - val sourceDirectoryProperty = SimpleObjectProperty() - val sourceDirectory by sourceDirectoryProperty -} +package com.bartlomiejpluta.base.editor.project.model + +import javafx.beans.property.SimpleObjectProperty +import javafx.beans.property.SimpleStringProperty +import tornadofx.* +import java.io.File + +class Project { + val nameProperty = SimpleStringProperty() + var name by nameProperty + + val sourceDirectoryProperty = SimpleObjectProperty() + val sourceDirectory by sourceDirectoryProperty +} diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectDeserializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectDeserializer.kt old mode 100755 new mode 100644 index 85f17115..c6ea244c --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectDeserializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectDeserializer.kt @@ -1,6 +1,6 @@ -package com.bartlomiejpluta.base.editor.project.serial - -import com.bartlomiejpluta.base.editor.common.serial.Deserializer -import com.bartlomiejpluta.base.editor.project.model.Project - +package com.bartlomiejpluta.base.editor.project.serial + +import com.bartlomiejpluta.base.editor.common.serial.Deserializer +import com.bartlomiejpluta.base.editor.project.model.Project + interface ProjectDeserializer : Deserializer \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectSerializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectSerializer.kt old mode 100755 new mode 100644 index 82a0f2a5..21db544d --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectSerializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProjectSerializer.kt @@ -1,6 +1,6 @@ -package com.bartlomiejpluta.base.editor.project.serial - -import com.bartlomiejpluta.base.editor.common.serial.Serializer -import com.bartlomiejpluta.base.editor.project.model.Project - +package com.bartlomiejpluta.base.editor.project.serial + +import com.bartlomiejpluta.base.editor.common.serial.Serializer +import com.bartlomiejpluta.base.editor.project.model.Project + interface ProjectSerializer : Serializer \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectDeserializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectDeserializer.kt old mode 100755 new mode 100644 index 70c4ed51..739b8a1e --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectDeserializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectDeserializer.kt @@ -1,18 +1,18 @@ -package com.bartlomiejpluta.base.editor.project.serial - -import com.bartlomiejpluta.base.editor.project.model.Project -import com.bartlomiejpluta.base.proto.ProjectProto -import org.springframework.stereotype.Component -import java.io.InputStream - -@Component -class ProtobufProjectDeserializer : ProjectDeserializer { - - override fun deserialize(input: InputStream): Project { - val proto = ProjectProto.Project.parseFrom(input) - val project = Project() - project.name = proto.name - - return project - } +package com.bartlomiejpluta.base.editor.project.serial + +import com.bartlomiejpluta.base.editor.project.model.Project +import com.bartlomiejpluta.base.proto.ProjectProto +import org.springframework.stereotype.Component +import java.io.InputStream + +@Component +class ProtobufProjectDeserializer : ProjectDeserializer { + + override fun deserialize(input: InputStream): Project { + val proto = ProjectProto.Project.parseFrom(input) + val project = Project() + project.name = proto.name + + return project + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectSerializer.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectSerializer.kt old mode 100755 new mode 100644 index d351731b..7bc1ad73 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectSerializer.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/serial/ProtobufProjectSerializer.kt @@ -1,16 +1,16 @@ -package com.bartlomiejpluta.base.editor.project.serial - -import com.bartlomiejpluta.base.editor.project.model.Project -import com.bartlomiejpluta.base.proto.ProjectProto -import org.springframework.stereotype.Component -import java.io.OutputStream - -@Component -class ProtobufProjectSerializer : ProjectSerializer { - - override fun serialize(item: Project, output: OutputStream) { - val proto = ProjectProto.Project.newBuilder() - proto.name = item.name - proto.build().writeTo(output) - } +package com.bartlomiejpluta.base.editor.project.serial + +import com.bartlomiejpluta.base.editor.project.model.Project +import com.bartlomiejpluta.base.proto.ProjectProto +import org.springframework.stereotype.Component +import java.io.OutputStream + +@Component +class ProtobufProjectSerializer : ProjectSerializer { + + override fun serialize(item: Project, output: OutputStream) { + val proto = ProjectProto.Project.newBuilder() + proto.name = item.name + proto.build().writeTo(output) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/view/ProjectSettingsFragment.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/view/ProjectSettingsFragment.kt old mode 100755 new mode 100644 index bf880a8e..749623f8 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/view/ProjectSettingsFragment.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/view/ProjectSettingsFragment.kt @@ -1,96 +1,96 @@ -package com.bartlomiejpluta.base.editor.project.view - -import com.bartlomiejpluta.base.editor.project.viewmodel.ProjectVM -import javafx.beans.binding.Bindings -import javafx.beans.binding.Bindings.createStringBinding -import javafx.beans.property.SimpleStringProperty -import tornadofx.* -import java.io.File - -class ProjectSettingsFragment : Fragment("Project Settings") { - private val projectVM = find(FX.defaultScope) - - private val rootDirectory = SimpleStringProperty("") - private val projectDirectory = SimpleStringProperty("") - private val directory = createStringBinding({ - File(rootDirectory.value, projectDirectory.value).absolutePath - }, rootDirectory, projectDirectory) - - init { - directory.addListener { _, _, path -> projectVM.sourceDirectoryProperty.value = File(path) } - } - - var result = false - private set - - override val root = form { - fieldset("Project Settings") { - field("Project Name") { - textfield(projectVM.nameProperty) { - required() - trimWhitespace() - whenDocked { requestFocus() } - } - } - - field("Project Location") { - hbox { - textfield(rootDirectory) { - trimWhitespace() - - projectVM.validationContext.addValidator(this, rootDirectory) { - when { - it.isNullOrBlank() -> error("Field is required") - !File(it).exists() -> error("Provide valid path to the direction") - else -> null - } - } - } - - button("Choose") { - action { - rootDirectory.value = chooseDirectory("Project Location")?.absolutePath - } - } - } - } - - field("Project Directory Name") { - textfield(projectDirectory) { - trimWhitespace() - - projectVM.validationContext.addValidator(this, projectDirectory) { - when { - it.isNullOrBlank() -> error("Field is required") - File(directory.value).exists() -> error("The directory ${directory.value} already exists") - else -> null - } - } - } - } - - label(Bindings.format("Directory:\n%s", directory)) - } - - buttonbar { - button("Ok") { - action { - projectVM.commit { - result = true - close() - } - } - - shortcut("Enter") - } - - button("Reset") { - action { projectVM.rollback() } - } - - button("Cancel") { - action { close() } - } - } - } +package com.bartlomiejpluta.base.editor.project.view + +import com.bartlomiejpluta.base.editor.project.viewmodel.ProjectVM +import javafx.beans.binding.Bindings +import javafx.beans.binding.Bindings.createStringBinding +import javafx.beans.property.SimpleStringProperty +import tornadofx.* +import java.io.File + +class ProjectSettingsFragment : Fragment("Project Settings") { + private val projectVM = find(FX.defaultScope) + + private val rootDirectory = SimpleStringProperty("") + private val projectDirectory = SimpleStringProperty("") + private val directory = createStringBinding({ + File(rootDirectory.value, projectDirectory.value).absolutePath + }, rootDirectory, projectDirectory) + + init { + directory.addListener { _, _, path -> projectVM.sourceDirectoryProperty.value = File(path) } + } + + var result = false + private set + + override val root = form { + fieldset("Project Settings") { + field("Project Name") { + textfield(projectVM.nameProperty) { + required() + trimWhitespace() + whenDocked { requestFocus() } + } + } + + field("Project Location") { + hbox { + textfield(rootDirectory) { + trimWhitespace() + + projectVM.validationContext.addValidator(this, rootDirectory) { + when { + it.isNullOrBlank() -> error("Field is required") + !File(it).exists() -> error("Provide valid path to the direction") + else -> null + } + } + } + + button("Choose") { + action { + rootDirectory.value = chooseDirectory("Project Location")?.absolutePath + } + } + } + } + + field("Project Directory Name") { + textfield(projectDirectory) { + trimWhitespace() + + projectVM.validationContext.addValidator(this, projectDirectory) { + when { + it.isNullOrBlank() -> error("Field is required") + File(directory.value).exists() -> error("The directory ${directory.value} already exists") + else -> null + } + } + } + } + + label(Bindings.format("Directory:\n%s", directory)) + } + + buttonbar { + button("Ok") { + action { + projectVM.commit { + result = true + close() + } + } + + shortcut("Enter") + } + + button("Reset") { + action { projectVM.rollback() } + } + + button("Cancel") { + action { close() } + } + } + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/viewmodel/ProjectVM.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/viewmodel/ProjectVM.kt old mode 100755 new mode 100644 index 54036763..51409011 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/viewmodel/ProjectVM.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/project/viewmodel/ProjectVM.kt @@ -1,12 +1,12 @@ -package com.bartlomiejpluta.base.editor.project.viewmodel - -import com.bartlomiejpluta.base.editor.project.model.Project -import tornadofx.* - -class ProjectVM(project: Project) : ItemViewModel(project) { - val nameProperty = bind(Project::nameProperty) - val name by nameProperty - - val sourceDirectoryProperty = bind(Project::sourceDirectoryProperty) - val sourceDirectory by sourceDirectoryProperty +package com.bartlomiejpluta.base.editor.project.viewmodel + +import com.bartlomiejpluta.base.editor.project.model.Project +import tornadofx.* + +class ProjectVM(project: Project) : ItemViewModel(project) { + val nameProperty = bind(Project::nameProperty) + val name by nameProperty + + val sourceDirectoryProperty = bind(Project::sourceDirectoryProperty) + val sourceDirectory by sourceDirectoryProperty } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEvent.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEvent.kt old mode 100755 new mode 100644 index 6f0d7a50..1de19890 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEvent.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEvent.kt @@ -1,18 +1,18 @@ -package com.bartlomiejpluta.base.editor.render.input - -import com.bartlomiejpluta.base.editor.tileset.model.TileSet -import javafx.event.EventType -import javafx.scene.input.MouseButton -import javafx.scene.input.MouseEvent - -class MapMouseEvent(val row: Int, val column: Int, val type: EventType, val button: MouseButton) { - - companion object { - fun of(event: MouseEvent, tileSet: TileSet) = MapMouseEvent( - (event.y / tileSet.tileHeight).toInt(), - (event.x / tileSet.tileWidth).toInt(), - event.eventType, - event.button - ) - } +package com.bartlomiejpluta.base.editor.render.input + +import com.bartlomiejpluta.base.editor.tileset.model.TileSet +import javafx.event.EventType +import javafx.scene.input.MouseButton +import javafx.scene.input.MouseEvent + +class MapMouseEvent(val row: Int, val column: Int, val type: EventType, val button: MouseButton) { + + companion object { + fun of(event: MouseEvent, tileSet: TileSet) = MapMouseEvent( + (event.y / tileSet.tileHeight).toInt(), + (event.x / tileSet.tileWidth).toInt(), + event.eventType, + event.button + ) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEventHandler.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEventHandler.kt old mode 100755 new mode 100644 index 4d23864d..5254e267 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEventHandler.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/input/MapMouseEventHandler.kt @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.editor.render.input - -interface MapMouseEventHandler { - fun handleMouseInput(event: MapMouseEvent) +package com.bartlomiejpluta.base.editor.render.input + +interface MapMouseEventHandler { + fun handleMouseInput(event: MapMouseEvent) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/model/Renderable.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/model/Renderable.kt old mode 100755 new mode 100644 index 534c27fd..b882950d --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/model/Renderable.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/render/model/Renderable.kt @@ -1,7 +1,7 @@ -package com.bartlomiejpluta.base.editor.render.model - -import javafx.scene.canvas.GraphicsContext - -interface Renderable { - fun render(gc: GraphicsContext) +package com.bartlomiejpluta.base.editor.render.model + +import javafx.scene.canvas.GraphicsContext + +interface Renderable { + fun render(gc: GraphicsContext) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UIDManager.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UIDManager.kt old mode 100755 new mode 100644 index b163f569..ea4f0995 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UIDManager.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UIDManager.kt @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.editor.resource.uid.manager - -import com.bartlomiejpluta.base.editor.resource.uid.model.UIDTarget - -interface UIDManager { - fun nextUID(target: UIDTarget): String - fun loadData(target: UIDTarget, uids: Set) +package com.bartlomiejpluta.base.editor.resource.uid.manager + +import com.bartlomiejpluta.base.editor.resource.uid.model.UIDTarget + +interface UIDManager { + fun nextUID(target: UIDTarget): String + fun loadData(target: UIDTarget, uids: Set) } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UUIDBasedUIDManager.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UUIDBasedUIDManager.kt old mode 100755 new mode 100644 index 02f98d86..a812b9cf --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UUIDBasedUIDManager.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/manager/UUIDBasedUIDManager.kt @@ -1,26 +1,26 @@ -package com.bartlomiejpluta.base.editor.resource.uid.manager - -import com.bartlomiejpluta.base.editor.resource.uid.model.UIDTarget -import org.springframework.stereotype.Component -import java.util.* - -@Component -class UUIDBasedUIDManager : UIDManager { - private val registry = mutableMapOf>() - - override fun nextUID(target: UIDTarget): String { - val set = registry.putIfAbsent(target, mutableSetOf())!! - - var uid = "" - - do { - uid = UUID.randomUUID().toString() - } while (uid !in set) - - return uid - } - - override fun loadData(target: UIDTarget, uids: Set) { - TODO("Not yet implemented") - } +package com.bartlomiejpluta.base.editor.resource.uid.manager + +import com.bartlomiejpluta.base.editor.resource.uid.model.UIDTarget +import org.springframework.stereotype.Component +import java.util.* + +@Component +class UUIDBasedUIDManager : UIDManager { + private val registry = mutableMapOf>() + + override fun nextUID(target: UIDTarget): String { + val set = registry.putIfAbsent(target, mutableSetOf())!! + + var uid = "" + + do { + uid = UUID.randomUUID().toString() + } while (uid !in set) + + return uid + } + + override fun loadData(target: UIDTarget, uids: Set) { + TODO("Not yet implemented") + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/model/UIDTarget.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/model/UIDTarget.kt old mode 100755 new mode 100644 index 79da9108..b80b5c3c --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/model/UIDTarget.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/resource/uid/model/UIDTarget.kt @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.editor.resource.uid.model - -enum class UIDTarget { - MAP +package com.bartlomiejpluta.base.editor.resource.uid.model + +enum class UIDTarget { + MAP } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetCanvas.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetCanvas.kt old mode 100755 new mode 100644 index 17f19c01..8c4ca5d9 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetCanvas.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetCanvas.kt @@ -1,69 +1,69 @@ -package com.bartlomiejpluta.base.editor.tileset.canvas - -import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent -import com.bartlomiejpluta.base.editor.render.input.MapMouseEventHandler -import com.bartlomiejpluta.base.editor.render.model.Renderable -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.canvas.GraphicsContext -import javafx.scene.input.MouseButton -import javafx.scene.input.MouseEvent -import javafx.scene.paint.Color - -class TileSetCanvas(private val gameMapVM: GameMapVM, private val selection: TileSetSelection) : Renderable, MapMouseEventHandler { - private var mouseRow = -1 - private var mouseColumn = -1 - - override fun render(gc: GraphicsContext) { - gc.clearRect(0.0, 0.0, gc.canvas.width, gc.canvas.height) - - renderTiles(gc) - selection.render(gc) - } - - private fun renderTiles(gc: GraphicsContext) { - gameMapVM.tileSet.forEach { row, column, tile -> - gc.fill = if ((row + column) % 2 == 0) BACKGROUND_COLOR1 else BACKGROUND_COLOR2 - gc.fillRect( - column * tile.image.width, - row * tile.image.height, - gameMapVM.tileSet.tileWidth.toDouble(), - gameMapVM.tileSet.tileHeight.toDouble() - ) - gc.drawImage(tile.image, column * tile.image.width, row * tile.image.height) - } - } - - override fun handleMouseInput(event: MapMouseEvent) { - mouseRow = event.row - mouseColumn = event.column - - when (event.type) { - MouseEvent.MOUSE_PRESSED -> beginSelection(event) - MouseEvent.MOUSE_DRAGGED -> proceedSelection(event) - MouseEvent.MOUSE_RELEASED -> finishSelection(event) - } - } - - private fun beginSelection(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY) { - selection.begin(event.row.toDouble(), event.column.toDouble()) - } - } - - private fun proceedSelection(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY) { - selection.proceed(event.row.toDouble(), event.column.toDouble()) - } - } - - private fun finishSelection(event: MapMouseEvent) { - if (event.button == MouseButton.PRIMARY) { - selection.finish(event.row.toDouble(), event.column.toDouble()) - } - } - - companion object { - private val BACKGROUND_COLOR1 = Color.color(1.0, 1.0, 1.0, 1.0) - private val BACKGROUND_COLOR2 = Color.color(0.95, 0.95, 0.95, 0.95) - } +package com.bartlomiejpluta.base.editor.tileset.canvas + +import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent +import com.bartlomiejpluta.base.editor.render.input.MapMouseEventHandler +import com.bartlomiejpluta.base.editor.render.model.Renderable +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.canvas.GraphicsContext +import javafx.scene.input.MouseButton +import javafx.scene.input.MouseEvent +import javafx.scene.paint.Color + +class TileSetCanvas(private val gameMapVM: GameMapVM, private val selection: TileSetSelection) : Renderable, MapMouseEventHandler { + private var mouseRow = -1 + private var mouseColumn = -1 + + override fun render(gc: GraphicsContext) { + gc.clearRect(0.0, 0.0, gc.canvas.width, gc.canvas.height) + + renderTiles(gc) + selection.render(gc) + } + + private fun renderTiles(gc: GraphicsContext) { + gameMapVM.tileSet.forEach { row, column, tile -> + gc.fill = if ((row + column) % 2 == 0) BACKGROUND_COLOR1 else BACKGROUND_COLOR2 + gc.fillRect( + column * tile.image.width, + row * tile.image.height, + gameMapVM.tileSet.tileWidth.toDouble(), + gameMapVM.tileSet.tileHeight.toDouble() + ) + gc.drawImage(tile.image, column * tile.image.width, row * tile.image.height) + } + } + + override fun handleMouseInput(event: MapMouseEvent) { + mouseRow = event.row + mouseColumn = event.column + + when (event.type) { + MouseEvent.MOUSE_PRESSED -> beginSelection(event) + MouseEvent.MOUSE_DRAGGED -> proceedSelection(event) + MouseEvent.MOUSE_RELEASED -> finishSelection(event) + } + } + + private fun beginSelection(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY) { + selection.begin(event.row.toDouble(), event.column.toDouble()) + } + } + + private fun proceedSelection(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY) { + selection.proceed(event.row.toDouble(), event.column.toDouble()) + } + } + + private fun finishSelection(event: MapMouseEvent) { + if (event.button == MouseButton.PRIMARY) { + selection.finish(event.row.toDouble(), event.column.toDouble()) + } + } + + companion object { + private val BACKGROUND_COLOR1 = Color.color(1.0, 1.0, 1.0, 1.0) + private val BACKGROUND_COLOR2 = Color.color(0.95, 0.95, 0.95, 0.95) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetSelection.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetSelection.kt old mode 100755 new mode 100644 index 13d64ecd..f66d5262 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetSelection.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/canvas/TileSetSelection.kt @@ -1,80 +1,80 @@ -package com.bartlomiejpluta.base.editor.tileset.canvas - -import com.bartlomiejpluta.base.editor.map.model.brush.Brush -import com.bartlomiejpluta.base.editor.render.model.Renderable -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.scene.canvas.GraphicsContext -import javafx.scene.paint.Color -import kotlin.math.abs -import kotlin.math.min - - -class TileSetSelection(private val gameMapVM: GameMapVM, private val brushVM: BrushVM) : Renderable { - private var startRow = 0.0 - private var startColumn = 0.0 - private var offsetRow = 0.0 - private var offsetColumn = 0.0 - private var x = 0.0 - private var y = 0.0 - private var width = gameMapVM.tileSet.tileWidth.toDouble() - private var height = gameMapVM.tileSet.tileHeight.toDouble() - - - fun begin(row: Double, column: Double) { - startRow = row - offsetRow = 0.0 - startColumn = column - offsetColumn = 0.0 - - updateRect(row, column) - } - - private fun updateRect(row: Double, column: Double) { - x = min(column, startColumn) * gameMapVM.tileSet.tileWidth - y = min(row, startRow) * gameMapVM.tileSet.tileHeight - width = (offsetColumn + 1) * gameMapVM.tileSet.tileWidth - height = (offsetRow + 1) * gameMapVM.tileSet.tileHeight - } - - fun proceed(row: Double, column: Double) { - offsetRow = abs(row - startRow) - offsetColumn = abs(column - startColumn) - - updateRect(row, column) - } - - fun finish(row: Double, column: Double) { - proceed(row, column) - - startRow = min(row, startRow) - startColumn = min(column, startColumn) - - val firstRow = startRow.toInt() - val firstColumn = startColumn.toInt() - val rows = offsetRow.toInt() + 1 - val columns = offsetColumn.toInt() + 1 - - val brushArray = Array(rows) { rowIndex -> - Array(columns) { columnIndex -> - gameMapVM.tileSet.getTile(firstRow + rowIndex, firstColumn + columnIndex) - } - } - - brushVM.item = Brush.of(brushArray) - brushVM.commit() - } - - override fun render(gc: GraphicsContext) { - gc.fill = SELECTION_FILL_COLOR - gc.fillRect(x, y, width, height) - - gc.stroke = SELECTION_STROKE_COLOR - gc.strokeRect(x, y, width, height) - } - - companion object { - private val SELECTION_FILL_COLOR = Color.color(0.0, 0.7, 1.0, 0.4) - private val SELECTION_STROKE_COLOR = Color.color(0.0, 0.7, 1.0, 1.0) - } +package com.bartlomiejpluta.base.editor.tileset.canvas + +import com.bartlomiejpluta.base.editor.map.model.brush.Brush +import com.bartlomiejpluta.base.editor.render.model.Renderable +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.scene.canvas.GraphicsContext +import javafx.scene.paint.Color +import kotlin.math.abs +import kotlin.math.min + + +class TileSetSelection(private val gameMapVM: GameMapVM, private val brushVM: BrushVM) : Renderable { + private var startRow = 0.0 + private var startColumn = 0.0 + private var offsetRow = 0.0 + private var offsetColumn = 0.0 + private var x = 0.0 + private var y = 0.0 + private var width = gameMapVM.tileSet.tileWidth.toDouble() + private var height = gameMapVM.tileSet.tileHeight.toDouble() + + + fun begin(row: Double, column: Double) { + startRow = row + offsetRow = 0.0 + startColumn = column + offsetColumn = 0.0 + + updateRect(row, column) + } + + private fun updateRect(row: Double, column: Double) { + x = min(column, startColumn) * gameMapVM.tileSet.tileWidth + y = min(row, startRow) * gameMapVM.tileSet.tileHeight + width = (offsetColumn + 1) * gameMapVM.tileSet.tileWidth + height = (offsetRow + 1) * gameMapVM.tileSet.tileHeight + } + + fun proceed(row: Double, column: Double) { + offsetRow = abs(row - startRow) + offsetColumn = abs(column - startColumn) + + updateRect(row, column) + } + + fun finish(row: Double, column: Double) { + proceed(row, column) + + startRow = min(row, startRow) + startColumn = min(column, startColumn) + + val firstRow = startRow.toInt() + val firstColumn = startColumn.toInt() + val rows = offsetRow.toInt() + 1 + val columns = offsetColumn.toInt() + 1 + + val brushArray = Array(rows) { rowIndex -> + Array(columns) { columnIndex -> + gameMapVM.tileSet.getTile(firstRow + rowIndex, firstColumn + columnIndex) + } + } + + brushVM.item = Brush.of(brushArray) + brushVM.commit() + } + + override fun render(gc: GraphicsContext) { + gc.fill = SELECTION_FILL_COLOR + gc.fillRect(x, y, width, height) + + gc.stroke = SELECTION_STROKE_COLOR + gc.strokeRect(x, y, width, height) + } + + companion object { + private val SELECTION_FILL_COLOR = Color.color(0.0, 0.7, 1.0, 0.4) + private val SELECTION_STROKE_COLOR = Color.color(0.0, 0.7, 1.0, 1.0) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/component/TileSetPane.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/component/TileSetPane.kt old mode 100755 new mode 100644 index 791f6b1f..ff5b1c37 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/component/TileSetPane.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/component/TileSetPane.kt @@ -1,42 +1,42 @@ -package com.bartlomiejpluta.base.editor.tileset.component - -import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent -import com.bartlomiejpluta.base.editor.tileset.canvas.TileSetCanvas -import com.bartlomiejpluta.base.editor.tileset.canvas.TileSetSelection -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import javafx.event.EventHandler -import javafx.scene.canvas.Canvas -import javafx.scene.input.MouseEvent - -class TileSetPane(private val gameMapVM: GameMapVM, brushVM: BrushVM) : Canvas(), EventHandler { - private val selection = TileSetSelection(gameMapVM, brushVM) - private val tileSetCanvas = TileSetCanvas(gameMapVM, selection) - - init { - onMouseMoved = this - onMouseDragged = this - onMousePressed = this - onMouseReleased = this - - width = gameMapVM.tileSet.width.toDouble() - height = gameMapVM.tileSet.height.toDouble() - - - brushVM.itemProperty.addListener { _, _, _ -> render() } - - render() - } - - private fun render() { - tileSetCanvas.render(graphicsContext2D) - } - - override fun handle(event: MouseEvent?) { - if (event != null) { - tileSetCanvas.handleMouseInput(MapMouseEvent.of(event, gameMapVM.tileSet)) - } - - tileSetCanvas.render(graphicsContext2D) - } +package com.bartlomiejpluta.base.editor.tileset.component + +import com.bartlomiejpluta.base.editor.render.input.MapMouseEvent +import com.bartlomiejpluta.base.editor.tileset.canvas.TileSetCanvas +import com.bartlomiejpluta.base.editor.tileset.canvas.TileSetSelection +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import javafx.event.EventHandler +import javafx.scene.canvas.Canvas +import javafx.scene.input.MouseEvent + +class TileSetPane(private val gameMapVM: GameMapVM, brushVM: BrushVM) : Canvas(), EventHandler { + private val selection = TileSetSelection(gameMapVM, brushVM) + private val tileSetCanvas = TileSetCanvas(gameMapVM, selection) + + init { + onMouseMoved = this + onMouseDragged = this + onMousePressed = this + onMouseReleased = this + + width = gameMapVM.tileSet.width.toDouble() + height = gameMapVM.tileSet.height.toDouble() + + + brushVM.itemProperty.addListener { _, _, _ -> render() } + + render() + } + + private fun render() { + tileSetCanvas.render(graphicsContext2D) + } + + override fun handle(event: MouseEvent?) { + if (event != null) { + tileSetCanvas.handleMouseInput(MapMouseEvent.of(event, gameMapVM.tileSet)) + } + + tileSetCanvas.render(graphicsContext2D) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/Tile.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/Tile.kt old mode 100755 new mode 100644 index 78a5538d..8c660367 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/Tile.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/Tile.kt @@ -1,55 +1,55 @@ -package com.bartlomiejpluta.base.editor.tileset.model - -import javafx.scene.image.Image - -import javafx.scene.image.PixelReader - -import javafx.scene.image.WritableImage - - -class Tile( - tileSet: TileSet, - row: Int, - column: Int, - val image: Image, -) { - val id = row * tileSet.columns + column - - private fun cloneImage(image: Image): Image { - val height = image.height.toInt() - val width = image.width.toInt() - val pixelReader = image.pixelReader - val writableImage = WritableImage(width, height) - val pixelWriter = writableImage.pixelWriter - - for (y in 0 until height) { - for (x in 0 until width) { - val color = pixelReader.getColor(x, y) - pixelWriter.setColor(x, y, color) - } - } - return writableImage - } - - fun scale(image: Image, factor: Int): Image { - val width = image.width.toInt() - val height = image.height.toInt() - val output = WritableImage(width * factor, height * factor) - - val reader: PixelReader = image.pixelReader - val writer = output.pixelWriter - - for (y in 0 until height) { - for (x in 0 until width) { - val argb = reader.getArgb(x, y) - for (dy in 0 until factor) { - for (dx in 0 until factor) { - writer.setArgb(x * factor + dx, y * factor + dy, argb) - } - } - } - } - - return output - } +package com.bartlomiejpluta.base.editor.tileset.model + +import javafx.scene.image.Image + +import javafx.scene.image.PixelReader + +import javafx.scene.image.WritableImage + + +class Tile( + tileSet: TileSet, + row: Int, + column: Int, + val image: Image, +) { + val id = row * tileSet.columns + column + + private fun cloneImage(image: Image): Image { + val height = image.height.toInt() + val width = image.width.toInt() + val pixelReader = image.pixelReader + val writableImage = WritableImage(width, height) + val pixelWriter = writableImage.pixelWriter + + for (y in 0 until height) { + for (x in 0 until width) { + val color = pixelReader.getColor(x, y) + pixelWriter.setColor(x, y, color) + } + } + return writableImage + } + + fun scale(image: Image, factor: Int): Image { + val width = image.width.toInt() + val height = image.height.toInt() + val output = WritableImage(width * factor, height * factor) + + val reader: PixelReader = image.pixelReader + val writer = output.pixelWriter + + for (y in 0 until height) { + for (x in 0 until width) { + val argb = reader.getArgb(x, y) + for (dy in 0 until factor) { + for (dx in 0 until factor) { + writer.setArgb(x * factor + dx, y * factor + dy, argb) + } + } + } + } + + return output + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/TileSet.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/TileSet.kt old mode 100755 new mode 100644 index 45c7f42c..813409b3 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/TileSet.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/model/TileSet.kt @@ -1,63 +1,63 @@ -package com.bartlomiejpluta.base.editor.tileset.model - -import com.bartlomiejpluta.base.editor.map.model.brush.Brush -import javafx.beans.property.SimpleIntegerProperty -import javafx.scene.image.Image -import javafx.scene.image.PixelFormat -import javafx.scene.image.WritableImage -import tornadofx.getValue -import tornadofx.toObservable -import java.nio.ByteBuffer - - -class TileSet(private val image: Image, rows: Int, columns: Int) { - val rowsProperty = SimpleIntegerProperty(rows) - val rows by rowsProperty - - val columnsProperty = SimpleIntegerProperty(columns) - val columns by columnsProperty - - val tileWidthProperty = SimpleIntegerProperty(image.width.toInt() / columns) - val tileWidth by tileWidthProperty - - val tileHeightProperty = SimpleIntegerProperty(image.height.toInt() / rows) - val tileHeight by tileHeightProperty - - val widthProperty = SimpleIntegerProperty(tileWidth * columns) - val width by widthProperty - - val heightProperty = SimpleIntegerProperty(tileHeight * rows) - val height by heightProperty - - val tiles = (0 until rows * columns).map { cropTile(it / columns, it % columns) }.toObservable() - - val baseBrush: Brush - get() = Brush.of(arrayOf(arrayOf(tiles[0]))) - - private fun cropTile(row: Int, column: Int): Tile { - val reader = image.pixelReader - val buffer = ByteBuffer.allocate(tileWidth * tileHeight * 4) - reader.getPixels( - column * tileWidth, - row * tileHeight, - tileWidth, - tileHeight, - PixelFormat.getByteBgraInstance(), - buffer, - 4 * tileWidth - ) - val tile = WritableImage(tileWidth, tileHeight) - val writer = tile.pixelWriter - writer.setPixels(0, 0, tileWidth, tileHeight, PixelFormat.getByteBgraInstance(), buffer, 4 * tileWidth) - - return Tile(this, row, column, tile) - } - - fun getTile(row: Int, column: Int) = tiles[(row.coerceIn(0 until rows)) * columns + column.coerceIn(0 until columns)] - - fun getTile(id: Int) = tiles[id] - - fun forEach(consumer: (row: Int, column: Int, tile: Tile) -> Unit) = tiles.forEachIndexed { id, tile -> - consumer(id / columns, id % columns, tile) - } +package com.bartlomiejpluta.base.editor.tileset.model + +import com.bartlomiejpluta.base.editor.map.model.brush.Brush +import javafx.beans.property.SimpleIntegerProperty +import javafx.scene.image.Image +import javafx.scene.image.PixelFormat +import javafx.scene.image.WritableImage +import tornadofx.getValue +import tornadofx.toObservable +import java.nio.ByteBuffer + + +class TileSet(private val image: Image, rows: Int, columns: Int) { + val rowsProperty = SimpleIntegerProperty(rows) + val rows by rowsProperty + + val columnsProperty = SimpleIntegerProperty(columns) + val columns by columnsProperty + + val tileWidthProperty = SimpleIntegerProperty(image.width.toInt() / columns) + val tileWidth by tileWidthProperty + + val tileHeightProperty = SimpleIntegerProperty(image.height.toInt() / rows) + val tileHeight by tileHeightProperty + + val widthProperty = SimpleIntegerProperty(tileWidth * columns) + val width by widthProperty + + val heightProperty = SimpleIntegerProperty(tileHeight * rows) + val height by heightProperty + + val tiles = (0 until rows * columns).map { cropTile(it / columns, it % columns) }.toObservable() + + val baseBrush: Brush + get() = Brush.of(arrayOf(arrayOf(tiles[0]))) + + private fun cropTile(row: Int, column: Int): Tile { + val reader = image.pixelReader + val buffer = ByteBuffer.allocate(tileWidth * tileHeight * 4) + reader.getPixels( + column * tileWidth, + row * tileHeight, + tileWidth, + tileHeight, + PixelFormat.getByteBgraInstance(), + buffer, + 4 * tileWidth + ) + val tile = WritableImage(tileWidth, tileHeight) + val writer = tile.pixelWriter + writer.setPixels(0, 0, tileWidth, tileHeight, PixelFormat.getByteBgraInstance(), buffer, 4 * tileWidth) + + return Tile(this, row, column, tile) + } + + fun getTile(row: Int, column: Int) = tiles[(row.coerceIn(0 until rows)) * columns + column.coerceIn(0 until columns)] + + fun getTile(id: Int) = tiles[id] + + fun forEach(consumer: (row: Int, column: Int, tile: Tile) -> Unit) = tiles.forEachIndexed { id, tile -> + consumer(id / columns, id % columns, tile) + } } \ No newline at end of file diff --git a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/view/TileSetView.kt b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/view/TileSetView.kt old mode 100755 new mode 100644 index 3d876b49..f6ce9548 --- a/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/view/TileSetView.kt +++ b/editor/src/main/kotlin/com/bartlomiejpluta/base/editor/tileset/view/TileSetView.kt @@ -1,19 +1,19 @@ -package com.bartlomiejpluta.base.editor.tileset.view - -import com.bartlomiejpluta.base.editor.tileset.component.TileSetPane -import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM -import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM -import tornadofx.View -import tornadofx.plusAssign -import tornadofx.scrollpane - -class TileSetView : View() { - private val gameMapVM = find() - private val brushVM = find() - - private val tileSetPane = TileSetPane(gameMapVM, brushVM) - - override val root = scrollpane { - this += tileSetPane - } +package com.bartlomiejpluta.base.editor.tileset.view + +import com.bartlomiejpluta.base.editor.tileset.component.TileSetPane +import com.bartlomiejpluta.base.editor.map.viewmodel.BrushVM +import com.bartlomiejpluta.base.editor.map.viewmodel.GameMapVM +import tornadofx.View +import tornadofx.plusAssign +import tornadofx.scrollpane + +class TileSetView : View() { + private val gameMapVM = find() + private val brushVM = find() + + private val tileSetPane = TileSetPane(gameMapVM, brushVM) + + override val root = scrollpane { + this += tileSetPane + } } \ No newline at end of file diff --git a/editor/src/main/resources/application.yml b/editor/src/main/resources/application.yml old mode 100755 new mode 100644 index 1753f5db..9345e5b4 --- a/editor/src/main/resources/application.yml +++ b/editor/src/main/resources/application.yml @@ -1,3 +1,3 @@ -logging: - level: +logging: + level: com.bartlomiejpluta.base.editor: DEBUG \ No newline at end of file diff --git a/engine/build.gradle b/engine/build.gradle old mode 100755 new mode 100644 diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/engine/DefaultGameEngine.java b/engine/src/main/java/com/bartlomiejpluta/base/core/engine/DefaultGameEngine.java old mode 100755 new mode 100644 index aa6711cb..ee2d14f8 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/engine/DefaultGameEngine.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/engine/DefaultGameEngine.java @@ -1,111 +1,111 @@ -package com.bartlomiejpluta.base.core.engine; - -import com.bartlomiejpluta.base.core.gc.OffHeapGarbageCollector; -import com.bartlomiejpluta.base.core.logic.GameLogic; -import com.bartlomiejpluta.base.core.thread.ThreadManager; -import com.bartlomiejpluta.base.core.time.ChronoMeter; -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.ui.WindowManager; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -public class DefaultGameEngine implements GameEngine { - private static final String THREAD_NAME = "Game Main Thread"; - - private final WindowManager windowManager; - private final ThreadManager threadManager; - private final GameLogic logic; - private final OffHeapGarbageCollector garbageCollector; - - private final Thread thread; - private final Window window; - private final ChronoMeter chrono; - private final int targetUps; - - private boolean running = false; - - @Autowired - public DefaultGameEngine(WindowManager windowManager, - ThreadManager threadManager, - GameLogic logic, - OffHeapGarbageCollector garbageCollector, - @Value("${app.window.title}") String title, - @Value("${app.window.width}") int width, - @Value("${app.window.height}") int height, - @Value("${app.core.targetUps}") int targetUps) { - this.windowManager = windowManager; - this.threadManager = threadManager; - this.logic = logic; - this.garbageCollector = garbageCollector; - - this.window = windowManager.createWindow(title, width, height); - this.thread = threadManager.createThread(THREAD_NAME, this::run); - this.chrono = new ChronoMeter(); - this.targetUps = targetUps; - } - - private void run() { - try { - init(); - loop(); - } finally { - cleanUp(); - } - } - - private void init() { - log.info("Initializing game engine"); - window.init(); - chrono.init(); - logic.init(window); - } - - private void loop() { - log.info("Starting game loop"); - running = true; - var dt = 0.0f; - var accumulator = 0.0f; - var step = 1.0f / targetUps; - - while (running && !window.shouldClose()) { - dt = chrono.getElapsedTime(); - accumulator += dt; - - input(); - - while (accumulator >= step) { - update(dt); - accumulator -= step; - } - - render(); - } - } - - private void input() { - logic.input(window); - } - - private void update(float dt) { - logic.update(dt); - } - - private void render() { - window.update(); - logic.render(window); - } - - private void cleanUp() { - log.info("Performing off heap garbage collection"); - garbageCollector.cleanUp(); - } - - @Override - public void start() { - thread.start(); - } -} +package com.bartlomiejpluta.base.core.engine; + +import com.bartlomiejpluta.base.core.gc.OffHeapGarbageCollector; +import com.bartlomiejpluta.base.core.logic.GameLogic; +import com.bartlomiejpluta.base.core.thread.ThreadManager; +import com.bartlomiejpluta.base.core.time.ChronoMeter; +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.ui.WindowManager; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class DefaultGameEngine implements GameEngine { + private static final String THREAD_NAME = "Game Main Thread"; + + private final WindowManager windowManager; + private final ThreadManager threadManager; + private final GameLogic logic; + private final OffHeapGarbageCollector garbageCollector; + + private final Thread thread; + private final Window window; + private final ChronoMeter chrono; + private final int targetUps; + + private boolean running = false; + + @Autowired + public DefaultGameEngine(WindowManager windowManager, + ThreadManager threadManager, + GameLogic logic, + OffHeapGarbageCollector garbageCollector, + @Value("${app.window.title}") String title, + @Value("${app.window.width}") int width, + @Value("${app.window.height}") int height, + @Value("${app.core.targetUps}") int targetUps) { + this.windowManager = windowManager; + this.threadManager = threadManager; + this.logic = logic; + this.garbageCollector = garbageCollector; + + this.window = windowManager.createWindow(title, width, height); + this.thread = threadManager.createThread(THREAD_NAME, this::run); + this.chrono = new ChronoMeter(); + this.targetUps = targetUps; + } + + private void run() { + try { + init(); + loop(); + } finally { + cleanUp(); + } + } + + private void init() { + log.info("Initializing game engine"); + window.init(); + chrono.init(); + logic.init(window); + } + + private void loop() { + log.info("Starting game loop"); + running = true; + var dt = 0.0f; + var accumulator = 0.0f; + var step = 1.0f / targetUps; + + while (running && !window.shouldClose()) { + dt = chrono.getElapsedTime(); + accumulator += dt; + + input(); + + while (accumulator >= step) { + update(dt); + accumulator -= step; + } + + render(); + } + } + + private void input() { + logic.input(window); + } + + private void update(float dt) { + logic.update(dt); + } + + private void render() { + window.update(); + logic.render(window); + } + + private void cleanUp() { + log.info("Performing off heap garbage collection"); + garbageCollector.cleanUp(); + } + + @Override + public void start() { + thread.start(); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/engine/GameEngine.java b/engine/src/main/java/com/bartlomiejpluta/base/core/engine/GameEngine.java old mode 100755 new mode 100644 index a993c243..650d9c1d --- a/engine/src/main/java/com/bartlomiejpluta/base/core/engine/GameEngine.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/engine/GameEngine.java @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.core.engine; - -public interface GameEngine { - void start(); -} +package com.bartlomiejpluta.base.core.engine; + +public interface GameEngine { + void start(); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/error/AppException.java b/engine/src/main/java/com/bartlomiejpluta/base/core/error/AppException.java old mode 100755 new mode 100644 index ab3e5902..197102e5 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/error/AppException.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/error/AppException.java @@ -1,22 +1,22 @@ -package com.bartlomiejpluta.base.core.error; - -public class AppException extends RuntimeException { - public AppException() { - } - - public AppException(String message, Object... args) { - super(String.format(message, args)); - } - - public AppException(String message, Throwable cause) { - super(message, cause); - } - - public AppException(Throwable cause) { - super(cause); - } - - public AppException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} +package com.bartlomiejpluta.base.core.error; + +public class AppException extends RuntimeException { + public AppException() { + } + + public AppException(String message, Object... args) { + super(String.format(message, args)); + } + + public AppException(String message, Throwable cause) { + super(message, cause); + } + + public AppException(Throwable cause) { + super(cause); + } + + public AppException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Cleanable.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Cleanable.java old mode 100755 new mode 100644 index 4eec5c50..a9a20b1e --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Cleanable.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Cleanable.java @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.core.gc; - -public interface Cleanable { - void cleanUp(); -} +package com.bartlomiejpluta.base.core.gc; + +public interface Cleanable { + void cleanUp(); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/DefaultOffHeapGarbageCollector.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/DefaultOffHeapGarbageCollector.java old mode 100755 new mode 100644 index 980f910a..549d5538 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/DefaultOffHeapGarbageCollector.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/DefaultOffHeapGarbageCollector.java @@ -1,22 +1,22 @@ -package com.bartlomiejpluta.base.core.gc; - -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.List; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultOffHeapGarbageCollector implements OffHeapGarbageCollector { - private final List cleanables; - - @Override - public void cleanUp() { - cleanables.stream() - .peek(cleanable -> log.info("Performing {} cleaning", cleanable.getClass().getSimpleName())) - .forEach(Cleanable::cleanUp); - } -} +package com.bartlomiejpluta.base.core.gc; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultOffHeapGarbageCollector implements OffHeapGarbageCollector { + private final List cleanables; + + @Override + public void cleanUp() { + cleanables.stream() + .peek(cleanable -> log.info("Performing {} cleaning", cleanable.getClass().getSimpleName())) + .forEach(Cleanable::cleanUp); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Disposable.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Disposable.java old mode 100755 new mode 100644 index 14c95506..47825fa3 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Disposable.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/Disposable.java @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.core.gc; - -public interface Disposable { - void dispose(); -} +package com.bartlomiejpluta.base.core.gc; + +public interface Disposable { + void dispose(); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/OffHeapGarbageCollector.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/OffHeapGarbageCollector.java old mode 100755 new mode 100644 index a9b6edb0..68bdb2b7 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gc/OffHeapGarbageCollector.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gc/OffHeapGarbageCollector.java @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.core.gc; - -public interface OffHeapGarbageCollector { - void cleanUp(); -} +package com.bartlomiejpluta.base.core.gc; + +public interface OffHeapGarbageCollector { + void cleanUp(); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/material/Material.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/material/Material.java old mode 100755 new mode 100644 index 6b21f30d..c047d31f --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/material/Material.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/material/Material.java @@ -1,83 +1,83 @@ -package com.bartlomiejpluta.base.core.gl.object.material; - -import com.bartlomiejpluta.base.core.gl.object.texture.Texture; -import lombok.Getter; -import org.joml.Vector2f; -import org.joml.Vector4f; - -@Getter -public class Material { - private final Vector4f color = new Vector4f(); - private final Vector2f spriteSize = new Vector2f(1, 1); - private final Vector2f spritePosition = new Vector2f(0, 0); - private final Texture texture; - - private Material(Texture texture, float r, float g, float b, float alpha) { - this.texture = texture; - setColor(r, g, b, alpha); - } - - public void setAlpha(float alpha) { - this.color.w = alpha; - } - - public void setColor(Vector4f color) { - this.color.x = color.x; - this.color.y = color.y; - this.color.z = color.z; - this.color.w = color.w; - } - - public void setColor(float r, float g, float b, float alpha) { - color.x = r; - color.y = g; - color.z = b; - color.w = alpha; - } - - public void setSpriteSize(Vector2f spriteSize) { - this.spriteSize.x = spriteSize.x; - this.spriteSize.y = spriteSize.y; - } - - public void setSpriteSize(float w, float h) { - this.spriteSize.x = w; - this.spriteSize.y = h; - } - - public void setSpritePosition(Vector2f spritePosition) { - this.spritePosition.x = spritePosition.x; - this.spritePosition.y = spritePosition.y; - } - - public void setSpritePosition(float x, float y) { - this.spritePosition.x = x; - this.spritePosition.y = y; - } - - public boolean hasTexture() { - return texture != null; - } - - public void activateTextureIfExists() { - if(hasTexture()) { - texture.activate(); - } - } - - public static Material colored(float r, float g, float b, float alpha) { - return new Material(null, r, g, b, alpha); - } - - public static Material textured(Texture texture) { - return new Material(texture, 1, 1, 1, 1); - } - - public static Material textured(Texture texture, float r, float g, float b, float alpha) { - return new Material(texture, r, g, b, alpha); - } - - public static Material textured(Texture texture, float alpha) { - return new Material(texture, 1, 1, 1, alpha); - } -} +package com.bartlomiejpluta.base.core.gl.object.material; + +import com.bartlomiejpluta.base.core.gl.object.texture.Texture; +import lombok.Getter; +import org.joml.Vector2f; +import org.joml.Vector4f; + +@Getter +public class Material { + private final Vector4f color = new Vector4f(); + private final Vector2f spriteSize = new Vector2f(1, 1); + private final Vector2f spritePosition = new Vector2f(0, 0); + private final Texture texture; + + private Material(Texture texture, float r, float g, float b, float alpha) { + this.texture = texture; + setColor(r, g, b, alpha); + } + + public void setAlpha(float alpha) { + this.color.w = alpha; + } + + public void setColor(Vector4f color) { + this.color.x = color.x; + this.color.y = color.y; + this.color.z = color.z; + this.color.w = color.w; + } + + public void setColor(float r, float g, float b, float alpha) { + color.x = r; + color.y = g; + color.z = b; + color.w = alpha; + } + + public void setSpriteSize(Vector2f spriteSize) { + this.spriteSize.x = spriteSize.x; + this.spriteSize.y = spriteSize.y; + } + + public void setSpriteSize(float w, float h) { + this.spriteSize.x = w; + this.spriteSize.y = h; + } + + public void setSpritePosition(Vector2f spritePosition) { + this.spritePosition.x = spritePosition.x; + this.spritePosition.y = spritePosition.y; + } + + public void setSpritePosition(float x, float y) { + this.spritePosition.x = x; + this.spritePosition.y = y; + } + + public boolean hasTexture() { + return texture != null; + } + + public void activateTextureIfExists() { + if(hasTexture()) { + texture.activate(); + } + } + + public static Material colored(float r, float g, float b, float alpha) { + return new Material(null, r, g, b, alpha); + } + + public static Material textured(Texture texture) { + return new Material(texture, 1, 1, 1, 1); + } + + public static Material textured(Texture texture, float r, float g, float b, float alpha) { + return new Material(texture, r, g, b, alpha); + } + + public static Material textured(Texture texture, float alpha) { + return new Material(texture, 1, 1, 1, alpha); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/mesh/Mesh.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/mesh/Mesh.java old mode 100755 new mode 100644 index af6822b5..dd1ebca9 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/mesh/Mesh.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/mesh/Mesh.java @@ -1,94 +1,94 @@ -package com.bartlomiejpluta.base.core.gl.object.mesh; - -import com.bartlomiejpluta.base.core.gc.Disposable; -import com.bartlomiejpluta.base.core.gl.render.Renderable; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; -import org.lwjgl.opengl.GL15; -import org.lwjgl.system.MemoryStack; - -import java.util.ArrayList; -import java.util.List; - -import static org.lwjgl.opengl.GL15.*; -import static org.lwjgl.opengl.GL20.*; -import static org.lwjgl.opengl.GL30.*; - -public class Mesh implements Renderable, Disposable { - private final int vaoId; - private final List vboIds = new ArrayList<>(2); - private final int elementsCount; - - public Mesh(float[] vertices, float[] texCoords, int[] elements) { - try(var stack = MemoryStack.stackPush()) { - elementsCount = elements.length; - var verticesBuffer = stack.mallocFloat(vertices.length); - var texCoordsBuffer = stack.mallocFloat(texCoords.length); - var elementsBuffer = stack.mallocInt(elementsCount); - verticesBuffer.put(vertices).flip(); - texCoordsBuffer.put(texCoords).flip(); - elementsBuffer.put(elements).flip(); - - vaoId = glGenVertexArrays(); - glBindVertexArray(vaoId); - - int vboId = glGenBuffers(); - vboIds.add(vboId); - glBindBuffer(GL_ARRAY_BUFFER, vboId); - glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW); - glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0); - - vboId = glGenBuffers(); - vboIds.add(vboId); - glBindBuffer(GL_ARRAY_BUFFER, vboId); - glBufferData(GL_ARRAY_BUFFER, texCoordsBuffer, GL_STATIC_DRAW); - glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); - - vboId = glGenBuffers(); - vboIds.add(vboId); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboId); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementsBuffer, GL_STATIC_DRAW); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - } - } - - @Override - public void render(Window window, ShaderManager shaderManager) { - glBindVertexArray(vaoId); - glEnableVertexAttribArray(0); - glEnableVertexAttribArray(1); - glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_INT, 0); - glDisableVertexAttribArray(0); - glDisableVertexAttribArray(1); - glBindVertexArray(0); - } - - @Override - public void dispose() { - glDisableVertexAttribArray(0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - vboIds.forEach(GL15::glDeleteBuffers); - - glBindVertexArray(0); - glDeleteVertexArrays(vaoId); - } - - public static Mesh quad(float width, float height, float originX, float originY) { - var vertices = new float[] { - -originX, -originY, - -originX, height - originY, - width - originX, height - originY, - width - originX, - originY - }; - - var texCoords = new float[] { 0, 0, 0, 1, 1, 1, 1, 0 }; - - var elements = new int[] { 0, 1, 2, 2, 3, 0 }; - - return new Mesh(vertices, texCoords, elements); - } -} +package com.bartlomiejpluta.base.core.gl.object.mesh; + +import com.bartlomiejpluta.base.core.gc.Disposable; +import com.bartlomiejpluta.base.core.gl.render.Renderable; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; +import org.lwjgl.opengl.GL15; +import org.lwjgl.system.MemoryStack; + +import java.util.ArrayList; +import java.util.List; + +import static org.lwjgl.opengl.GL15.*; +import static org.lwjgl.opengl.GL20.*; +import static org.lwjgl.opengl.GL30.*; + +public class Mesh implements Renderable, Disposable { + private final int vaoId; + private final List vboIds = new ArrayList<>(2); + private final int elementsCount; + + public Mesh(float[] vertices, float[] texCoords, int[] elements) { + try(var stack = MemoryStack.stackPush()) { + elementsCount = elements.length; + var verticesBuffer = stack.mallocFloat(vertices.length); + var texCoordsBuffer = stack.mallocFloat(texCoords.length); + var elementsBuffer = stack.mallocInt(elementsCount); + verticesBuffer.put(vertices).flip(); + texCoordsBuffer.put(texCoords).flip(); + elementsBuffer.put(elements).flip(); + + vaoId = glGenVertexArrays(); + glBindVertexArray(vaoId); + + int vboId = glGenBuffers(); + vboIds.add(vboId); + glBindBuffer(GL_ARRAY_BUFFER, vboId); + glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW); + glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0); + + vboId = glGenBuffers(); + vboIds.add(vboId); + glBindBuffer(GL_ARRAY_BUFFER, vboId); + glBufferData(GL_ARRAY_BUFFER, texCoordsBuffer, GL_STATIC_DRAW); + glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); + + vboId = glGenBuffers(); + vboIds.add(vboId); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboId); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementsBuffer, GL_STATIC_DRAW); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); + } + } + + @Override + public void render(Window window, ShaderManager shaderManager) { + glBindVertexArray(vaoId); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_INT, 0); + glDisableVertexAttribArray(0); + glDisableVertexAttribArray(1); + glBindVertexArray(0); + } + + @Override + public void dispose() { + glDisableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + vboIds.forEach(GL15::glDeleteBuffers); + + glBindVertexArray(0); + glDeleteVertexArrays(vaoId); + } + + public static Mesh quad(float width, float height, float originX, float originY) { + var vertices = new float[] { + -originX, -originY, + -originX, height - originY, + width - originX, height - originY, + width - originX, - originY + }; + + var texCoords = new float[] { 0, 0, 0, 1, 1, 1, 1, 0 }; + + var elements = new int[] { 0, 1, 2, 2, 3, 0 }; + + return new Mesh(vertices, texCoords, elements); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/DefaultTextureManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/DefaultTextureManager.java old mode 100755 new mode 100644 index d6b7866c..89498734 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/DefaultTextureManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/DefaultTextureManager.java @@ -1,39 +1,39 @@ -package com.bartlomiejpluta.base.core.gl.object.texture; - -import com.bartlomiejpluta.base.core.util.res.ResourcesManager; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultTextureManager implements TextureManager { - private final ResourcesManager resourcesManager; - private final Map loadedTextures = new HashMap<>(); - - @Override - public Texture loadTexture(String textureFileName) { - var texture = loadedTextures.get(textureFileName); - - if (texture == null) { - log.info("Loading [{}] texture to cache", textureFileName); - var buffer = resourcesManager.loadResourceAsByteBuffer(textureFileName); - texture = new Texture(textureFileName, buffer); - loadedTextures.put(textureFileName, texture); - } - - return texture; - } - - @Override - public void cleanUp() { - log.info("Disposing textures"); - loadedTextures.forEach((name, texture) -> texture.dispose()); - log.info("{} textures has been disposed", loadedTextures.size()); - } -} +package com.bartlomiejpluta.base.core.gl.object.texture; + +import com.bartlomiejpluta.base.core.util.res.ResourcesManager; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultTextureManager implements TextureManager { + private final ResourcesManager resourcesManager; + private final Map loadedTextures = new HashMap<>(); + + @Override + public Texture loadTexture(String textureFileName) { + var texture = loadedTextures.get(textureFileName); + + if (texture == null) { + log.info("Loading [{}] texture to cache", textureFileName); + var buffer = resourcesManager.loadResourceAsByteBuffer(textureFileName); + texture = new Texture(textureFileName, buffer); + loadedTextures.put(textureFileName, texture); + } + + return texture; + } + + @Override + public void cleanUp() { + log.info("Disposing textures"); + loadedTextures.forEach((name, texture) -> texture.dispose()); + log.info("{} textures has been disposed", loadedTextures.size()); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/Texture.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/Texture.java old mode 100755 new mode 100644 index 0d4c7fd5..09f11654 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/Texture.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/Texture.java @@ -1,66 +1,66 @@ -package com.bartlomiejpluta.base.core.gl.object.texture; - -import com.bartlomiejpluta.base.core.error.AppException; -import com.bartlomiejpluta.base.core.gc.Disposable; -import lombok.Getter; -import org.lwjgl.system.MemoryStack; - -import java.nio.ByteBuffer; - -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.opengl.GL13.GL_TEXTURE0; -import static org.lwjgl.opengl.GL13.glActiveTexture; -import static org.lwjgl.stb.STBImage.stbi_failure_reason; -import static org.lwjgl.stb.STBImage.stbi_load_from_memory; - -public class Texture implements Disposable { - private static final int DESIRED_CHANNELS = 4; - - private final int textureId; - - @Getter - private final String fileName; - - @Getter - private final int width; - - @Getter - private final int height; - - Texture(String textureFilename, ByteBuffer buffer) { - try (var stack = MemoryStack.stackPush()) { - var widthBuffer = stack.mallocInt(1); - var heightBuffer = stack.mallocInt(1); - var channelsBuffer = stack.mallocInt(1); - - buffer = stbi_load_from_memory(buffer, widthBuffer, heightBuffer, channelsBuffer, DESIRED_CHANNELS); - if (buffer == null) { - throw new AppException("Image file [%s] could not be loaded: %s", textureFilename, stbi_failure_reason()); - } - - width = widthBuffer.get(); - height = heightBuffer.get(); - - textureId = glGenTextures(); - - glBindTexture(GL_TEXTURE_2D, textureId); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - - fileName = textureFilename; - } - } - - public void activate() { - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textureId); - } - - @Override - public void dispose() { - glDeleteTextures(textureId); - } -} +package com.bartlomiejpluta.base.core.gl.object.texture; + +import com.bartlomiejpluta.base.core.error.AppException; +import com.bartlomiejpluta.base.core.gc.Disposable; +import lombok.Getter; +import org.lwjgl.system.MemoryStack; + +import java.nio.ByteBuffer; + +import static org.lwjgl.opengl.GL11.*; +import static org.lwjgl.opengl.GL13.GL_TEXTURE0; +import static org.lwjgl.opengl.GL13.glActiveTexture; +import static org.lwjgl.stb.STBImage.stbi_failure_reason; +import static org.lwjgl.stb.STBImage.stbi_load_from_memory; + +public class Texture implements Disposable { + private static final int DESIRED_CHANNELS = 4; + + private final int textureId; + + @Getter + private final String fileName; + + @Getter + private final int width; + + @Getter + private final int height; + + Texture(String textureFilename, ByteBuffer buffer) { + try (var stack = MemoryStack.stackPush()) { + var widthBuffer = stack.mallocInt(1); + var heightBuffer = stack.mallocInt(1); + var channelsBuffer = stack.mallocInt(1); + + buffer = stbi_load_from_memory(buffer, widthBuffer, heightBuffer, channelsBuffer, DESIRED_CHANNELS); + if (buffer == null) { + throw new AppException("Image file [%s] could not be loaded: %s", textureFilename, stbi_failure_reason()); + } + + width = widthBuffer.get(); + height = heightBuffer.get(); + + textureId = glGenTextures(); + + glBindTexture(GL_TEXTURE_2D, textureId); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + fileName = textureFilename; + } + } + + public void activate() { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, textureId); + } + + @Override + public void dispose() { + glDeleteTextures(textureId); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/TextureManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/TextureManager.java old mode 100755 new mode 100644 index c56cd6a9..49c42091 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/TextureManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/object/texture/TextureManager.java @@ -1,7 +1,7 @@ -package com.bartlomiejpluta.base.core.gl.object.texture; - -import com.bartlomiejpluta.base.core.gc.Cleanable; - -public interface TextureManager extends Cleanable { - Texture loadTexture(String textureFileName); -} +package com.bartlomiejpluta.base.core.gl.object.texture; + +import com.bartlomiejpluta.base.core.gc.Cleanable; + +public interface TextureManager extends Cleanable { + Texture loadTexture(String textureFileName); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/DefaultRenderer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/DefaultRenderer.java old mode 100755 new mode 100644 index 9a9ba4d7..a739e450 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/DefaultRenderer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/DefaultRenderer.java @@ -1,62 +1,62 @@ -package com.bartlomiejpluta.base.core.gl.render; - -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import static org.lwjgl.opengl.GL15.*; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultRenderer implements Renderer { - private final ShaderManager shaderManager; - - @Override - public void init() { - log.info("Initializing renderer"); - shaderManager - .createShader("default", "/shaders/default.vs", "/shaders/default.fs") - .selectShader("default") - .createUniform(UniformName.UNI_MODEL_MATRIX) - .createUniform(UniformName.UNI_VIEW_MATRIX) - .createUniform(UniformName.UNI_PROJECTION_MATRIX) - .createUniform(UniformName.UNI_OBJECT_COLOR) - .createUniform(UniformName.UNI_HAS_OBJECT_TEXTURE) - .createUniform(UniformName.UNI_TEXTURE_SAMPLER) - .createUniform(UniformName.UNI_SPRITE_SIZE) - .createUniform(UniformName.UNI_SPRITE_POSITION); - } - - @Override - public void render(Window window, Renderable renderable) { - clear(); - updateViewport(window); - - shaderManager.selectShader("default").useSelectedShader(); - - renderable.render(window, shaderManager); - - shaderManager.detachCurrentShader(); - } - - private void clear() { - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - } - - private void updateViewport(Window window) { - if (window.isResized()) { - glViewport(0, 0, window.getWidth(), window.getHeight()); - window.setResized(false); - } - } - - @Override - public void cleanUp() { - log.info("There is nothing to clean up here"); - } -} +package com.bartlomiejpluta.base.core.gl.render; + +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import static org.lwjgl.opengl.GL15.*; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultRenderer implements Renderer { + private final ShaderManager shaderManager; + + @Override + public void init() { + log.info("Initializing renderer"); + shaderManager + .createShader("default", "/shaders/default.vs", "/shaders/default.fs") + .selectShader("default") + .createUniform(UniformName.UNI_MODEL_MATRIX) + .createUniform(UniformName.UNI_VIEW_MATRIX) + .createUniform(UniformName.UNI_PROJECTION_MATRIX) + .createUniform(UniformName.UNI_OBJECT_COLOR) + .createUniform(UniformName.UNI_HAS_OBJECT_TEXTURE) + .createUniform(UniformName.UNI_TEXTURE_SAMPLER) + .createUniform(UniformName.UNI_SPRITE_SIZE) + .createUniform(UniformName.UNI_SPRITE_POSITION); + } + + @Override + public void render(Window window, Renderable renderable) { + clear(); + updateViewport(window); + + shaderManager.selectShader("default").useSelectedShader(); + + renderable.render(window, shaderManager); + + shaderManager.detachCurrentShader(); + } + + private void clear() { + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } + + private void updateViewport(Window window) { + if (window.isResized()) { + glViewport(0, 0, window.getWidth(), window.getHeight()); + window.setResized(false); + } + } + + @Override + public void cleanUp() { + log.info("There is nothing to clean up here"); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderable.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderable.java old mode 100755 new mode 100644 index 6dbd8151..85aea00b --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderable.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderable.java @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.core.gl.render; - -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; - -public interface Renderable { - void render(Window window, ShaderManager shaderManager); -} +package com.bartlomiejpluta.base.core.gl.render; + +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; + +public interface Renderable { + void render(Window window, ShaderManager shaderManager); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderer.java old mode 100755 new mode 100644 index d8931e8a..0ff8ab6f --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/render/Renderer.java @@ -1,9 +1,9 @@ -package com.bartlomiejpluta.base.core.gl.render; - -import com.bartlomiejpluta.base.core.gc.Cleanable; -import com.bartlomiejpluta.base.core.ui.Window; - -public interface Renderer extends Cleanable { - void init(); - void render(Window window, Renderable renderable); -} +package com.bartlomiejpluta.base.core.gl.render; + +import com.bartlomiejpluta.base.core.gc.Cleanable; +import com.bartlomiejpluta.base.core.ui.Window; + +public interface Renderer extends Cleanable { + void init(); + void render(Window window, Renderable renderable); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/constant/UniformName.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/constant/UniformName.java old mode 100755 new mode 100644 index 6638bc68..3ec8caaf --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/constant/UniformName.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/constant/UniformName.java @@ -1,12 +1,12 @@ -package com.bartlomiejpluta.base.core.gl.shader.constant; - -public interface UniformName { - String UNI_MODEL_MATRIX = "modelMatrix"; - String UNI_VIEW_MATRIX = "viewMatrix"; - String UNI_PROJECTION_MATRIX = "projectionMatrix"; - String UNI_OBJECT_COLOR = "objectColor"; - String UNI_HAS_OBJECT_TEXTURE = "hasTexture"; - String UNI_TEXTURE_SAMPLER = "sampler"; - String UNI_SPRITE_SIZE = "spriteSize"; - String UNI_SPRITE_POSITION = "spritePosition"; -} +package com.bartlomiejpluta.base.core.gl.shader.constant; + +public interface UniformName { + String UNI_MODEL_MATRIX = "modelMatrix"; + String UNI_VIEW_MATRIX = "viewMatrix"; + String UNI_PROJECTION_MATRIX = "projectionMatrix"; + String UNI_OBJECT_COLOR = "objectColor"; + String UNI_HAS_OBJECT_TEXTURE = "hasTexture"; + String UNI_TEXTURE_SAMPLER = "sampler"; + String UNI_SPRITE_SIZE = "spriteSize"; + String UNI_SPRITE_POSITION = "spritePosition"; +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/DefaultShaderManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/DefaultShaderManager.java old mode 100755 new mode 100644 index 8953ca0f..df65904c --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/DefaultShaderManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/DefaultShaderManager.java @@ -1,149 +1,149 @@ -package com.bartlomiejpluta.base.core.gl.shader.manager; - -import com.bartlomiejpluta.base.core.gl.shader.program.ShaderProgram; -import com.bartlomiejpluta.base.core.gl.shader.uniform.Uniform; -import com.bartlomiejpluta.base.core.util.res.ResourcesManager; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.joml.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultShaderManager implements ShaderManager { - private final ResourcesManager resourcesManager; - private final Map shaders = new HashMap<>(); - private ShaderProgram current; - - @Override - public ShaderManager createShader(String programName, String vertexShaderFilename, String fragmentShaderFilename) { - log.info("Creating {} shader", programName); - var vertexShaderCode = resourcesManager.loadResourceAsString(vertexShaderFilename); - var fragmentShaderCode = resourcesManager.loadResourceAsString(fragmentShaderFilename); - var program = ShaderProgram.compile(vertexShaderCode, fragmentShaderCode); - - shaders.put(programName, program); - - return this; - } - - @Override - public ShaderManager selectShader(String programName) { - current = shaders.get(programName); - return this; - } - - @Override - public ShaderManager useSelectedShader() { - current.use(); - return this; - } - - @Override - public ShaderManager detachCurrentShader() { - current.detach(); - return this; - } - - @Override - public ShaderManager createUniform(String uniformName) { - current.createUniform(uniformName); - return this; - } - - @Override - public ShaderManager createUniform(String uniformName, Uniform uniform) { - current.createUniform(uniformName, uniform); - return this; - } - - @Override - public ShaderManager createUniforms(String uniformName, int size) { - current.createUniforms(uniformName, size); - return this; - } - - @Override - public ShaderManager createUniforms(String uniformName, int size, Uniform uniform) { - current.createUniforms(uniformName, size, uniform); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, int value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, boolean value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, float value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Vector2f value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Vector3f value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Vector4f value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Matrix3f value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Matrix4f value) { - current.setUniform(uniformName, value); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, Uniform uniform) { - current.setUniform(uniformName, uniform); - return this; - } - - @Override - public ShaderManager setUniform(String uniformName, int index, Uniform uniform) { - current.setUniform(uniformName, index, uniform); - return this; - } - - @Override - public ShaderManager setUniforms(String uniformName, Uniform[] uniforms) { - current.setUniforms(uniformName, uniforms); - return this; - } - - @Override - public void cleanUp() { - log.info("Disposing shaders"); - shaders.forEach((name, program) -> program.dispose()); - log.info("{} shaders has been disposed", shaders.size()); - } -} +package com.bartlomiejpluta.base.core.gl.shader.manager; + +import com.bartlomiejpluta.base.core.gl.shader.program.ShaderProgram; +import com.bartlomiejpluta.base.core.gl.shader.uniform.Uniform; +import com.bartlomiejpluta.base.core.util.res.ResourcesManager; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.joml.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultShaderManager implements ShaderManager { + private final ResourcesManager resourcesManager; + private final Map shaders = new HashMap<>(); + private ShaderProgram current; + + @Override + public ShaderManager createShader(String programName, String vertexShaderFilename, String fragmentShaderFilename) { + log.info("Creating {} shader", programName); + var vertexShaderCode = resourcesManager.loadResourceAsString(vertexShaderFilename); + var fragmentShaderCode = resourcesManager.loadResourceAsString(fragmentShaderFilename); + var program = ShaderProgram.compile(vertexShaderCode, fragmentShaderCode); + + shaders.put(programName, program); + + return this; + } + + @Override + public ShaderManager selectShader(String programName) { + current = shaders.get(programName); + return this; + } + + @Override + public ShaderManager useSelectedShader() { + current.use(); + return this; + } + + @Override + public ShaderManager detachCurrentShader() { + current.detach(); + return this; + } + + @Override + public ShaderManager createUniform(String uniformName) { + current.createUniform(uniformName); + return this; + } + + @Override + public ShaderManager createUniform(String uniformName, Uniform uniform) { + current.createUniform(uniformName, uniform); + return this; + } + + @Override + public ShaderManager createUniforms(String uniformName, int size) { + current.createUniforms(uniformName, size); + return this; + } + + @Override + public ShaderManager createUniforms(String uniformName, int size, Uniform uniform) { + current.createUniforms(uniformName, size, uniform); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, int value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, boolean value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, float value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Vector2f value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Vector3f value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Vector4f value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Matrix3f value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Matrix4f value) { + current.setUniform(uniformName, value); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, Uniform uniform) { + current.setUniform(uniformName, uniform); + return this; + } + + @Override + public ShaderManager setUniform(String uniformName, int index, Uniform uniform) { + current.setUniform(uniformName, index, uniform); + return this; + } + + @Override + public ShaderManager setUniforms(String uniformName, Uniform[] uniforms) { + current.setUniforms(uniformName, uniforms); + return this; + } + + @Override + public void cleanUp() { + log.info("Disposing shaders"); + shaders.forEach((name, program) -> program.dispose()); + log.info("{} shaders has been disposed", shaders.size()); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/ShaderManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/ShaderManager.java old mode 100755 new mode 100644 index 43582dc5..13566263 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/ShaderManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/manager/ShaderManager.java @@ -1,45 +1,45 @@ -package com.bartlomiejpluta.base.core.gl.shader.manager; - -import com.bartlomiejpluta.base.core.gc.Cleanable; -import com.bartlomiejpluta.base.core.gl.shader.uniform.Uniform; -import org.joml.*; - -public interface ShaderManager extends Cleanable { - ShaderManager createShader(String programName, String vertexShaderFilename, String fragmentShaderFilename); - - ShaderManager selectShader(String programName); - - ShaderManager useSelectedShader(); - - ShaderManager detachCurrentShader(); - - ShaderManager createUniform(String uniformName); - - ShaderManager createUniform(String uniformName, Uniform uniform); - - ShaderManager createUniforms(String uniformName, int size); - - ShaderManager createUniforms(String uniformName, int size, Uniform uniform); - - ShaderManager setUniform(String uniformName, int value); - - ShaderManager setUniform(String uniformName, boolean value); - - ShaderManager setUniform(String uniformName, float value); - - ShaderManager setUniform(String uniformName, Vector2f value); - - ShaderManager setUniform(String uniformName, Vector3f value); - - ShaderManager setUniform(String uniformName, Vector4f value); - - ShaderManager setUniform(String uniformName, Matrix3f value); - - ShaderManager setUniform(String uniformName, Matrix4f value); - - ShaderManager setUniform(String uniformName, Uniform uniform); - - ShaderManager setUniform(String uniformName, int index, Uniform uniform); - - ShaderManager setUniforms(String uniformName, Uniform[] uniforms); +package com.bartlomiejpluta.base.core.gl.shader.manager; + +import com.bartlomiejpluta.base.core.gc.Cleanable; +import com.bartlomiejpluta.base.core.gl.shader.uniform.Uniform; +import org.joml.*; + +public interface ShaderManager extends Cleanable { + ShaderManager createShader(String programName, String vertexShaderFilename, String fragmentShaderFilename); + + ShaderManager selectShader(String programName); + + ShaderManager useSelectedShader(); + + ShaderManager detachCurrentShader(); + + ShaderManager createUniform(String uniformName); + + ShaderManager createUniform(String uniformName, Uniform uniform); + + ShaderManager createUniforms(String uniformName, int size); + + ShaderManager createUniforms(String uniformName, int size, Uniform uniform); + + ShaderManager setUniform(String uniformName, int value); + + ShaderManager setUniform(String uniformName, boolean value); + + ShaderManager setUniform(String uniformName, float value); + + ShaderManager setUniform(String uniformName, Vector2f value); + + ShaderManager setUniform(String uniformName, Vector3f value); + + ShaderManager setUniform(String uniformName, Vector4f value); + + ShaderManager setUniform(String uniformName, Matrix3f value); + + ShaderManager setUniform(String uniformName, Matrix4f value); + + ShaderManager setUniform(String uniformName, Uniform uniform); + + ShaderManager setUniform(String uniformName, int index, Uniform uniform); + + ShaderManager setUniforms(String uniformName, Uniform[] uniforms); } \ No newline at end of file diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/program/ShaderProgram.java b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/program/ShaderProgram.java old mode 100755 new mode 100644 index d2250531..bc8c885d --- a/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/program/ShaderProgram.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/gl/shader/program/ShaderProgram.java @@ -1,175 +1,175 @@ -package com.bartlomiejpluta.base.core.gl.shader.program; - -import com.bartlomiejpluta.base.core.error.AppException; -import com.bartlomiejpluta.base.core.gc.Disposable; -import com.bartlomiejpluta.base.core.gl.shader.uniform.Uniform; -import lombok.extern.slf4j.Slf4j; -import org.joml.*; -import org.lwjgl.system.MemoryStack; - -import java.util.HashMap; -import java.util.Map; - -import static java.lang.String.format; -import static org.lwjgl.opengl.GL20.*; - -@Slf4j -public class ShaderProgram implements Disposable { - private final int programId; - private final int vertexShaderId; - private final int fragmentShaderId; - private final Map uniforms = new HashMap<>(); - - private ShaderProgram(String vertexShaderCode, String fragmentShaderCode) { - this.programId = glCreateProgram(); - - if(this.programId == 0) { - throw new AppException("Could not create shader program"); - } - - this.vertexShaderId = createShader(vertexShaderCode, GL_VERTEX_SHADER); - this.fragmentShaderId = createShader(fragmentShaderCode, GL_FRAGMENT_SHADER); - - linkProgram(); - } - - private int createShader(String shaderCode, int shaderType) { - int shaderId = glCreateShader(shaderType); - if(shaderId == 0) { - throw new AppException("Could not create shader of type: %s", shaderType); - } - - glShaderSource(shaderId, shaderCode); - glCompileShader(shaderId); - - if(glGetShaderi(shaderId, GL_COMPILE_STATUS) == 0) { - throw new AppException("Could not compile shader code: %s", glGetShaderInfoLog(shaderId, 1024)); - } - - glAttachShader(programId, shaderId); - - return shaderId; - } - - private void linkProgram() { - glLinkProgram(programId); - if(glGetProgrami(programId, GL_LINK_STATUS) == 0) { - throw new AppException("Could not link shader program: %s", glGetProgramInfoLog(programId, 1024)); - } - - if(vertexShaderId != 0) { - glDetachShader(programId, vertexShaderId); - } - - if(fragmentShaderId != 0) { - glDetachShader(programId, fragmentShaderId); - } - - glValidateProgram(programId); - if(glGetProgrami(programId, GL_VALIDATE_STATUS) == 0) { - log.warn("Program validation failed: {}", glGetProgramInfoLog(programId, 1024)); - } - } - - public void createUniform(String uniformName) { - int location = glGetUniformLocation(programId, uniformName); - - if(location < 0) { - throw new AppException("Could not find uniform: %s", uniformName); - } - - uniforms.put(uniformName, location); - } - - public void createUniform(String uniformName, Uniform uniform) { - uniform.createUniform(this, uniformName); - } - - public void createUniforms(String uniformName, int size) { - for(int i=0; i uniforms = new HashMap<>(); + + private ShaderProgram(String vertexShaderCode, String fragmentShaderCode) { + this.programId = glCreateProgram(); + + if(this.programId == 0) { + throw new AppException("Could not create shader program"); + } + + this.vertexShaderId = createShader(vertexShaderCode, GL_VERTEX_SHADER); + this.fragmentShaderId = createShader(fragmentShaderCode, GL_FRAGMENT_SHADER); + + linkProgram(); + } + + private int createShader(String shaderCode, int shaderType) { + int shaderId = glCreateShader(shaderType); + if(shaderId == 0) { + throw new AppException("Could not create shader of type: %s", shaderType); + } + + glShaderSource(shaderId, shaderCode); + glCompileShader(shaderId); + + if(glGetShaderi(shaderId, GL_COMPILE_STATUS) == 0) { + throw new AppException("Could not compile shader code: %s", glGetShaderInfoLog(shaderId, 1024)); + } + + glAttachShader(programId, shaderId); + + return shaderId; + } + + private void linkProgram() { + glLinkProgram(programId); + if(glGetProgrami(programId, GL_LINK_STATUS) == 0) { + throw new AppException("Could not link shader program: %s", glGetProgramInfoLog(programId, 1024)); + } + + if(vertexShaderId != 0) { + glDetachShader(programId, vertexShaderId); + } + + if(fragmentShaderId != 0) { + glDetachShader(programId, fragmentShaderId); + } + + glValidateProgram(programId); + if(glGetProgrami(programId, GL_VALIDATE_STATUS) == 0) { + log.warn("Program validation failed: {}", glGetProgramInfoLog(programId, 1024)); + } + } + + public void createUniform(String uniformName) { + int location = glGetUniformLocation(programId, uniformName); + + if(location < 0) { + throw new AppException("Could not find uniform: %s", uniformName); + } + + uniforms.put(uniformName, location); + } + + public void createUniform(String uniformName, Uniform uniform) { + uniform.createUniform(this, uniformName); + } + + public void createUniforms(String uniformName, int size) { + for(int i=0; i values = new LinkedList<>(); - private float fpsAccumulator = 0; - private int pointer = 0; - private double fps = 0; - - @Override - public void update(float dt) { - fpsAccumulator += dt; - - if (++pointer % MOD == 0) { - fps = pointer / fpsAccumulator; - fpsAccumulator = 0; - pointer = 0; - - values.add(fps); - } - } - - @Override - public void cleanUp() { - log.info("Min FPS: {}, max FPS: {}, avg FPS: {}", - values.stream().min(Double::compareTo).orElse(-1.0), - values.stream().max(Double::compareTo).orElse(-1.0), - totalAverage() - ); - - printHistogram(); - } - - private double totalAverage() { - return values.stream().reduce(0.0, Double::sum) / values.size(); - } - - private void printHistogram() { - values - .stream() - .mapToInt(Double::intValue) - .boxed() - .collect(groupingBy(identity(), counting())) - .entrySet() - .stream() - .sorted(comparingInt(Map.Entry::getKey)) - .forEach(e -> log.info("{} FPS: {}% ({} occurrences)", e.getKey(), e.getValue() * 100.0f / values.size(), e.getValue())); - } -} +package com.bartlomiejpluta.base.core.profiling.fps; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static java.util.Comparator.comparingInt; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; + +@Slf4j +@Component +public class LogFPSMonitor implements FPSMonitor { + private static final int MOD = 30; + private final List values = new LinkedList<>(); + private float fpsAccumulator = 0; + private int pointer = 0; + private double fps = 0; + + @Override + public void update(float dt) { + fpsAccumulator += dt; + + if (++pointer % MOD == 0) { + fps = pointer / fpsAccumulator; + fpsAccumulator = 0; + pointer = 0; + + values.add(fps); + } + } + + @Override + public void cleanUp() { + log.info("Min FPS: {}, max FPS: {}, avg FPS: {}", + values.stream().min(Double::compareTo).orElse(-1.0), + values.stream().max(Double::compareTo).orElse(-1.0), + totalAverage() + ); + + printHistogram(); + } + + private double totalAverage() { + return values.stream().reduce(0.0, Double::sum) / values.size(); + } + + private void printHistogram() { + values + .stream() + .mapToInt(Double::intValue) + .boxed() + .collect(groupingBy(identity(), counting())) + .entrySet() + .stream() + .sorted(comparingInt(Map.Entry::getKey)) + .forEach(e -> log.info("{} FPS: {}% ({} occurrences)", e.getKey(), e.getValue() * 100.0f / values.size(), e.getValue())); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/annotation/MeasureExecutionTime.java b/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/annotation/MeasureExecutionTime.java old mode 100755 new mode 100644 index 9159fc77..8e6597d1 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/annotation/MeasureExecutionTime.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/annotation/MeasureExecutionTime.java @@ -1,11 +1,11 @@ -package com.bartlomiejpluta.base.core.profiling.time.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface MeasureExecutionTime { -} +package com.bartlomiejpluta.base.core.profiling.time.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface MeasureExecutionTime { +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/aspect/ExecutionTimeAspect.java b/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/aspect/ExecutionTimeAspect.java old mode 100755 new mode 100644 index ec86ca84..c3c164ca --- a/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/aspect/ExecutionTimeAspect.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/profiling/time/aspect/ExecutionTimeAspect.java @@ -1,38 +1,38 @@ -package com.bartlomiejpluta.base.core.profiling.time.aspect; - -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.stereotype.Component; - -@Slf4j -@Aspect -@Component -@ConditionalOnExpression("${app.profiling.aspects:false}") -public class ExecutionTimeAspect { - - @Around("@annotation(com.bartlomiejpluta.base.core.stat.metrics.annotation.MeasureExecutionTime)") - public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { - long start = 0; - long end = 0; - long elapsed; - Object result; - try { - start = System.nanoTime(); - result = joinPoint.proceed(); - } finally { - end = System.nanoTime(); - } - - elapsed = end - start; - log.debug("[{}.{}] = [{}s] [{}ms] [{}ns]", - joinPoint.getTarget().getClass().getSimpleName(), - joinPoint.getSignature().getName(), - elapsed / 1000000.0, elapsed / 1000.0, elapsed - ); - - return result; - } -} +package com.bartlomiejpluta.base.core.profiling.time.aspect; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.stereotype.Component; + +@Slf4j +@Aspect +@Component +@ConditionalOnExpression("${app.profiling.aspects:false}") +public class ExecutionTimeAspect { + + @Around("@annotation(com.bartlomiejpluta.base.core.stat.metrics.annotation.MeasureExecutionTime)") + public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { + long start = 0; + long end = 0; + long elapsed; + Object result; + try { + start = System.nanoTime(); + result = joinPoint.proceed(); + } finally { + end = System.nanoTime(); + } + + elapsed = end - start; + log.debug("[{}.{}] = [{}s] [{}ms] [{}ns]", + joinPoint.getTarget().getClass().getSimpleName(), + joinPoint.getSignature().getName(), + elapsed / 1000000.0, elapsed / 1000.0, elapsed + ); + + return result; + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/thread/ThreadManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/thread/ThreadManager.java old mode 100755 new mode 100644 index 3b3b9c29..bee61600 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/thread/ThreadManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/thread/ThreadManager.java @@ -1,10 +1,10 @@ -package com.bartlomiejpluta.base.core.thread; - -import org.springframework.stereotype.Component; - -@Component -public class ThreadManager { - public Thread createThread(String name, Runnable runnable) { - return new Thread(runnable, name); - } -} +package com.bartlomiejpluta.base.core.thread; + +import org.springframework.stereotype.Component; + +@Component +public class ThreadManager { + public Thread createThread(String name, Runnable runnable) { + return new Thread(runnable, name); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/time/ChronoMeter.java b/engine/src/main/java/com/bartlomiejpluta/base/core/time/ChronoMeter.java old mode 100755 new mode 100644 index 52db247b..030fd609 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/time/ChronoMeter.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/time/ChronoMeter.java @@ -1,20 +1,20 @@ -package com.bartlomiejpluta.base.core.time; - -public class ChronoMeter { - private double latchedTime; - - public void init() { - latchedTime = getTime(); - } - - private double getTime() { - return System.nanoTime() / 1_000_000_000.0; - } - - public float getElapsedTime() { - double time = getTime(); - float elapsedTime = (float) (time - latchedTime); - latchedTime = time; - return elapsedTime; - } -} +package com.bartlomiejpluta.base.core.time; + +public class ChronoMeter { + private double latchedTime; + + public void init() { + latchedTime = getTime(); + } + + private double getTime() { + return System.nanoTime() / 1_000_000_000.0; + } + + public float getElapsedTime() { + double time = getTime(); + float elapsedTime = (float) (time - latchedTime); + latchedTime = time; + return elapsedTime; + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/ui/Window.java b/engine/src/main/java/com/bartlomiejpluta/base/core/ui/Window.java old mode 100755 new mode 100644 index 8dce66e6..abbe69d5 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/ui/Window.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/ui/Window.java @@ -1,119 +1,119 @@ -package com.bartlomiejpluta.base.core.ui; - -import com.bartlomiejpluta.base.core.error.AppException; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import org.joml.Vector2f; -import org.lwjgl.glfw.GLFWErrorCallback; -import org.lwjgl.glfw.GLFWVidMode; -import org.lwjgl.opengl.GL; - -import static org.lwjgl.glfw.GLFW.*; -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.system.MemoryUtil.NULL; - -@AllArgsConstructor(access = AccessLevel.PRIVATE) -public class Window { - private final String title; - private long windowHandle; - - @Getter - private int width; - - @Getter - private int height; - - @Getter - @Setter - private boolean resized; - - public void init() { - // Setup an error callback. The default implementation - // will print the error message in System.err. - GLFWErrorCallback.createPrint(System.err).set(); - - // Initialize GLFW. Most GLFW functions will not work before doing this. - if (!glfwInit()) { - throw new AppException("Unable to initialize GLFW"); - } - - glfwDefaultWindowHints(); // optional, the current window hints are already the default - glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden after creation - glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - - // Create the window - windowHandle = glfwCreateWindow(width, height, title, NULL, NULL); - if (windowHandle == NULL) { - throw new AppException("Failed to create the GLFW window"); - } - - // Setup resize callback - glfwSetFramebufferSizeCallback(windowHandle, (window, width, height) -> { - Window.this.width = width; - Window.this.height = height; - Window.this.resized = true; - }); - - // Setup a key callback. It will be called every time a key is pressed, repeated or released. - glfwSetKeyCallback(windowHandle, (window, key, scancode, action, mods) -> { - if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { - glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop - } - }); - - // Get the resolution of the primary monitor - GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - - // Center our window - glfwSetWindowPos(windowHandle, (videoMode.width() - width) / 2, (videoMode.height() - height) / 2); - - // Make the OpenGL context current - glfwMakeContextCurrent(windowHandle); - - // Enable V-Sync -// glfwSwapInterval(1); - - // Make the window visible - glfwShowWindow(windowHandle); - - GL.createCapabilities(); - - // Support for transparencies - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - // Set the clear color - glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - } - - public void update() { - glfwSwapBuffers(windowHandle); - glfwPollEvents(); - } - - public boolean isKeyPressed(int keyCode) { - return glfwGetKey(windowHandle, keyCode) == GLFW_PRESS; - } - - public void clear(float r, float g, float b, float alpha) { - glClearColor(r, g, b, alpha); - } - - public boolean shouldClose() { - return glfwWindowShouldClose(windowHandle); - } - - public Vector2f getSize() { - return new Vector2f(width, height); - } - - public static Window create(String title, int width, int height) { - return new Window(title, -1, width, height, false); - } -} +package com.bartlomiejpluta.base.core.ui; + +import com.bartlomiejpluta.base.core.error.AppException; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.joml.Vector2f; +import org.lwjgl.glfw.GLFWErrorCallback; +import org.lwjgl.glfw.GLFWVidMode; +import org.lwjgl.opengl.GL; + +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.opengl.GL11.*; +import static org.lwjgl.system.MemoryUtil.NULL; + +@AllArgsConstructor(access = AccessLevel.PRIVATE) +public class Window { + private final String title; + private long windowHandle; + + @Getter + private int width; + + @Getter + private int height; + + @Getter + @Setter + private boolean resized; + + public void init() { + // Setup an error callback. The default implementation + // will print the error message in System.err. + GLFWErrorCallback.createPrint(System.err).set(); + + // Initialize GLFW. Most GLFW functions will not work before doing this. + if (!glfwInit()) { + throw new AppException("Unable to initialize GLFW"); + } + + glfwDefaultWindowHints(); // optional, the current window hints are already the default + glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden after creation + glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + + // Create the window + windowHandle = glfwCreateWindow(width, height, title, NULL, NULL); + if (windowHandle == NULL) { + throw new AppException("Failed to create the GLFW window"); + } + + // Setup resize callback + glfwSetFramebufferSizeCallback(windowHandle, (window, width, height) -> { + Window.this.width = width; + Window.this.height = height; + Window.this.resized = true; + }); + + // Setup a key callback. It will be called every time a key is pressed, repeated or released. + glfwSetKeyCallback(windowHandle, (window, key, scancode, action, mods) -> { + if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { + glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop + } + }); + + // Get the resolution of the primary monitor + GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + + // Center our window + glfwSetWindowPos(windowHandle, (videoMode.width() - width) / 2, (videoMode.height() - height) / 2); + + // Make the OpenGL context current + glfwMakeContextCurrent(windowHandle); + + // Enable V-Sync +// glfwSwapInterval(1); + + // Make the window visible + glfwShowWindow(windowHandle); + + GL.createCapabilities(); + + // Support for transparencies + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Set the clear color + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + } + + public void update() { + glfwSwapBuffers(windowHandle); + glfwPollEvents(); + } + + public boolean isKeyPressed(int keyCode) { + return glfwGetKey(windowHandle, keyCode) == GLFW_PRESS; + } + + public void clear(float r, float g, float b, float alpha) { + glClearColor(r, g, b, alpha); + } + + public boolean shouldClose() { + return glfwWindowShouldClose(windowHandle); + } + + public Vector2f getSize() { + return new Vector2f(width, height); + } + + public static Window create(String title, int width, int height) { + return new Window(title, -1, width, height, false); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/ui/WindowManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/ui/WindowManager.java old mode 100755 new mode 100644 index f0bd4fd5..c89d7145 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/ui/WindowManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/ui/WindowManager.java @@ -1,10 +1,10 @@ -package com.bartlomiejpluta.base.core.ui; - -import org.springframework.stereotype.Component; - -@Component -public class WindowManager { - public Window createWindow(String title, int width, int height) { - return Window.create(title, width, height); - } -} +package com.bartlomiejpluta.base.core.ui; + +import org.springframework.stereotype.Component; + +@Component +public class WindowManager { + public Window createWindow(String title, int width, int height) { + return Window.create(title, width, height); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/util/math/MathUtil.java b/engine/src/main/java/com/bartlomiejpluta/base/core/util/math/MathUtil.java old mode 100755 new mode 100644 index d2690bcd..c4f9ebd0 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/util/math/MathUtil.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/util/math/MathUtil.java @@ -1,32 +1,32 @@ -package com.bartlomiejpluta.base.core.util.math; - -import static java.lang.Math.max; -import static java.lang.Math.min; - -public class MathUtil { - public static int gcdEuclidean(int a, int b) { - int x = a; - int y = b; - int z; - - while(y != 0) { - z = x % y; - x = y; - y = z; - } - - return x; - } - - public static int clamp(int value, int min, int max) { - return min(max, max(value, min)); - } - - public static float clamp(float value, float min, float max) { - return min(max, max(value, min)); - } - - public static double clamp(double value, double min, double max) { - return min(max, max(value, min)); - } -} +package com.bartlomiejpluta.base.core.util.math; + +import static java.lang.Math.max; +import static java.lang.Math.min; + +public class MathUtil { + public static int gcdEuclidean(int a, int b) { + int x = a; + int y = b; + int z; + + while(y != 0) { + z = x % y; + x = y; + y = z; + } + + return x; + } + + public static int clamp(int value, int min, int max) { + return min(max, max(value, min)); + } + + public static float clamp(float value, float min, float max) { + return min(max, max(value, min)); + } + + public static double clamp(double value, double min, double max) { + return min(max, max(value, min)); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/DefaultMeshManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/DefaultMeshManager.java old mode 100755 new mode 100644 index 52597958..50e19206 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/DefaultMeshManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/DefaultMeshManager.java @@ -1,43 +1,43 @@ -package com.bartlomiejpluta.base.core.util.mesh; - -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.joml.Vector2f; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Slf4j -@Component -public class DefaultMeshManager implements MeshManager { - private final Map quads = new HashMap<>(); - - @Override - public Mesh createQuad(float width, float height, float originX, float originY) { - var dim = new QuadDimension(new Vector2f(width, height), new Vector2f(originX, originY)); - var mesh = quads.get(dim); - - if(mesh == null) { - log.info("Creating [w:{}, h:{} | O:{},{}] and putting it into the cache", width, height, originX, originY); - mesh = Mesh.quad(width, height, originX, originY); - quads.put(dim, mesh); - } - - return mesh; - } - - @Override - public void cleanUp() { - log.info("Disposing meshes"); - quads.forEach((dim, mesh) -> mesh.dispose()); - log.info("{} meshes has been disposed", quads.size()); - } - - @Data - private static class QuadDimension { - private final Vector2f size; - private final Vector2f origin; - } -} +package com.bartlomiejpluta.base.core.util.mesh; + +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.joml.Vector2f; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +public class DefaultMeshManager implements MeshManager { + private final Map quads = new HashMap<>(); + + @Override + public Mesh createQuad(float width, float height, float originX, float originY) { + var dim = new QuadDimension(new Vector2f(width, height), new Vector2f(originX, originY)); + var mesh = quads.get(dim); + + if(mesh == null) { + log.info("Creating [w:{}, h:{} | O:{},{}] and putting it into the cache", width, height, originX, originY); + mesh = Mesh.quad(width, height, originX, originY); + quads.put(dim, mesh); + } + + return mesh; + } + + @Override + public void cleanUp() { + log.info("Disposing meshes"); + quads.forEach((dim, mesh) -> mesh.dispose()); + log.info("{} meshes has been disposed", quads.size()); + } + + @Data + private static class QuadDimension { + private final Vector2f size; + private final Vector2f origin; + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/MeshManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/MeshManager.java old mode 100755 new mode 100644 index 23dfc0d0..01e8b712 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/MeshManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/util/mesh/MeshManager.java @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.core.util.mesh; - -import com.bartlomiejpluta.base.core.gc.Cleanable; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; - -public interface MeshManager extends Cleanable { - Mesh createQuad(float width, float height, float originX, float originY); -} +package com.bartlomiejpluta.base.core.util.mesh; + +import com.bartlomiejpluta.base.core.gc.Cleanable; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; + +public interface MeshManager extends Cleanable { + Mesh createQuad(float width, float height, float originX, float originY); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/util/res/ResourcesManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/util/res/ResourcesManager.java old mode 100755 new mode 100644 index f3187768..3250878a --- a/engine/src/main/java/com/bartlomiejpluta/base/core/util/res/ResourcesManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/util/res/ResourcesManager.java @@ -1,35 +1,35 @@ -package com.bartlomiejpluta.base.core.util.res; - -import com.bartlomiejpluta.base.core.error.AppException; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Scanner; - -@Component -public class ResourcesManager { - public String loadResourceAsString(String fileName) { - try (InputStream in = ResourcesManager.class.getResourceAsStream(fileName); - Scanner scanner = new Scanner(in, java.nio.charset.StandardCharsets.UTF_8.name())) { - return scanner.useDelimiter("\\A").next(); - } catch (Exception e) { - throw new AppException(e); - } - } - - public ByteBuffer loadResourceAsByteBuffer(String fileName) { - try { - var bytes = ResourcesManager.class.getResourceAsStream(fileName).readAllBytes(); - return ByteBuffer - .allocateDirect(bytes.length) - .order(ByteOrder.nativeOrder()) - .put(bytes) - .flip(); - } catch (IOException e) { - throw new AppException(e); - } - } -} +package com.bartlomiejpluta.base.core.util.res; + +import com.bartlomiejpluta.base.core.error.AppException; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Scanner; + +@Component +public class ResourcesManager { + public String loadResourceAsString(String fileName) { + try (InputStream in = ResourcesManager.class.getResourceAsStream(fileName); + Scanner scanner = new Scanner(in, java.nio.charset.StandardCharsets.UTF_8.name())) { + return scanner.useDelimiter("\\A").next(); + } catch (Exception e) { + throw new AppException(e); + } + } + + public ByteBuffer loadResourceAsByteBuffer(String fileName) { + try { + var bytes = ResourcesManager.class.getResourceAsStream(fileName).readAllBytes(); + return ByteBuffer + .allocateDirect(bytes.length) + .order(ByteOrder.nativeOrder()) + .put(bytes) + .flip(); + } catch (IOException e) { + throw new AppException(e); + } + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/AnimationableObject.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/AnimationableObject.java old mode 100755 new mode 100644 index af3cdd78..02c7d466 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/AnimationableObject.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/AnimationableObject.java @@ -1,33 +1,33 @@ -package com.bartlomiejpluta.base.core.world.animation; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.world.object.RenderableObject; -import lombok.EqualsAndHashCode; -import org.joml.Vector2f; -import org.joml.Vector2i; - -@EqualsAndHashCode(callSuper = true) -public abstract class AnimationableObject extends RenderableObject { - protected final Vector2i spriteSheetDimension; - - public AnimationableObject(Mesh mesh, Material material, Vector2i spriteSheetDimension) { - super(mesh); - this.spriteSheetDimension = spriteSheetDimension; - - material.setSpriteSize(1 / (float) spriteSheetDimension.y, 1 / (float) spriteSheetDimension.x); - setMaterial(material); - } - - // Returns time in ms between frames - public abstract int getAnimationSpeed(); - - public abstract boolean shouldAnimate(); - - public abstract Vector2f[] getSpriteAnimationFramesPositions(); - - protected void setAnimationFrame(Vector2f framePosition) { - var spriteSize = getMaterial().getSpriteSize(); - setSpritePosition(spriteSize.x * framePosition.x, spriteSize.y * framePosition.y); - } -} +package com.bartlomiejpluta.base.core.world.animation; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.world.object.RenderableObject; +import lombok.EqualsAndHashCode; +import org.joml.Vector2f; +import org.joml.Vector2i; + +@EqualsAndHashCode(callSuper = true) +public abstract class AnimationableObject extends RenderableObject { + protected final Vector2i spriteSheetDimension; + + public AnimationableObject(Mesh mesh, Material material, Vector2i spriteSheetDimension) { + super(mesh); + this.spriteSheetDimension = spriteSheetDimension; + + material.setSpriteSize(1 / (float) spriteSheetDimension.y, 1 / (float) spriteSheetDimension.x); + setMaterial(material); + } + + // Returns time in ms between frames + public abstract int getAnimationSpeed(); + + public abstract boolean shouldAnimate(); + + public abstract Vector2f[] getSpriteAnimationFramesPositions(); + + protected void setAnimationFrame(Vector2f framePosition) { + var spriteSize = getMaterial().getSpriteSize(); + setSpritePosition(spriteSize.x * framePosition.x, spriteSize.y * framePosition.y); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/Animator.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/Animator.java old mode 100755 new mode 100644 index 7b9dcc3d..8a258c6a --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/Animator.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/Animator.java @@ -1,5 +1,5 @@ -package com.bartlomiejpluta.base.core.world.animation; - -public interface Animator { - void animate(AnimationableObject objects); -} +package com.bartlomiejpluta.base.core.world.animation; + +public interface Animator { + void animate(AnimationableObject objects); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/DefaultAnimator.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/DefaultAnimator.java old mode 100755 new mode 100644 index bde76fb9..87a49020 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/DefaultAnimator.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/animation/DefaultAnimator.java @@ -1,18 +1,18 @@ -package com.bartlomiejpluta.base.core.world.animation; - -import org.springframework.stereotype.Component; - -@Component -public class DefaultAnimator implements Animator { - - @Override - public void animate(AnimationableObject object) { - if(object.shouldAnimate()) { - var positions = object.getSpriteAnimationFramesPositions(); - var delay = object.getAnimationSpeed(); - var currentPosition = (int) (System.currentTimeMillis() % (positions.length * delay)) / delay; - var current = positions[currentPosition]; - object.setAnimationFrame(current); - } - } -} +package com.bartlomiejpluta.base.core.world.animation; + +import org.springframework.stereotype.Component; + +@Component +public class DefaultAnimator implements Animator { + + @Override + public void animate(AnimationableObject object) { + if(object.shouldAnimate()) { + var positions = object.getSpriteAnimationFramesPositions(); + var delay = object.getAnimationSpeed(); + var currentPosition = (int) (System.currentTimeMillis() % (positions.length * delay)) / delay; + var current = positions[currentPosition]; + object.setAnimationFrame(current); + } + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/camera/Camera.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/camera/Camera.java old mode 100755 new mode 100644 index 11ea4dd1..f06fdd2b --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/camera/Camera.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/camera/Camera.java @@ -1,22 +1,22 @@ -package com.bartlomiejpluta.base.core.world.camera; - -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.world.object.PositionableObject; -import org.joml.Matrix4f; - -public class Camera extends PositionableObject { - private final Matrix4f projectionMatrix = new Matrix4f(); - private final Matrix4f viewMatrix = new Matrix4f(); - - public Matrix4f getProjectionMatrix(Window window) { - return projectionMatrix - .identity() - .setOrtho2D(0, window.getWidth(), window.getHeight(), 0); - } - - public Matrix4f getViewMatrix() { - return viewMatrix - .identity() - .translate(-position.x, -position.y, 0); - } -} +package com.bartlomiejpluta.base.core.world.camera; + +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.world.object.PositionableObject; +import org.joml.Matrix4f; + +public class Camera extends PositionableObject { + private final Matrix4f projectionMatrix = new Matrix4f(); + private final Matrix4f viewMatrix = new Matrix4f(); + + public Matrix4f getProjectionMatrix(Window window) { + return projectionMatrix + .identity() + .setOrtho2D(0, window.getWidth(), window.getHeight(), 0); + } + + public Matrix4f getViewMatrix() { + return viewMatrix + .identity() + .translate(-position.x, -position.y, 0); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/GameMap.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/GameMap.java old mode 100755 new mode 100644 index 91eff8aa..606cdaa1 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/GameMap.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/GameMap.java @@ -1,136 +1,136 @@ -package com.bartlomiejpluta.base.core.world.map; - -import com.bartlomiejpluta.base.core.gl.render.Renderable; -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.image.Image; -import com.bartlomiejpluta.base.core.logic.Updatable; -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.world.animation.Animator; -import com.bartlomiejpluta.base.core.world.camera.Camera; -import com.bartlomiejpluta.base.core.world.movement.MovableObject; -import com.bartlomiejpluta.base.core.world.movement.Movement; -import com.bartlomiejpluta.base.core.world.tileset.model.Tile; -import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; -import lombok.Getter; -import org.joml.Vector2f; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class GameMap implements Renderable, Updatable { - private final Animator animator; - - private final Camera camera; - private final TileSet tileSet; - private final List layers = new ArrayList<>(); - - private final float scale; - - @Getter - private final int rows; - - @Getter - private final int columns; - - @Getter - private final Vector2f stepSize; - - public GameMap(Animator animator, Camera camera, TileSet tileSet, int rows, int columns, float scale) { - this.animator = animator; - this.camera = camera; - this.tileSet = tileSet; - this.scale = scale; - this.rows = rows; - this.columns = columns; - this.stepSize = new Vector2f(this.scale * this.tileSet.getTileWidth(), this.scale * this.tileSet.getTileHeight()); - } - - @Override - public void render(Window window, ShaderManager shaderManager) { - shaderManager.setUniform(UniformName.UNI_PROJECTION_MATRIX, camera.getProjectionMatrix(window)); - shaderManager.setUniform(UniformName.UNI_VIEW_MATRIX, camera.getViewMatrix()); - - for (var layer : layers) { - layer.render(window, shaderManager); - } - } - - @Override - public void update(float dt) { - for (var layer : layers) { - layer.update(dt); - } - } - - public Vector2f getSize() { - return new Vector2f(columns * stepSize.x, rows * stepSize.y); - } - - public GameMap createObjectLayer() { - var passageMap = new PassageAbility[rows][columns]; - for (int i = 0; i < rows; ++i) { - Arrays.fill(passageMap[i], 0, columns, PassageAbility.ALLOW); - } - - layers.add(new ObjectLayer(animator, new ArrayList<>(), passageMap)); - - return this; - } - - public GameMap createTileLayer() { - layers.add(new TileLayer(new Tile[rows][columns], stepSize, scale)); - - return this; - } - - public GameMap createImageLayer(Image image, ImageLayer.Mode imageDisplayMode) { - layers.add(new ImageLayer(this, image, imageDisplayMode)); - - return this; - } - - public GameMap addObject(int layerIndex, MovableObject object) { - ((ObjectLayer) layers.get(layerIndex)).addObject(object); - - return this; - } - - public GameMap removeObject(int layerIndex, MovableObject object) { - ((ObjectLayer) layers.get(layerIndex)).removeObject(object); - - return this; - } - - public GameMap setPassageAbility(int layerIndex, int row, int column, PassageAbility passageAbility) { - ((ObjectLayer) layers.get(layerIndex)).setPassageAbility(row, column, passageAbility); - return this; - } - - public GameMap setTile(int layerIndex, int row, int column, Tile tile) { - ((TileLayer) layers.get(layerIndex)).setTile(row, column, tile); - - return this; - } - - public GameMap setImage(int layerIndex, Image image) { - ((ImageLayer) layers.get(layerIndex)).setImage(image); - - return this; - } - - public boolean isMovementPossible(int layerIndex, Movement movement) { - var target = movement.getTargetCoordinate(); - - // Is trying to go beyond the map - if(target.x < 0 || target.y < 0 || target.x >= columns || target.y >= rows) { - return false; - } - - var source = movement.getSourceCoordinate(); - var direction = movement.getDirection(); - - return ((ObjectLayer) layers.get(layerIndex)).isMovementPossible(source, target, direction); - } -} +package com.bartlomiejpluta.base.core.world.map; + +import com.bartlomiejpluta.base.core.gl.render.Renderable; +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.image.Image; +import com.bartlomiejpluta.base.core.logic.Updatable; +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.world.animation.Animator; +import com.bartlomiejpluta.base.core.world.camera.Camera; +import com.bartlomiejpluta.base.core.world.movement.MovableObject; +import com.bartlomiejpluta.base.core.world.movement.Movement; +import com.bartlomiejpluta.base.core.world.tileset.model.Tile; +import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; +import lombok.Getter; +import org.joml.Vector2f; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class GameMap implements Renderable, Updatable { + private final Animator animator; + + private final Camera camera; + private final TileSet tileSet; + private final List layers = new ArrayList<>(); + + private final float scale; + + @Getter + private final int rows; + + @Getter + private final int columns; + + @Getter + private final Vector2f stepSize; + + public GameMap(Animator animator, Camera camera, TileSet tileSet, int rows, int columns, float scale) { + this.animator = animator; + this.camera = camera; + this.tileSet = tileSet; + this.scale = scale; + this.rows = rows; + this.columns = columns; + this.stepSize = new Vector2f(this.scale * this.tileSet.getTileWidth(), this.scale * this.tileSet.getTileHeight()); + } + + @Override + public void render(Window window, ShaderManager shaderManager) { + shaderManager.setUniform(UniformName.UNI_PROJECTION_MATRIX, camera.getProjectionMatrix(window)); + shaderManager.setUniform(UniformName.UNI_VIEW_MATRIX, camera.getViewMatrix()); + + for (var layer : layers) { + layer.render(window, shaderManager); + } + } + + @Override + public void update(float dt) { + for (var layer : layers) { + layer.update(dt); + } + } + + public Vector2f getSize() { + return new Vector2f(columns * stepSize.x, rows * stepSize.y); + } + + public GameMap createObjectLayer() { + var passageMap = new PassageAbility[rows][columns]; + for (int i = 0; i < rows; ++i) { + Arrays.fill(passageMap[i], 0, columns, PassageAbility.ALLOW); + } + + layers.add(new ObjectLayer(animator, new ArrayList<>(), passageMap)); + + return this; + } + + public GameMap createTileLayer() { + layers.add(new TileLayer(new Tile[rows][columns], stepSize, scale)); + + return this; + } + + public GameMap createImageLayer(Image image, ImageLayer.Mode imageDisplayMode) { + layers.add(new ImageLayer(this, image, imageDisplayMode)); + + return this; + } + + public GameMap addObject(int layerIndex, MovableObject object) { + ((ObjectLayer) layers.get(layerIndex)).addObject(object); + + return this; + } + + public GameMap removeObject(int layerIndex, MovableObject object) { + ((ObjectLayer) layers.get(layerIndex)).removeObject(object); + + return this; + } + + public GameMap setPassageAbility(int layerIndex, int row, int column, PassageAbility passageAbility) { + ((ObjectLayer) layers.get(layerIndex)).setPassageAbility(row, column, passageAbility); + return this; + } + + public GameMap setTile(int layerIndex, int row, int column, Tile tile) { + ((TileLayer) layers.get(layerIndex)).setTile(row, column, tile); + + return this; + } + + public GameMap setImage(int layerIndex, Image image) { + ((ImageLayer) layers.get(layerIndex)).setImage(image); + + return this; + } + + public boolean isMovementPossible(int layerIndex, Movement movement) { + var target = movement.getTargetCoordinate(); + + // Is trying to go beyond the map + if(target.x < 0 || target.y < 0 || target.x >= columns || target.y >= rows) { + return false; + } + + var source = movement.getSourceCoordinate(); + var direction = movement.getDirection(); + + return ((ObjectLayer) layers.get(layerIndex)).isMovementPossible(source, target, direction); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ImageLayer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ImageLayer.java old mode 100755 new mode 100644 index e57b2894..bf830ea4 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ImageLayer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ImageLayer.java @@ -1,58 +1,58 @@ -package com.bartlomiejpluta.base.core.world.map; - -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.image.Image; -import com.bartlomiejpluta.base.core.ui.Window; - -public class ImageLayer implements Layer { - - public enum Mode { - NORMAL, - FIT_SCREEN, - FIT_MAP; - } - - private final float mapWidth; - private final float mapHeight; - - private Image image; - private float imageInitialWidth; - private float imageInitialHeight; - private final Mode mode; - - public ImageLayer(GameMap map, Image image, Mode mode) { - var stepSize = map.getStepSize(); - this.mapWidth = map.getColumns() * stepSize.x; - this.mapHeight = map.getRows() * stepSize.y; - this.mode = mode; - setImage(image); - } - - public void setImage(Image image) { - this.image = image; - this.imageInitialWidth = image.getInitialWidth(); - this.imageInitialHeight = image.getInitialHeight(); - } - - @Override - public void render(Window window, ShaderManager shaderManager) { - if (image == null) { - return; - } - - shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, image.getModelMatrix()); - - switch (mode) { - case FIT_SCREEN -> image.setScale(window.getWidth() / imageInitialWidth, window.getHeight() / imageInitialHeight); - case FIT_MAP -> image.setScale(mapWidth / imageInitialWidth, mapHeight / imageInitialHeight); - } - - image.render(window, shaderManager); - } - - @Override - public void update(float dt) { - - } -} +package com.bartlomiejpluta.base.core.world.map; + +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.image.Image; +import com.bartlomiejpluta.base.core.ui.Window; + +public class ImageLayer implements Layer { + + public enum Mode { + NORMAL, + FIT_SCREEN, + FIT_MAP; + } + + private final float mapWidth; + private final float mapHeight; + + private Image image; + private float imageInitialWidth; + private float imageInitialHeight; + private final Mode mode; + + public ImageLayer(GameMap map, Image image, Mode mode) { + var stepSize = map.getStepSize(); + this.mapWidth = map.getColumns() * stepSize.x; + this.mapHeight = map.getRows() * stepSize.y; + this.mode = mode; + setImage(image); + } + + public void setImage(Image image) { + this.image = image; + this.imageInitialWidth = image.getInitialWidth(); + this.imageInitialHeight = image.getInitialHeight(); + } + + @Override + public void render(Window window, ShaderManager shaderManager) { + if (image == null) { + return; + } + + shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, image.getModelMatrix()); + + switch (mode) { + case FIT_SCREEN -> image.setScale(window.getWidth() / imageInitialWidth, window.getHeight() / imageInitialHeight); + case FIT_MAP -> image.setScale(mapWidth / imageInitialWidth, mapHeight / imageInitialHeight); + } + + image.render(window, shaderManager); + } + + @Override + public void update(float dt) { + + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/Layer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/Layer.java old mode 100755 new mode 100644 index cf011c5f..1737267d --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/Layer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/Layer.java @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.core.world.map; - -import com.bartlomiejpluta.base.core.gl.render.Renderable; -import com.bartlomiejpluta.base.core.logic.Updatable; - -public interface Layer extends Renderable, Updatable { - -} +package com.bartlomiejpluta.base.core.world.map; + +import com.bartlomiejpluta.base.core.gl.render.Renderable; +import com.bartlomiejpluta.base.core.logic.Updatable; + +public interface Layer extends Renderable, Updatable { + +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ObjectLayer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ObjectLayer.java old mode 100755 new mode 100644 index c84770a4..698ce8e3 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ObjectLayer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/ObjectLayer.java @@ -1,73 +1,73 @@ -package com.bartlomiejpluta.base.core.world.map; - -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.world.animation.Animator; -import com.bartlomiejpluta.base.core.world.movement.Direction; -import com.bartlomiejpluta.base.core.world.movement.MovableObject; -import org.joml.Vector2i; - -import java.util.List; - -public class ObjectLayer implements Layer { - private final Animator animator; - private final List objects; - - private final PassageAbility[][] passageMap; - - public ObjectLayer(Animator animator, List objects, PassageAbility[][] passageMap) { - this.animator = animator; - this.objects = objects; - this.passageMap = passageMap; - } - - public void addObject(MovableObject object) { - objects.add(object); - } - - public void removeObject(MovableObject object) { - objects.remove(object); - } - - public void setPassageAbility(int row, int column, PassageAbility passageAbility) { - passageMap[row][column] = passageAbility; - } - - public boolean isMovementPossible(Vector2i source, Vector2i target, Direction direction) { - var isTargetReachable = switch (passageMap[target.y][target.x]) { - case UP_ONLY -> direction != Direction.DOWN; - case DOWN_ONLY -> direction != Direction.UP; - case LEFT_ONLY -> direction != Direction.RIGHT; - case RIGHT_ONLY -> direction != Direction.LEFT; - case BLOCK -> false; - case ALLOW -> true; - }; - - var canMoveFromCurrentTile = switch (passageMap[source.y][source.x]) { - case UP_ONLY -> direction == Direction.UP; - case DOWN_ONLY -> direction == Direction.DOWN; - case LEFT_ONLY -> direction == Direction.LEFT; - case RIGHT_ONLY -> direction == Direction.RIGHT; - default -> true; - }; - - return isTargetReachable && canMoveFromCurrentTile; - } - - @Override - public void render(Window window, ShaderManager shaderManager) { - for (var object : objects) { - shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, object.getModelMatrix()); - animator.animate(object); - object.render(window, shaderManager); - } - } - - @Override - public void update(float dt) { - for (var object : objects) { - object.update(dt); - } - } -} +package com.bartlomiejpluta.base.core.world.map; + +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.world.animation.Animator; +import com.bartlomiejpluta.base.core.world.movement.Direction; +import com.bartlomiejpluta.base.core.world.movement.MovableObject; +import org.joml.Vector2i; + +import java.util.List; + +public class ObjectLayer implements Layer { + private final Animator animator; + private final List objects; + + private final PassageAbility[][] passageMap; + + public ObjectLayer(Animator animator, List objects, PassageAbility[][] passageMap) { + this.animator = animator; + this.objects = objects; + this.passageMap = passageMap; + } + + public void addObject(MovableObject object) { + objects.add(object); + } + + public void removeObject(MovableObject object) { + objects.remove(object); + } + + public void setPassageAbility(int row, int column, PassageAbility passageAbility) { + passageMap[row][column] = passageAbility; + } + + public boolean isMovementPossible(Vector2i source, Vector2i target, Direction direction) { + var isTargetReachable = switch (passageMap[target.y][target.x]) { + case UP_ONLY -> direction != Direction.DOWN; + case DOWN_ONLY -> direction != Direction.UP; + case LEFT_ONLY -> direction != Direction.RIGHT; + case RIGHT_ONLY -> direction != Direction.LEFT; + case BLOCK -> false; + case ALLOW -> true; + }; + + var canMoveFromCurrentTile = switch (passageMap[source.y][source.x]) { + case UP_ONLY -> direction == Direction.UP; + case DOWN_ONLY -> direction == Direction.DOWN; + case LEFT_ONLY -> direction == Direction.LEFT; + case RIGHT_ONLY -> direction == Direction.RIGHT; + default -> true; + }; + + return isTargetReachable && canMoveFromCurrentTile; + } + + @Override + public void render(Window window, ShaderManager shaderManager) { + for (var object : objects) { + shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, object.getModelMatrix()); + animator.animate(object); + object.render(window, shaderManager); + } + } + + @Override + public void update(float dt) { + for (var object : objects) { + object.update(dt); + } + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/PassageAbility.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/PassageAbility.java old mode 100755 new mode 100644 index 27108cfd..10d4c7c4 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/PassageAbility.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/PassageAbility.java @@ -1,10 +1,10 @@ -package com.bartlomiejpluta.base.core.world.map; - -public enum PassageAbility { - BLOCK, - ALLOW, - UP_ONLY, - DOWN_ONLY, - LEFT_ONLY, - RIGHT_ONLY -} +package com.bartlomiejpluta.base.core.world.map; + +public enum PassageAbility { + BLOCK, + ALLOW, + UP_ONLY, + DOWN_ONLY, + LEFT_ONLY, + RIGHT_ONLY +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/TileLayer.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/TileLayer.java old mode 100755 new mode 100644 index 4445f6c4..e945ad26 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/TileLayer.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/map/TileLayer.java @@ -1,46 +1,46 @@ -package com.bartlomiejpluta.base.core.world.map; - -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.world.tileset.model.Tile; -import org.joml.Vector2f; - -public class TileLayer implements Layer { - private final Tile[][] layer; - private final Vector2f stepSize; - private final float scale; - - public TileLayer(Tile[][] layer, Vector2f stepSize, float scale) { - this.layer = layer; - this.stepSize = stepSize; - this.scale = scale; - } - - public void setTile(int row, int column, Tile tile) { - layer[row][column] = tile; - recalculateTileGeometry(tile, row, column); - } - - private void recalculateTileGeometry(Tile tile, int row, int column) { - tile.setScale(scale); - tile.setPosition(column * stepSize.x, row * stepSize.y); - } - - @Override - public void render(Window window, ShaderManager shaderManager) { - for (var row : layer) { - for (var tile : row) { - if (tile != null) { - shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, tile.getModelMatrix()); - tile.render(window, shaderManager); - } - } - } - } - - @Override - public void update(float dt) { - - } -} +package com.bartlomiejpluta.base.core.world.map; + +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.world.tileset.model.Tile; +import org.joml.Vector2f; + +public class TileLayer implements Layer { + private final Tile[][] layer; + private final Vector2f stepSize; + private final float scale; + + public TileLayer(Tile[][] layer, Vector2f stepSize, float scale) { + this.layer = layer; + this.stepSize = stepSize; + this.scale = scale; + } + + public void setTile(int row, int column, Tile tile) { + layer[row][column] = tile; + recalculateTileGeometry(tile, row, column); + } + + private void recalculateTileGeometry(Tile tile, int row, int column) { + tile.setScale(scale); + tile.setPosition(column * stepSize.x, row * stepSize.y); + } + + @Override + public void render(Window window, ShaderManager shaderManager) { + for (var row : layer) { + for (var tile : row) { + if (tile != null) { + shaderManager.setUniform(UniformName.UNI_MODEL_MATRIX, tile.getModelMatrix()); + tile.render(window, shaderManager); + } + } + } + } + + @Override + public void update(float dt) { + + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Direction.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Direction.java old mode 100755 new mode 100644 index 3bda4733..e26bfd22 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Direction.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Direction.java @@ -1,24 +1,24 @@ -package com.bartlomiejpluta.base.core.world.movement; - -import lombok.AccessLevel; -import lombok.RequiredArgsConstructor; -import org.joml.Vector2f; -import org.joml.Vector2i; - -@RequiredArgsConstructor(access = AccessLevel.PRIVATE) -public enum Direction { - UP(new Vector2i(0, -1)), - DOWN(new Vector2i(0, 1)), - LEFT(new Vector2i(-1, 0)), - RIGHT(new Vector2i(1, 0)); - - private final Vector2i vector; - - public Vector2i asIntVector() { - return new Vector2i(vector); - } - - public Vector2f asFloatVector() { - return new Vector2f(vector); - } -} +package com.bartlomiejpluta.base.core.world.movement; + +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import org.joml.Vector2f; +import org.joml.Vector2i; + +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public enum Direction { + UP(new Vector2i(0, -1)), + DOWN(new Vector2i(0, 1)), + LEFT(new Vector2i(-1, 0)), + RIGHT(new Vector2i(1, 0)); + + private final Vector2i vector; + + public Vector2i asIntVector() { + return new Vector2i(vector); + } + + public Vector2f asFloatVector() { + return new Vector2f(vector); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/MovableObject.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/MovableObject.java old mode 100755 new mode 100644 index 63688baa..8c4b83b8 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/MovableObject.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/MovableObject.java @@ -1,81 +1,81 @@ -package com.bartlomiejpluta.base.core.world.movement; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.logic.Updatable; -import com.bartlomiejpluta.base.core.world.animation.AnimationableObject; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import org.joml.Vector2f; -import org.joml.Vector2i; - -@EqualsAndHashCode(callSuper = true) -public abstract class MovableObject extends AnimationableObject implements Updatable { - private final Vector2f coordinateStepSize; - - private int moveTime = 0; - private Vector2f movementVector; - - @Getter - private final Vector2i coordinates = new Vector2i(0, 0); - - protected int framesToCrossOneTile = 1; - - public boolean isMoving() { - return movementVector != null; - } - - @Override - public void update(float dt) { - if(movementVector != null) { - if(moveTime > 0) { - --moveTime; - movePosition(movementVector); - } else { - adjustCoordinates(); - setDefaultAnimationFrame(); - movementVector = null; - } - } - } - - protected abstract void setDefaultAnimationFrame(); - - private void adjustCoordinates() { - var position = new Vector2f(getPosition()); - setCoordinates(new Vector2i((int) (position.x / coordinateStepSize.x), (int) (position.y / coordinateStepSize.y))); - } - - public Movement prepareMovement(Direction direction) { - return new Movement(this, direction); - } - - protected boolean move(Direction direction) { - if (this.movementVector != null) { - return false; - } - - var speed = new Vector2f(coordinateStepSize).div(framesToCrossOneTile); - movementVector = direction.asFloatVector().mul(speed); - moveTime = framesToCrossOneTile; - - return true; - } - - public MovableObject setCoordinates(int x, int y) { - coordinates.x = x; - coordinates.y = y; - setPosition((x + 0.5f) * coordinateStepSize.x, (y + 0.5f) * coordinateStepSize.y); - return this; - } - - public MovableObject setCoordinates(Vector2i coordinates) { - return setCoordinates(coordinates.x, coordinates.y); - } - - public MovableObject(Mesh mesh, Material material, Vector2f coordinateStepSize, Vector2i spriteSheetDimensions) { - super(mesh, material, spriteSheetDimensions); - this.coordinateStepSize = coordinateStepSize; - setCoordinates(0, 0); - } -} +package com.bartlomiejpluta.base.core.world.movement; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.logic.Updatable; +import com.bartlomiejpluta.base.core.world.animation.AnimationableObject; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import org.joml.Vector2f; +import org.joml.Vector2i; + +@EqualsAndHashCode(callSuper = true) +public abstract class MovableObject extends AnimationableObject implements Updatable { + private final Vector2f coordinateStepSize; + + private int moveTime = 0; + private Vector2f movementVector; + + @Getter + private final Vector2i coordinates = new Vector2i(0, 0); + + protected int framesToCrossOneTile = 1; + + public boolean isMoving() { + return movementVector != null; + } + + @Override + public void update(float dt) { + if(movementVector != null) { + if(moveTime > 0) { + --moveTime; + movePosition(movementVector); + } else { + adjustCoordinates(); + setDefaultAnimationFrame(); + movementVector = null; + } + } + } + + protected abstract void setDefaultAnimationFrame(); + + private void adjustCoordinates() { + var position = new Vector2f(getPosition()); + setCoordinates(new Vector2i((int) (position.x / coordinateStepSize.x), (int) (position.y / coordinateStepSize.y))); + } + + public Movement prepareMovement(Direction direction) { + return new Movement(this, direction); + } + + protected boolean move(Direction direction) { + if (this.movementVector != null) { + return false; + } + + var speed = new Vector2f(coordinateStepSize).div(framesToCrossOneTile); + movementVector = direction.asFloatVector().mul(speed); + moveTime = framesToCrossOneTile; + + return true; + } + + public MovableObject setCoordinates(int x, int y) { + coordinates.x = x; + coordinates.y = y; + setPosition((x + 0.5f) * coordinateStepSize.x, (y + 0.5f) * coordinateStepSize.y); + return this; + } + + public MovableObject setCoordinates(Vector2i coordinates) { + return setCoordinates(coordinates.x, coordinates.y); + } + + public MovableObject(Mesh mesh, Material material, Vector2f coordinateStepSize, Vector2i spriteSheetDimensions) { + super(mesh, material, spriteSheetDimensions); + this.coordinateStepSize = coordinateStepSize; + setCoordinates(0, 0); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Movement.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Movement.java old mode 100755 new mode 100644 index 5f8dfed4..933779a7 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Movement.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/movement/Movement.java @@ -1,49 +1,49 @@ -package com.bartlomiejpluta.base.core.world.movement; - -import lombok.AccessLevel; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.joml.Vector2i; - -@Data -@RequiredArgsConstructor(access = AccessLevel.PACKAGE) -public class Movement { - private final MovableObject object; - private final Direction direction; - private boolean performed = false; - - public boolean perform() { - performed = object.move(direction); - return performed; - } - - public Vector2i getSourceCoordinate() { - return new Vector2i(object.getCoordinates()); - } - - public Vector2i getTargetCoordinate() { - return direction.asIntVector().add(object.getCoordinates()); - } - - public Movement getAnother() { - return object.prepareMovement(direction); - } -} -//@Data -//public class Movement { -// private final MovableObject object; -// private final Direction direction; -// private final Vector2i source; -// private final Vector2i target; -// -// Movement(MovableObject object, Direction direction) { -// this.object = object; -// this.direction = direction; -// this.source = new Vector2i(object.getCoordinates()); -// this.target = direction.asIntVector().add(source); -// } -// -// public boolean perform() { -// return object.move(direction); -// } -//} +package com.bartlomiejpluta.base.core.world.movement; + +import lombok.AccessLevel; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.joml.Vector2i; + +@Data +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +public class Movement { + private final MovableObject object; + private final Direction direction; + private boolean performed = false; + + public boolean perform() { + performed = object.move(direction); + return performed; + } + + public Vector2i getSourceCoordinate() { + return new Vector2i(object.getCoordinates()); + } + + public Vector2i getTargetCoordinate() { + return direction.asIntVector().add(object.getCoordinates()); + } + + public Movement getAnother() { + return object.prepareMovement(direction); + } +} +//@Data +//public class Movement { +// private final MovableObject object; +// private final Direction direction; +// private final Vector2i source; +// private final Vector2i target; +// +// Movement(MovableObject object, Direction direction) { +// this.object = object; +// this.direction = direction; +// this.source = new Vector2i(object.getCoordinates()); +// this.target = direction.asIntVector().add(source); +// } +// +// public boolean perform() { +// return object.move(direction); +// } +//} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/PositionableObject.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/PositionableObject.java old mode 100755 new mode 100644 index 886f8f04..c0f0f209 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/PositionableObject.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/PositionableObject.java @@ -1,78 +1,78 @@ -package com.bartlomiejpluta.base.core.world.object; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.joml.Matrix4f; -import org.joml.Vector2f; - -import static java.lang.Math.toRadians; - -@EqualsAndHashCode -public abstract class PositionableObject { - private final Matrix4f modelMatrix = new Matrix4f(); - - @Getter - protected final Vector2f position = new Vector2f(0, 0); - - @Getter - @Setter - protected float rotation; - - @Getter - @Setter - protected float scaleX = 1.0f; - - @Getter - @Setter - protected float scaleY = 1.0f; - - public PositionableObject setPosition(float x, float y) { - position.x = x; - position.y = y; - return this; - } - - public PositionableObject setPosition(Vector2f position) { - this.position.x = position.x; - this.position.y = position.y; - return this; - } - - public PositionableObject movePosition(float x, float y) { - position.x += x; - position.y += y; - return this; - } - - public PositionableObject movePosition(Vector2f position) { - this.position.x += position.x; - this.position.y += position.y; - return this; - } - - public PositionableObject moveRotation(float rotation) { - this.rotation += rotation; - return this; - } - - public PositionableObject setScale(float scale) { - this.scaleX = scale; - this.scaleY = scale; - return this; - } - - public PositionableObject setScale(float scaleX, float scaleY) { - this.scaleX = scaleX; - this.scaleY = scaleY; - return this; - } - - public Matrix4f getModelMatrix() { - return modelMatrix - .identity() - .translate(position.x, position.y, 0) - .rotateZ((float) toRadians(-rotation)) - .scaleXY(scaleX, scaleY); - } -} +package com.bartlomiejpluta.base.core.world.object; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.joml.Matrix4f; +import org.joml.Vector2f; + +import static java.lang.Math.toRadians; + +@EqualsAndHashCode +public abstract class PositionableObject { + private final Matrix4f modelMatrix = new Matrix4f(); + + @Getter + protected final Vector2f position = new Vector2f(0, 0); + + @Getter + @Setter + protected float rotation; + + @Getter + @Setter + protected float scaleX = 1.0f; + + @Getter + @Setter + protected float scaleY = 1.0f; + + public PositionableObject setPosition(float x, float y) { + position.x = x; + position.y = y; + return this; + } + + public PositionableObject setPosition(Vector2f position) { + this.position.x = position.x; + this.position.y = position.y; + return this; + } + + public PositionableObject movePosition(float x, float y) { + position.x += x; + position.y += y; + return this; + } + + public PositionableObject movePosition(Vector2f position) { + this.position.x += position.x; + this.position.y += position.y; + return this; + } + + public PositionableObject moveRotation(float rotation) { + this.rotation += rotation; + return this; + } + + public PositionableObject setScale(float scale) { + this.scaleX = scale; + this.scaleY = scale; + return this; + } + + public PositionableObject setScale(float scaleX, float scaleY) { + this.scaleX = scaleX; + this.scaleY = scaleY; + return this; + } + + public Matrix4f getModelMatrix() { + return modelMatrix + .identity() + .translate(position.x, position.y, 0) + .rotateZ((float) toRadians(-rotation)) + .scaleXY(scaleX, scaleY); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/RenderableObject.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/RenderableObject.java old mode 100755 new mode 100644 index 2c49cfcc..08f731d6 --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/RenderableObject.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/object/RenderableObject.java @@ -1,65 +1,65 @@ -package com.bartlomiejpluta.base.core.world.object; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.gl.render.Renderable; -import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; -import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; -import com.bartlomiejpluta.base.core.ui.Window; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.Setter; -import org.joml.Vector2f; -import org.joml.Vector4f; - -@RequiredArgsConstructor -@EqualsAndHashCode(callSuper = true) -public abstract class RenderableObject extends PositionableObject implements Renderable { - private final Mesh mesh; - - @Getter - @Setter - private Material material; - - @Override - public void render(Window window, ShaderManager shaderManager) { - material.activateTextureIfExists(); - - shaderManager.setUniform(UniformName.UNI_OBJECT_COLOR, material.getColor()); - shaderManager.setUniform(UniformName.UNI_HAS_OBJECT_TEXTURE, material.hasTexture()); - shaderManager.setUniform(UniformName.UNI_TEXTURE_SAMPLER, 0); - shaderManager.setUniform(UniformName.UNI_SPRITE_SIZE, material.getSpriteSize()); - shaderManager.setUniform(UniformName.UNI_SPRITE_POSITION, material.getSpritePosition()); - - mesh.render(window, shaderManager); - } - - public void setAlpha(float alpha) { - material.setAlpha(alpha); - } - - public void setColor(Vector4f color) { - material.setColor(color); - } - - public void setColor(float r, float g, float b, float alpha) { - material.setColor(r, g, b, alpha); - } - - public void setSpriteSize(Vector2f spriteSize) { - material.setSpriteSize(spriteSize); - } - - public void setSpriteSize(float w, float h) { - material.setSpriteSize(w, h); - } - - public void setSpritePosition(Vector2f spritePosition) { - material.setSpritePosition(spritePosition); - } - - public void setSpritePosition(float x, float y) { - material.setSpritePosition(x, y); - } -} +package com.bartlomiejpluta.base.core.world.object; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.gl.render.Renderable; +import com.bartlomiejpluta.base.core.gl.shader.constant.UniformName; +import com.bartlomiejpluta.base.core.gl.shader.manager.ShaderManager; +import com.bartlomiejpluta.base.core.ui.Window; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import org.joml.Vector2f; +import org.joml.Vector4f; + +@RequiredArgsConstructor +@EqualsAndHashCode(callSuper = true) +public abstract class RenderableObject extends PositionableObject implements Renderable { + private final Mesh mesh; + + @Getter + @Setter + private Material material; + + @Override + public void render(Window window, ShaderManager shaderManager) { + material.activateTextureIfExists(); + + shaderManager.setUniform(UniformName.UNI_OBJECT_COLOR, material.getColor()); + shaderManager.setUniform(UniformName.UNI_HAS_OBJECT_TEXTURE, material.hasTexture()); + shaderManager.setUniform(UniformName.UNI_TEXTURE_SAMPLER, 0); + shaderManager.setUniform(UniformName.UNI_SPRITE_SIZE, material.getSpriteSize()); + shaderManager.setUniform(UniformName.UNI_SPRITE_POSITION, material.getSpritePosition()); + + mesh.render(window, shaderManager); + } + + public void setAlpha(float alpha) { + material.setAlpha(alpha); + } + + public void setColor(Vector4f color) { + material.setColor(color); + } + + public void setColor(float r, float g, float b, float alpha) { + material.setColor(r, g, b, alpha); + } + + public void setSpriteSize(Vector2f spriteSize) { + material.setSpriteSize(spriteSize); + } + + public void setSpriteSize(float w, float h) { + material.setSpriteSize(w, h); + } + + public void setSpritePosition(Vector2f spritePosition) { + material.setSpritePosition(spritePosition); + } + + public void setSpritePosition(float x, float y) { + material.setSpritePosition(x, y); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/DefaultTileSetManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/DefaultTileSetManager.java old mode 100755 new mode 100644 index 169f3ebb..e0e49cab --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/DefaultTileSetManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/DefaultTileSetManager.java @@ -1,42 +1,42 @@ -package com.bartlomiejpluta.base.core.world.tileset.manager; - -import com.bartlomiejpluta.base.core.gl.object.texture.TextureManager; -import com.bartlomiejpluta.base.core.util.mesh.MeshManager; -import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultTileSetManager implements TileSetManager { - private final TextureManager textureManager; - private final MeshManager meshManager; - private final Map tileSets = new HashMap<>(); - - @Override - public TileSet createTileSet(String tileSetFileName, int rows, int columns) { - var tileset = tileSets.get(tileSetFileName); - - if(tileset == null) { - log.info("Loading [{}] tileset to cache", tileSetFileName); - var texture = textureManager.loadTexture(tileSetFileName); - var tileWidth = texture.getWidth() / columns; - var tileHeight = texture.getHeight() / rows; - var mesh = meshManager.createQuad(tileWidth, tileHeight, 0, 0); - tileset = new TileSet(mesh, texture, rows, columns, tileWidth, tileHeight); - } - - return tileset; - } - - @Override - public void cleanUp() { - log.info("There is nothing to clean up here"); - } -} +package com.bartlomiejpluta.base.core.world.tileset.manager; + +import com.bartlomiejpluta.base.core.gl.object.texture.TextureManager; +import com.bartlomiejpluta.base.core.util.mesh.MeshManager; +import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultTileSetManager implements TileSetManager { + private final TextureManager textureManager; + private final MeshManager meshManager; + private final Map tileSets = new HashMap<>(); + + @Override + public TileSet createTileSet(String tileSetFileName, int rows, int columns) { + var tileset = tileSets.get(tileSetFileName); + + if(tileset == null) { + log.info("Loading [{}] tileset to cache", tileSetFileName); + var texture = textureManager.loadTexture(tileSetFileName); + var tileWidth = texture.getWidth() / columns; + var tileHeight = texture.getHeight() / rows; + var mesh = meshManager.createQuad(tileWidth, tileHeight, 0, 0); + tileset = new TileSet(mesh, texture, rows, columns, tileWidth, tileHeight); + } + + return tileset; + } + + @Override + public void cleanUp() { + log.info("There is nothing to clean up here"); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/TileSetManager.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/TileSetManager.java old mode 100755 new mode 100644 index fe87153f..6066daee --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/TileSetManager.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/manager/TileSetManager.java @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.core.world.tileset.manager; - -import com.bartlomiejpluta.base.core.gc.Cleanable; -import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; - -public interface TileSetManager extends Cleanable { - TileSet createTileSet(String tileSetFileName, int rows, int columns); -} +package com.bartlomiejpluta.base.core.world.tileset.manager; + +import com.bartlomiejpluta.base.core.gc.Cleanable; +import com.bartlomiejpluta.base.core.world.tileset.model.TileSet; + +public interface TileSetManager extends Cleanable { + TileSet createTileSet(String tileSetFileName, int rows, int columns); +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/Tile.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/Tile.java old mode 100755 new mode 100644 index 0315aa97..6680990c --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/Tile.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/Tile.java @@ -1,19 +1,19 @@ -package com.bartlomiejpluta.base.core.world.tileset.model; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.world.object.RenderableObject; -import lombok.Getter; - -@Getter -public class Tile extends RenderableObject { - private final int width; - private final int height; - - Tile(Mesh mesh, Material material, int width, int height) { - super(mesh); - this.width = width; - this.height = height; - setMaterial(material); - } -} +package com.bartlomiejpluta.base.core.world.tileset.model; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.world.object.RenderableObject; +import lombok.Getter; + +@Getter +public class Tile extends RenderableObject { + private final int width; + private final int height; + + Tile(Mesh mesh, Material material, int width, int height) { + super(mesh); + this.width = width; + this.height = height; + setMaterial(material); + } +} diff --git a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/TileSet.java b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/TileSet.java old mode 100755 new mode 100644 index d794fd04..463344cc --- a/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/TileSet.java +++ b/engine/src/main/java/com/bartlomiejpluta/base/core/world/tileset/model/TileSet.java @@ -1,39 +1,39 @@ -package com.bartlomiejpluta.base.core.world.tileset.model; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.gl.object.texture.Texture; -import lombok.Getter; - -public class TileSet { - private final Texture texture; - private final int rows; - private final int columns; - private final float columnStep; - private final float rowStep; - private final Mesh mesh; - - @Getter - private final int tileWidth; - - @Getter - private final int tileHeight; - - public TileSet(Mesh mesh, Texture texture, int rows, int columns, int tileWidth, int tileHeight) { - this.texture = texture; - this.rows = rows; - this.columns = columns; - this.columnStep = 1/(float) columns; - this.rowStep = 1/(float) rows; - this.tileWidth = tileWidth; - this.tileHeight = tileHeight; - this.mesh = mesh; - } - - public Tile getTile(int row, int column) { - var material = Material.textured(texture); - material.setSpriteSize(columnStep, rowStep); - material.setSpritePosition(column * columnStep, row * rowStep); - return new Tile(mesh, material, tileWidth, tileHeight); - } -} +package com.bartlomiejpluta.base.core.world.tileset.model; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.gl.object.texture.Texture; +import lombok.Getter; + +public class TileSet { + private final Texture texture; + private final int rows; + private final int columns; + private final float columnStep; + private final float rowStep; + private final Mesh mesh; + + @Getter + private final int tileWidth; + + @Getter + private final int tileHeight; + + public TileSet(Mesh mesh, Texture texture, int rows, int columns, int tileWidth, int tileHeight) { + this.texture = texture; + this.rows = rows; + this.columns = columns; + this.columnStep = 1/(float) columns; + this.rowStep = 1/(float) rows; + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.mesh = mesh; + } + + public Tile getTile(int row, int column) { + var material = Material.textured(texture); + material.setSpriteSize(columnStep, rowStep); + material.setSpritePosition(column * columnStep, row * rowStep); + return new Tile(mesh, material, tileWidth, tileHeight); + } +} diff --git a/engine/src/main/resources/shaders/default.fs b/engine/src/main/resources/shaders/default.fs old mode 100755 new mode 100644 index 17588409..0f807b33 --- a/engine/src/main/resources/shaders/default.fs +++ b/engine/src/main/resources/shaders/default.fs @@ -1,23 +1,23 @@ -#version 330 - -uniform vec4 objectColor; -uniform int hasTexture; -uniform sampler2D sampler; -uniform vec2 spriteSize; -uniform vec2 spritePosition; - -in vec2 fragmentTexCoord; - -out vec4 fragColor; - -void main() -{ - if(hasTexture == 1) - { - fragColor = objectColor * texture(sampler, fragmentTexCoord * spriteSize + spritePosition); - } - else - { - fragColor = objectColor; - } +#version 330 + +uniform vec4 objectColor; +uniform int hasTexture; +uniform sampler2D sampler; +uniform vec2 spriteSize; +uniform vec2 spritePosition; + +in vec2 fragmentTexCoord; + +out vec4 fragColor; + +void main() +{ + if(hasTexture == 1) + { + fragColor = objectColor * texture(sampler, fragmentTexCoord * spriteSize + spritePosition); + } + else + { + fragColor = objectColor; + } } \ No newline at end of file diff --git a/engine/src/main/resources/shaders/default.vs b/engine/src/main/resources/shaders/default.vs old mode 100755 new mode 100644 index 1d57c527..0c4fea45 --- a/engine/src/main/resources/shaders/default.vs +++ b/engine/src/main/resources/shaders/default.vs @@ -1,16 +1,16 @@ -#version 330 - -uniform mat4 modelMatrix; -uniform mat4 viewMatrix; -uniform mat4 projectionMatrix; - -layout(location=0) in vec2 position; -layout(location=1) in vec2 texCoord; - -out vec2 fragmentTexCoord; - -void main() -{ - gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 0.0, 1.0); - fragmentTexCoord = texCoord; +#version 330 + +uniform mat4 modelMatrix; +uniform mat4 viewMatrix; +uniform mat4 projectionMatrix; + +layout(location=0) in vec2 position; +layout(location=1) in vec2 texCoord; + +out vec2 fragmentTexCoord; + +void main() +{ + gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 0.0, 1.0); + fragmentTexCoord = texCoord; } \ No newline at end of file diff --git a/game/build.gradle b/game/build.gradle old mode 100755 new mode 100644 index 01140414..32a2459a --- a/game/build.gradle +++ b/game/build.gradle @@ -1,55 +1,55 @@ -plugins { - id 'org.springframework.boot' version "$springBootVersion" - id 'io.spring.dependency-management' version "$springDependencyManagementVersion" - id 'java' - id 'application' -} - -group 'com.bartlomiejpluta.base' -version 'unspecified' - -import org.gradle.internal.os.OperatingSystem - -switch (OperatingSystem.current()) { - case OperatingSystem.LINUX: - def osArch = System.getProperty("os.arch") - project.ext.lwjglNatives = osArch.startsWith("arm") || osArch.startsWith("aarch64") - ? "natives-linux-${osArch.contains("64") || osArch.startsWith("armv8") ? "arm64" : "arm32"}" - : "natives-linux" - break - case OperatingSystem.MAC_OS: - project.ext.lwjglNatives = "natives-macos" - break - case OperatingSystem.WINDOWS: - project.ext.lwjglNatives = System.getProperty("os.arch").contains("64") ? "natives-windows" : "natives-windows-x86" - break -} - -configurations { - compileOnly { - extendsFrom annotationProcessor - } -} - -repositories { - mavenCentral() - jcenter() -} - -dependencies { - implementation project(":engine") - implementation project(":proto") - - compileOnly 'org.projectlombok:lombok' - annotationProcessor 'org.projectlombok:lombok' -} - -application { - // Define the main class for the application. - mainClass = 'com.bartlomiejpluta.base.game.App' -} - -build { - dependsOn(":engine:build") - dependsOn(":proto:build") -} +plugins { + id 'org.springframework.boot' version "$springBootVersion" + id 'io.spring.dependency-management' version "$springDependencyManagementVersion" + id 'java' + id 'application' +} + +group 'com.bartlomiejpluta.base' +version 'unspecified' + +import org.gradle.internal.os.OperatingSystem + +switch (OperatingSystem.current()) { + case OperatingSystem.LINUX: + def osArch = System.getProperty("os.arch") + project.ext.lwjglNatives = osArch.startsWith("arm") || osArch.startsWith("aarch64") + ? "natives-linux-${osArch.contains("64") || osArch.startsWith("armv8") ? "arm64" : "arm32"}" + : "natives-linux" + break + case OperatingSystem.MAC_OS: + project.ext.lwjglNatives = "natives-macos" + break + case OperatingSystem.WINDOWS: + project.ext.lwjglNatives = System.getProperty("os.arch").contains("64") ? "natives-windows" : "natives-windows-x86" + break +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() + jcenter() +} + +dependencies { + implementation project(":engine") + implementation project(":proto") + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' +} + +application { + // Define the main class for the application. + mainClass = 'com.bartlomiejpluta.base.game.App' +} + +build { + dependsOn(":engine:build") + dependsOn(":proto:build") +} diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/App.java b/game/src/main/java/com/bartlomiejpluta/base/game/App.java old mode 100755 new mode 100644 diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/logic/DefaultGameLogic.java b/game/src/main/java/com/bartlomiejpluta/base/game/logic/DefaultGameLogic.java old mode 100755 new mode 100644 index c59d10d8..cb503858 --- a/game/src/main/java/com/bartlomiejpluta/base/game/logic/DefaultGameLogic.java +++ b/game/src/main/java/com/bartlomiejpluta/base/game/logic/DefaultGameLogic.java @@ -1,67 +1,62 @@ -package com.bartlomiejpluta.base.game.logic; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.texture.TextureManager; -import com.bartlomiejpluta.base.core.gl.render.Renderer; -import com.bartlomiejpluta.base.core.logic.GameLogic; -import com.bartlomiejpluta.base.core.ui.Window; -import com.bartlomiejpluta.base.core.util.mesh.MeshManager; -import com.bartlomiejpluta.base.core.world.animation.Animator; -import com.bartlomiejpluta.base.core.world.camera.Camera; -import com.bartlomiejpluta.base.core.world.map.GameMap; -import com.bartlomiejpluta.base.core.world.movement.Direction; -import com.bartlomiejpluta.base.core.world.scene.Scene; -import com.bartlomiejpluta.base.core.world.tileset.manager.TileSetManager; -import com.bartlomiejpluta.base.game.world.entity.Entity; -import com.bartlomiejpluta.base.game.world.entity.EntityManager; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import static org.lwjgl.glfw.GLFW.*; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultGameLogic implements GameLogic { - private final Renderer renderer; - private final TileSetManager tileSetManager; - private final MeshManager meshManager; - private final TextureManager textureManager; - private final EntityManager entityManager; - private final Animator animator; - - private Camera camera; - private GameMap map; - private Scene scene; - - private Entity player; - - @Override - public void init(Window window) { - log.info("Initializing game logic"); - renderer.init(); - } - - @Override - public void input(Window window) { - - } - - @Override - public void update(float dt) { - - } - - @Override - public void render(Window window) { - renderer.render(window, scene); - } - - @Override - public void cleanUp() { - renderer.cleanUp(); - scene.cleanUp(); - } -} +package com.bartlomiejpluta.base.game.logic; + +import com.bartlomiejpluta.base.core.error.AppException; +import com.bartlomiejpluta.base.core.gl.object.texture.TextureManager; +import com.bartlomiejpluta.base.core.gl.render.Renderer; +import com.bartlomiejpluta.base.core.image.ImageManager; +import com.bartlomiejpluta.base.core.logic.GameLogic; +import com.bartlomiejpluta.base.core.profiling.fps.FPSMonitor; +import com.bartlomiejpluta.base.core.ui.Window; +import com.bartlomiejpluta.base.core.util.mesh.MeshManager; +import com.bartlomiejpluta.base.core.world.animation.Animator; +import com.bartlomiejpluta.base.core.world.map.GameMap; +import com.bartlomiejpluta.base.core.world.tileset.manager.TileSetManager; +import com.bartlomiejpluta.base.game.world.entity.manager.EntityManager; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultGameLogic implements GameLogic { + private final Renderer renderer; + private final TileSetManager tileSetManager; + private final MeshManager meshManager; + private final TextureManager textureManager; + private final EntityManager entityManager; + private final ImageManager imageManager; + private final Animator animator; + private final FPSMonitor fpsMonitor; + + private GameMap map; + + @Override + public void init(Window window) { + log.info("Initializing game logic"); + renderer.init(); + + throw new AppException("TODO: Everything seems to be working fine. The game engine logic is not implemented yet though..."); + } + + @Override + public void input(Window window) { + + } + + @Override + public void update(float dt) { + fpsMonitor.update(dt); + } + + @Override + public void render(Window window) { + renderer.render(window, map); + } + + @Override + public void cleanUp() { + log.info("There is nothing to clean up here"); + } +} diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/config/EntitySpriteConfiguration.java b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/config/EntitySpriteConfiguration.java old mode 100755 new mode 100644 index f3da3b82..6aa83924 --- a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/config/EntitySpriteConfiguration.java +++ b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/config/EntitySpriteConfiguration.java @@ -1,28 +1,28 @@ -package com.bartlomiejpluta.base.game.world.entity.config; - -import com.bartlomiejpluta.base.core.world.movement.Direction; -import lombok.Data; -import org.joml.Vector2i; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import java.util.Map; - -@Data -@Configuration -@ConfigurationProperties(prefix = "app.sprite.entity") -public class EntitySpriteConfiguration { - private EntitySpriteDimensionConfiguration dimension; - private int defaultSpriteColumn; - private Map spriteDirectionRows; - - @Data - public static class EntitySpriteDimensionConfiguration { - private int rows; - private int cols; - - public Vector2i asVector() { - return new Vector2i(rows, cols); - } - } -} +package com.bartlomiejpluta.base.game.world.entity.config; + +import com.bartlomiejpluta.base.core.world.movement.Direction; +import lombok.Data; +import org.joml.Vector2i; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.Map; + +@Data +@Configuration +@ConfigurationProperties(prefix = "app.sprite.entity") +public class EntitySpriteConfiguration { + private EntitySpriteDimensionConfiguration dimension; + private int defaultSpriteColumn; + private Map spriteDirectionRows; + + @Data + public static class EntitySpriteDimensionConfiguration { + private int rows; + private int cols; + + public Vector2i asVector() { + return new Vector2i(rows, cols); + } + } +} diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/DefaultEntityManager.java b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/DefaultEntityManager.java old mode 100755 new mode 100644 index cb280ea6..c97cf455 --- a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/DefaultEntityManager.java +++ b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/DefaultEntityManager.java @@ -1,38 +1,38 @@ -package com.bartlomiejpluta.base.game.world.entity.manager; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.util.mesh.MeshManager; -import com.bartlomiejpluta.base.core.world.map.GameMap; -import com.bartlomiejpluta.base.game.world.entity.config.EntitySpriteConfiguration; -import com.bartlomiejpluta.base.game.world.entity.model.Entity; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -@RequiredArgsConstructor(onConstructor = @__(@Autowired)) -public class DefaultEntityManager implements EntityManager { - private final MeshManager meshManager; - private final EntitySpriteConfiguration configuration; - - @Override - public Entity createEntity(Material material, GameMap map) { - return new Entity(buildMesh(material), material, map.getStepSize(), configuration); - } - - private Mesh buildMesh(Material material) { - var texture = material.getTexture(); - var dimension = configuration.getDimension().asVector(); - var spriteWidth = texture.getWidth() / (float) dimension.y; - var spriteHeight = texture.getHeight() / (float) dimension.x; - return meshManager.createQuad(spriteWidth, spriteHeight, spriteWidth / 2, spriteHeight*0.9f); - } - - @Override - public void cleanUp() { - log.info("There is nothing to clean up here"); - } -} +package com.bartlomiejpluta.base.game.world.entity.manager; + +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; +import com.bartlomiejpluta.base.core.util.mesh.MeshManager; +import com.bartlomiejpluta.base.core.world.map.GameMap; +import com.bartlomiejpluta.base.game.world.entity.config.EntitySpriteConfiguration; +import com.bartlomiejpluta.base.game.world.entity.model.Entity; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class DefaultEntityManager implements EntityManager { + private final MeshManager meshManager; + private final EntitySpriteConfiguration configuration; + + @Override + public Entity createEntity(Material material, GameMap map) { + return new Entity(buildMesh(material), material, map.getStepSize(), configuration); + } + + private Mesh buildMesh(Material material) { + var texture = material.getTexture(); + var dimension = configuration.getDimension().asVector(); + var spriteWidth = texture.getWidth() / (float) dimension.y; + var spriteHeight = texture.getHeight() / (float) dimension.x; + return meshManager.createQuad(spriteWidth, spriteHeight, spriteWidth / 2, spriteHeight*0.9f); + } + + @Override + public void cleanUp() { + log.info("There is nothing to clean up here"); + } +} diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/EntityManager.java b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/EntityManager.java old mode 100755 new mode 100644 index f804867b..9b451b9d --- a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/EntityManager.java +++ b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/manager/EntityManager.java @@ -1,10 +1,10 @@ -package com.bartlomiejpluta.base.game.world.entity.manager; - -import com.bartlomiejpluta.base.core.gc.Cleanable; -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.world.map.GameMap; -import com.bartlomiejpluta.base.game.world.entity.model.Entity; - -public interface EntityManager extends Cleanable { - Entity createEntity(Material material, GameMap map); -} +package com.bartlomiejpluta.base.game.world.entity.manager; + +import com.bartlomiejpluta.base.core.gc.Cleanable; +import com.bartlomiejpluta.base.core.gl.object.material.Material; +import com.bartlomiejpluta.base.core.world.map.GameMap; +import com.bartlomiejpluta.base.game.world.entity.model.Entity; + +public interface EntityManager extends Cleanable { + Entity createEntity(Material material, GameMap map); +} diff --git a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/model/Entity.java b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/model/Entity.java old mode 100755 new mode 100644 index 9cdacafd..31410432 --- a/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/model/Entity.java +++ b/game/src/main/java/com/bartlomiejpluta/base/game/world/entity/model/Entity.java @@ -1,79 +1,79 @@ -package com.bartlomiejpluta.base.game.world.entity.model; - -import com.bartlomiejpluta.base.core.gl.object.material.Material; -import com.bartlomiejpluta.base.core.gl.object.mesh.Mesh; -import com.bartlomiejpluta.base.core.world.movement.Direction; -import com.bartlomiejpluta.base.core.world.movement.MovableObject; -import com.bartlomiejpluta.base.game.world.entity.config.EntitySpriteConfiguration; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.joml.Vector2f; - -import java.util.Map; - -@EqualsAndHashCode(callSuper = true) -public class Entity extends MovableObject { - private final Map spriteDirectionRows; - private final int defaultSpriteColumn; - - @Setter - private int animationSpeed = 100; - - @Setter - @Getter - private Direction faceDirection; - - @Override - public int getAnimationSpeed() { - return animationSpeed; - } - - @Override - public boolean shouldAnimate() { - return isMoving(); - } - - @Override - public Vector2f[] getSpriteAnimationFramesPositions() { - var row = spriteDirectionRows.get(faceDirection); - var frames = spriteSheetDimension.y; - var array = new Vector2f[frames]; - - for(int column=0; column spriteDirectionRows; + private final int defaultSpriteColumn; + + @Setter + private int animationSpeed = 100; + + @Setter + @Getter + private Direction faceDirection; + + @Override + public int getAnimationSpeed() { + return animationSpeed; + } + + @Override + public boolean shouldAnimate() { + return isMoving(); + } + + @Override + public Vector2f[] getSpriteAnimationFramesPositions() { + var row = spriteDirectionRows.get(faceDirection); + var frames = spriteSheetDimension.y; + var array = new Vector2f[frames]; + + for(int column=0; column - task.builtins { - java { } - } - } - } +plugins { + id 'java-library' + id "com.google.protobuf" version "$protobufPluginVersion" +} + +group 'com.bartlomiejpluta.base' +version 'unspecified' + +repositories { + mavenCentral() +} + +dependencies { + api "com.google.protobuf:protobuf-java:$protobufVersion" +} + +test { + useJUnitPlatform() +} + +sourceSets { + main { + java { + srcDirs "$projectDir/build/proto/main/java" + } + } +} + +protobuf { + // Fetch protoc compiler + protoc { + artifact = "com.google.protobuf:protoc:$protobufVersion" + } + + generatedFilesBaseDir = "$projectDir/build/proto/" + + // Enable compiling proto files to Java + generateProtoTasks { + all().each { task -> + task.builtins { + java { } + } + } + } } \ No newline at end of file diff --git a/proto/src/main/proto/map.proto b/proto/src/main/proto/map.proto old mode 100755 new mode 100644 index 5edfd653..d87cbfe2 --- a/proto/src/main/proto/map.proto +++ b/proto/src/main/proto/map.proto @@ -1,23 +1,23 @@ -package com.bartlomiejpluta.base.proto; - -option java_package = "com.bartlomiejpluta.base.proto"; -option java_outer_classname = "GameMapProto"; - -message GameMap { - required string name = 1; - required uint32 rows = 2; - required uint32 columns = 3; - repeated Layer layers = 4; -} - -message Layer { - required string name = 1; - - oneof layer { - TileLayer tileLayer = 2; - } -} - -message TileLayer { - repeated uint32 tiles = 1; +package com.bartlomiejpluta.base.proto; + +option java_package = "com.bartlomiejpluta.base.proto"; +option java_outer_classname = "GameMapProto"; + +message GameMap { + required string name = 1; + required uint32 rows = 2; + required uint32 columns = 3; + repeated Layer layers = 4; +} + +message Layer { + required string name = 1; + + oneof layer { + TileLayer tileLayer = 2; + } +} + +message TileLayer { + repeated uint32 tiles = 1; } \ No newline at end of file diff --git a/proto/src/main/proto/project.proto b/proto/src/main/proto/project.proto old mode 100755 new mode 100644 index eff1bd92..897da3ce --- a/proto/src/main/proto/project.proto +++ b/proto/src/main/proto/project.proto @@ -1,8 +1,8 @@ -package com.bartlomiejpluta.base.proto; - -option java_package = "com.bartlomiejpluta.base.proto"; -option java_outer_classname = "ProjectProto"; - -message Project { - required string name = 1; +package com.bartlomiejpluta.base.proto; + +option java_package = "com.bartlomiejpluta.base.proto"; +option java_outer_classname = "ProjectProto"; + +message Project { + required string name = 1; } \ No newline at end of file diff --git a/settings.gradle b/settings.gradle old mode 100755 new mode 100644