├── settings.gradle ├── src └── main │ ├── resources │ └── META-INF │ │ └── MANIFEST.MF │ └── java │ ├── components │ ├── Ground.java │ ├── NonPickable.java │ ├── Frame.java │ ├── BreakableBrick.java │ ├── FontRenderer.java │ ├── Flagpole.java │ ├── ScaleGizmo.java │ ├── TranslateGizmo.java │ ├── BlockCoin.java │ ├── Flower.java │ ├── Coin.java │ ├── ComponentDeserializer.java │ ├── Sprite.java │ ├── GizmoSystem.java │ ├── GridLines.java │ ├── AnimationState.java │ ├── GameCamera.java │ ├── MushroomAI.java │ ├── Spritesheet.java │ ├── Block.java │ ├── QuestionBlock.java │ ├── SpriteRenderer.java │ ├── Fireball.java │ ├── EditorCamera.java │ ├── KeyControls.java │ ├── GoombaAI.java │ ├── StateMachine.java │ ├── Component.java │ ├── Pipe.java │ ├── TurtleAI.java │ ├── Gizmo.java │ └── MouseControls.java │ ├── jade │ ├── Direction.java │ ├── GameObjectDeserializer.java │ ├── KeyListener.java │ ├── Transform.java │ ├── Camera.java │ ├── Sound.java │ ├── GameObject.java │ └── MouseListener.java │ ├── physics2d │ ├── enums │ │ └── BodyType.java │ ├── components │ │ ├── Box2DCollider.java │ │ ├── CircleCollider.java │ │ ├── PillboxCollider.java │ │ └── Rigidbody2D.java │ ├── RaycastInfo.java │ └── JadeContactListener.java │ ├── util │ ├── Settings.java │ ├── JMath.java │ └── AssetPool.java │ ├── Main.java │ ├── observers │ ├── Observer.java │ ├── events │ │ ├── EventType.java │ │ └── Event.java │ └── EventSystem.java │ ├── physics2dtmp │ ├── forces │ │ ├── ForceGenerator.java │ │ ├── Gravity2D.java │ │ ├── ForceRegistration.java │ │ └── ForceRegistry.java │ ├── primitives │ │ ├── Collider2D.java │ │ ├── Ray2D.java │ │ ├── Circle.java │ │ ├── RaycastResult.java │ │ ├── AABB.java │ │ └── Box2D.java │ ├── rigidbody │ │ ├── CollisionManifold.java │ │ ├── Collisions.java │ │ └── Rigidbody2D.java │ └── PhysicsSystem2D.java │ ├── scenes │ ├── SceneInitializer.java │ ├── LevelSceneInitializer.java │ └── Scene.java │ ├── editor │ ├── MenuBar.java │ ├── SceneHierarchyWindow.java │ ├── GameViewWindow.java │ └── PropertiesWindow.java │ └── renderer │ ├── Line2D.java │ ├── Framebuffer.java │ ├── Renderer.java │ ├── PickingTexture.java │ ├── Texture.java │ └── Shader.java ├── assets ├── sounds │ ├── 1-up.ogg │ ├── bump.ogg │ ├── coin.ogg │ ├── kick.ogg │ ├── pipe.ogg │ ├── vine.ogg │ ├── stomp.ogg │ ├── fireball.ogg │ ├── fireworks.ogg │ ├── flagpole.ogg │ ├── gameover.ogg │ ├── mario_die.ogg │ ├── powerup.ogg │ ├── warning.ogg │ ├── bowserfalls.ogg │ ├── bowserfire.ogg │ ├── break_block.ogg │ ├── invincible.ogg │ ├── jump-small.ogg │ ├── jump-super.ogg │ ├── stage_clear.ogg │ ├── world_clear.ogg │ ├── powerup_appears.ogg │ └── main-theme-overworld.ogg ├── images │ ├── gizmos.png │ ├── items.png │ ├── pipes.png │ ├── turtle.png │ ├── testImage.png │ ├── blendImage1.png │ ├── blendImage2.png │ ├── spritesheet.png │ ├── testImage2.png │ ├── bigSpritesheet.png │ └── spritesheets │ │ ├── icons.png │ │ ├── pipes.png │ │ └── decorationsAndBlocks.png └── shaders │ ├── debugLine2D.glsl │ ├── pickingShader.glsl │ └── default.glsl ├── libs └── jbox2d-library.jar ├── .gitignore ├── LICENSE ├── imgui.ini ├── README.md ├── gradlew.bat ├── pom.xml └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'mario' 2 | 3 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: Main 3 | 4 | -------------------------------------------------------------------------------- /assets/sounds/1-up.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/1-up.ogg -------------------------------------------------------------------------------- /assets/sounds/bump.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/bump.ogg -------------------------------------------------------------------------------- /assets/sounds/coin.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/coin.ogg -------------------------------------------------------------------------------- /assets/sounds/kick.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/kick.ogg -------------------------------------------------------------------------------- /assets/sounds/pipe.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/pipe.ogg -------------------------------------------------------------------------------- /assets/sounds/vine.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/vine.ogg -------------------------------------------------------------------------------- /assets/images/gizmos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/gizmos.png -------------------------------------------------------------------------------- /assets/images/items.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/items.png -------------------------------------------------------------------------------- /assets/images/pipes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/pipes.png -------------------------------------------------------------------------------- /assets/images/turtle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/turtle.png -------------------------------------------------------------------------------- /assets/sounds/stomp.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/stomp.ogg -------------------------------------------------------------------------------- /libs/jbox2d-library.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/libs/jbox2d-library.jar -------------------------------------------------------------------------------- /assets/images/testImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/testImage.png -------------------------------------------------------------------------------- /assets/sounds/fireball.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/fireball.ogg -------------------------------------------------------------------------------- /assets/sounds/fireworks.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/fireworks.ogg -------------------------------------------------------------------------------- /assets/sounds/flagpole.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/flagpole.ogg -------------------------------------------------------------------------------- /assets/sounds/gameover.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/gameover.ogg -------------------------------------------------------------------------------- /assets/sounds/mario_die.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/mario_die.ogg -------------------------------------------------------------------------------- /assets/sounds/powerup.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/powerup.ogg -------------------------------------------------------------------------------- /assets/sounds/warning.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/warning.ogg -------------------------------------------------------------------------------- /src/main/java/components/Ground.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | public class Ground extends Component { 4 | } 5 | -------------------------------------------------------------------------------- /assets/images/blendImage1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/blendImage1.png -------------------------------------------------------------------------------- /assets/images/blendImage2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/blendImage2.png -------------------------------------------------------------------------------- /assets/images/spritesheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/spritesheet.png -------------------------------------------------------------------------------- /assets/images/testImage2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/testImage2.png -------------------------------------------------------------------------------- /assets/sounds/bowserfalls.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/bowserfalls.ogg -------------------------------------------------------------------------------- /assets/sounds/bowserfire.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/bowserfire.ogg -------------------------------------------------------------------------------- /assets/sounds/break_block.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/break_block.ogg -------------------------------------------------------------------------------- /assets/sounds/invincible.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/invincible.ogg -------------------------------------------------------------------------------- /assets/sounds/jump-small.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/jump-small.ogg -------------------------------------------------------------------------------- /assets/sounds/jump-super.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/jump-super.ogg -------------------------------------------------------------------------------- /assets/sounds/stage_clear.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/stage_clear.ogg -------------------------------------------------------------------------------- /assets/sounds/world_clear.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/world_clear.ogg -------------------------------------------------------------------------------- /assets/images/bigSpritesheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/bigSpritesheet.png -------------------------------------------------------------------------------- /src/main/java/components/NonPickable.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | public class NonPickable extends Component { 4 | } 5 | -------------------------------------------------------------------------------- /assets/sounds/powerup_appears.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/powerup_appears.ogg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | build/* 3 | gradle/* 4 | .gradle/* 5 | uiPreview.svg 6 | tilesets.svg 7 | assets/fonts/* 8 | assets/*.svg -------------------------------------------------------------------------------- /assets/images/spritesheets/icons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/spritesheets/icons.png -------------------------------------------------------------------------------- /assets/images/spritesheets/pipes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/spritesheets/pipes.png -------------------------------------------------------------------------------- /assets/sounds/main-theme-overworld.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/sounds/main-theme-overworld.ogg -------------------------------------------------------------------------------- /src/main/java/jade/Direction.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | public enum Direction { 4 | Up, 5 | Down, 6 | Left, 7 | Right 8 | } 9 | -------------------------------------------------------------------------------- /assets/images/spritesheets/decorationsAndBlocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingminecraft/MarioYoutube/HEAD/assets/images/spritesheets/decorationsAndBlocks.png -------------------------------------------------------------------------------- /src/main/java/physics2d/enums/BodyType.java: -------------------------------------------------------------------------------- 1 | package physics2d.enums; 2 | 3 | public enum BodyType { 4 | Static, 5 | Dynamic, 6 | Kinematic 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/util/Settings.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class Settings { 4 | public static float GRID_WIDTH = 0.25f; 5 | public static float GRID_HEIGHT = 0.25f; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | import jade.Window; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Window window = Window.get(); 6 | window.run(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/observers/Observer.java: -------------------------------------------------------------------------------- 1 | package observers; 2 | 3 | import jade.GameObject; 4 | import observers.events.Event; 5 | 6 | public interface Observer { 7 | void onNotify(GameObject object, Event event); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/observers/events/EventType.java: -------------------------------------------------------------------------------- 1 | package observers.events; 2 | 3 | public enum EventType { 4 | GameEngineStartPlay, 5 | GameEngineStopPlay, 6 | SaveLevel, 7 | LoadLevel, 8 | UserEvent 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/forces/ForceGenerator.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.forces; 2 | 3 | import physics2dtmp.rigidbody.Rigidbody2D; 4 | 5 | public interface ForceGenerator { 6 | void updateForce(Rigidbody2D body, float dt); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/scenes/SceneInitializer.java: -------------------------------------------------------------------------------- 1 | package scenes; 2 | 3 | public abstract class SceneInitializer { 4 | public abstract void init(Scene scene); 5 | public abstract void loadResources(Scene scene); 6 | public abstract void imgui(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/observers/events/Event.java: -------------------------------------------------------------------------------- 1 | package observers.events; 2 | 3 | public class Event { 4 | public EventType type; 5 | 6 | public Event(EventType type) { 7 | this.type = type; 8 | } 9 | 10 | public Event() { 11 | this.type = EventType.UserEvent; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/components/Frame.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | class Frame { 4 | public Sprite sprite; 5 | public float frameTime; 6 | 7 | public Frame() { 8 | 9 | } 10 | 11 | public Frame(Sprite sprite, float frameTime) { 12 | this.sprite = sprite; 13 | this.frameTime = frameTime; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/Collider2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import components.Component; 4 | import org.joml.Vector2f; 5 | 6 | public class Collider2D extends Component { 7 | protected Vector2f offset = new Vector2f(); 8 | 9 | // TODO: IMPLEMENT THIS 10 | //public abstract float getInertiaTensor(float mass); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/components/BreakableBrick.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import util.AssetPool; 4 | 5 | public class BreakableBrick extends Block { 6 | 7 | @Override 8 | void playerHit(PlayerController playerController) { 9 | if (!playerController.isSmall()) { 10 | AssetPool.getSound("assets/sounds/break_block.ogg").play(); 11 | gameObject.destroy(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/components/FontRenderer.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | public class FontRenderer extends Component { 4 | 5 | @Override 6 | public void start() { 7 | if (gameObject.getComponent(SpriteRenderer.class) != null) { 8 | System.out.println("Found Font Renderer!"); 9 | } 10 | } 11 | 12 | @Override 13 | public void update(float dt) { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /assets/shaders/debugLine2D.glsl: -------------------------------------------------------------------------------- 1 | #type vertex 2 | #version 330 core 3 | layout (location = 0) in vec3 aPos; 4 | layout (location = 1) in vec3 aColor; 5 | 6 | out vec3 fColor; 7 | 8 | uniform mat4 uView; 9 | uniform mat4 uProjection; 10 | 11 | void main() 12 | { 13 | fColor = aColor; 14 | 15 | gl_Position = uProjection * uView * vec4(aPos, 1.0); 16 | } 17 | 18 | #type fragment 19 | #version 330 core 20 | in vec3 fColor; 21 | 22 | out vec4 color; 23 | 24 | void main() 25 | { 26 | color = vec4(fColor, 1); 27 | } -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/forces/Gravity2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.forces; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.rigidbody.Rigidbody2D; 5 | 6 | public class Gravity2D implements ForceGenerator { 7 | 8 | private Vector2f gravity; 9 | 10 | public Gravity2D(Vector2f force) { 11 | this.gravity = new Vector2f(force); 12 | } 13 | 14 | @Override 15 | public void updateForce(Rigidbody2D body, float dt) { 16 | body.addForce(new Vector2f(gravity).mul(body.getMass())); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/Ray2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import org.joml.Vector2f; 4 | 5 | public class Ray2D { 6 | private Vector2f origin; 7 | private Vector2f direction; 8 | 9 | public Ray2D(Vector2f origin, Vector2f direction) { 10 | this.origin = origin; 11 | this.direction = direction; 12 | this.direction.normalize(); 13 | } 14 | 15 | public Vector2f getOrigin() { 16 | return this.origin; 17 | } 18 | 19 | public Vector2f getDirection() { 20 | return this.direction; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/observers/EventSystem.java: -------------------------------------------------------------------------------- 1 | package observers; 2 | 3 | import jade.GameObject; 4 | import observers.events.Event; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class EventSystem { 10 | private static List observers = new ArrayList<>(); 11 | 12 | public static void addObserver(Observer observer) { 13 | observers.add(observer); 14 | } 15 | 16 | public static void notify(GameObject obj, Event event) { 17 | for (Observer observer : observers) { 18 | observer.onNotify(obj, event); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/Circle.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.rigidbody.Rigidbody2D; 5 | 6 | public class Circle extends Collider2D { 7 | private float radius = 1.0f; 8 | private Rigidbody2D rigidbody = null; 9 | 10 | public float getRadius() { 11 | return this.radius; 12 | } 13 | 14 | public Vector2f getCenter() { 15 | return rigidbody.getPosition(); 16 | } 17 | 18 | public void setRadius(float r) { 19 | this.radius = r; 20 | } 21 | 22 | public void setRigidbody(Rigidbody2D rb) { 23 | this.rigidbody = rb; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/components/Flagpole.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.dynamics.contacts.Contact; 5 | import org.joml.Vector2f; 6 | import util.AssetPool; 7 | 8 | public class Flagpole extends Component { 9 | private boolean isTop = false; 10 | 11 | public Flagpole(boolean isTop) { 12 | this.isTop = isTop; 13 | } 14 | 15 | @Override 16 | public void beginCollision(GameObject obj, Contact contact, Vector2f contactNormal) { 17 | PlayerController playerController = obj.getComponent(PlayerController.class); 18 | if (playerController != null) { 19 | playerController.playWinAnimation(this.gameObject); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/forces/ForceRegistration.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.forces; 2 | 3 | import physics2dtmp.rigidbody.Rigidbody2D; 4 | 5 | public class ForceRegistration { 6 | public ForceGenerator fg; 7 | public Rigidbody2D rb; 8 | 9 | public ForceRegistration(ForceGenerator fg, Rigidbody2D rb) { 10 | this.fg = fg; 11 | this.rb = rb; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object other) { 16 | if (other == null) return false; 17 | if (other.getClass() != ForceRegistration.class) return false; 18 | 19 | ForceRegistration fr = (ForceRegistration)other; 20 | return fr.rb == this.rb && fr.fg == this.fg; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/editor/MenuBar.java: -------------------------------------------------------------------------------- 1 | package editor; 2 | 3 | import imgui.ImGui; 4 | import observers.EventSystem; 5 | import observers.events.Event; 6 | import observers.events.EventType; 7 | 8 | public class MenuBar { 9 | 10 | public void imgui() { 11 | ImGui.beginMenuBar(); 12 | 13 | if (ImGui.beginMenu("File")) { 14 | if (ImGui.menuItem("Save", "Ctrl+S")) { 15 | EventSystem.notify(null, new Event(EventType.SaveLevel)); 16 | } 17 | 18 | if (ImGui.menuItem("Load", "Ctrl+O")) { 19 | EventSystem.notify(null, new Event(EventType.LoadLevel)); 20 | } 21 | 22 | ImGui.endMenu(); 23 | } 24 | 25 | ImGui.endMenuBar(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/components/ScaleGizmo.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.PropertiesWindow; 4 | import jade.MouseListener; 5 | 6 | public class ScaleGizmo extends Gizmo { 7 | public ScaleGizmo(Sprite scaleSprite, PropertiesWindow propertiesWindow) { 8 | super(scaleSprite, propertiesWindow); 9 | } 10 | 11 | @Override 12 | public void editorUpdate(float dt) { 13 | if (activeGameObject != null) { 14 | if (xAxisActive && !yAxisActive) { 15 | activeGameObject.transform.scale.x -= MouseListener.getWorldDx(); 16 | } else if (yAxisActive) { 17 | activeGameObject.transform.scale.y -= MouseListener.getWorldDy(); 18 | } 19 | } 20 | 21 | super.editorUpdate(dt); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/components/TranslateGizmo.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.PropertiesWindow; 4 | import jade.MouseListener; 5 | 6 | public class TranslateGizmo extends Gizmo { 7 | 8 | public TranslateGizmo(Sprite arrowSprite, PropertiesWindow propertiesWindow) { 9 | super(arrowSprite, propertiesWindow); 10 | } 11 | 12 | @Override 13 | public void editorUpdate(float dt) { 14 | if (activeGameObject != null) { 15 | if (xAxisActive && !yAxisActive) { 16 | activeGameObject.transform.position.x -= MouseListener.getWorldDx(); 17 | } else if (yAxisActive) { 18 | activeGameObject.transform.position.y -= MouseListener.getWorldDy(); 19 | } 20 | } 21 | 22 | super.editorUpdate(dt); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/components/BlockCoin.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import org.joml.Vector2f; 4 | import util.AssetPool; 5 | 6 | public class BlockCoin extends Component { 7 | private Vector2f topY; 8 | private float coinSpeed = 1.4f; 9 | 10 | @Override 11 | public void start() { 12 | topY = new Vector2f(this.gameObject.transform.position.y).add(0, 0.5f); 13 | AssetPool.getSound("assets/sounds/coin.ogg").play(); 14 | } 15 | 16 | @Override 17 | public void update(float dt) { 18 | if (this.gameObject.transform.position.y < topY.y) { 19 | this.gameObject.transform.position.y += dt * coinSpeed; 20 | this.gameObject.transform.scale.x -= (0.5f * dt) % -1.0f; 21 | } else { 22 | gameObject.destroy(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/components/Flower.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.dynamics.contacts.Contact; 5 | import org.joml.Vector2f; 6 | import physics2d.components.Rigidbody2D; 7 | import util.AssetPool; 8 | 9 | public class Flower extends Component { 10 | private transient Rigidbody2D rb; 11 | 12 | @Override 13 | public void start() { 14 | this.rb = gameObject.getComponent(Rigidbody2D.class); 15 | AssetPool.getSound("assets/sounds/powerup_appears.ogg").play(); 16 | this.rb.setIsSensor(); 17 | } 18 | 19 | @Override 20 | public void beginCollision(GameObject obj, Contact contact, Vector2f contactNormal) { 21 | PlayerController playerController = obj.getComponent(PlayerController.class); 22 | if (playerController != null) { 23 | playerController.powerup(); 24 | this.gameObject.destroy(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/jade/GameObjectDeserializer.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import com.google.gson.*; 4 | import components.Component; 5 | 6 | import java.lang.reflect.Type; 7 | 8 | public class GameObjectDeserializer implements JsonDeserializer { 9 | @Override 10 | public GameObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 11 | JsonObject jsonObject = json.getAsJsonObject(); 12 | String name = jsonObject.get("name").getAsString(); 13 | JsonArray components = jsonObject.getAsJsonArray("components"); 14 | 15 | GameObject go = new GameObject(name); 16 | for (JsonElement e : components) { 17 | Component c = context.deserialize(e, Component.class); 18 | go.addComponent(c); 19 | } 20 | go.transform = go.getComponent(Transform.class); 21 | return go; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/RaycastResult.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import org.joml.Vector2f; 4 | 5 | public class RaycastResult { 6 | private Vector2f point; 7 | private Vector2f normal; 8 | private float t; 9 | private boolean hit; 10 | 11 | public RaycastResult() { 12 | this.point = new Vector2f(); 13 | this.normal = new Vector2f(); 14 | this.t = -1; 15 | this.hit = false; 16 | } 17 | 18 | public void init(Vector2f point, Vector2f normal, float t, boolean hit) { 19 | this.point.set(point); 20 | this.normal.set(normal); 21 | this.t = t; 22 | this.hit = hit; 23 | } 24 | 25 | public static void reset(RaycastResult result) { 26 | if (result != null) { 27 | result.point.zero(); 28 | result.normal.set(0, 0); 29 | result.t = -1; 30 | result.hit = false; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 codingminecraft 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/physics2d/components/Box2DCollider.java: -------------------------------------------------------------------------------- 1 | package physics2d.components; 2 | 3 | import components.Component; 4 | import org.joml.Vector2f; 5 | import renderer.DebugDraw; 6 | 7 | public class Box2DCollider extends Component { 8 | private Vector2f halfSize = new Vector2f(1); 9 | private Vector2f origin = new Vector2f(); 10 | private Vector2f offset = new Vector2f(); 11 | 12 | public Vector2f getOffset() { 13 | return this.offset; 14 | } 15 | 16 | public void setOffset(Vector2f newOffset) { this.offset.set(newOffset); } 17 | 18 | public Vector2f getHalfSize() { 19 | return halfSize; 20 | } 21 | 22 | public void setHalfSize(Vector2f halfSize) { 23 | this.halfSize = halfSize; 24 | } 25 | 26 | public Vector2f getOrigin() { 27 | return this.origin; 28 | } 29 | 30 | @Override 31 | public void editorUpdate(float dt) { 32 | Vector2f center = new Vector2f(this.gameObject.transform.position).add(this.offset); 33 | DebugDraw.addBox2D(center, this.halfSize, this.gameObject.transform.rotation); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/AABB.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.rigidbody.Rigidbody2D; 5 | 6 | // Axis Aligned Bounding Box 7 | public class AABB { 8 | private Vector2f size = new Vector2f(); 9 | private Vector2f halfSize; 10 | private Rigidbody2D rigidbody = null; 11 | 12 | public AABB() { 13 | this.halfSize = new Vector2f(size).mul(0.5f); 14 | } 15 | 16 | public AABB(Vector2f min, Vector2f max) { 17 | this.size = new Vector2f(max).sub(min); 18 | this.halfSize = new Vector2f(size).mul(0.5f); 19 | } 20 | 21 | public Vector2f getMin() { 22 | return new Vector2f(this.rigidbody.getPosition()).sub(this.halfSize); 23 | } 24 | 25 | public Vector2f getMax() { 26 | return new Vector2f(this.rigidbody.getPosition()).add(this.halfSize); 27 | } 28 | 29 | public void setRigidbody(Rigidbody2D rb) { 30 | this.rigidbody = rb; 31 | } 32 | 33 | public void setSize(Vector2f size) { 34 | this.size.set(size); 35 | this.halfSize.set(size.x / 2.0f, size.y / 2.0f); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/forces/ForceRegistry.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.forces; 2 | 3 | import physics2dtmp.rigidbody.Rigidbody2D; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class ForceRegistry { 9 | private List registry; 10 | 11 | public ForceRegistry() { 12 | this.registry = new ArrayList<>(); 13 | } 14 | 15 | public void add(Rigidbody2D rb, ForceGenerator fg) { 16 | ForceRegistration fr = new ForceRegistration(fg, rb); 17 | registry.add(fr); 18 | } 19 | 20 | public void remove(Rigidbody2D rb, ForceGenerator fg) { 21 | ForceRegistration fr = new ForceRegistration(fg, rb); 22 | registry.remove(fr); 23 | } 24 | 25 | public void clear() { 26 | registry.clear(); 27 | } 28 | 29 | public void updateForces(float dt) { 30 | for (ForceRegistration fr : registry) { 31 | fr.fg.updateForce(fr.rb, dt); 32 | } 33 | } 34 | 35 | public void zeroForces() { 36 | for (ForceRegistration fr : registry) { 37 | // TODO: IMPLEMENT ME 38 | //fr.rb.zeroForces(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /assets/shaders/pickingShader.glsl: -------------------------------------------------------------------------------- 1 | #type vertex 2 | #version 330 core 3 | layout (location=0) in vec3 aPos; 4 | layout (location=1) in vec4 aColor; 5 | layout (location=2) in vec2 aTexCoords; 6 | layout (location=3) in float aTexId; 7 | layout (location=4) in float aEntityId; 8 | 9 | uniform mat4 uProjection; 10 | uniform mat4 uView; 11 | 12 | out vec4 fColor; 13 | out vec2 fTexCoords; 14 | out float fTexId; 15 | out float fEntityId; 16 | 17 | void main() 18 | { 19 | fColor = aColor; 20 | fTexCoords = aTexCoords; 21 | fTexId = aTexId; 22 | fEntityId = aEntityId; 23 | 24 | gl_Position = uProjection * uView * vec4(aPos, 1.0); 25 | } 26 | 27 | #type fragment 28 | #version 330 core 29 | 30 | in vec4 fColor; 31 | in vec2 fTexCoords; 32 | in float fTexId; 33 | in float fEntityId; 34 | 35 | uniform sampler2D uTextures[8]; 36 | 37 | out vec3 color; 38 | 39 | void main() 40 | { 41 | vec4 texColor = vec4(1, 1, 1, 1); 42 | if (fTexId > 0) { 43 | int id = int(fTexId); 44 | texColor = fColor * texture(uTextures[id], fTexCoords); 45 | } 46 | 47 | if (texColor.a < 0.5) { 48 | discard; 49 | } 50 | color = vec3(fEntityId, fEntityId, fEntityId); 51 | } -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/rigidbody/CollisionManifold.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.rigidbody; 2 | 3 | import org.joml.Vector2f; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class CollisionManifold { 9 | private boolean isColliding; 10 | private Vector2f normal; 11 | private List contactPoints; 12 | private float depth; 13 | 14 | public CollisionManifold() { 15 | normal = new Vector2f(); 16 | depth = 0.0f; 17 | isColliding = false; 18 | } 19 | 20 | public CollisionManifold(Vector2f normal, float depth) { 21 | this.normal = normal; 22 | this.contactPoints = new ArrayList<>(); 23 | this.depth = depth; 24 | isColliding = true; 25 | } 26 | 27 | public void addContactPoint(Vector2f contact) { 28 | this.contactPoints.add(contact); 29 | } 30 | 31 | public Vector2f getNormal() { 32 | return normal; 33 | } 34 | 35 | public List getContactPoints() { 36 | return contactPoints; 37 | } 38 | 39 | public float getDepth() { 40 | return depth; 41 | } 42 | 43 | public boolean isColliding() { 44 | return this.isColliding; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/components/Coin.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.dynamics.contacts.Contact; 5 | import org.joml.Vector2f; 6 | import util.AssetPool; 7 | 8 | public class Coin extends Component { 9 | private Vector2f topY; 10 | private float coinSpeed = 1.4f; 11 | private transient boolean playAnim = false; 12 | 13 | @Override 14 | public void start() { 15 | topY = new Vector2f(this.gameObject.transform.position.y).add(0, 0.5f); 16 | } 17 | 18 | @Override 19 | public void update(float dt) { 20 | if (playAnim) { 21 | if (this.gameObject.transform.position.y < topY.y) { 22 | this.gameObject.transform.position.y += dt * coinSpeed; 23 | this.gameObject.transform.scale.x -= (0.5f * dt) % -1.0f; 24 | } else { 25 | gameObject.destroy(); 26 | } 27 | } 28 | } 29 | 30 | @Override 31 | public void preSolve(GameObject obj, Contact contact, Vector2f contactNormal) { 32 | if (obj.getComponent(PlayerController.class) != null) { 33 | AssetPool.getSound("assets/sounds/coin.ogg").play(); 34 | playAnim = true; 35 | contact.setEnabled(false); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/renderer/Line2D.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import org.joml.Vector2f; 4 | import org.joml.Vector3f; 5 | 6 | public class Line2D { 7 | private Vector2f from; 8 | private Vector2f to; 9 | private Vector3f color; 10 | private int lifetime; 11 | 12 | public Line2D(Vector2f from, Vector2f to) { 13 | this.from = from; 14 | this.to = to; 15 | } 16 | 17 | public Line2D(Vector2f from, Vector2f to, Vector3f color, int lifetime) { 18 | this.from = from; 19 | this.to = to; 20 | this.color = color; 21 | this.lifetime = lifetime; 22 | } 23 | 24 | public int beginFrame() { 25 | this.lifetime--; 26 | return this.lifetime; 27 | } 28 | 29 | public Vector2f getFrom() { 30 | return from; 31 | } 32 | 33 | public Vector2f getTo() { 34 | return to; 35 | } 36 | 37 | public Vector2f getStart() { 38 | return this.from; 39 | } 40 | 41 | public Vector2f getEnd() { 42 | return this.to; 43 | } 44 | 45 | public Vector3f getColor() { 46 | return color; 47 | } 48 | 49 | public float lengthSquared() { 50 | return new Vector2f(to).sub(from).lengthSquared(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/components/ComponentDeserializer.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import com.google.gson.*; 4 | import components.Component; 5 | 6 | import java.lang.reflect.Type; 7 | 8 | public class ComponentDeserializer implements JsonSerializer, 9 | JsonDeserializer { 10 | 11 | @Override 12 | public Component deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 13 | JsonObject jsonObject = json.getAsJsonObject(); 14 | String type = jsonObject.get("type").getAsString(); 15 | JsonElement element = jsonObject.get("properties"); 16 | 17 | try { 18 | return context.deserialize(element, Class.forName(type)); 19 | } catch (ClassNotFoundException e) { 20 | throw new JsonParseException("Unknown element type: " + type, e); 21 | } 22 | } 23 | 24 | @Override 25 | public JsonElement serialize(Component src, Type typeOfSrc, JsonSerializationContext context) { 26 | JsonObject result = new JsonObject(); 27 | result.add("type", new JsonPrimitive(src.getClass().getCanonicalName())); 28 | result.add("properties", context.serialize(src, src.getClass())); 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/components/Sprite.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import org.joml.Vector2f; 4 | import renderer.Texture; 5 | 6 | public class Sprite { 7 | 8 | private float width, height; 9 | 10 | private Texture texture = null; 11 | private Vector2f[] texCoords = { 12 | new Vector2f(1, 1), 13 | new Vector2f(1, 0), 14 | new Vector2f(0, 0), 15 | new Vector2f(0, 1) 16 | }; 17 | 18 | public Texture getTexture() { 19 | return this.texture; 20 | } 21 | 22 | public Vector2f[] getTexCoords() { 23 | return this.texCoords; 24 | } 25 | 26 | public float getWidth() { 27 | return width; 28 | } 29 | 30 | public void setWidth(float width) { 31 | this.width = width; 32 | } 33 | 34 | public float getHeight() { 35 | return height; 36 | } 37 | 38 | public void setHeight(float height) { 39 | this.height = height; 40 | } 41 | 42 | public void setTexture(Texture tex) { 43 | this.texture = tex; 44 | } 45 | 46 | public void setTexCoords(Vector2f[] texCoords) { 47 | this.texCoords = texCoords; 48 | } 49 | 50 | public int getTexId() { 51 | return texture == null ? -1 : texture.getId(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/physics2d/RaycastInfo.java: -------------------------------------------------------------------------------- 1 | package physics2d; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.callbacks.RayCastCallback; 5 | import org.jbox2d.common.Vec2; 6 | import org.jbox2d.dynamics.Fixture; 7 | import org.joml.Vector2f; 8 | 9 | public class RaycastInfo implements RayCastCallback { 10 | public Fixture fixture; 11 | public Vector2f point; 12 | public Vector2f normal; 13 | public float fraction; 14 | public boolean hit; 15 | public GameObject hitObject; 16 | private GameObject requestingObject; 17 | 18 | public RaycastInfo(GameObject obj) { 19 | fixture = null; 20 | point = new Vector2f(); 21 | normal = new Vector2f(); 22 | fraction = 0.0f; 23 | hit = false; 24 | hitObject = null; 25 | this.requestingObject = obj; 26 | } 27 | 28 | @Override 29 | public float reportFixture(Fixture fixture, Vec2 point, Vec2 normal, float fraction) { 30 | if (fixture.m_userData == requestingObject) { 31 | return 1; 32 | } 33 | this.fixture = fixture; 34 | this.point = new Vector2f(point.x, point.y); 35 | this.normal = new Vector2f(normal.x, normal.y); 36 | this.fraction = fraction; 37 | this.hit = fraction != 0; 38 | this.hitObject = (GameObject)fixture.m_userData; 39 | 40 | return fraction; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/util/JMath.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import org.joml.Vector2f; 4 | 5 | public class JMath { 6 | 7 | public static void rotate(Vector2f vec, float angleDeg, Vector2f origin) { 8 | float x = vec.x - origin.x; 9 | float y = vec.y - origin.y; 10 | 11 | float cos = (float)Math.cos(Math.toRadians(angleDeg)); 12 | float sin = (float)Math.sin(Math.toRadians(angleDeg)); 13 | 14 | float xPrime = (x * cos) - (y * sin); 15 | float yPrime = (x * sin) + (y * cos); 16 | 17 | xPrime += origin.x; 18 | yPrime += origin.y; 19 | 20 | vec.x = xPrime; 21 | vec.y = yPrime; 22 | } 23 | 24 | public static boolean compare(float x, float y, float epsilon) { 25 | return Math.abs(x - y) <= epsilon * Math.max(1.0f, Math.max(Math.abs(x), Math.abs(y))); 26 | } 27 | 28 | public static boolean compare(Vector2f vec1, Vector2f vec2, float epsilon) { 29 | return compare(vec1.x, vec2.x, epsilon) && compare(vec1.y, vec2.y, epsilon); 30 | } 31 | 32 | public static boolean compare(float x, float y) { 33 | return Math.abs(x - y) <= Float.MIN_VALUE * Math.max(1.0f, Math.max(Math.abs(x), Math.abs(y))); 34 | } 35 | 36 | public static boolean compare(Vector2f vec1, Vector2f vec2) { 37 | return compare(vec1.x, vec2.x) && compare(vec1.y, vec2.y); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/components/GizmoSystem.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.KeyListener; 4 | import jade.Window; 5 | 6 | import static org.lwjgl.glfw.GLFW.GLFW_KEY_E; 7 | import static org.lwjgl.glfw.GLFW.GLFW_KEY_R; 8 | 9 | public class GizmoSystem extends Component { 10 | private Spritesheet gizmos; 11 | private int usingGizmo = 0; 12 | 13 | public GizmoSystem(Spritesheet gizmoSprites) { 14 | gizmos = gizmoSprites; 15 | } 16 | 17 | @Override 18 | public void start() { 19 | gameObject.addComponent(new TranslateGizmo(gizmos.getSprite(1), 20 | Window.getImguiLayer().getPropertiesWindow())); 21 | gameObject.addComponent(new ScaleGizmo(gizmos.getSprite(2), 22 | Window.getImguiLayer().getPropertiesWindow())); 23 | } 24 | 25 | @Override 26 | public void editorUpdate(float dt) { 27 | if (usingGizmo == 0) { 28 | gameObject.getComponent(TranslateGizmo.class).setUsing(); 29 | gameObject.getComponent(ScaleGizmo.class).setNotUsing(); 30 | } else if (usingGizmo == 1) { 31 | gameObject.getComponent(TranslateGizmo.class).setNotUsing(); 32 | gameObject.getComponent(ScaleGizmo.class).setUsing(); 33 | } 34 | 35 | if (KeyListener.isKeyPressed(GLFW_KEY_E)) { 36 | usingGizmo = 0; 37 | } else if (KeyListener.isKeyPressed(GLFW_KEY_R)) { 38 | usingGizmo = 1; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/rigidbody/Collisions.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.rigidbody; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.primitives.Circle; 5 | import physics2dtmp.primitives.Collider2D; 6 | 7 | public class Collisions { 8 | public static CollisionManifold findCollisionFeatures(Collider2D c1, Collider2D c2) { 9 | if (c1 instanceof Circle && c2 instanceof Circle) { 10 | return findCollisionFeatures((Circle)c1, (Circle)c2); 11 | } else { 12 | assert false : "Unknown collider '" + c1.getClass() + "' vs '" + c2.getClass() + "'"; 13 | } 14 | 15 | return null; 16 | } 17 | 18 | public static CollisionManifold findCollisionFeatures(Circle a, Circle b) { 19 | CollisionManifold result = new CollisionManifold(); 20 | float sumRadii = a.getRadius() + b.getRadius(); 21 | Vector2f distance = new Vector2f(b.getCenter()).sub(a.getCenter()); 22 | if (distance.lengthSquared() - (sumRadii * sumRadii) > 0) { 23 | return result; 24 | } 25 | 26 | // Multiply by 0.5 because we want to separate each circle the same 27 | // amount. Consider updating to factor in the momentum and velocity 28 | float depth = Math.abs(distance.length() - sumRadii) * 0.5f; 29 | Vector2f normal = new Vector2f(distance); 30 | normal.normalize(); 31 | float distanceToPoint = a.getRadius() - depth; 32 | Vector2f contactPoint = new Vector2f(a.getCenter()).add( 33 | new Vector2f(normal).mul(distanceToPoint)); 34 | 35 | result = new CollisionManifold(normal, depth); 36 | result.addContactPoint(contactPoint); 37 | return result; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/jade/KeyListener.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import java.util.Arrays; 4 | 5 | import static org.lwjgl.glfw.GLFW.*; 6 | 7 | public class KeyListener { 8 | private static KeyListener instance; 9 | private boolean keyPressed[] = new boolean[GLFW_KEY_LAST + 1]; 10 | private boolean keyBeginPress[] = new boolean[GLFW_KEY_LAST + 1]; 11 | 12 | private KeyListener() { 13 | 14 | } 15 | 16 | public static void endFrame() { 17 | Arrays.fill(get().keyBeginPress, false); 18 | } 19 | 20 | public static KeyListener get() { 21 | if (KeyListener.instance == null) { 22 | KeyListener.instance = new KeyListener(); 23 | } 24 | 25 | return KeyListener.instance; 26 | } 27 | 28 | public static void keyCallback(long window, int key, int scancode, int action, int mods) { 29 | if (key <= GLFW_KEY_LAST && key >= 0) { 30 | if (action == GLFW_PRESS) { 31 | get().keyPressed[key] = true; 32 | get().keyBeginPress[key] = true; 33 | } else if (action == GLFW_RELEASE) { 34 | get().keyPressed[key] = false; 35 | get().keyBeginPress[key] = false; 36 | } 37 | } 38 | } 39 | 40 | public static boolean isKeyPressed(int keyCode) { 41 | if (keyCode <= GLFW_KEY_LAST && keyCode >= 0) { 42 | return get().keyPressed[keyCode]; 43 | } 44 | 45 | return false; 46 | } 47 | 48 | public static boolean keyBeginPress(int keyCode) { 49 | if (keyCode <= GLFW_KEY_LAST && keyCode >= 0) { 50 | return get().keyBeginPress[keyCode]; 51 | } 52 | 53 | return false; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/renderer/Framebuffer.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import static org.lwjgl.opengl.GL30.*; 4 | 5 | public class Framebuffer { 6 | private int fboID = 0; 7 | private Texture texture = null; 8 | 9 | public int width, height; 10 | 11 | public Framebuffer(int width, int height) { 12 | this.width = width; 13 | this.height = height; 14 | 15 | // Generate framebuffer 16 | fboID = glGenFramebuffers(); 17 | glBindFramebuffer(GL_FRAMEBUFFER, fboID); 18 | 19 | // Create the texture to render the data to, and attach it to our framebuffer 20 | this.texture = new Texture(width, height); 21 | glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 22 | this.texture.getId(), 0); 23 | 24 | // Create renderbuffer store the depth info 25 | int rboID = glGenRenderbuffers(); 26 | glBindRenderbuffer(GL_RENDERBUFFER, rboID); 27 | glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height); 28 | glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboID); 29 | 30 | if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { 31 | assert false : "Error: Framebuffer is not complete"; 32 | } 33 | glBindFramebuffer(GL_FRAMEBUFFER, 0); 34 | } 35 | 36 | public void bind() { 37 | glBindFramebuffer(GL_FRAMEBUFFER, fboID); 38 | } 39 | 40 | public void unbind() { 41 | glBindFramebuffer(GL_FRAMEBUFFER, 0); 42 | } 43 | 44 | public int getFboID() { 45 | return fboID; 46 | } 47 | 48 | public int getTextureId() { 49 | return texture.getId(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/components/GridLines.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.Window; 5 | import org.joml.Vector2f; 6 | import org.joml.Vector3f; 7 | import renderer.DebugDraw; 8 | import util.Settings; 9 | 10 | public class GridLines extends Component { 11 | 12 | @Override 13 | public void editorUpdate(float dt) { 14 | Camera camera = Window.getScene().camera(); 15 | Vector2f cameraPos = camera.position; 16 | Vector2f projectionSize = camera.getProjectionSize(); 17 | 18 | float firstX = ((int)Math.floor(cameraPos.x / Settings.GRID_WIDTH)) * Settings.GRID_HEIGHT; 19 | float firstY = ((int)Math.floor(cameraPos.y / Settings.GRID_HEIGHT)) * Settings.GRID_HEIGHT; 20 | 21 | int numVtLines = (int)(projectionSize.x * camera.getZoom() / Settings.GRID_WIDTH) + 2; 22 | int numHzLines = (int)(projectionSize.y * camera.getZoom() / Settings.GRID_HEIGHT) + 2; 23 | 24 | float width = (int)(projectionSize.x * camera.getZoom()) + (5 * Settings.GRID_WIDTH); 25 | float height = (int)(projectionSize.y * camera.getZoom()) + (5 * Settings.GRID_HEIGHT); 26 | 27 | int maxLines = Math.max(numVtLines, numHzLines); 28 | Vector3f color = new Vector3f(0.2f, 0.2f, 0.2f); 29 | for (int i=0; i < maxLines; i++) { 30 | float x = firstX + (Settings.GRID_WIDTH * i); 31 | float y = firstY + (Settings.GRID_HEIGHT * i); 32 | 33 | if (i < numVtLines) { 34 | DebugDraw.addLine2D(new Vector2f(x, firstY), new Vector2f(x, firstY + height), color); 35 | } 36 | 37 | if (i < numHzLines) { 38 | DebugDraw.addLine2D(new Vector2f(firstX, y), new Vector2f(firstX + width, y), color); 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/physics2d/components/CircleCollider.java: -------------------------------------------------------------------------------- 1 | package physics2d.components; 2 | 3 | import components.Component; 4 | import jade.Window; 5 | import org.joml.Vector2f; 6 | import physics2d.Physics2D; 7 | import renderer.DebugDraw; 8 | 9 | public class CircleCollider extends Component { 10 | private float radius = 1f; 11 | private transient boolean resetFixtureNextFrame = false; 12 | protected Vector2f offset = new Vector2f(); 13 | 14 | public float getRadius() { 15 | return radius; 16 | } 17 | 18 | public Vector2f getOffset() { 19 | return this.offset; 20 | } 21 | 22 | public void setOffset(Vector2f newOffset) { this.offset.set(newOffset); } 23 | 24 | public void setRadius(float radius) { 25 | resetFixtureNextFrame = true; 26 | this.radius = radius; 27 | } 28 | 29 | @Override 30 | public void editorUpdate(float dt) { 31 | Vector2f center = new Vector2f(this.gameObject.transform.position).add(this.offset); 32 | DebugDraw.addCircle(center, this.radius); 33 | 34 | if (resetFixtureNextFrame) { 35 | resetFixture(); 36 | } 37 | } 38 | 39 | @Override 40 | public void update(float dt) { 41 | if (resetFixtureNextFrame) { 42 | resetFixture(); 43 | } 44 | } 45 | 46 | public void resetFixture() { 47 | if (Window.getPhysics().isLocked()) { 48 | resetFixtureNextFrame = true; 49 | return; 50 | } 51 | resetFixtureNextFrame = false; 52 | 53 | if (gameObject != null) { 54 | Rigidbody2D rb = gameObject.getComponent(Rigidbody2D.class); 55 | if (rb != null) { 56 | Window.getPhysics().resetCircleCollider(rb, this); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /imgui.ini: -------------------------------------------------------------------------------- 1 | [Window][Debug##Default] 2 | Pos=60,60 3 | Size=400,400 4 | Collapsed=0 5 | 6 | [Window][Test window] 7 | Pos=8,1780 8 | Size=3050,327 9 | Collapsed=0 10 | DockId=0x00000004,0 11 | 12 | [Window][Dear ImGui Demo] 13 | Pos=8,46 14 | Size=750,1981 15 | Collapsed=0 16 | 17 | [Window][Inspector] 18 | Pos=8,1039 19 | Size=848,988 20 | Collapsed=0 21 | 22 | [Window][Dockspace Demo] 23 | Pos=0,-45 24 | Size=3840,2160 25 | Collapsed=0 26 | 27 | [Window][Game Viewport] 28 | Pos=8,1 29 | Size=3050,1777 30 | Collapsed=0 31 | DockId=0x00000003,0 32 | 33 | [Window][Properties] 34 | Pos=1706,197 35 | Size=772,695 36 | Collapsed=0 37 | 38 | [Window][Level Editor Stuff] 39 | Pos=3060,1 40 | Size=772,695 41 | Collapsed=0 42 | DockId=0x00000002,0 43 | 44 | [Window][Scene Heirarchy] 45 | Pos=2965,1 46 | Size=867,991 47 | Collapsed=0 48 | DockId=0x00000001,0 49 | 50 | [Window][Scene Hierarchy] 51 | Pos=3060,698 52 | Size=772,1409 53 | Collapsed=0 54 | DockId=0x00000008,0 55 | 56 | [Docking][Data] 57 | DockSpace ID=0x6D3A3A6E Window=0x091AB4BE Pos=8,46 Size=3824,2106 Split=X Selected=0xAE7BB42F 58 | DockNode ID=0x00000005 Parent=0x6D3A3A6E SizeRef=3050,1981 Split=Y 59 | DockNode ID=0x00000003 Parent=0x00000005 SizeRef=3824,1652 CentralNode=1 Selected=0xAE7BB42F 60 | DockNode ID=0x00000004 Parent=0x00000005 SizeRef=3824,327 Selected=0x8081D1E6 61 | DockNode ID=0x00000007 Parent=0x6D3A3A6E SizeRef=772,1981 Split=Y Selected=0x0A670937 62 | DockNode ID=0x00000001 Parent=0x00000007 SizeRef=431,513 Selected=0x0A670937 63 | DockNode ID=0x00000006 Parent=0x00000007 SizeRef=431,511 Split=Y Selected=0x4D7EC7FC 64 | DockNode ID=0x00000002 Parent=0x00000006 SizeRef=867,654 Selected=0x4D7EC7FC 65 | DockNode ID=0x00000008 Parent=0x00000006 SizeRef=867,1325 Selected=0x9A68760C 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/components/AnimationState.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import util.AssetPool; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class AnimationState { 9 | 10 | public String title; 11 | public List animationFrames = new ArrayList<>(); 12 | 13 | private static Sprite defaultSprite = new Sprite(); 14 | private float time = 0.0f; 15 | private transient int currentSprite = 0; 16 | private boolean doesLoop = false; 17 | 18 | public void refreshTextures() { 19 | for (Frame frame : animationFrames) { 20 | frame.sprite.setTexture(AssetPool.getTexture(frame.sprite.getTexture().getFilepath())); 21 | } 22 | } 23 | 24 | public void addFrame(Sprite sprite, float frameTime) { 25 | animationFrames.add(new Frame(sprite, frameTime)); 26 | } 27 | 28 | public void addFrames(List sprites, float frameTime) { 29 | for (Sprite sprite : sprites) { 30 | this.animationFrames.add(new Frame(sprite, frameTime)); 31 | } 32 | } 33 | 34 | public void setLoop(boolean doesLoop) { 35 | this.doesLoop = doesLoop; 36 | } 37 | 38 | public void update(float dt) { 39 | if (currentSprite < animationFrames.size()) { 40 | time -= dt; 41 | if (time <= 0) { 42 | if (!(currentSprite == animationFrames.size() - 1 && !doesLoop)) { 43 | currentSprite = (currentSprite + 1) % animationFrames.size(); 44 | } 45 | time = animationFrames.get(currentSprite).frameTime; 46 | } 47 | } 48 | } 49 | 50 | public Sprite getCurrentSprite() { 51 | if (currentSprite < animationFrames.size()) { 52 | return animationFrames.get(currentSprite).sprite; 53 | } 54 | 55 | return defaultSprite; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/components/GameCamera.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.GameObject; 5 | import jade.Window; 6 | import org.joml.Vector4f; 7 | 8 | public class GameCamera extends Component { 9 | private transient GameObject player; 10 | private transient Camera gameCamera; 11 | private transient float highestX = Float.MIN_VALUE; 12 | private transient float undergroundYLevel = 0.0f; 13 | private transient float cameraBuffer = 1.5f; 14 | private transient float playerBuffer = 0.25f; 15 | 16 | private Vector4f skyColor = new Vector4f(92.0f / 255.0f, 148.0f / 255.0f, 252.0f / 255.0f, 1.0f); 17 | private Vector4f undergroundColor = new Vector4f(0, 0, 0, 1); 18 | 19 | public GameCamera(Camera gameCamera) { 20 | this.gameCamera = gameCamera; 21 | } 22 | 23 | @Override 24 | public void start() { 25 | this.player = Window.getScene().getGameObjectWith(PlayerController.class); 26 | this.gameCamera.clearColor.set(skyColor); 27 | this.undergroundYLevel = this.gameCamera.position.y - 28 | this.gameCamera.getProjectionSize().y - this.cameraBuffer; 29 | } 30 | 31 | @Override 32 | public void update(float dt) { 33 | if (player != null && !player.getComponent(PlayerController.class).hasWon()) { 34 | gameCamera.position.x = Math.max(player.transform.position.x - 2.5f, highestX); 35 | highestX = Math.max(highestX, gameCamera.position.x); 36 | 37 | if (player.transform.position.y < -playerBuffer) { 38 | this.gameCamera.position.y = undergroundYLevel; 39 | this.gameCamera.clearColor.set(undergroundColor); 40 | } else if (player.transform.position.y >= 0.0f) { 41 | this.gameCamera.position.y = 0.0f; 42 | this.gameCamera.clearColor.set(skyColor); 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/jade/Transform.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import components.Component; 4 | import editor.JImGui; 5 | import org.joml.Vector2f; 6 | 7 | public class Transform extends Component { 8 | 9 | public Vector2f position; 10 | public Vector2f scale; 11 | public float rotation = 0.0f; 12 | public int zIndex; 13 | 14 | public Transform() { 15 | init(new Vector2f(), new Vector2f()); 16 | } 17 | 18 | public Transform(Vector2f position) { 19 | init(position, new Vector2f()); 20 | } 21 | 22 | public Transform(Vector2f position, Vector2f scale) { 23 | init(position, scale); 24 | } 25 | 26 | public void init(Vector2f position, Vector2f scale) { 27 | this.position = position; 28 | this.scale = scale; 29 | this.zIndex = 0; 30 | } 31 | 32 | public Transform copy() { 33 | return new Transform(new Vector2f(this.position), new Vector2f(this.scale)); 34 | } 35 | 36 | @Override 37 | public void imgui() { 38 | gameObject.name = JImGui.inputText("Name: ", gameObject.name); 39 | JImGui.drawVec2Control("Position", this.position); 40 | JImGui.drawVec2Control("Scale", this.scale, 32.0f); 41 | this.rotation = JImGui.dragFloat("Rotation", this.rotation); 42 | this.zIndex = JImGui.dragInt("Z-Index", this.zIndex); 43 | } 44 | 45 | public void copy(Transform to) { 46 | to.position.set(this.position); 47 | to.scale.set(this.scale); 48 | } 49 | 50 | @Override 51 | public boolean equals(Object o) { 52 | if (o == null) return false; 53 | if (!(o instanceof Transform)) return false; 54 | 55 | Transform t = (Transform)o; 56 | return t.position.equals(this.position) && t.scale.equals(this.scale) && 57 | t.rotation == this.rotation && t.zIndex == this.zIndex; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/components/MushroomAI.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.dynamics.contacts.Contact; 5 | import org.joml.Vector2f; 6 | import physics2d.components.Rigidbody2D; 7 | import util.AssetPool; 8 | 9 | public class MushroomAI extends Component { 10 | private transient boolean goingRight = true; 11 | private transient Rigidbody2D rb; 12 | private transient Vector2f speed = new Vector2f(1.0f, 0.0f); 13 | private transient float maxSpeed = 0.8f; 14 | private transient boolean hitPlayer = false; 15 | 16 | @Override 17 | public void start() { 18 | this.rb = gameObject.getComponent(Rigidbody2D.class); 19 | AssetPool.getSound("assets/sounds/powerup_appears.ogg").play(); 20 | } 21 | 22 | @Override 23 | public void update(float dt) { 24 | if (goingRight && Math.abs(rb.getVelocity().x) < maxSpeed) { 25 | rb.addVelocity(speed); 26 | } else if (!goingRight && Math.abs(rb.getVelocity().x) < maxSpeed) { 27 | rb.addVelocity(new Vector2f(-speed.x, speed.y)); 28 | } 29 | } 30 | 31 | @Override 32 | public void preSolve(GameObject obj, Contact contact, Vector2f contactNormal) { 33 | PlayerController playerController = obj.getComponent(PlayerController.class); 34 | if (playerController != null) { 35 | contact.setEnabled(false); 36 | if (!hitPlayer) { 37 | if (playerController.isSmall()) { 38 | playerController.powerup(); 39 | } else { 40 | AssetPool.getSound("assets/sounds/coin.ogg").play(); 41 | } 42 | this.gameObject.destroy(); 43 | hitPlayer = true; 44 | } 45 | } else if (obj.getComponent(Ground.class) == null) { 46 | contact.setEnabled(false); 47 | return; 48 | } 49 | 50 | if (Math.abs(contactNormal.y) < 0.1f) { 51 | goingRight = contactNormal.x < 0; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/components/Spritesheet.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import org.joml.Vector2f; 4 | import renderer.Texture; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class Spritesheet { 10 | 11 | private Texture texture; 12 | private List sprites; 13 | 14 | public Spritesheet(Texture texture, int spriteWidth, int spriteHeight, int numSprites, int spacing) { 15 | this.sprites = new ArrayList<>(); 16 | 17 | this.texture = texture; 18 | int currentX = 0; 19 | int currentY = texture.getHeight() - spriteHeight; 20 | for (int i=0; i < numSprites; i++) { 21 | float topY = (currentY + spriteHeight) / (float)texture.getHeight(); 22 | float rightX = (currentX + spriteWidth) / (float)texture.getWidth(); 23 | float leftX = currentX / (float)texture.getWidth(); 24 | float bottomY = currentY / (float)texture.getHeight(); 25 | 26 | Vector2f[] texCoords = { 27 | new Vector2f(rightX, topY), 28 | new Vector2f(rightX, bottomY), 29 | new Vector2f(leftX, bottomY), 30 | new Vector2f(leftX, topY) 31 | }; 32 | Sprite sprite = new Sprite(); 33 | sprite.setTexture(this.texture); 34 | sprite.setTexCoords(texCoords); 35 | sprite.setWidth(spriteWidth); 36 | sprite.setHeight(spriteHeight); 37 | this.sprites.add(sprite); 38 | 39 | currentX += spriteWidth + spacing; 40 | if (currentX >= texture.getWidth()) { 41 | currentX = 0; 42 | currentY -= spriteHeight + spacing; 43 | } 44 | } 45 | } 46 | 47 | public Sprite getSprite(int index) { 48 | return this.sprites.get(index); 49 | } 50 | 51 | public List getSprites() { return this.sprites; } 52 | 53 | public int size() { 54 | return sprites.size(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/primitives/Box2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.primitives; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.rigidbody.Rigidbody2D; 5 | import util.JMath; 6 | 7 | public class Box2D { 8 | private Vector2f size = new Vector2f(); 9 | private Vector2f halfSize = new Vector2f(); 10 | private Rigidbody2D rigidbody = null; 11 | 12 | public Box2D() { 13 | this.halfSize = new Vector2f(size).mul(0.5f); 14 | } 15 | 16 | public Box2D(Vector2f min, Vector2f max) { 17 | this.size = new Vector2f(max).sub(min); 18 | this.halfSize = new Vector2f(size).mul(0.5f); 19 | } 20 | 21 | public Vector2f getLocalMin() { 22 | return new Vector2f(this.rigidbody.getPosition()).sub(this.halfSize); 23 | } 24 | 25 | public Vector2f getLocalMax() { 26 | return new Vector2f(this.rigidbody.getPosition()).add(this.halfSize); 27 | } 28 | 29 | public Vector2f getHalfSize() { 30 | return this.halfSize; 31 | } 32 | 33 | public Vector2f[] getVertices() { 34 | Vector2f min = getLocalMin(); 35 | Vector2f max = getLocalMax(); 36 | 37 | Vector2f[] vertices = { 38 | new Vector2f(min.x, min.y), new Vector2f(min.x, max.y), 39 | new Vector2f(max.x, min.y), new Vector2f(max.x, max.y) 40 | }; 41 | 42 | if (rigidbody.getRotation() != 0.0f) { 43 | for (Vector2f vert : vertices) { 44 | // Rotates point(Vector2f) about center(Vector2f) by rotation(float in degrees) 45 | JMath.rotate(vert, this.rigidbody.getRotation(), this.rigidbody.getPosition()); 46 | } 47 | } 48 | 49 | return vertices; 50 | } 51 | 52 | public Rigidbody2D getRigidbody() { 53 | return this.rigidbody; 54 | } 55 | 56 | public void setRigidbody(Rigidbody2D rb) { 57 | this.rigidbody = rb; 58 | } 59 | 60 | public void setSize(Vector2f size) { 61 | this.size.set(size); 62 | this.halfSize.set(size.x / 2.0f, size.y / 2.0f); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/components/Block.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import org.jbox2d.dynamics.contacts.Contact; 5 | import org.joml.Vector2f; 6 | import util.AssetPool; 7 | 8 | public abstract class Block extends Component { 9 | private transient boolean bopGoingUp = true; 10 | private transient boolean doBopAnimation = false; 11 | private transient Vector2f bopStart; 12 | private transient Vector2f topBopLocation; 13 | private transient boolean active = true; 14 | 15 | public float bopSpeed = 0.4f; 16 | 17 | @Override 18 | public void start() { 19 | this.bopStart = new Vector2f(this.gameObject.transform.position); 20 | this.topBopLocation = new Vector2f(bopStart).add(0.0f, 0.02f); 21 | } 22 | 23 | @Override 24 | public void update(float dt) { 25 | if (doBopAnimation) { 26 | if (bopGoingUp) { 27 | if (this.gameObject.transform.position.y < topBopLocation.y) { 28 | this.gameObject.transform.position.y += bopSpeed * dt; 29 | } else { 30 | bopGoingUp = false; 31 | } 32 | } else { 33 | if (this.gameObject.transform.position.y > bopStart.y) { 34 | this.gameObject.transform.position.y -= bopSpeed * dt; 35 | } else { 36 | this.gameObject.transform.position.y = this.bopStart.y; 37 | bopGoingUp = true; 38 | doBopAnimation = false; 39 | } 40 | } 41 | } 42 | } 43 | 44 | @Override 45 | public void beginCollision(GameObject obj, Contact contact, Vector2f contactNormal) { 46 | PlayerController playerController = obj.getComponent(PlayerController.class); 47 | if (active && playerController != null && contactNormal.y < -0.8f) { 48 | doBopAnimation = true; 49 | AssetPool.getSound("assets/sounds/bump.ogg").play(); 50 | playerHit(playerController); 51 | } 52 | } 53 | 54 | public void setInactive() { this.active = false; } 55 | 56 | abstract void playerHit(PlayerController playerController); 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/editor/SceneHierarchyWindow.java: -------------------------------------------------------------------------------- 1 | package editor; 2 | 3 | import imgui.ImGui; 4 | import imgui.flag.ImGuiDragDropFlags; 5 | import imgui.flag.ImGuiTreeNodeFlags; 6 | import jade.GameObject; 7 | import jade.Window; 8 | 9 | import java.util.List; 10 | 11 | public class SceneHierarchyWindow { 12 | 13 | private static String payloadDragDropType = "SceneHierarchy"; 14 | 15 | public void imgui() { 16 | ImGui.begin("Scene Hierarchy"); 17 | 18 | List gameObjects = Window.getScene().getGameObjects(); 19 | int index = 0; 20 | for (GameObject obj : gameObjects) { 21 | if (!obj.doSerialization()) { 22 | continue; 23 | } 24 | 25 | boolean treeNodeOpen = doTreeNode(obj, index); 26 | if (treeNodeOpen) { 27 | ImGui.treePop(); 28 | } 29 | index++; 30 | } 31 | 32 | ImGui.end(); 33 | } 34 | 35 | private boolean doTreeNode(GameObject obj, int index) { 36 | ImGui.pushID(index); 37 | boolean treeNodeOpen = ImGui.treeNodeEx( 38 | obj.name, 39 | ImGuiTreeNodeFlags.DefaultOpen | 40 | ImGuiTreeNodeFlags.FramePadding | 41 | ImGuiTreeNodeFlags.OpenOnArrow | 42 | ImGuiTreeNodeFlags.SpanAvailWidth, 43 | obj.name 44 | ); 45 | ImGui.popID(); 46 | 47 | if (ImGui.beginDragDropSource()) { 48 | ImGui.setDragDropPayloadObject(payloadDragDropType, obj); 49 | ImGui.text(obj.name); 50 | ImGui.endDragDropSource(); 51 | } 52 | 53 | if (ImGui.beginDragDropTarget()) { 54 | Object payloadObj = ImGui.acceptDragDropPayloadObject(payloadDragDropType); 55 | if (payloadObj != null) { 56 | if (payloadObj.getClass().isAssignableFrom(GameObject.class)) { 57 | GameObject playerGameObj = (GameObject)payloadObj; 58 | System.out.println("Payload accepted '" + playerGameObj.name + "'"); 59 | } 60 | } 61 | ImGui.endDragDropTarget(); 62 | } 63 | 64 | return treeNodeOpen; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding a 2D Game Engine in Java 2 | 3 | This is the repository for a YouTube series [here](https://www.youtube.com/watch?v=VyKE7vz65rY&list=PLtrSb4XxIVbp8AKuEAlwNXDxr99e3woGE). If you want to run the code yourself follow these instructions: 4 | 5 | ## To Run 6 | 7 | 1. You must have Gradle 6.3+ and Java 1.8+ installed. If you do not have these installed, you should install them and add them to your environment variables. 8 | * Once you have them installed you should be able to run: 9 | 10 | > ```gradle --version``` 11 | 12 | and 13 | 14 | > ```java -version``` 15 | 16 | And get no errors. The output should read similar to the following (it's ok if it doesn't read exactly the same way): 17 | > ``` 18 | > ------------------------------------------------------------ 19 | > Gradle 6.3 20 | > ------------------------------------------------------------ 21 | > 22 | > Build time: 2020-03-24 19:52:07 UTC 23 | > Revision: bacd40b727b0130eeac8855ae3f9fd9a0b207c60 24 | > 25 | > Kotlin: 1.3.70 26 | > Groovy: 2.5.10 27 | > Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019 28 | > JVM: 1.8.0_231 (Oracle Corporation 25.231-b11) 29 | > OS: Windows 10 10.0 amd64 30 | > 31 | > java version "1.8.0_231" 32 | > Java(TM) SE Runtime Environment (build 1.8.0_231-b11) 33 | > Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode) 34 | > ``` 35 | 2. Open a Command Prompt in the projects root directory. 36 | * If you run ```ls``` (Mac, Linux) or ```dir``` (Windows) you should see ```libs```, ```src```, and ```assets``` listed as *part* of the output. 37 | 3. Run: 38 | >```gradle fatJar``` 39 | * This will create a fat JAR containing all the dependencies for the project. 40 | 4. Run 41 | >```java -jar build/libs/mario-1.0-SNAPSHOT-all.jar``` 42 | * This should open a new Window with the Mario game running. 43 | * NOTE: The ImGui Windows will probably be placed in very weird places. This is because I can't export default settings for ImGui, so you'll have to reposition the windows in the dock before it looks correct. 44 | -------------------------------------------------------------------------------- /src/main/java/components/QuestionBlock.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.GameObject; 4 | import jade.Prefabs; 5 | import jade.Window; 6 | 7 | public class QuestionBlock extends Block { 8 | private enum BlockType { 9 | Coin, 10 | Powerup, 11 | Invincibility 12 | } 13 | 14 | public BlockType blockType = BlockType.Coin; 15 | 16 | @Override 17 | void playerHit(PlayerController playerController) { 18 | switch(blockType) { 19 | case Coin: 20 | doCoin(playerController); 21 | break; 22 | case Powerup: 23 | doPowerup(playerController); 24 | break; 25 | case Invincibility: 26 | doInvincibility(playerController); 27 | break; 28 | } 29 | 30 | StateMachine stateMachine = gameObject.getComponent(StateMachine.class); 31 | if (stateMachine != null) { 32 | stateMachine.trigger("setInactive"); 33 | this.setInactive(); 34 | } 35 | } 36 | 37 | private void doInvincibility(PlayerController playerController) { 38 | } 39 | 40 | private void doPowerup(PlayerController playerController) { 41 | if (playerController.isSmall()) { 42 | spawnMushroom(); 43 | } else { 44 | spawnFlower(); 45 | } 46 | } 47 | 48 | private void doCoin(PlayerController playerController) { 49 | GameObject coin = Prefabs.generateBlockCoin(); 50 | coin.transform.position.set(this.gameObject.transform.position); 51 | coin.transform.position.y += 0.25f; 52 | Window.getScene().addGameObjectToScene(coin); 53 | } 54 | 55 | private void spawnMushroom() { 56 | GameObject mushroom = Prefabs.generateMushroom(); 57 | mushroom.transform.position.set(gameObject.transform.position); 58 | mushroom.transform.position.y += 0.25f; 59 | Window.getScene().addGameObjectToScene(mushroom); 60 | } 61 | 62 | private void spawnFlower() { 63 | GameObject flower = Prefabs.generateFlower(); 64 | flower.transform.position.set(gameObject.transform.position); 65 | flower.transform.position.y += 0.25f; 66 | Window.getScene().addGameObjectToScene(flower); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /assets/shaders/default.glsl: -------------------------------------------------------------------------------- 1 | #type vertex 2 | #version 330 core 3 | layout (location=0) in vec3 aPos; 4 | layout (location=1) in vec4 aColor; 5 | layout (location=2) in vec2 aTexCoords; 6 | layout (location=3) in float aTexId; 7 | 8 | uniform mat4 uProjection; 9 | uniform mat4 uView; 10 | 11 | out vec4 fColor; 12 | out vec2 fTexCoords; 13 | out float fTexId; 14 | 15 | void main() 16 | { 17 | fColor = aColor; 18 | fTexCoords = aTexCoords; 19 | fTexId = aTexId; 20 | 21 | gl_Position = uProjection * uView * vec4(aPos, 1.0); 22 | } 23 | 24 | #type fragment 25 | #version 330 core 26 | 27 | in vec4 fColor; 28 | in vec2 fTexCoords; 29 | in float fTexId; 30 | 31 | uniform sampler2D uTextures[8]; 32 | 33 | out vec4 color; 34 | 35 | void main() 36 | { 37 | if (fTexId > 0) { 38 | // NOTE: If you're on AMD GPUs try commenting this line out and replacing it with 39 | // the next few lines. The issue here is dynamic indexing is undefined behavior 40 | // in GLSL, so this is not guaranteed to work on all hardware 41 | // 42 | // int id = int(fTexId); 43 | // color = fColor * texture(uTextures[id], fTexCoords); 44 | 45 | int id = int(fTexId); 46 | switch (id) { 47 | case 0: 48 | color = fColor * texture(uTextures[0], fTexCoords); 49 | break; 50 | case 1: 51 | color = fColor * texture(uTextures[1], fTexCoords); 52 | break; 53 | case 2: 54 | color = fColor * texture(uTextures[2], fTexCoords); 55 | break; 56 | case 3: 57 | color = fColor * texture(uTextures[3], fTexCoords); 58 | break; 59 | case 4: 60 | color = fColor * texture(uTextures[4], fTexCoords); 61 | break; 62 | case 5: 63 | color = fColor * texture(uTextures[5], fTexCoords); 64 | break; 65 | case 6: 66 | color = fColor * texture(uTextures[6], fTexCoords); 67 | break; 68 | case 7: 69 | color = fColor * texture(uTextures[7], fTexCoords); 70 | break; 71 | } 72 | } else { 73 | color = fColor; 74 | } 75 | } -------------------------------------------------------------------------------- /src/main/java/renderer/Renderer.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import components.SpriteRenderer; 4 | import jade.GameObject; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | import java.util.Collections; 9 | import java.util.List; 10 | 11 | public class Renderer { 12 | private final int MAX_BATCH_SIZE = 1000; 13 | private List batches; 14 | private static Shader currentShader; 15 | 16 | public Renderer() { 17 | this.batches = new ArrayList<>(); 18 | } 19 | 20 | public void add(GameObject go) { 21 | SpriteRenderer spr = go.getComponent(SpriteRenderer.class); 22 | if (spr != null) { 23 | add(spr); 24 | } 25 | } 26 | 27 | private void add(SpriteRenderer sprite) { 28 | boolean added = false; 29 | for (RenderBatch batch : batches) { 30 | if (batch.hasRoom() && batch.zIndex() == sprite.gameObject.transform.zIndex) { 31 | Texture tex = sprite.getTexture(); 32 | if (tex == null || (batch.hasTexture(tex) || batch.hasTextureRoom())) { 33 | batch.addSprite(sprite); 34 | added = true; 35 | break; 36 | } 37 | } 38 | } 39 | 40 | if (!added) { 41 | RenderBatch newBatch = new RenderBatch(MAX_BATCH_SIZE, 42 | sprite.gameObject.transform.zIndex, this); 43 | newBatch.start(); 44 | batches.add(newBatch); 45 | newBatch.addSprite(sprite); 46 | Collections.sort(batches); 47 | } 48 | } 49 | 50 | public void destroyGameObject(GameObject go) { 51 | if (go.getComponent(SpriteRenderer.class) == null) return; 52 | for (RenderBatch batch : batches) { 53 | if (batch.destroyIfExists(go)) { 54 | return; 55 | } 56 | } 57 | } 58 | 59 | public static void bindShader(Shader shader) { 60 | currentShader = shader; 61 | } 62 | 63 | public static Shader getBoundShader() { 64 | return currentShader; 65 | } 66 | 67 | public void render() { 68 | currentShader.use(); 69 | for (int i = 0; i < batches.size(); i++) { 70 | RenderBatch batch = batches.get(i); 71 | batch.render(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/jade/Camera.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import org.joml.Matrix4f; 4 | import org.joml.Vector2f; 5 | import org.joml.Vector3f; 6 | import org.joml.Vector4f; 7 | 8 | public class Camera { 9 | private Matrix4f projectionMatrix, viewMatrix, inverseProjection, inverseView; 10 | public Vector2f position; 11 | 12 | private float projectionWidth = 6; 13 | private float projectionHeight = 3; 14 | public Vector4f clearColor = new Vector4f(1, 1, 1, 1); 15 | private Vector2f projectionSize = new Vector2f(projectionWidth, projectionHeight); 16 | 17 | private float zoom = 1.0f; 18 | 19 | public Camera(Vector2f position) { 20 | this.position = position; 21 | this.projectionMatrix = new Matrix4f(); 22 | this.viewMatrix = new Matrix4f(); 23 | this.inverseProjection = new Matrix4f(); 24 | this.inverseView = new Matrix4f(); 25 | adjustProjection(); 26 | } 27 | 28 | public void adjustProjection() { 29 | projectionMatrix.identity(); 30 | projectionMatrix.ortho(0.0f, projectionSize.x * this.zoom, 31 | 0.0f, projectionSize.y * zoom, 0.0f, 100.0f); 32 | inverseProjection = new Matrix4f(projectionMatrix).invert(); 33 | } 34 | 35 | public Matrix4f getViewMatrix() { 36 | Vector3f cameraFront = new Vector3f(0.0f, 0.0f, -1.0f); 37 | Vector3f cameraUp = new Vector3f(0.0f, 1.0f, 0.0f); 38 | viewMatrix.identity(); 39 | viewMatrix.lookAt(new Vector3f(position.x, position.y, 20.0f), 40 | cameraFront.add(position.x, position.y, 0.0f), 41 | cameraUp); 42 | inverseView = new Matrix4f(this.viewMatrix).invert(); 43 | 44 | return this.viewMatrix; 45 | } 46 | 47 | public Matrix4f getProjectionMatrix() { 48 | return this.projectionMatrix; 49 | } 50 | 51 | public Matrix4f getInverseProjection() { 52 | return this.inverseProjection; 53 | } 54 | 55 | public Matrix4f getInverseView() { 56 | return this.inverseView; 57 | } 58 | 59 | public Vector2f getProjectionSize() { 60 | return this.projectionSize; 61 | } 62 | 63 | public float getZoom() { 64 | return zoom; 65 | } 66 | 67 | public void setZoom(float zoom) { 68 | this.zoom = zoom; 69 | } 70 | 71 | public void addZoom(float value) { 72 | this.zoom += value; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/components/SpriteRenderer.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.JImGui; 4 | import imgui.ImGui; 5 | import jade.Transform; 6 | import org.joml.Vector2f; 7 | import org.joml.Vector4f; 8 | import renderer.Texture; 9 | import util.AssetPool; 10 | 11 | public class SpriteRenderer extends Component { 12 | 13 | private Vector4f color = new Vector4f(1, 1, 1, 1); 14 | private Sprite sprite = new Sprite(); 15 | 16 | private transient Transform lastTransform; 17 | private transient boolean isDirty = true; 18 | 19 | @Override 20 | public void start() { 21 | if (this.sprite.getTexture() != null) { 22 | this.sprite.setTexture(AssetPool.getTexture(this.sprite.getTexture().getFilepath())); 23 | } 24 | this.lastTransform = gameObject.transform.copy(); 25 | } 26 | 27 | @Override 28 | public void update(float dt) { 29 | if (!this.lastTransform.equals(this.gameObject.transform)) { 30 | this.gameObject.transform.copy(this.lastTransform); 31 | isDirty = true; 32 | } 33 | } 34 | 35 | @Override 36 | public void editorUpdate(float dt) { 37 | if (!this.lastTransform.equals(this.gameObject.transform)) { 38 | this.gameObject.transform.copy(this.lastTransform); 39 | isDirty = true; 40 | } 41 | } 42 | 43 | @Override 44 | public void imgui() { 45 | if (JImGui.colorPicker4("Color Pickier", this.color)) { 46 | this.isDirty = true; 47 | } 48 | } 49 | 50 | public void setDirty() { 51 | this.isDirty = true; 52 | } 53 | 54 | public Vector4f getColor() { 55 | return this.color; 56 | } 57 | 58 | public Texture getTexture() { 59 | return sprite.getTexture(); 60 | } 61 | 62 | public Vector2f[] getTexCoords() { 63 | return sprite.getTexCoords(); 64 | } 65 | 66 | public void setSprite(Sprite sprite) { 67 | this.sprite = sprite; 68 | this.isDirty = true; 69 | } 70 | 71 | public void setColor(Vector4f color) { 72 | if (!this.color.equals(color)) { 73 | this.isDirty = true; 74 | this.color.set(color); 75 | } 76 | } 77 | 78 | public boolean isDirty() { 79 | return this.isDirty; 80 | } 81 | 82 | public void setClean() { 83 | this.isDirty = false; 84 | } 85 | 86 | public void setTexture(Texture texture) { 87 | this.sprite.setTexture(texture); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/physics2d/components/PillboxCollider.java: -------------------------------------------------------------------------------- 1 | package physics2d.components; 2 | 3 | import components.Component; 4 | import jade.Window; 5 | import org.jbox2d.dynamics.contacts.ContactVelocityConstraint; 6 | import org.joml.Vector2f; 7 | import physics2d.components.Box2DCollider; 8 | import physics2d.components.CircleCollider; 9 | 10 | public class PillboxCollider extends Component { 11 | private transient CircleCollider bottomCircle = new CircleCollider(); 12 | private transient Box2DCollider box = new Box2DCollider(); 13 | private transient boolean resetFixtureNextFrame = false; 14 | 15 | public float width = 0.1f; 16 | public float height = 0.2f; 17 | public Vector2f offset = new Vector2f(); 18 | 19 | @Override 20 | public void start() { 21 | this.bottomCircle.gameObject = this.gameObject; 22 | this.box.gameObject = this.gameObject; 23 | recalculateColliders(); 24 | } 25 | 26 | @Override 27 | public void editorUpdate(float dt) { 28 | bottomCircle.editorUpdate(dt); 29 | box.editorUpdate(dt); 30 | recalculateColliders(); 31 | 32 | if (resetFixtureNextFrame) { 33 | resetFixture(); 34 | } 35 | } 36 | 37 | @Override 38 | public void update(float dt) { 39 | if (resetFixtureNextFrame) { 40 | resetFixture(); 41 | } 42 | } 43 | 44 | public void setWidth(float newVal) { 45 | this.width = newVal; 46 | recalculateColliders(); 47 | resetFixture(); 48 | } 49 | 50 | public void setHeight(float newVal) { 51 | this.height = newVal; 52 | recalculateColliders(); 53 | resetFixture(); 54 | } 55 | 56 | public void resetFixture() { 57 | if (Window.getPhysics().isLocked()) { 58 | resetFixtureNextFrame = true; 59 | return; 60 | } 61 | resetFixtureNextFrame = false; 62 | 63 | if (gameObject != null) { 64 | Rigidbody2D rb = gameObject.getComponent(Rigidbody2D.class); 65 | if (rb != null) { 66 | Window.getPhysics().resetPillboxCollider(rb, this); 67 | } 68 | } 69 | } 70 | 71 | public void recalculateColliders() { 72 | float circleRadius = width / 2.0f; 73 | float boxHeight = height - circleRadius; 74 | bottomCircle.setRadius(circleRadius); 75 | bottomCircle.setOffset(new Vector2f(offset).sub(0, (height - circleRadius * 2.0f) / 2.0f)); 76 | box.setHalfSize(new Vector2f(width - 0.01f, boxHeight)); 77 | box.setOffset(new Vector2f(offset).add(0, (height - boxHeight) / 2.0f)); 78 | } 79 | 80 | public CircleCollider getBottomCircle() { 81 | return bottomCircle; 82 | } 83 | 84 | public Box2DCollider getBox() { 85 | return box; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/components/Fireball.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.GameObject; 5 | import jade.Window; 6 | import org.jbox2d.dynamics.contacts.Contact; 7 | import org.joml.Vector2f; 8 | import physics2d.Physics2D; 9 | import physics2d.components.Rigidbody2D; 10 | 11 | public class Fireball extends Component { 12 | public transient boolean goingRight = false; 13 | private transient Rigidbody2D rb; 14 | private transient float fireballSpeed = 1.7f; 15 | private transient Vector2f velocity = new Vector2f(); 16 | private transient Vector2f acceleration = new Vector2f(); 17 | private transient Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); 18 | private transient boolean onGround = false; 19 | private transient float lifetime = 4.0f; 20 | 21 | private static int fireballCount = 0; 22 | 23 | public static boolean canSpawn() { 24 | return fireballCount < 4; 25 | } 26 | 27 | @Override 28 | public void start() { 29 | this.rb = this.gameObject.getComponent(Rigidbody2D.class); 30 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 31 | fireballCount++; 32 | } 33 | 34 | @Override 35 | public void update(float dt) { 36 | lifetime -= dt; 37 | if (lifetime <= 0) { 38 | disappear(); 39 | return; 40 | } 41 | 42 | if (goingRight) { 43 | velocity.x = fireballSpeed; 44 | } else { 45 | velocity.x = -fireballSpeed; 46 | } 47 | 48 | checkOnGround(); 49 | if (onGround) { 50 | this.acceleration.y = 1.5f; 51 | this.velocity.y = 2.5f; 52 | } else { 53 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 54 | } 55 | 56 | this.velocity.y += this.acceleration.y * dt; 57 | this.velocity.y = Math.max(Math.min(this.velocity.y, this.terminalVelocity.y), -terminalVelocity.y); 58 | this.rb.setVelocity(velocity); 59 | } 60 | 61 | public void checkOnGround() { 62 | float innerPlayerWidth = 0.25f * 0.7f; 63 | float yVal = -0.09f; 64 | onGround = Physics2D.checkOnGround(this.gameObject, innerPlayerWidth, yVal); 65 | } 66 | 67 | @Override 68 | public void beginCollision(GameObject obj, Contact contact, Vector2f contactNormal) { 69 | if (Math.abs(contactNormal.x) > 0.8f) { 70 | this.goingRight = contactNormal.x < 0; 71 | } 72 | } 73 | 74 | @Override 75 | public void preSolve(GameObject obj, Contact contact, Vector2f contactNormal) { 76 | if (obj.getComponent(PlayerController.class) != null || 77 | obj.getComponent(Fireball.class) != null) { 78 | contact.setEnabled(false); 79 | } 80 | } 81 | 82 | public void disappear() { 83 | fireballCount--; 84 | this.gameObject.destroy(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/components/EditorCamera.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.KeyListener; 5 | import jade.MouseListener; 6 | import org.joml.Vector2f; 7 | 8 | import static org.lwjgl.glfw.GLFW.GLFW_KEY_KP_DECIMAL; 9 | import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_MIDDLE; 10 | 11 | public class EditorCamera extends Component { 12 | 13 | private float dragDebounce = 0.032f; 14 | 15 | private Camera levelEditorCamera; 16 | private Vector2f clickOrigin; 17 | private boolean reset = false; 18 | 19 | private float lerpTime = 0.0f; 20 | private float dragSensitivity = 30.0f; 21 | private float scrollSensitivity = 0.1f; 22 | 23 | public EditorCamera(Camera levelEditorCamera) { 24 | this.levelEditorCamera = levelEditorCamera; 25 | this.clickOrigin = new Vector2f(); 26 | } 27 | 28 | @Override 29 | public void editorUpdate(float dt) { 30 | if (MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_MIDDLE) && dragDebounce > 0) { 31 | this.clickOrigin = new Vector2f(MouseListener.getWorldX(), MouseListener.getWorldY()); 32 | dragDebounce -= dt; 33 | return; 34 | } else if (MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_MIDDLE)) { 35 | Vector2f mousePos = new Vector2f(MouseListener.getWorldX(), MouseListener.getWorldY()); 36 | Vector2f delta = new Vector2f(mousePos).sub(this.clickOrigin); 37 | levelEditorCamera.position.sub(delta.mul(dt).mul(dragSensitivity)); 38 | this.clickOrigin.lerp(mousePos, dt); 39 | } 40 | 41 | if (dragDebounce <= 0.0f && !MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_MIDDLE)) { 42 | dragDebounce = 0.1f; 43 | } 44 | 45 | if (MouseListener.getScrollY() != 0.0f) { 46 | float addValue = (float)Math.pow(Math.abs(MouseListener.getScrollY() * scrollSensitivity), 47 | 1 / levelEditorCamera.getZoom()); 48 | addValue *= -Math.signum(MouseListener.getScrollY()); 49 | levelEditorCamera.addZoom(addValue); 50 | } 51 | 52 | if (KeyListener.isKeyPressed(GLFW_KEY_KP_DECIMAL)) { 53 | reset = true; 54 | } 55 | 56 | if (reset) { 57 | levelEditorCamera.position.lerp(new Vector2f(), lerpTime); 58 | levelEditorCamera.setZoom(this.levelEditorCamera.getZoom() + 59 | ((1.0f - levelEditorCamera.getZoom()) * lerpTime)); 60 | this.lerpTime += 0.1f * dt; 61 | if (Math.abs(levelEditorCamera.position.x) <= 5.0f && 62 | Math.abs(levelEditorCamera.position.y) <= 5.0f) { 63 | this.lerpTime = 0.0f; 64 | levelEditorCamera.position.set(0f, 0f); 65 | this.levelEditorCamera.setZoom(1.0f); 66 | reset = false; 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/editor/GameViewWindow.java: -------------------------------------------------------------------------------- 1 | package editor; 2 | 3 | import imgui.ImGui; 4 | import imgui.ImVec2; 5 | import imgui.flag.ImGuiWindowFlags; 6 | import jade.MouseListener; 7 | import jade.Window; 8 | import observers.EventSystem; 9 | import observers.events.Event; 10 | import observers.events.EventType; 11 | import org.joml.Vector2f; 12 | 13 | public class GameViewWindow { 14 | 15 | private boolean isPlaying = false; 16 | private boolean windowIsHovered; 17 | 18 | public void imgui() { 19 | ImGui.begin("Game Viewport", ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse 20 | | ImGuiWindowFlags.MenuBar); 21 | 22 | ImGui.beginMenuBar(); 23 | if (ImGui.menuItem("Play", "", isPlaying, !isPlaying)) { 24 | isPlaying = true; 25 | EventSystem.notify(null, new Event(EventType.GameEngineStartPlay)); 26 | } 27 | if (ImGui.menuItem("Stop", "", !isPlaying, isPlaying)) { 28 | isPlaying = false; 29 | EventSystem.notify(null, new Event(EventType.GameEngineStopPlay)); 30 | } 31 | ImGui.endMenuBar(); 32 | 33 | 34 | ImGui.setCursorPos(ImGui.getCursorPosX(), ImGui.getCursorPosY()); 35 | ImVec2 windowSize = getLargestSizeForViewport(); 36 | ImVec2 windowPos = getCenteredPositionForViewport(windowSize); 37 | ImGui.setCursorPos(windowPos.x, windowPos.y); 38 | 39 | int textureId = Window.getFramebuffer().getTextureId(); 40 | ImGui.imageButton(textureId, windowSize.x, windowSize.y, 0, 1, 1, 0); 41 | windowIsHovered = ImGui.isItemHovered(); 42 | 43 | MouseListener.setGameViewportPos(new Vector2f(windowPos.x + 10, windowPos.y)); 44 | MouseListener.setGameViewportSize(new Vector2f(windowSize.x, windowSize.y)); 45 | 46 | ImGui.end(); 47 | } 48 | 49 | public boolean getWantCaptureMouse() { 50 | return windowIsHovered; 51 | } 52 | 53 | private ImVec2 getLargestSizeForViewport() { 54 | ImVec2 windowSize = new ImVec2(); 55 | ImGui.getContentRegionAvail(windowSize); 56 | 57 | float aspectWidth = windowSize.x; 58 | float aspectHeight = aspectWidth / Window.getTargetAspectRatio(); 59 | if (aspectHeight > windowSize.y) { 60 | // We must switch to pillarbox mode 61 | aspectHeight = windowSize.y; 62 | aspectWidth = aspectHeight * Window.getTargetAspectRatio(); 63 | } 64 | 65 | return new ImVec2(aspectWidth, aspectHeight); 66 | } 67 | 68 | private ImVec2 getCenteredPositionForViewport(ImVec2 aspectSize) { 69 | ImVec2 windowSize = new ImVec2(); 70 | ImGui.getContentRegionAvail(windowSize); 71 | 72 | float viewportX = (windowSize.x / 2.0f) - (aspectSize.x / 2.0f); 73 | float viewportY = (windowSize.y / 2.0f) - (aspectSize.y / 2.0f); 74 | 75 | return new ImVec2(viewportX + ImGui.getCursorPosX(), viewportY + ImGui.getCursorPosY()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/jade/Sound.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import java.nio.IntBuffer; 4 | import java.nio.ShortBuffer; 5 | 6 | import static org.lwjgl.openal.AL10.*; 7 | import static org.lwjgl.stb.STBVorbis.stb_vorbis_decode_filename; 8 | import static org.lwjgl.system.MemoryStack.*; 9 | import static org.lwjgl.system.libc.LibCStdlib.free; 10 | 11 | public class Sound { 12 | private int bufferId; 13 | private int sourceId; 14 | private String filepath; 15 | 16 | private boolean isPlaying = false; 17 | 18 | public Sound(String filepath, boolean loops) { 19 | this.filepath = filepath; 20 | 21 | // Allocate space to store the return information from stb 22 | stackPush(); 23 | IntBuffer channelsBuffer = stackMallocInt(1); 24 | stackPush(); 25 | IntBuffer sampleRateBuffer = stackMallocInt(1); 26 | 27 | ShortBuffer rawAudioBuffer = 28 | stb_vorbis_decode_filename(filepath, channelsBuffer, sampleRateBuffer); 29 | if (rawAudioBuffer == null) { 30 | System.out.println("Could not load sound '" + filepath + "'"); 31 | stackPop(); 32 | stackPop(); 33 | return; 34 | } 35 | 36 | // Retrieve the extra information that was stored in the buffers by stb 37 | int channels = channelsBuffer.get(); 38 | int sampleRate = sampleRateBuffer.get(); 39 | // Free 40 | stackPop(); 41 | stackPop(); 42 | 43 | // Find the correct openAL format 44 | int format = -1; 45 | if (channels == 1) { 46 | format = AL_FORMAT_MONO16; 47 | } else if (channels == 2) { 48 | format = AL_FORMAT_STEREO16; 49 | } 50 | 51 | bufferId = alGenBuffers(); 52 | alBufferData(bufferId, format, rawAudioBuffer, sampleRate); 53 | 54 | // Generate the source 55 | sourceId = alGenSources(); 56 | 57 | alSourcei(sourceId, AL_BUFFER, bufferId); 58 | alSourcei(sourceId, AL_LOOPING, loops ? 1 : 0); 59 | alSourcei(sourceId, AL_POSITION, 0); 60 | alSourcef(sourceId, AL_GAIN, 0.3f); 61 | 62 | // Free stb raw audio buffer 63 | free(rawAudioBuffer); 64 | } 65 | 66 | public void delete() { 67 | alDeleteSources(sourceId); 68 | alDeleteBuffers(bufferId); 69 | } 70 | 71 | public void play() { 72 | int state = alGetSourcei(sourceId, AL_SOURCE_STATE); 73 | if (state == AL_STOPPED) { 74 | isPlaying = false; 75 | alSourcei(sourceId, AL_POSITION, 0); 76 | } 77 | 78 | if (!isPlaying) { 79 | alSourcePlay(sourceId); 80 | isPlaying = true; 81 | } 82 | } 83 | 84 | public void stop() { 85 | if (isPlaying) { 86 | alSourceStop(sourceId); 87 | isPlaying = false; 88 | } 89 | } 90 | 91 | public String getFilepath() { 92 | return this.filepath; 93 | } 94 | 95 | public boolean isPlaying() { 96 | int state = alGetSourcei(sourceId, AL_SOURCE_STATE); 97 | if (state == AL_STOPPED) { 98 | isPlaying = false; 99 | } 100 | return isPlaying; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/util/AssetPool.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import components.Spritesheet; 4 | import jade.Sound; 5 | import renderer.Shader; 6 | import renderer.Texture; 7 | 8 | import java.io.File; 9 | import java.util.Collection; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | public class AssetPool { 14 | private static Map shaders = new HashMap<>(); 15 | private static Map textures = new HashMap<>(); 16 | private static Map spritesheets = new HashMap<>(); 17 | private static Map sounds = new HashMap<>(); 18 | 19 | public static Shader getShader(String resourceName) { 20 | File file = new File(resourceName); 21 | if (AssetPool.shaders.containsKey(file.getAbsolutePath())) { 22 | return AssetPool.shaders.get(file.getAbsolutePath()); 23 | } else { 24 | Shader shader = new Shader(resourceName); 25 | shader.compile(); 26 | AssetPool.shaders.put(file.getAbsolutePath(), shader); 27 | return shader; 28 | } 29 | } 30 | 31 | public static Texture getTexture(String resourceName) { 32 | File file = new File(resourceName); 33 | if (AssetPool.textures.containsKey(file.getAbsolutePath())) { 34 | return AssetPool.textures.get(file.getAbsolutePath()); 35 | } else { 36 | Texture texture = new Texture(); 37 | texture.init(resourceName); 38 | AssetPool.textures.put(file.getAbsolutePath(), texture); 39 | return texture; 40 | } 41 | } 42 | 43 | public static void addSpritesheet(String resourceName, Spritesheet spritesheet) { 44 | File file = new File(resourceName); 45 | if (!AssetPool.spritesheets.containsKey(file.getAbsolutePath())) { 46 | AssetPool.spritesheets.put(file.getAbsolutePath(), spritesheet); 47 | } 48 | } 49 | 50 | public static Spritesheet getSpritesheet(String resourceName) { 51 | File file = new File(resourceName); 52 | if (!AssetPool.spritesheets.containsKey(file.getAbsolutePath())) { 53 | assert false : "Error: Tried to access spritesheet '" + resourceName + "' and it has not been added to asset pool."; 54 | } 55 | return AssetPool.spritesheets.getOrDefault(file.getAbsolutePath(), null); 56 | } 57 | 58 | public static Collection getAllSounds() { 59 | return sounds.values(); 60 | } 61 | 62 | public static Sound getSound(String soundFile) { 63 | File file = new File(soundFile); 64 | if (sounds.containsKey(file.getAbsolutePath())) { 65 | return sounds.get(file.getAbsolutePath()); 66 | } else { 67 | assert false : "Sound file not added '" + soundFile + "'"; 68 | } 69 | 70 | return null; 71 | } 72 | 73 | public static Sound addSound(String soundFile, boolean loops) { 74 | File file = new File(soundFile); 75 | if (sounds.containsKey(file.getAbsolutePath())) { 76 | return sounds.get(file.getAbsolutePath()); 77 | } else { 78 | Sound sound = new Sound(file.getAbsolutePath(), loops); 79 | AssetPool.sounds.put(file.getAbsolutePath(), sound); 80 | return sound; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/physics2d/JadeContactListener.java: -------------------------------------------------------------------------------- 1 | package physics2d; 2 | 3 | import components.Component; 4 | import jade.GameObject; 5 | import org.jbox2d.callbacks.ContactImpulse; 6 | import org.jbox2d.callbacks.ContactListener; 7 | import org.jbox2d.collision.Manifold; 8 | import org.jbox2d.collision.WorldManifold; 9 | import org.jbox2d.dynamics.contacts.Contact; 10 | import org.joml.Vector2f; 11 | 12 | public class JadeContactListener implements ContactListener { 13 | @Override 14 | public void beginContact(Contact contact) { 15 | GameObject objA = (GameObject)contact.getFixtureA().getUserData(); 16 | GameObject objB = (GameObject)contact.getFixtureB().getUserData(); 17 | WorldManifold worldManifold = new WorldManifold(); 18 | contact.getWorldManifold(worldManifold); 19 | Vector2f aNormal = new Vector2f(worldManifold.normal.x, worldManifold.normal.y); 20 | Vector2f bNormal = new Vector2f(aNormal).negate(); 21 | 22 | for (Component c : objA.getAllComponents()) { 23 | c.beginCollision(objB, contact, aNormal); 24 | } 25 | 26 | for (Component c : objB.getAllComponents()) { 27 | c.beginCollision(objA, contact, bNormal); 28 | } 29 | } 30 | 31 | @Override 32 | public void endContact(Contact contact) { 33 | GameObject objA = (GameObject)contact.getFixtureA().getUserData(); 34 | GameObject objB = (GameObject)contact.getFixtureB().getUserData(); 35 | WorldManifold worldManifold = new WorldManifold(); 36 | contact.getWorldManifold(worldManifold); 37 | Vector2f aNormal = new Vector2f(worldManifold.normal.x, worldManifold.normal.y); 38 | Vector2f bNormal = new Vector2f(aNormal).negate(); 39 | 40 | for (Component c : objA.getAllComponents()) { 41 | c.endCollision(objB, contact, aNormal); 42 | } 43 | 44 | for (Component c : objB.getAllComponents()) { 45 | c.endCollision(objA, contact, bNormal); 46 | } 47 | } 48 | 49 | @Override 50 | public void preSolve(Contact contact, Manifold manifold) { 51 | GameObject objA = (GameObject)contact.getFixtureA().getUserData(); 52 | GameObject objB = (GameObject)contact.getFixtureB().getUserData(); 53 | WorldManifold worldManifold = new WorldManifold(); 54 | contact.getWorldManifold(worldManifold); 55 | Vector2f aNormal = new Vector2f(worldManifold.normal.x, worldManifold.normal.y); 56 | Vector2f bNormal = new Vector2f(aNormal).negate(); 57 | 58 | for (Component c : objA.getAllComponents()) { 59 | c.preSolve(objB, contact, aNormal); 60 | } 61 | 62 | for (Component c : objB.getAllComponents()) { 63 | c.preSolve(objA, contact, bNormal); 64 | } 65 | } 66 | 67 | @Override 68 | public void postSolve(Contact contact, ContactImpulse contactImpulse) { 69 | GameObject objA = (GameObject)contact.getFixtureA().getUserData(); 70 | GameObject objB = (GameObject)contact.getFixtureB().getUserData(); 71 | WorldManifold worldManifold = new WorldManifold(); 72 | contact.getWorldManifold(worldManifold); 73 | Vector2f aNormal = new Vector2f(worldManifold.normal.x, worldManifold.normal.y); 74 | Vector2f bNormal = new Vector2f(aNormal).negate(); 75 | 76 | for (Component c : objA.getAllComponents()) { 77 | c.postSolve(objB, contact, aNormal); 78 | } 79 | 80 | for (Component c : objB.getAllComponents()) { 81 | c.postSolve(objA, contact, bNormal); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/rigidbody/Rigidbody2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp.rigidbody; 2 | 3 | import components.Component; 4 | import jade.Transform; 5 | import org.joml.Vector2f; 6 | import physics2dtmp.primitives.Collider2D; 7 | 8 | public class Rigidbody2D extends Component { 9 | private Transform rawTransform; 10 | private Collider2D collider; 11 | 12 | private Vector2f position = new Vector2f(); 13 | private float rotation = 0.0f; 14 | private float mass = 0.0f; 15 | private float inverseMass = 0.0f; 16 | 17 | private Vector2f forceAccum = new Vector2f(); 18 | private Vector2f linearVelocity = new Vector2f(); 19 | private float angularVelocity = 0.0f; 20 | private float linearDamping = 0.0f; 21 | private float angularDamping = 0.0f; 22 | 23 | // Coefficient of restitution 24 | private float cor = 1.0f; 25 | 26 | private boolean fixedRotation = false; 27 | 28 | public Vector2f getPosition() { 29 | return position; 30 | } 31 | 32 | public void physicsUpdate(float dt) { 33 | if (this.mass == 0.0f) return; 34 | 35 | // Calculate linear velocity 36 | Vector2f acceleration = new Vector2f(forceAccum).mul(this.inverseMass); 37 | linearVelocity.add(acceleration.mul(dt)); 38 | 39 | // Update the linear position 40 | this.position.add(new Vector2f(linearVelocity).mul(dt)); 41 | 42 | synchCollisionTransforms(); 43 | clearAccumulators(); 44 | } 45 | 46 | public void synchCollisionTransforms() { 47 | if (rawTransform != null) { 48 | rawTransform.position.set(this.position); 49 | } 50 | } 51 | 52 | public void clearAccumulators() { 53 | this.forceAccum.zero(); 54 | } 55 | 56 | public void setTransform(Vector2f position, float rotation) { 57 | this.position.set(position); 58 | this.rotation = rotation; 59 | } 60 | 61 | public void setTransform(Vector2f position) { 62 | this.position.set(position); 63 | } 64 | 65 | public void setVelocity(Vector2f velocity) { 66 | this.linearVelocity.set(velocity); 67 | } 68 | 69 | public Vector2f getVelocity() { 70 | return this.linearVelocity; 71 | } 72 | 73 | public float getRotation() { 74 | return rotation; 75 | } 76 | 77 | public float getMass() { 78 | return mass; 79 | } 80 | 81 | public float getInverseMass() { 82 | return this.inverseMass; 83 | } 84 | 85 | public void setMass(float mass) { 86 | this.mass = mass; 87 | if (this.mass != 0.0f) { 88 | this.inverseMass = 1.0f / this.mass; 89 | } 90 | } 91 | 92 | public boolean hasInfiniteMass() { 93 | return this.mass == 0.0f; 94 | } 95 | 96 | public void addForce(Vector2f force) { 97 | this.forceAccum.add(force); 98 | } 99 | 100 | public void setRawTransform(Transform rawTransform) { 101 | this.rawTransform = rawTransform; 102 | this.position.set(rawTransform.position); 103 | } 104 | 105 | public void setCollider(Collider2D collider) { 106 | this.collider = collider; 107 | } 108 | 109 | public Collider2D getCollider() { 110 | return this.collider; 111 | } 112 | 113 | public float getCor() { 114 | return cor; 115 | } 116 | 117 | public void setCor(float cor) { 118 | this.cor = cor; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/renderer/PickingTexture.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import org.joml.Vector2i; 4 | 5 | import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; 6 | import static org.lwjgl.opengl.GL14.GL_DEPTH_COMPONENT32; 7 | import static org.lwjgl.opengl.GL30.*; 8 | import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER; 9 | 10 | public class PickingTexture { 11 | private int pickingTextureId; 12 | private int fbo; 13 | private int depthTexture; 14 | 15 | public PickingTexture(int width, int height) { 16 | if (!init(width, height)) { 17 | assert false : "Error initializing picking texture"; 18 | } 19 | } 20 | 21 | public boolean init(int width, int height) { 22 | // Generate framebuffer 23 | fbo = glGenFramebuffers(); 24 | glBindFramebuffer(GL_FRAMEBUFFER, fbo); 25 | 26 | // Create the texture to render the data to, and attach it to our framebuffer 27 | pickingTextureId = glGenTextures(); 28 | glBindTexture(GL_TEXTURE_2D, pickingTextureId); 29 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 30 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 31 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 32 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 33 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, 34 | GL_RGB, GL_FLOAT, 0); 35 | glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 36 | this.pickingTextureId, 0); 37 | 38 | // Create the texture object for the depth buffer 39 | glEnable(GL_TEXTURE_2D); 40 | depthTexture = glGenTextures(); 41 | glBindTexture(GL_TEXTURE_2D, depthTexture); 42 | glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, 43 | GL_DEPTH_COMPONENT, GL_FLOAT, 0); 44 | glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, 45 | GL_TEXTURE_2D, depthTexture, 0); 46 | 47 | // Disable the reading 48 | glReadBuffer(GL_NONE); 49 | glDrawBuffer(GL_COLOR_ATTACHMENT0); 50 | 51 | if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { 52 | assert false : "Error: Framebuffer is not complete"; 53 | return false; 54 | } 55 | 56 | // Unbind the texture and framebuffer 57 | glBindTexture(GL_TEXTURE_2D, 0); 58 | glBindFramebuffer(GL_FRAMEBUFFER, 0); 59 | return true; 60 | } 61 | 62 | public void enableWriting() { 63 | glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); 64 | } 65 | 66 | public void disableWriting() { 67 | glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); 68 | } 69 | 70 | public int readPixel(int x, int y) { 71 | glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); 72 | glReadBuffer(GL_COLOR_ATTACHMENT0); 73 | 74 | float pixels[] = new float[3]; 75 | glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, pixels); 76 | 77 | return (int)(pixels[0]) - 1; 78 | } 79 | 80 | public float[] readPixels(Vector2i start, Vector2i end) { 81 | glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); 82 | glReadBuffer(GL_COLOR_ATTACHMENT0); 83 | 84 | Vector2i size = new Vector2i(end).sub(start).absolute(); 85 | int numPixels = size.x * size.y; 86 | float pixels[] = new float[3 * numPixels]; 87 | glReadPixels(start.x, start.y, size.x, size.y, GL_RGB, GL_FLOAT, pixels); 88 | for (int i = 0; i < pixels.length; i++) { 89 | pixels[i] -= 1; 90 | } 91 | 92 | return pixels; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/renderer/Texture.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import org.lwjgl.BufferUtils; 4 | 5 | import java.nio.ByteBuffer; 6 | import java.nio.IntBuffer; 7 | 8 | import static org.lwjgl.opengl.GL11.*; 9 | import static org.lwjgl.stb.STBImage.*; 10 | 11 | public class Texture { 12 | private String filepath; 13 | private transient int texID; 14 | private int width, height; 15 | 16 | public Texture() { 17 | texID = -1; 18 | width = -1; 19 | height = -1; 20 | } 21 | 22 | public Texture(int width, int height) { 23 | this.filepath = "Generated"; 24 | 25 | // Generate texture on GPU 26 | texID = glGenTextures(); 27 | glBindTexture(GL_TEXTURE_2D, texID); 28 | 29 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 30 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 31 | 32 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 33 | 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 34 | } 35 | 36 | public void init(String filepath) { 37 | this.filepath = filepath; 38 | 39 | // Generate texture on GPU 40 | texID = glGenTextures(); 41 | glBindTexture(GL_TEXTURE_2D, texID); 42 | 43 | // Set texture parameters 44 | // Repeat image in both directions 45 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 46 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 47 | // When stretching the image, pixelate 48 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 49 | // When shrinking an image, pixelate 50 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 51 | 52 | IntBuffer width = BufferUtils.createIntBuffer(1); 53 | IntBuffer height = BufferUtils.createIntBuffer(1); 54 | IntBuffer channels = BufferUtils.createIntBuffer(1); 55 | stbi_set_flip_vertically_on_load(true); 56 | ByteBuffer image = stbi_load(filepath, width, height, channels, 0); 57 | 58 | if (image != null) { 59 | this.width = width.get(0); 60 | this.height = height.get(0); 61 | 62 | if (channels.get(0) == 3) { 63 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width.get(0), height.get(0), 64 | 0, GL_RGB, GL_UNSIGNED_BYTE, image); 65 | } else if (channels.get(0) == 4) { 66 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width.get(0), height.get(0), 67 | 0, GL_RGBA, GL_UNSIGNED_BYTE, image); 68 | } else { 69 | assert false : "Error: (Texture) Unknown number of channesl '" + channels.get(0) + "'"; 70 | } 71 | } else { 72 | assert false : "Error: (Texture) Could not load image '" + filepath + "'"; 73 | } 74 | 75 | stbi_image_free(image); 76 | } 77 | 78 | public void bind() { 79 | glBindTexture(GL_TEXTURE_2D, texID); 80 | } 81 | 82 | public void unbind() { 83 | glBindTexture(GL_TEXTURE_2D, 0); 84 | } 85 | 86 | public int getWidth() { 87 | return this.width; 88 | } 89 | 90 | public String getFilepath() { 91 | return this.filepath; 92 | } 93 | 94 | public int getHeight() { 95 | return this.height; 96 | } 97 | 98 | public int getId() { 99 | return texID; 100 | } 101 | 102 | @Override 103 | public boolean equals(Object o) { 104 | if (o == null) return false; 105 | if (!(o instanceof Texture)) return false; 106 | Texture oTex = (Texture)o; 107 | return oTex.getWidth() == this.width && oTex.getHeight() == this.height && 108 | oTex.getId() == this.texID && 109 | oTex.getFilepath().equals(this.filepath); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/components/KeyControls.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.PropertiesWindow; 4 | import jade.GameObject; 5 | import jade.KeyListener; 6 | import jade.Window; 7 | import util.Settings; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import static org.lwjgl.glfw.GLFW.*; 13 | 14 | public class KeyControls extends Component { 15 | private float debounceTime = 0.2f; 16 | private float debounce = 0.0f; 17 | 18 | @Override 19 | public void editorUpdate(float dt) { 20 | debounce -= dt; 21 | 22 | PropertiesWindow propertiesWindow = Window.getImguiLayer().getPropertiesWindow(); 23 | GameObject activeGameObject = propertiesWindow.getActiveGameObject(); 24 | List activeGameObjects = propertiesWindow.getActiveGameObjects(); 25 | float multiplier = KeyListener.isKeyPressed(GLFW_KEY_LEFT_SHIFT) ? 0.1f : 1.0f; 26 | 27 | if (KeyListener.isKeyPressed(GLFW_KEY_LEFT_CONTROL) && 28 | KeyListener.keyBeginPress(GLFW_KEY_D) && activeGameObject != null) { 29 | GameObject newObj = activeGameObject.copy(); 30 | Window.getScene().addGameObjectToScene(newObj); 31 | newObj.transform.position.add(Settings.GRID_WIDTH, 0.0f); 32 | propertiesWindow.setActiveGameObject(newObj); 33 | if (newObj.getComponent(StateMachine.class) != null) { 34 | newObj.getComponent(StateMachine.class).refreshTextures(); 35 | } 36 | } else if (KeyListener.isKeyPressed(GLFW_KEY_LEFT_CONTROL) && 37 | KeyListener.keyBeginPress(GLFW_KEY_D) && activeGameObjects.size() > 1) { 38 | List gameObjects = new ArrayList<>(activeGameObjects); 39 | propertiesWindow.clearSelected(); 40 | for (GameObject go : gameObjects) { 41 | GameObject copy = go.copy(); 42 | Window.getScene().addGameObjectToScene(copy); 43 | propertiesWindow.addActiveGameObject(copy); 44 | if (copy.getComponent(StateMachine.class) != null) { 45 | copy.getComponent(StateMachine.class).refreshTextures(); 46 | } 47 | } 48 | } else if (KeyListener.keyBeginPress(GLFW_KEY_DELETE)) { 49 | for (GameObject go : activeGameObjects) { 50 | go.destroy(); 51 | } 52 | propertiesWindow.clearSelected(); 53 | } else if (KeyListener.isKeyPressed(GLFW_KEY_PAGE_DOWN) && debounce < 0) { 54 | debounce = debounceTime; 55 | for (GameObject go : activeGameObjects) { 56 | go.transform.zIndex--; 57 | } 58 | } else if (KeyListener.isKeyPressed(GLFW_KEY_PAGE_UP) && debounce < 0) { 59 | debounce = debounceTime; 60 | for (GameObject go : activeGameObjects) { 61 | go.transform.zIndex++; 62 | } 63 | } else if (KeyListener.isKeyPressed(GLFW_KEY_UP) && debounce < 0) { 64 | debounce = debounceTime; 65 | for (GameObject go : activeGameObjects) { 66 | go.transform.position.y += Settings.GRID_HEIGHT * multiplier; 67 | } 68 | } else if (KeyListener.isKeyPressed(GLFW_KEY_LEFT) && debounce < 0) { 69 | debounce = debounceTime; 70 | for (GameObject go : activeGameObjects) { 71 | go.transform.position.x -= Settings.GRID_HEIGHT * multiplier; 72 | } 73 | } else if (KeyListener.isKeyPressed(GLFW_KEY_RIGHT) && debounce < 0) { 74 | debounce = debounceTime; 75 | for (GameObject go : activeGameObjects) { 76 | go.transform.position.x += Settings.GRID_HEIGHT * multiplier; 77 | } 78 | } else if (KeyListener.isKeyPressed(GLFW_KEY_DOWN) && debounce < 0) { 79 | debounce = debounceTime; 80 | for (GameObject go : activeGameObjects) { 81 | go.transform.position.y -= Settings.GRID_HEIGHT * multiplier; 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | 6 | testiamgui 7 | testiamgui 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | testiamgui 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 12 17 | 12 18 | 3.2.3 19 | 1.9.24 20 | natives-windows 21 | 22 | 23 | 24 | 25 | 26 | org.lwjgl 27 | lwjgl-bom 28 | ${lwjgl.version} 29 | import 30 | pom 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | io.imgui.java 39 | binding 40 | 1.76-0.9 41 | 42 | 43 | io.imgui.java 44 | lwjgl3 45 | 1.76-0.9 46 | 47 | 48 | io.imgui.java 49 | natives-windows 50 | 1.76-0.9 51 | 52 | 53 | 54 | org.lwjgl 55 | lwjgl 56 | 57 | 58 | org.lwjgl 59 | lwjgl-nfd 60 | 61 | 62 | org.lwjgl 63 | lwjgl-assimp 64 | 65 | 66 | org.lwjgl 67 | lwjgl-glfw 68 | 69 | 70 | org.lwjgl 71 | lwjgl-openal 72 | 73 | 74 | org.lwjgl 75 | lwjgl-opengl 76 | 77 | 78 | org.lwjgl 79 | lwjgl-stb 80 | 81 | 82 | org.lwjgl 83 | lwjgl 84 | ${lwjgl.natives} 85 | 86 | 87 | org.lwjgl 88 | lwjgl-assimp 89 | ${lwjgl.natives} 90 | 91 | 92 | org.lwjgl 93 | lwjgl-glfw 94 | ${lwjgl.natives} 95 | 96 | 97 | org.lwjgl 98 | lwjgl-openal 99 | ${lwjgl.natives} 100 | 101 | 102 | org.lwjgl 103 | lwjgl-opengl 104 | ${lwjgl.natives} 105 | 106 | 107 | org.lwjgl 108 | lwjgl-stb 109 | ${lwjgl.natives} 110 | 111 | 112 | org.lwjgl 113 | lwjgl-nfd 114 | ${lwjgl.natives} 115 | 116 | 117 | org.joml 118 | joml 119 | ${joml.version} 120 | 121 | 122 | 123 | 124 | 125 | central 126 | bintray-plugins 127 | https://jcenter.bintray.com 128 | 129 | 130 | 131 | 132 | -------------------------------------------------------------------------------- /src/main/java/editor/PropertiesWindow.java: -------------------------------------------------------------------------------- 1 | package editor; 2 | 3 | import components.NonPickable; 4 | import components.SpriteRenderer; 5 | import imgui.ImGui; 6 | import jade.GameObject; 7 | import jade.MouseListener; 8 | import org.joml.Vector4f; 9 | import physics2d.components.Box2DCollider; 10 | import physics2d.components.CircleCollider; 11 | import physics2d.components.Rigidbody2D; 12 | import renderer.PickingTexture; 13 | import scenes.Scene; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT; 19 | 20 | public class PropertiesWindow { 21 | private List activeGameObjects; 22 | private List activeGameObjectsOgColor; 23 | private GameObject activeGameObject = null; 24 | private PickingTexture pickingTexture; 25 | 26 | public PropertiesWindow(PickingTexture pickingTexture) { 27 | this.activeGameObjects = new ArrayList<>(); 28 | this.pickingTexture = pickingTexture; 29 | this.activeGameObjectsOgColor = new ArrayList<>(); 30 | } 31 | 32 | public void imgui() { 33 | if (activeGameObjects.size() == 1 && activeGameObjects.get(0) != null) { 34 | activeGameObject = activeGameObjects.get(0); 35 | ImGui.begin("Properties"); 36 | 37 | if (ImGui.beginPopupContextWindow("ComponentAdder")) { 38 | if (ImGui.menuItem("Add Rigidbody")) { 39 | if (activeGameObject.getComponent(Rigidbody2D.class) == null) { 40 | activeGameObject.addComponent(new Rigidbody2D()); 41 | } 42 | } 43 | 44 | if (ImGui.menuItem("Add Box Collider")) { 45 | if (activeGameObject.getComponent(Box2DCollider.class) == null && 46 | activeGameObject.getComponent(CircleCollider.class) == null) { 47 | activeGameObject.addComponent(new Box2DCollider()); 48 | } 49 | } 50 | 51 | if (ImGui.menuItem("Add Circle Collider")) { 52 | if (activeGameObject.getComponent(CircleCollider.class) == null && 53 | activeGameObject.getComponent(Box2DCollider.class) == null) { 54 | activeGameObject.addComponent(new CircleCollider()); 55 | } 56 | } 57 | 58 | ImGui.endPopup(); 59 | } 60 | 61 | activeGameObject.imgui(); 62 | ImGui.end(); 63 | } 64 | } 65 | 66 | public GameObject getActiveGameObject() { 67 | return activeGameObjects.size() == 1 ? this.activeGameObjects.get(0) : 68 | null; 69 | } 70 | 71 | public List getActiveGameObjects() { 72 | return this.activeGameObjects; 73 | } 74 | 75 | public void clearSelected() { 76 | if (activeGameObjectsOgColor.size() > 0) { 77 | int i = 0; 78 | for (GameObject go : activeGameObjects) { 79 | SpriteRenderer spr = go.getComponent(SpriteRenderer.class); 80 | if (spr != null) { 81 | spr.setColor(activeGameObjectsOgColor.get(i)); 82 | } 83 | i++; 84 | } 85 | } 86 | this.activeGameObjects.clear(); 87 | this.activeGameObjectsOgColor.clear(); 88 | } 89 | 90 | public void setActiveGameObject(GameObject go) { 91 | if (go != null) { 92 | clearSelected(); 93 | this.activeGameObjects.add(go); 94 | } 95 | } 96 | 97 | public void addActiveGameObject(GameObject go) { 98 | SpriteRenderer spr = go.getComponent(SpriteRenderer.class); 99 | if (spr != null ) { 100 | this.activeGameObjectsOgColor.add(new Vector4f(spr.getColor())); 101 | spr.setColor(new Vector4f(0.8f, 0.8f, 0.0f, 0.8f)); 102 | } else { 103 | this.activeGameObjectsOgColor.add(new Vector4f()); 104 | } 105 | this.activeGameObjects.add(go); 106 | } 107 | 108 | public PickingTexture getPickingTexture() { 109 | return this.pickingTexture; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/scenes/LevelSceneInitializer.java: -------------------------------------------------------------------------------- 1 | package scenes; 2 | 3 | import components.*; 4 | import imgui.ImGui; 5 | import imgui.ImVec2; 6 | import jade.*; 7 | import org.joml.Vector2f; 8 | import physics2d.components.Box2DCollider; 9 | import physics2d.components.Rigidbody2D; 10 | import physics2d.enums.BodyType; 11 | import util.AssetPool; 12 | 13 | import java.io.File; 14 | import java.util.Collection; 15 | 16 | public class LevelSceneInitializer extends SceneInitializer { 17 | public LevelSceneInitializer() { 18 | 19 | } 20 | 21 | @Override 22 | public void init(Scene scene) { 23 | Spritesheet sprites = AssetPool.getSpritesheet("assets/images/spritesheets/decorationsAndBlocks.png"); 24 | 25 | GameObject cameraObject = scene.createGameObject("GameCamera"); 26 | cameraObject.addComponent(new GameCamera(scene.camera())); 27 | cameraObject.start(); 28 | scene.addGameObjectToScene(cameraObject); 29 | } 30 | 31 | @Override 32 | public void loadResources(Scene scene) { 33 | AssetPool.getShader("assets/shaders/default.glsl"); 34 | 35 | AssetPool.addSpritesheet("assets/images/spritesheets/decorationsAndBlocks.png", 36 | new Spritesheet(AssetPool.getTexture("assets/images/spritesheets/decorationsAndBlocks.png"), 37 | 16, 16, 81, 0)); 38 | AssetPool.addSpritesheet("assets/images/spritesheet.png", 39 | new Spritesheet(AssetPool.getTexture("assets/images/spritesheet.png"), 40 | 16, 16, 26, 0)); 41 | AssetPool.addSpritesheet("assets/images/turtle.png", 42 | new Spritesheet(AssetPool.getTexture("assets/images/turtle.png"), 43 | 16, 24, 4, 0)); 44 | AssetPool.addSpritesheet("assets/images/bigSpritesheet.png", 45 | new Spritesheet(AssetPool.getTexture("assets/images/bigSpritesheet.png"), 46 | 16, 32, 42, 0)); 47 | AssetPool.addSpritesheet("assets/images/pipes.png", 48 | new Spritesheet(AssetPool.getTexture("assets/images/pipes.png"), 49 | 32, 32, 4, 0)); 50 | AssetPool.addSpritesheet("assets/images/items.png", 51 | new Spritesheet(AssetPool.getTexture("assets/images/items.png"), 52 | 16, 16, 43, 0)); 53 | AssetPool.addSpritesheet("assets/images/gizmos.png", 54 | new Spritesheet(AssetPool.getTexture("assets/images/gizmos.png"), 55 | 24, 48, 3, 0)); 56 | AssetPool.getTexture("assets/images/blendImage2.png"); 57 | 58 | AssetPool.addSound("assets/sounds/main-theme-overworld.ogg", true); 59 | AssetPool.addSound("assets/sounds/flagpole.ogg", false); 60 | AssetPool.addSound("assets/sounds/break_block.ogg", false); 61 | AssetPool.addSound("assets/sounds/bump.ogg", false); 62 | AssetPool.addSound("assets/sounds/coin.ogg", false); 63 | AssetPool.addSound("assets/sounds/gameover.ogg", false); 64 | AssetPool.addSound("assets/sounds/jump-small.ogg", false); 65 | AssetPool.addSound("assets/sounds/mario_die.ogg", false); 66 | AssetPool.addSound("assets/sounds/pipe.ogg", false); 67 | AssetPool.addSound("assets/sounds/powerup.ogg", false); 68 | AssetPool.addSound("assets/sounds/powerup_appears.ogg", false); 69 | AssetPool.addSound("assets/sounds/stage_clear.ogg", false); 70 | AssetPool.addSound("assets/sounds/stomp.ogg", false); 71 | AssetPool.addSound("assets/sounds/kick.ogg", false); 72 | AssetPool.addSound("assets/sounds/invincible.ogg", false); 73 | 74 | AssetPool.getSound(("assets/sounds/main-theme-overworld.ogg")).play(); 75 | 76 | for (GameObject g : scene.getGameObjects()) { 77 | if (g.getComponent(SpriteRenderer.class) != null) { 78 | SpriteRenderer spr = g.getComponent(SpriteRenderer.class); 79 | if (spr.getTexture() != null) { 80 | spr.setTexture(AssetPool.getTexture(spr.getTexture().getFilepath())); 81 | } 82 | } 83 | 84 | if (g.getComponent(StateMachine.class) != null) { 85 | StateMachine stateMachine = g.getComponent(StateMachine.class); 86 | stateMachine.refreshTextures(); 87 | } 88 | } 89 | } 90 | 91 | @Override 92 | public void imgui() { 93 | 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/components/GoombaAI.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.GameObject; 5 | import jade.Window; 6 | import org.jbox2d.dynamics.contacts.Contact; 7 | import org.joml.Vector2f; 8 | import physics2d.Physics2D; 9 | import physics2d.components.Rigidbody2D; 10 | import util.AssetPool; 11 | 12 | public class GoombaAI extends Component { 13 | 14 | private transient boolean goingRight = false; 15 | private transient Rigidbody2D rb; 16 | private transient float walkSpeed = 0.6f; 17 | private transient Vector2f velocity = new Vector2f(); 18 | private transient Vector2f acceleration = new Vector2f(); 19 | private transient Vector2f terminalVelocity = new Vector2f(); 20 | private transient boolean onGround = false; 21 | private transient boolean isDead = false; 22 | private transient float timeToKill = 0.5f; 23 | private transient StateMachine stateMachine; 24 | 25 | @Override 26 | public void start() { 27 | this.stateMachine = gameObject.getComponent(StateMachine.class); 28 | this.rb = gameObject.getComponent(Rigidbody2D.class); 29 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 30 | } 31 | 32 | @Override 33 | public void update(float dt) { 34 | Camera camera = Window.getScene().camera(); 35 | if (this.gameObject.transform.position.x > 36 | camera.position.x + camera.getProjectionSize().x * camera.getZoom()) { 37 | return; 38 | } 39 | 40 | if (isDead) { 41 | timeToKill -= dt; 42 | if (timeToKill <= 0) { 43 | this.gameObject.destroy(); 44 | } 45 | this.rb.setVelocity(new Vector2f()); 46 | return; 47 | } 48 | 49 | if (goingRight) { 50 | velocity.x = walkSpeed; 51 | } else { 52 | velocity.x = -walkSpeed; 53 | } 54 | 55 | checkOnGround(); 56 | if (onGround) { 57 | this.acceleration.y = 0; 58 | this.velocity.y = 0; 59 | } else { 60 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 61 | } 62 | 63 | this.velocity.y += this.acceleration.y * dt; 64 | this.velocity.y = Math.max(Math.min(this.velocity.y, this.terminalVelocity.y), -terminalVelocity.y); 65 | this.rb.setVelocity(velocity); 66 | if (this.gameObject.transform.position.x < Window.getScene().camera().position.x - 0.5f) { 67 | this.gameObject.destroy(); 68 | } 69 | } 70 | 71 | public void checkOnGround() { 72 | float innerPlayerWidth = 0.25f * 0.7f; 73 | float yVal = -0.14f; 74 | onGround = Physics2D.checkOnGround(this.gameObject, innerPlayerWidth, yVal); 75 | } 76 | 77 | @Override 78 | public void preSolve(GameObject obj, Contact contact, Vector2f contactNormal) { 79 | if (isDead) { 80 | return; 81 | } 82 | 83 | PlayerController playerController = obj.getComponent(PlayerController.class); 84 | if (playerController != null) { 85 | if (!playerController.isDead() && !playerController.isHurtInvincible() && 86 | contactNormal.y > 0.58f) { 87 | playerController.enemyBounce(); 88 | stomp(); 89 | } else if (!playerController.isDead() && !playerController.isInvincible()) { 90 | playerController.die(); 91 | if (!playerController.isDead()) { 92 | contact.setEnabled(false); 93 | } 94 | } else if (!playerController.isDead() && playerController.isInvincible()) { 95 | contact.setEnabled(false); 96 | } 97 | } else if (Math.abs(contactNormal.y) < 0.1f) { 98 | goingRight = contactNormal.x < 0; 99 | } 100 | 101 | if (obj.getComponent(Fireball.class) != null) { 102 | stomp(); 103 | obj.getComponent(Fireball.class).disappear(); 104 | } 105 | } 106 | 107 | public void stomp() { 108 | stomp(true); 109 | } 110 | 111 | public void stomp(boolean playSound) { 112 | this.isDead = true; 113 | this.velocity.zero(); 114 | this.rb.setVelocity(new Vector2f()); 115 | this.rb.setAngularVelocity(0.0f); 116 | this.rb.setGravityScale(0.0f); 117 | this.stateMachine.trigger("squashMe"); 118 | this.rb.setIsSensor(); 119 | if (playSound) { 120 | AssetPool.getSound("assets/sounds/bump.ogg").play(); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/jade/GameObject.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import components.Component; 6 | import components.ComponentDeserializer; 7 | import components.SpriteRenderer; 8 | import imgui.ImGui; 9 | import util.AssetPool; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class GameObject { 15 | private static int ID_COUNTER = 0; 16 | private int uid = -1; 17 | 18 | public String name; 19 | private List components; 20 | public transient Transform transform; 21 | private boolean doSerialization = true; 22 | private boolean isDead = false; 23 | 24 | public GameObject(String name) { 25 | this.name = name; 26 | this.components = new ArrayList<>(); 27 | 28 | this.uid = ID_COUNTER++; 29 | } 30 | 31 | public T getComponent(Class componentClass) { 32 | for (Component c : components) { 33 | if (componentClass.isAssignableFrom(c.getClass())) { 34 | try { 35 | return componentClass.cast(c); 36 | } catch (ClassCastException e) { 37 | e.printStackTrace(); 38 | assert false : "Error: Casting component."; 39 | } 40 | } 41 | } 42 | 43 | return null; 44 | } 45 | 46 | public void removeComponent(Class componentClass) { 47 | for (int i=0; i < components.size(); i++) { 48 | Component c = components.get(i); 49 | if (componentClass.isAssignableFrom(c.getClass())) { 50 | components.remove(i); 51 | return; 52 | } 53 | } 54 | } 55 | 56 | public void addComponent(Component c) { 57 | c.generateId(); 58 | this.components.add(c); 59 | c.gameObject = this; 60 | } 61 | 62 | public void update(float dt) { 63 | for (int i=0; i < components.size(); i++) { 64 | components.get(i).update(dt); 65 | } 66 | } 67 | 68 | public void editorUpdate(float dt) { 69 | for (int i=0; i < components.size(); i++) { 70 | components.get(i).editorUpdate(dt); 71 | } 72 | } 73 | 74 | public void start() { 75 | for (int i=0; i < components.size(); i++) { 76 | components.get(i).start(); 77 | } 78 | } 79 | 80 | public void imgui() { 81 | for (Component c : components) { 82 | if (ImGui.collapsingHeader(c.getClass().getSimpleName())) 83 | c.imgui(); 84 | } 85 | } 86 | 87 | public void destroy() { 88 | this.isDead = true; 89 | for (int i=0; i < components.size(); i++) { 90 | components.get(i).destroy(); 91 | } 92 | } 93 | 94 | public GameObject copy() { 95 | // TODO: come up with cleaner solution 96 | Gson gson = new GsonBuilder() 97 | .registerTypeAdapter(Component.class, new ComponentDeserializer()) 98 | .registerTypeAdapter(GameObject.class, new GameObjectDeserializer()) 99 | .enableComplexMapKeySerialization() 100 | .create(); 101 | String objAsJson = gson.toJson(this); 102 | GameObject obj = gson.fromJson(objAsJson, GameObject.class); 103 | 104 | obj.generateUid(); 105 | for (Component c : obj.getAllComponents()) { 106 | c.generateId(); 107 | } 108 | 109 | SpriteRenderer sprite = obj.getComponent(SpriteRenderer.class); 110 | if (sprite != null && sprite.getTexture() != null) { 111 | sprite.setTexture(AssetPool.getTexture(sprite.getTexture().getFilepath())); 112 | } 113 | 114 | return obj; 115 | } 116 | 117 | public boolean isDead() { 118 | return this.isDead; 119 | } 120 | 121 | public static void init(int maxId) { 122 | ID_COUNTER = maxId; 123 | } 124 | 125 | public int getUid() { 126 | return this.uid; 127 | } 128 | 129 | public List getAllComponents() { 130 | return this.components; 131 | } 132 | 133 | public void setNoSerialize() { 134 | this.doSerialization = false; 135 | } 136 | 137 | public void generateUid() { 138 | this.uid = ID_COUNTER++; 139 | } 140 | 141 | public boolean doSerialization() { 142 | return this.doSerialization; 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/components/StateMachine.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import imgui.ImGui; 4 | import imgui.type.ImString; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Objects; 10 | 11 | public class StateMachine extends Component { 12 | private class StateTrigger { 13 | public String state; 14 | public String trigger; 15 | 16 | public StateTrigger() {} 17 | 18 | public StateTrigger(String state, String trigger) { 19 | this.state = state; 20 | this.trigger = trigger; 21 | } 22 | 23 | @Override 24 | public boolean equals(Object o) { 25 | if (o.getClass() != StateTrigger.class) return false; 26 | StateTrigger t2 = (StateTrigger)o; 27 | return t2.trigger.equals(this.trigger) && t2.state.equals(this.state); 28 | } 29 | 30 | @Override 31 | public int hashCode() { 32 | return Objects.hash(state, trigger); 33 | } 34 | } 35 | 36 | public HashMap stateTransfers = new HashMap<>(); 37 | private List states = new ArrayList<>(); 38 | private transient AnimationState currentState = null; 39 | private String defaultStateTitle = ""; 40 | 41 | public void refreshTextures() { 42 | for (AnimationState state : states) { 43 | state.refreshTextures(); 44 | } 45 | } 46 | 47 | public void setDefaultState(String animationTitle) { 48 | for (AnimationState state : states) { 49 | if (state.title.equals(animationTitle)) { 50 | defaultStateTitle = animationTitle; 51 | if (currentState == null) { 52 | currentState = state; 53 | } 54 | return; 55 | } 56 | } 57 | 58 | System.out.println("Unable to find default state '" + animationTitle + "'"); 59 | } 60 | 61 | public void addState(String from, String to, String onTrigger) { 62 | this.stateTransfers.put(new StateTrigger(from, onTrigger), to); 63 | } 64 | 65 | public void addState(AnimationState state) { 66 | this.states.add(state); 67 | } 68 | 69 | public void trigger(String trigger) { 70 | for (StateTrigger state : stateTransfers.keySet()) { 71 | if (state.state.equals(currentState.title) && state.trigger.equals(trigger)) { 72 | if (stateTransfers.get(state) != null) { 73 | int newStateIndex = stateIndexOf(stateTransfers.get(state)); 74 | if (newStateIndex > -1) { 75 | currentState = states.get(newStateIndex); 76 | } 77 | } 78 | return; 79 | } 80 | } 81 | } 82 | 83 | private int stateIndexOf(String stateTitle) { 84 | int index = 0; 85 | for (AnimationState state : states) { 86 | if (state.title.equals(stateTitle)) { 87 | return index; 88 | } 89 | index++; 90 | } 91 | 92 | return -1; 93 | } 94 | 95 | @Override 96 | public void start() { 97 | for (AnimationState state : states) { 98 | if (state.title.equals(defaultStateTitle)) { 99 | currentState = state; 100 | break; 101 | } 102 | } 103 | } 104 | 105 | @Override 106 | public void update(float dt) { 107 | if (currentState != null) { 108 | currentState.update(dt); 109 | SpriteRenderer sprite = gameObject.getComponent(SpriteRenderer.class); 110 | if (sprite != null) { 111 | sprite.setSprite(currentState.getCurrentSprite()); 112 | sprite.setTexture(currentState.getCurrentSprite().getTexture()); 113 | } 114 | } 115 | } 116 | 117 | @Override 118 | public void editorUpdate(float dt) { 119 | if (currentState != null) { 120 | currentState.update(dt); 121 | SpriteRenderer sprite = gameObject.getComponent(SpriteRenderer.class); 122 | if (sprite != null) { 123 | sprite.setSprite(currentState.getCurrentSprite()); 124 | sprite.setTexture(currentState.getCurrentSprite().getTexture()); 125 | } 126 | } 127 | } 128 | 129 | @Override 130 | public void imgui() { 131 | for (AnimationState state : states) { 132 | ImString title = new ImString(state.title); 133 | ImGui.inputText("State: ", title); 134 | state.title = title.get(); 135 | 136 | int index = 0; 137 | for (Frame frame : state.animationFrames) { 138 | float[] tmp = new float[1]; 139 | tmp[0] = frame.frameTime; 140 | ImGui.dragFloat("Frame(" + index + ") Time: ", tmp, 0.01f); 141 | frame.frameTime = tmp[0]; 142 | index++; 143 | } 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/main/java/physics2dtmp/PhysicsSystem2D.java: -------------------------------------------------------------------------------- 1 | package physics2dtmp; 2 | 3 | import org.joml.Vector2f; 4 | import physics2dtmp.forces.ForceRegistry; 5 | import physics2dtmp.forces.Gravity2D; 6 | import physics2dtmp.primitives.Collider2D; 7 | import physics2dtmp.rigidbody.CollisionManifold; 8 | import physics2dtmp.rigidbody.Collisions; 9 | import physics2dtmp.rigidbody.Rigidbody2D; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class PhysicsSystem2D { 15 | private ForceRegistry forceRegistry; 16 | private Gravity2D gravity; 17 | 18 | private List rigidbodies; 19 | private List bodies1; 20 | private List bodies2; 21 | private List collisions; 22 | 23 | private float fixedUpdate; 24 | private int impulseIterations = 6; 25 | 26 | public PhysicsSystem2D(float fixedUpdateDt, Vector2f gravity) { 27 | this.forceRegistry = new ForceRegistry(); 28 | this.gravity = new Gravity2D(gravity); 29 | 30 | this.rigidbodies = new ArrayList<>(); 31 | this.bodies1 = new ArrayList<>(); 32 | this.bodies2 = new ArrayList<>(); 33 | this.collisions = new ArrayList<>(); 34 | 35 | this.fixedUpdate = fixedUpdateDt; 36 | } 37 | 38 | public void update(float dt) { 39 | fixedUpdate(); 40 | } 41 | 42 | public void fixedUpdate() { 43 | bodies1.clear(); 44 | bodies2.clear(); 45 | collisions.clear(); 46 | 47 | // Find any collisions 48 | int size = rigidbodies.size(); 49 | for (int i=0; i < size; i++) { 50 | for (int j=i; j < size; j++) { 51 | if (i == j) continue; 52 | 53 | CollisionManifold result = new CollisionManifold(); 54 | Rigidbody2D r1 = rigidbodies.get(i); 55 | Rigidbody2D r2 = rigidbodies.get(j); 56 | Collider2D c1 = r1.getCollider(); 57 | Collider2D c2 = r2.getCollider(); 58 | 59 | if (c1 != null && c2 != null && !(r1.hasInfiniteMass() && r2.hasInfiniteMass())) { 60 | result = Collisions.findCollisionFeatures(c1, c2); 61 | } 62 | 63 | if (result != null && result.isColliding()) { 64 | bodies1.add(r1); 65 | bodies2.add(r2); 66 | collisions.add(result); 67 | } 68 | } 69 | } 70 | 71 | // Update the forces 72 | forceRegistry.updateForces(fixedUpdate); 73 | 74 | // Resolve collisions via iterative impulse resolution 75 | // iterate a certain amount of times to get an approximate solution 76 | for (int k=0; k < impulseIterations; k++) { 77 | for (int i=0; i < collisions.size(); i++) { 78 | int jSize = collisions.get(i).getContactPoints().size(); 79 | for (int j=0; j < jSize; j++) { 80 | Rigidbody2D r1 = bodies1.get(i); 81 | Rigidbody2D r2 = bodies2.get(i); 82 | applyImpulse(r1, r2, collisions.get(i)); 83 | } 84 | } 85 | } 86 | 87 | // Update the velocities of all rigidbodies 88 | for (int i=0; i < rigidbodies.size(); i++) { 89 | rigidbodies.get(i).physicsUpdate(fixedUpdate); 90 | } 91 | 92 | // Apply linear projection 93 | } 94 | 95 | private void applyImpulse(Rigidbody2D a, Rigidbody2D b, CollisionManifold m) { 96 | // Linear velocity 97 | float invMass1 = a.getInverseMass(); 98 | float invMass2 = b.getInverseMass(); 99 | float invMassSum = invMass1 + invMass2; 100 | if (invMassSum == 0f) { 101 | return; 102 | } 103 | 104 | // Relative velocity 105 | Vector2f relativeVel = new Vector2f(b.getVelocity()).sub(a.getVelocity()); 106 | Vector2f relativeNormal = new Vector2f(m.getNormal()).normalize(); 107 | // Moving away from each other? Do nothing 108 | if (relativeVel.dot(relativeNormal) > 0.0f) { 109 | return; 110 | } 111 | 112 | float e = Math.min(a.getCor(), b.getCor()); 113 | float numerator = (-(1.0f + e) * relativeVel.dot(relativeNormal)); 114 | float j = numerator / invMassSum; 115 | if (m.getContactPoints().size() > 0 && j != 0.0f) { 116 | j /= (float)m.getContactPoints().size(); 117 | } 118 | 119 | Vector2f impulse = new Vector2f(relativeNormal).mul(j); 120 | a.setVelocity( 121 | new Vector2f(a.getVelocity()).add(new Vector2f(impulse).mul(invMass1).mul(-1f))); 122 | b.setVelocity( 123 | new Vector2f(b.getVelocity()).add(new Vector2f(impulse).mul(invMass2).mul(1f))); 124 | } 125 | 126 | public void addRigidbody(Rigidbody2D body, boolean addGravity) { 127 | this.rigidbodies.add(body); 128 | if (addGravity) 129 | this.forceRegistry.add(body, gravity); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/main/java/components/Component.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.JImGui; 4 | import imgui.ImGui; 5 | import imgui.type.ImInt; 6 | import jade.GameObject; 7 | import org.jbox2d.dynamics.contacts.Contact; 8 | import org.joml.Vector2f; 9 | import org.joml.Vector3f; 10 | import org.joml.Vector4f; 11 | 12 | import java.lang.reflect.Field; 13 | import java.lang.reflect.Modifier; 14 | 15 | public abstract class Component { 16 | private static int ID_COUNTER = 0; 17 | private int uid = -1; 18 | 19 | public transient GameObject gameObject = null; 20 | 21 | public void start() { 22 | 23 | } 24 | 25 | public void update(float dt) { 26 | 27 | } 28 | 29 | public void editorUpdate(float dt) { 30 | 31 | } 32 | 33 | public void beginCollision(GameObject collidingObject, Contact contact, Vector2f hitNormal) { 34 | 35 | } 36 | 37 | public void endCollision(GameObject collidingObject, Contact contact, Vector2f hitNormal) { 38 | 39 | } 40 | 41 | public void preSolve(GameObject collidingObject, Contact contact, Vector2f hitNormal) { 42 | 43 | } 44 | 45 | public void postSolve(GameObject collidingObject, Contact contact, Vector2f hitNormal) { 46 | 47 | } 48 | 49 | public void imgui() { 50 | try { 51 | Field[] fields = this.getClass().getDeclaredFields(); 52 | for (Field field : fields) { 53 | boolean isTransient = Modifier.isTransient(field.getModifiers()); 54 | if (isTransient) { 55 | continue; 56 | } 57 | 58 | boolean isPrivate = Modifier.isPrivate(field.getModifiers()); 59 | if (isPrivate) { 60 | field.setAccessible(true); 61 | } 62 | 63 | Class type = field.getType(); 64 | Object value = field.get(this); 65 | String name = field.getName(); 66 | 67 | if (type == int.class) { 68 | int val = (int)value; 69 | field.set(this, JImGui.dragInt(name, val)); 70 | } else if (type == float.class) { 71 | float val = (float)value; 72 | field.set(this, JImGui.dragFloat(name, val)); 73 | } else if (type == boolean.class) { 74 | boolean val = (boolean)value; 75 | if (ImGui.checkbox(name + ": ", val)) { 76 | field.set(this, !val); 77 | } 78 | } else if (type == Vector2f.class) { 79 | Vector2f val = (Vector2f)value; 80 | JImGui.drawVec2Control(name, val); 81 | } else if (type == Vector3f.class) { 82 | Vector3f val = (Vector3f)value; 83 | float[] imVec = {val.x, val.y, val.z}; 84 | if (ImGui.dragFloat3(name + ": ", imVec)) { 85 | val.set(imVec[0], imVec[1], imVec[2]); 86 | } 87 | } else if (type == Vector4f.class) { 88 | Vector4f val = (Vector4f)value; 89 | JImGui.colorPicker4(name, val); 90 | } else if (type.isEnum()) { 91 | String[] enumValues = getEnumValues(type); 92 | String enumType = ((Enum)value).name(); 93 | ImInt index = new ImInt(indexOf(enumType, enumValues)); 94 | if (ImGui.combo(field.getName(), index, enumValues, enumValues.length)) { 95 | field.set(this, type.getEnumConstants()[index.get()]); 96 | } 97 | } else if (type == String.class) { 98 | field.set(this, 99 | JImGui.inputText(field.getName() + ": ", 100 | (String)value)); 101 | } 102 | 103 | 104 | if (isPrivate) { 105 | field.setAccessible(false); 106 | } 107 | } 108 | } catch (IllegalAccessException e) { 109 | e.printStackTrace(); 110 | } 111 | } 112 | 113 | public void generateId() { 114 | if (this.uid == -1) { 115 | this.uid = ID_COUNTER++; 116 | } 117 | } 118 | 119 | private > String[] getEnumValues(Class enumType) { 120 | String[] enumValues = new String[enumType.getEnumConstants().length]; 121 | int i = 0; 122 | for (T enumIntegerValue : enumType.getEnumConstants()) { 123 | enumValues[i] = enumIntegerValue.name(); 124 | i++; 125 | } 126 | return enumValues; 127 | } 128 | 129 | private int indexOf(String str, String[] arr) { 130 | for (int i=0; i < arr.length; i++) { 131 | if (str.equals(arr[i])) { 132 | return i; 133 | } 134 | } 135 | 136 | return -1; 137 | } 138 | 139 | public void destroy() { 140 | 141 | } 142 | 143 | public int getUid() { 144 | return this.uid; 145 | } 146 | 147 | public static void init(int maxId) { 148 | ID_COUNTER = maxId; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/physics2d/components/Rigidbody2D.java: -------------------------------------------------------------------------------- 1 | package physics2d.components; 2 | 3 | import components.Component; 4 | import jade.Window; 5 | import org.jbox2d.common.Vec2; 6 | import org.jbox2d.dynamics.Body; 7 | import org.joml.Vector2f; 8 | import physics2d.enums.BodyType; 9 | 10 | public class Rigidbody2D extends Component { 11 | private Vector2f velocity = new Vector2f(); 12 | private float angularDamping = 0.8f; 13 | private float linearDamping = 0.9f; 14 | private float mass = 0; 15 | private BodyType bodyType = BodyType.Dynamic; 16 | private float friction = 0.1f; 17 | public float angularVelocity = 0.0f; 18 | public float gravityScale = 1.0f; 19 | private boolean isSensor = false; 20 | 21 | private boolean fixedRotation = false; 22 | private boolean continuousCollision = true; 23 | 24 | private transient Body rawBody = null; 25 | 26 | @Override 27 | public void update(float dt) { 28 | if (rawBody != null) { 29 | if (this.bodyType == BodyType.Dynamic || this.bodyType == BodyType.Kinematic) { 30 | this.gameObject.transform.position.set( 31 | rawBody.getPosition().x, rawBody.getPosition().y 32 | ); 33 | this.gameObject.transform.rotation = (float) Math.toDegrees(rawBody.getAngle()); 34 | Vec2 vel = rawBody.getLinearVelocity(); 35 | this.velocity.set(vel.x, vel.y); 36 | } else if (this.bodyType == BodyType.Static) { 37 | this.rawBody.setTransform( 38 | new Vec2(this.gameObject.transform.position.x, this.gameObject.transform.position.y), 39 | this.gameObject.transform.rotation 40 | ); 41 | } 42 | } 43 | } 44 | 45 | public void addVelocity(Vector2f forceToAdd) { 46 | if (rawBody != null) { 47 | rawBody.applyForceToCenter(new Vec2(forceToAdd.x, forceToAdd.y)); 48 | } 49 | } 50 | 51 | public void addImpulse(Vector2f impulse) { 52 | if (rawBody != null) { 53 | rawBody.applyLinearImpulse(new Vec2(velocity.x, velocity.y), rawBody.getWorldCenter()); 54 | } 55 | } 56 | 57 | public Vector2f getVelocity() { 58 | return velocity; 59 | } 60 | 61 | public void setVelocity(Vector2f velocity) { 62 | this.velocity.set(velocity); 63 | if (rawBody != null) { 64 | this.rawBody.setLinearVelocity(new Vec2(velocity.x, velocity.y)); 65 | } 66 | } 67 | 68 | public void setPosition(Vector2f newPos) { 69 | if (rawBody != null) { 70 | rawBody.setTransform(new Vec2(newPos.x, newPos.y), gameObject.transform.rotation); 71 | } 72 | } 73 | 74 | public void setAngularVelocity(float angularVelocity) { 75 | this.angularVelocity = angularVelocity; 76 | if (rawBody != null) { 77 | this.rawBody.setAngularVelocity(angularVelocity); 78 | } 79 | } 80 | 81 | public void setGravityScale(float gravityScale) { 82 | this.gravityScale = gravityScale; 83 | if (rawBody != null) { 84 | this.rawBody.setGravityScale(gravityScale); 85 | } 86 | } 87 | 88 | public void setIsSensor() { 89 | isSensor = true; 90 | if (rawBody != null) { 91 | Window.getPhysics().setIsSensor(this); 92 | } 93 | } 94 | 95 | public void setNotSensor() { 96 | isSensor = false; 97 | if (rawBody != null) { 98 | Window.getPhysics().setNotSensor(this); 99 | } 100 | } 101 | 102 | public float getFriction() { 103 | return this.friction; 104 | } 105 | 106 | public boolean isSensor() { 107 | return this.isSensor; 108 | } 109 | 110 | public float getAngularDamping() { 111 | return angularDamping; 112 | } 113 | 114 | public void setAngularDamping(float angularDamping) { 115 | this.angularDamping = angularDamping; 116 | } 117 | 118 | public float getLinearDamping() { 119 | return linearDamping; 120 | } 121 | 122 | public void setLinearDamping(float linearDamping) { 123 | this.linearDamping = linearDamping; 124 | } 125 | 126 | public float getMass() { 127 | return mass; 128 | } 129 | 130 | public void setMass(float mass) { 131 | this.mass = mass; 132 | } 133 | 134 | public BodyType getBodyType() { 135 | return bodyType; 136 | } 137 | 138 | public void setBodyType(BodyType bodyType) { 139 | this.bodyType = bodyType; 140 | } 141 | 142 | public boolean isFixedRotation() { 143 | return fixedRotation; 144 | } 145 | 146 | public void setFixedRotation(boolean fixedRotation) { 147 | this.fixedRotation = fixedRotation; 148 | } 149 | 150 | public boolean isContinuousCollision() { 151 | return continuousCollision; 152 | } 153 | 154 | public void setContinuousCollision(boolean continuousCollision) { 155 | this.continuousCollision = continuousCollision; 156 | } 157 | 158 | public Body getRawBody() { 159 | return rawBody; 160 | } 161 | 162 | public void setRawBody(Body rawBody) { 163 | this.rawBody = rawBody; 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/java/components/Pipe.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Direction; 4 | import jade.GameObject; 5 | import jade.KeyListener; 6 | import jade.Window; 7 | import org.jbox2d.dynamics.contacts.Contact; 8 | import org.joml.Vector2f; 9 | import util.AssetPool; 10 | 11 | import static org.lwjgl.glfw.GLFW.*; 12 | 13 | public class Pipe extends Component { 14 | private Direction direction; 15 | private String connectingPipeName = ""; 16 | private boolean isEntrance = false; 17 | private transient GameObject connectingPipe = null; 18 | private transient float entranceVectorTolerance = 0.6f; 19 | private transient PlayerController collidingPlayer = null; 20 | 21 | public Pipe(Direction direction) { 22 | this.direction = direction; 23 | } 24 | 25 | @Override 26 | public void start() { 27 | connectingPipe = Window.getScene().getGameObject(connectingPipeName); 28 | } 29 | 30 | @Override 31 | public void update(float dt) { 32 | if (connectingPipe == null) { 33 | return; 34 | } 35 | 36 | if (collidingPlayer != null) { 37 | boolean playerEntering = false; 38 | switch (direction) { 39 | case Up: 40 | if ((KeyListener.isKeyPressed(GLFW_KEY_DOWN) 41 | || KeyListener.isKeyPressed(GLFW_KEY_S)) 42 | && isEntrance 43 | && playerAtEntrance()) { 44 | playerEntering = true; 45 | } 46 | break; 47 | case Left: 48 | if ((KeyListener.isKeyPressed(GLFW_KEY_RIGHT) 49 | || KeyListener.isKeyPressed(GLFW_KEY_D)) 50 | && isEntrance 51 | && playerAtEntrance()) { 52 | playerEntering = true; 53 | } 54 | break; 55 | case Right: 56 | if ((KeyListener.isKeyPressed(GLFW_KEY_LEFT) 57 | || KeyListener.isKeyPressed(GLFW_KEY_A)) 58 | && isEntrance 59 | && playerAtEntrance()) { 60 | playerEntering = true; 61 | } 62 | break; 63 | case Down: 64 | if ((KeyListener.isKeyPressed(GLFW_KEY_UP) 65 | || KeyListener.isKeyPressed(GLFW_KEY_W)) 66 | && isEntrance 67 | && playerAtEntrance()) { 68 | playerEntering = true; 69 | } 70 | break; 71 | } 72 | 73 | if (playerEntering) { 74 | collidingPlayer.setPosition( 75 | getPlayerPosition(connectingPipe) 76 | ); 77 | AssetPool.getSound("assets/sounds/pipe.ogg").play(); 78 | } 79 | } 80 | } 81 | 82 | public boolean playerAtEntrance() { 83 | if (collidingPlayer == null) { 84 | return false; 85 | } 86 | 87 | Vector2f min = new Vector2f(gameObject.transform.position). 88 | sub(new Vector2f(gameObject.transform.scale).mul(0.5f)); 89 | Vector2f max = new Vector2f(gameObject.transform.position). 90 | add(new Vector2f(gameObject.transform.scale).mul(0.5f)); 91 | Vector2f playerMax = new Vector2f(collidingPlayer.gameObject.transform.position). 92 | add(new Vector2f(collidingPlayer.gameObject.transform.scale).mul(0.5f)); 93 | Vector2f playerMin = new Vector2f(collidingPlayer.gameObject.transform.position). 94 | sub(new Vector2f(collidingPlayer.gameObject.transform.scale).mul(0.5f)); 95 | 96 | switch (direction) { 97 | case Up: 98 | return playerMin.y >= max.y && 99 | playerMax.x > min.x && 100 | playerMin.x < max.x; 101 | case Down: 102 | return playerMax.y <= min.y && 103 | playerMax.x > min.x && 104 | playerMin.x < max.x; 105 | case Right: 106 | return playerMin.x >= max.x && 107 | playerMax.y > min.y && 108 | playerMin.y < max.y; 109 | case Left: 110 | return playerMin.x <= min.x && 111 | playerMax.y > min.y && 112 | playerMin.y < max.y; 113 | } 114 | 115 | System.out.println("HAHAHA"); 116 | return false; 117 | } 118 | 119 | @Override 120 | public void beginCollision(GameObject collidingObject, Contact contact, Vector2f contactNormal) { 121 | PlayerController playerController = collidingObject.getComponent(PlayerController.class); 122 | if (playerController != null) { 123 | collidingPlayer = playerController; 124 | } 125 | } 126 | 127 | @Override 128 | public void endCollision(GameObject collidingObject, Contact contact, Vector2f contactNormal) { 129 | PlayerController playerController = collidingObject.getComponent(PlayerController.class); 130 | if (playerController != null) { 131 | collidingPlayer = null; 132 | } 133 | } 134 | 135 | private Vector2f getPlayerPosition(GameObject pipe) { 136 | Pipe pipeComponent = pipe.getComponent(Pipe.class); 137 | switch (pipeComponent.direction) { 138 | case Up: 139 | return new Vector2f(pipe.transform.position).add(0.0f, 0.5f); 140 | case Left: 141 | return new Vector2f(pipe.transform.position).add(-0.5f, 0.0f); 142 | case Right: 143 | return new Vector2f(pipe.transform.position).add(0.5f, 0.0f); 144 | case Down: 145 | return new Vector2f(pipe.transform.position).add(0.0f, -0.5f); 146 | } 147 | 148 | return new Vector2f(); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/components/TurtleAI.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import jade.Camera; 4 | import jade.GameObject; 5 | import jade.Window; 6 | import org.jbox2d.dynamics.contacts.Contact; 7 | import org.joml.Vector2f; 8 | import physics2d.Physics2D; 9 | import physics2d.components.Rigidbody2D; 10 | import util.AssetPool; 11 | 12 | public class TurtleAI extends Component { 13 | private transient boolean goingRight = false; 14 | private transient Rigidbody2D rb; 15 | private transient float walkSpeed = 0.6f; 16 | private transient Vector2f velocity = new Vector2f(); 17 | private transient Vector2f acceleration = new Vector2f(); 18 | private transient Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); 19 | private transient boolean onGround = false; 20 | private transient boolean isDead = false; 21 | private transient boolean isMoving = false; 22 | private transient StateMachine stateMachine; 23 | private float movingDebounce = 0.32f; 24 | 25 | @Override 26 | public void start() { 27 | this.stateMachine = this.gameObject.getComponent(StateMachine.class); 28 | this.rb = gameObject.getComponent(Rigidbody2D.class); 29 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 30 | } 31 | 32 | @Override 33 | public void update(float dt) { 34 | movingDebounce -= dt; 35 | Camera camera = Window.getScene().camera(); 36 | if (this.gameObject.transform.position.x > 37 | camera.position.x + camera.getProjectionSize().x * camera.getZoom()) { 38 | return; 39 | } 40 | 41 | if (!isDead || isMoving) { 42 | if (goingRight) { 43 | gameObject.transform.scale.x = -0.25f; 44 | velocity.x = walkSpeed; 45 | acceleration.x = 0; 46 | } else { 47 | gameObject.transform.scale.x = 0.25f; 48 | velocity.x = -walkSpeed; 49 | acceleration.x = 0; 50 | } 51 | } else { 52 | velocity.x = 0; 53 | } 54 | 55 | checkOnGround(); 56 | if (onGround) { 57 | this.acceleration.y = 0; 58 | this.velocity.y = 0; 59 | } else { 60 | this.acceleration.y = Window.getPhysics().getGravity().y * 0.7f; 61 | } 62 | this.velocity.y += this.acceleration.y * dt; 63 | this.velocity.y = Math.max(Math.min(this.velocity.y, this.terminalVelocity.y), -terminalVelocity.y); 64 | this.rb.setVelocity(velocity); 65 | 66 | if (this.gameObject.transform.position.x < 67 | Window.getScene().camera().position.x - 0.5f) {// || 68 | //this.gameObject.transform.position.y < 0.0f) { 69 | this.gameObject.destroy(); 70 | } 71 | } 72 | 73 | public void checkOnGround() { 74 | float innerPlayerWidth = 0.25f * 0.7f; 75 | float yVal = -0.2f; 76 | onGround = Physics2D.checkOnGround(this.gameObject, innerPlayerWidth, yVal); 77 | } 78 | 79 | public void stomp() { 80 | this.isDead = true; 81 | this.isMoving = false; 82 | this.velocity.zero(); 83 | this.rb.setVelocity(this.velocity); 84 | this.rb.setAngularVelocity(0.0f); 85 | this.rb.setGravityScale(0.0f); 86 | this.stateMachine.trigger("squashMe"); 87 | AssetPool.getSound("assets/sounds/bump.ogg").play(); 88 | } 89 | 90 | @Override 91 | public void preSolve(GameObject obj, Contact contact, Vector2f contactNormal) { 92 | GoombaAI goomba = obj.getComponent(GoombaAI.class); 93 | if (isDead && isMoving && goomba != null) { 94 | goomba.stomp(); 95 | contact.setEnabled(false); 96 | AssetPool.getSound("assets/sounds/kick.ogg").play(); 97 | } 98 | 99 | PlayerController playerController = obj.getComponent(PlayerController.class); 100 | if (playerController != null) { 101 | if (!isDead && !playerController.isDead() && 102 | !playerController.isHurtInvincible() && 103 | contactNormal.y > 0.58f) { 104 | playerController.enemyBounce(); 105 | stomp(); 106 | walkSpeed *= 3.0f; 107 | } else if (movingDebounce < 0 && !playerController.isDead() && 108 | !playerController.isHurtInvincible() && 109 | (isMoving || !isDead) && contactNormal.y < 0.58f) { 110 | playerController.die(); 111 | if (!playerController.isDead()) { 112 | contact.setEnabled(false); 113 | } 114 | } else if (!playerController.isDead() && !playerController.isHurtInvincible()) { 115 | if (isDead && contactNormal.y > 0.58f) { 116 | playerController.enemyBounce(); 117 | isMoving = !isMoving; 118 | goingRight = contactNormal.x < 0; 119 | } else if (isDead && !isMoving) { 120 | isMoving = true; 121 | goingRight = contactNormal.x < 0; 122 | movingDebounce = 0.32f; 123 | } 124 | } else if (!playerController.isDead() && playerController.isHurtInvincible()) { 125 | contact.setEnabled(false); 126 | } 127 | } else if (Math.abs(contactNormal.y) < 0.1f && !obj.isDead() && obj.getComponent(MushroomAI.class) == null) { 128 | goingRight = contactNormal.x < 0; 129 | if (isMoving && isDead) { 130 | AssetPool.getSound("assets/sounds/bump.ogg").play(); 131 | } 132 | } 133 | 134 | if (obj.getComponent(Fireball.class) != null) { 135 | if (!isDead) { 136 | walkSpeed *= 3.0f; 137 | stomp(); 138 | } else { 139 | isMoving = !isMoving; 140 | goingRight = contactNormal.x < 0; 141 | } 142 | obj.getComponent(Fireball.class).disappear(); 143 | contact.setEnabled(false); 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/main/java/components/Gizmo.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.PropertiesWindow; 4 | import jade.*; 5 | import org.joml.Vector2f; 6 | import org.joml.Vector4f; 7 | 8 | import static org.lwjgl.glfw.GLFW.*; 9 | 10 | public class Gizmo extends Component { 11 | private Vector4f xAxisColor = new Vector4f(1, 0.3f, 0.3f, 1); 12 | private Vector4f xAxisColorHover = new Vector4f(1, 0, 0, 1); 13 | private Vector4f yAxisColor = new Vector4f(0.3f, 1, 0.3f, 1); 14 | private Vector4f yAxisColorHover = new Vector4f(0, 1, 0, 1); 15 | 16 | private GameObject xAxisObject; 17 | private GameObject yAxisObject; 18 | private SpriteRenderer xAxisSprite; 19 | private SpriteRenderer yAxisSprite; 20 | protected GameObject activeGameObject = null; 21 | 22 | private Vector2f xAxisOffset = new Vector2f(24f / 80f, -6f / 80f); 23 | private Vector2f yAxisOffset = new Vector2f(-7f / 80f, 21f / 80f); 24 | 25 | private float gizmoWidth = 16f / 80f; 26 | private float gizmoHeight = 48f / 80f; 27 | 28 | protected boolean xAxisActive = false; 29 | protected boolean yAxisActive = false; 30 | 31 | private boolean using = false; 32 | 33 | private PropertiesWindow propertiesWindow; 34 | 35 | public Gizmo(Sprite arrowSprite, PropertiesWindow propertiesWindow) { 36 | this.xAxisObject = Prefabs.generateSpriteObject(arrowSprite, gizmoWidth, gizmoHeight); 37 | this.yAxisObject = Prefabs.generateSpriteObject(arrowSprite, gizmoWidth, gizmoHeight); 38 | this.xAxisSprite = this.xAxisObject.getComponent(SpriteRenderer.class); 39 | this.yAxisSprite = this.yAxisObject.getComponent(SpriteRenderer.class); 40 | this.propertiesWindow = propertiesWindow; 41 | 42 | this.xAxisObject.addComponent(new NonPickable()); 43 | this.yAxisObject.addComponent(new NonPickable()); 44 | 45 | Window.getScene().addGameObjectToScene(this.xAxisObject); 46 | Window.getScene().addGameObjectToScene(this.yAxisObject); 47 | } 48 | 49 | @Override 50 | public void start() { 51 | this.xAxisObject.transform.rotation = 90; 52 | this.yAxisObject.transform.rotation = 180; 53 | this.xAxisObject.transform.zIndex = 100; 54 | this.yAxisObject.transform.zIndex = 100; 55 | this.xAxisObject.setNoSerialize(); 56 | this.yAxisObject.setNoSerialize(); 57 | } 58 | 59 | @Override 60 | public void update(float dt) { 61 | if (using) { 62 | this.setInactive(); 63 | } 64 | this.xAxisObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); 65 | this.yAxisObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); 66 | } 67 | 68 | @Override 69 | public void editorUpdate(float dt) { 70 | if (!using) return; 71 | 72 | this.activeGameObject = this.propertiesWindow.getActiveGameObject(); 73 | if (this.activeGameObject != null) { 74 | this.setActive(); 75 | } else { 76 | this.setInactive(); 77 | return; 78 | } 79 | 80 | boolean xAxisHot = checkXHoverState(); 81 | boolean yAxisHot = checkYHoverState(); 82 | 83 | if ((xAxisHot || xAxisActive) && MouseListener.isDragging() && MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) { 84 | xAxisActive = true; 85 | yAxisActive = false; 86 | } else if ((yAxisHot || yAxisActive) && MouseListener.isDragging() && MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) { 87 | yAxisActive = true; 88 | xAxisActive = false; 89 | } else { 90 | xAxisActive = false; 91 | yAxisActive = false; 92 | } 93 | 94 | if (this.activeGameObject != null) { 95 | this.xAxisObject.transform.position.set(this.activeGameObject.transform.position); 96 | this.yAxisObject.transform.position.set(this.activeGameObject.transform.position); 97 | this.xAxisObject.transform.position.add(this.xAxisOffset); 98 | this.yAxisObject.transform.position.add(this.yAxisOffset); 99 | } 100 | } 101 | 102 | private void setActive() { 103 | this.xAxisSprite.setColor(xAxisColor); 104 | this.yAxisSprite.setColor(yAxisColor); 105 | } 106 | 107 | private void setInactive() { 108 | this.activeGameObject = null; 109 | this.xAxisSprite.setColor(new Vector4f(0, 0, 0, 0)); 110 | this.yAxisSprite.setColor(new Vector4f(0, 0, 0, 0)); 111 | } 112 | 113 | private boolean checkXHoverState() { 114 | Vector2f mousePos = new Vector2f(MouseListener.getWorldX(), MouseListener.getWorldY()); 115 | if (mousePos.x <= xAxisObject.transform.position.x + (gizmoHeight / 2.0f) && 116 | mousePos.x >= xAxisObject.transform.position.x - (gizmoWidth / 2.0f) && 117 | mousePos.y >= xAxisObject.transform.position.y - (gizmoHeight / 2.0f) && 118 | mousePos.y <= xAxisObject.transform.position.y + (gizmoWidth / 2.0f)) { 119 | xAxisSprite.setColor(xAxisColorHover); 120 | return true; 121 | } 122 | 123 | xAxisSprite.setColor(xAxisColor); 124 | return false; 125 | } 126 | 127 | private boolean checkYHoverState() { 128 | Vector2f mousePos = new Vector2f(MouseListener.getWorldX(), MouseListener.getWorldY()); 129 | if (mousePos.x <= yAxisObject.transform.position.x + (gizmoWidth / 2.0f) && 130 | mousePos.x >= yAxisObject.transform.position.x - (gizmoWidth / 2.0f) && 131 | mousePos.y <= yAxisObject.transform.position.y + (gizmoHeight / 2.0f) && 132 | mousePos.y >= yAxisObject.transform.position.y - (gizmoHeight / 2.0f)) { 133 | yAxisSprite.setColor(yAxisColorHover); 134 | return true; 135 | } 136 | 137 | yAxisSprite.setColor(yAxisColor); 138 | return false; 139 | } 140 | 141 | public void setUsing() { 142 | this.using = true; 143 | } 144 | 145 | public void setNotUsing() { 146 | this.using = false; 147 | this.setInactive(); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/renderer/Shader.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import org.joml.*; 4 | import org.lwjgl.BufferUtils; 5 | 6 | import javax.print.DocFlavor; 7 | import java.io.IOException; 8 | import java.nio.FloatBuffer; 9 | import java.nio.file.Files; 10 | import java.nio.file.Paths; 11 | 12 | import static org.lwjgl.opengl.GL11.GL_FALSE; 13 | import static org.lwjgl.opengl.GL20.*; 14 | import static org.lwjgl.opengl.GL20.glGetShaderInfoLog; 15 | 16 | public class Shader { 17 | 18 | private int shaderProgramID; 19 | private boolean beingUsed = false; 20 | 21 | private String vertexSource; 22 | private String fragmentSource; 23 | private String filepath; 24 | 25 | public Shader(String filepath) { 26 | this.filepath = filepath; 27 | try { 28 | String source = new String(Files.readAllBytes(Paths.get(filepath))); 29 | String[] splitString = source.split("(#type)( )+([a-zA-Z]+)"); 30 | 31 | // Find the first pattern after #type 'pattern' 32 | int index = source.indexOf("#type") + 6; 33 | int eol = source.indexOf("\r\n", index); 34 | String firstPattern = source.substring(index, eol).trim(); 35 | 36 | // Find the second pattern after #type 'pattern' 37 | index = source.indexOf("#type", eol) + 6; 38 | eol = source.indexOf("\r\n", index); 39 | String secondPattern = source.substring(index, eol).trim(); 40 | 41 | if (firstPattern.equals("vertex")) { 42 | vertexSource = splitString[1]; 43 | } else if (firstPattern.equals("fragment")) { 44 | fragmentSource = splitString[1]; 45 | } else { 46 | throw new IOException("Unexpected token '" + firstPattern + "'"); 47 | } 48 | 49 | if (secondPattern.equals("vertex")) { 50 | vertexSource = splitString[2]; 51 | } else if (secondPattern.equals("fragment")) { 52 | fragmentSource = splitString[2]; 53 | } else { 54 | throw new IOException("Unexpected token '" + secondPattern + "'"); 55 | } 56 | } catch(IOException e) { 57 | e.printStackTrace(); 58 | assert false : "Error: Could not open file for shader: '" + filepath + "'"; 59 | } 60 | } 61 | 62 | public void compile() { 63 | // ============================================================ 64 | // Compile and link shaders 65 | // ============================================================ 66 | int vertexID, fragmentID; 67 | 68 | // First load and compile the vertex shader 69 | vertexID = glCreateShader(GL_VERTEX_SHADER); 70 | // Pass the shader source to the GPU 71 | glShaderSource(vertexID, vertexSource); 72 | glCompileShader(vertexID); 73 | 74 | // Check for errors in compilation 75 | int success = glGetShaderi(vertexID, GL_COMPILE_STATUS); 76 | if (success == GL_FALSE) { 77 | int len = glGetShaderi(vertexID, GL_INFO_LOG_LENGTH); 78 | System.out.println("ERROR: '" + filepath + "'\n\tVertex shader compilation failed."); 79 | System.out.println(glGetShaderInfoLog(vertexID, len)); 80 | assert false : ""; 81 | } 82 | 83 | // First load and compile the vertex shader 84 | fragmentID = glCreateShader(GL_FRAGMENT_SHADER); 85 | // Pass the shader source to the GPU 86 | glShaderSource(fragmentID, fragmentSource); 87 | glCompileShader(fragmentID); 88 | 89 | // Check for errors in compilation 90 | success = glGetShaderi(fragmentID, GL_COMPILE_STATUS); 91 | if (success == GL_FALSE) { 92 | int len = glGetShaderi(fragmentID, GL_INFO_LOG_LENGTH); 93 | System.out.println("ERROR: '" + filepath + "'\n\tFragment shader compilation failed."); 94 | System.out.println(glGetShaderInfoLog(fragmentID, len)); 95 | assert false : ""; 96 | } 97 | 98 | // Link shaders and check for errors 99 | shaderProgramID = glCreateProgram(); 100 | glAttachShader(shaderProgramID, vertexID); 101 | glAttachShader(shaderProgramID, fragmentID); 102 | glLinkProgram(shaderProgramID); 103 | 104 | // Check for linking errors 105 | success = glGetProgrami(shaderProgramID, GL_LINK_STATUS); 106 | if (success == GL_FALSE) { 107 | int len = glGetProgrami(shaderProgramID, GL_INFO_LOG_LENGTH); 108 | System.out.println("ERROR: '" + filepath + "'\n\tLinking of shaders failed."); 109 | System.out.println(glGetProgramInfoLog(shaderProgramID, len)); 110 | assert false : ""; 111 | } 112 | } 113 | 114 | public void use() { 115 | if (!beingUsed) { 116 | // Bind shader program 117 | glUseProgram(shaderProgramID); 118 | beingUsed = true; 119 | } 120 | } 121 | 122 | public void detach() { 123 | glUseProgram(0); 124 | beingUsed = false; 125 | } 126 | 127 | public void uploadMat4f(String varName, Matrix4f mat4) { 128 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 129 | use(); 130 | FloatBuffer matBuffer = BufferUtils.createFloatBuffer(16); 131 | mat4.get(matBuffer); 132 | glUniformMatrix4fv(varLocation, false, matBuffer); 133 | } 134 | 135 | public void uploadMat3f(String varName, Matrix3f mat3) { 136 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 137 | use(); 138 | FloatBuffer matBuffer = BufferUtils.createFloatBuffer(9); 139 | mat3.get(matBuffer); 140 | glUniformMatrix3fv(varLocation, false, matBuffer); 141 | } 142 | 143 | public void uploadVec4f(String varName, Vector4f vec) { 144 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 145 | use(); 146 | glUniform4f(varLocation, vec.x, vec.y, vec.z, vec.w); 147 | } 148 | 149 | public void uploadVec3f(String varName, Vector3f vec) { 150 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 151 | use(); 152 | glUniform3f(varLocation, vec.x, vec.y, vec.z); 153 | } 154 | 155 | public void uploadVec2f(String varName, Vector2f vec) { 156 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 157 | use(); 158 | glUniform2f(varLocation, vec.x, vec.y); 159 | } 160 | 161 | public void uploadFloat(String varName, float val) { 162 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 163 | use(); 164 | glUniform1f(varLocation, val); 165 | } 166 | 167 | public void uploadInt(String varName, int val) { 168 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 169 | use(); 170 | glUniform1i(varLocation, val); 171 | } 172 | 173 | public void uploadTexture(String varName, int slot) { 174 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 175 | use(); 176 | glUniform1i(varLocation, slot); 177 | } 178 | 179 | public void uploadIntArray(String varName, int[] array) { 180 | int varLocation = glGetUniformLocation(shaderProgramID, varName); 181 | use(); 182 | glUniform1iv(varLocation, array); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/jade/MouseListener.java: -------------------------------------------------------------------------------- 1 | package jade; 2 | 3 | import org.joml.Matrix4f; 4 | import org.joml.Vector2f; 5 | import org.joml.Vector4f; 6 | 7 | import java.util.Arrays; 8 | 9 | import static org.lwjgl.glfw.GLFW.GLFW_PRESS; 10 | import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; 11 | 12 | public class MouseListener { 13 | private static MouseListener instance; 14 | private double scrollX, scrollY; 15 | private double xPos, yPos, lastY, lastX, worldX, worldY, lastWorldX, lastWorldY; 16 | private boolean mouseButtonPressed[] = new boolean[9]; 17 | private boolean isDragging; 18 | 19 | private int mouseButtonDown = 0; 20 | 21 | private Vector2f gameViewportPos = new Vector2f(); 22 | private Vector2f gameViewportSize = new Vector2f(); 23 | 24 | private MouseListener() { 25 | this.scrollX = 0.0; 26 | this.scrollY = 0.0; 27 | this.xPos = 0.0; 28 | this.yPos = 0.0; 29 | this.lastX = 0.0; 30 | this.lastY = 0.0; 31 | } 32 | 33 | public static void endFrame() { 34 | get().scrollY = 0.0; 35 | get().scrollX = 0.0; 36 | } 37 | 38 | public static void clear() { 39 | get().scrollX = 0.0; 40 | get().scrollY = 0.0; 41 | get().xPos = 0.0; 42 | get().yPos = 0.0; 43 | get().lastX = 0.0; 44 | get().lastY = 0.0; 45 | get().mouseButtonDown = 0; 46 | get().isDragging = false; 47 | Arrays.fill(get().mouseButtonPressed, false); 48 | } 49 | 50 | public static MouseListener get() { 51 | if (MouseListener.instance == null) { 52 | MouseListener.instance = new MouseListener(); 53 | } 54 | 55 | return MouseListener.instance; 56 | } 57 | 58 | public static void mousePosCallback(long window, double xpos, double ypos) { 59 | if (!Window.RELEASE_BUILD) { 60 | if (!Window.getImguiLayer().getGameViewWindow().getWantCaptureMouse()) { 61 | clear(); 62 | } 63 | } 64 | 65 | if (get().mouseButtonDown > 0) { 66 | get().isDragging = true; 67 | } 68 | 69 | get().lastX = get().xPos; 70 | get().lastY = get().yPos; 71 | get().lastWorldX = get().worldX; 72 | get().lastWorldY = get().worldY; 73 | get().xPos = xpos; 74 | get().yPos = ypos; 75 | } 76 | 77 | public static void mouseButtonCallback(long window, int button, int action, int mods) { 78 | if (action == GLFW_PRESS) { 79 | get().mouseButtonDown++; 80 | 81 | if (button < get().mouseButtonPressed.length) { 82 | get().mouseButtonPressed[button] = true; 83 | } 84 | } else if (action == GLFW_RELEASE) { 85 | get().mouseButtonDown--; 86 | 87 | if (button < get().mouseButtonPressed.length) { 88 | get().mouseButtonPressed[button] = false; 89 | get().isDragging = false; 90 | } 91 | } 92 | } 93 | 94 | public static void mouseScrollCallback(long window, double xOffset, double yOffset) { 95 | get().scrollX = xOffset; 96 | get().scrollY = yOffset; 97 | } 98 | 99 | public static float getX() { 100 | return (float)get().xPos; 101 | } 102 | 103 | public static float getY() { 104 | return (float)get().yPos; 105 | } 106 | 107 | public static float getWorldDx() { 108 | return (float)(get().lastWorldX - get().worldX); 109 | } 110 | 111 | public static float getWorldDy() { 112 | return (float)(get().lastWorldY - get().worldY); 113 | } 114 | 115 | public static float getScrollX() { return (float)get().scrollX; } 116 | 117 | public static float getScrollY() { 118 | return (float)get().scrollY; 119 | } 120 | 121 | public static boolean isDragging() { return get().isDragging; } 122 | 123 | public static boolean mouseButtonDown(int button) { 124 | if (button < get().mouseButtonPressed.length) { 125 | return get().mouseButtonPressed[button]; 126 | } else { 127 | return false; 128 | } 129 | } 130 | 131 | public static float getWorldX() { 132 | return getWorld().x; 133 | } 134 | 135 | public static float getWorldY() { 136 | return getWorld().y; 137 | } 138 | 139 | public static Vector2f getWorld() { 140 | float currentX = getX() - get().gameViewportPos.x; 141 | currentX = (2.0f * (currentX / get().gameViewportSize.x)) - 1.0f; 142 | float currentY = (getY() - get().gameViewportPos.y); 143 | currentY = (2.0f * (1.0f - (currentY / get().gameViewportSize.y))) - 1; 144 | 145 | Camera camera = Window.getScene().camera(); 146 | Vector4f tmp = new Vector4f(currentX, currentY, 0, 1); 147 | Matrix4f inverseView = new Matrix4f(camera.getInverseView()); 148 | Matrix4f inverseProjection = new Matrix4f(camera.getInverseProjection()); 149 | tmp.mul(inverseView.mul(inverseProjection)); 150 | return new Vector2f(tmp.x, tmp.y); 151 | } 152 | 153 | public static Vector2f screenToWorld(Vector2f screenCoords) { 154 | Vector2f normalizedScreenCords = new Vector2f( 155 | screenCoords.x / Window.getWidth(), 156 | screenCoords.y / Window.getHeight() 157 | ); 158 | normalizedScreenCords.mul(2.0f).sub(new Vector2f(1.0f, 1.0f)); 159 | Camera camera = Window.getScene().camera(); 160 | Vector4f tmp = new Vector4f(normalizedScreenCords.x, normalizedScreenCords.y, 161 | 0, 1); 162 | Matrix4f inverseView = new Matrix4f(camera.getInverseView()); 163 | Matrix4f inverseProjection = new Matrix4f(camera.getInverseProjection()); 164 | tmp.mul(inverseView.mul(inverseProjection)); 165 | return new Vector2f(tmp.x, tmp.y); 166 | } 167 | 168 | public static Vector2f worldToScreen(Vector2f worldCoords) { 169 | Camera camera = Window.getScene().camera(); 170 | Vector4f ndcSpacePos = new Vector4f(worldCoords.x, worldCoords.y, 0, 1); 171 | Matrix4f view = new Matrix4f(camera.getViewMatrix()); 172 | Matrix4f projection = new Matrix4f(camera.getProjectionMatrix()); 173 | ndcSpacePos.mul(projection.mul(view)); 174 | Vector2f windowSpace = new Vector2f(ndcSpacePos.x, ndcSpacePos.y).mul(1.0f / ndcSpacePos.w); 175 | windowSpace.add(new Vector2f(1.0f, 1.0f)).mul(0.5f); 176 | windowSpace.mul(new Vector2f(Window.getWidth(), Window.getHeight())); 177 | 178 | return windowSpace; 179 | } 180 | 181 | public static float getScreenX() { 182 | return getScreen().x; 183 | } 184 | 185 | public static float getScreenY() { 186 | return getScreen().y; 187 | } 188 | 189 | public static Vector2f getScreen() { 190 | float currentX = getX() - get().gameViewportPos.x; 191 | currentX = (currentX / get().gameViewportSize.x) * 3840.0f; 192 | float currentY = (getY() - get().gameViewportPos.y); 193 | currentY = (1.0f - (currentY / get().gameViewportSize.y)) * 2160.0f; 194 | return new Vector2f(currentX, currentY); 195 | } 196 | 197 | public static void setGameViewportPos(Vector2f gameViewportPos) { get().gameViewportPos.set(gameViewportPos); } 198 | 199 | public static void setGameViewportSize(Vector2f gameViewportSize) { 200 | get().gameViewportSize.set(gameViewportSize); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /src/main/java/scenes/Scene.java: -------------------------------------------------------------------------------- 1 | package scenes; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import components.Component; 6 | import components.ComponentDeserializer; 7 | import imgui.ImGui; 8 | import jade.Camera; 9 | import jade.GameObject; 10 | import jade.GameObjectDeserializer; 11 | import jade.Transform; 12 | import org.joml.Vector2f; 13 | import physics2d.Physics2D; 14 | import renderer.Renderer; 15 | 16 | import java.io.FileWriter; 17 | import java.io.IOException; 18 | import java.nio.file.Files; 19 | import java.nio.file.Paths; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.Optional; 23 | 24 | public class Scene { 25 | 26 | private Renderer renderer; 27 | private Camera camera; 28 | private boolean isRunning; 29 | private List gameObjects; 30 | private List pendingObjects; 31 | private Physics2D physics2D; 32 | 33 | private SceneInitializer sceneInitializer; 34 | 35 | public Scene(SceneInitializer sceneInitializer) { 36 | this.sceneInitializer = sceneInitializer; 37 | this.physics2D = new Physics2D(); 38 | this.renderer = new Renderer(); 39 | this.gameObjects = new ArrayList<>(); 40 | this.pendingObjects = new ArrayList<>(); 41 | this.isRunning = false; 42 | } 43 | 44 | public Physics2D getPhysics() { 45 | return this.physics2D; 46 | } 47 | 48 | public void init() { 49 | this.camera = new Camera(new Vector2f(0, 0)); 50 | this.sceneInitializer.loadResources(this); 51 | this.sceneInitializer.init(this); 52 | } 53 | 54 | public void start() { 55 | for (int i=0; i < gameObjects.size(); i++) { 56 | GameObject go = gameObjects.get(i); 57 | go.start(); 58 | this.renderer.add(go); 59 | this.physics2D.add(go); 60 | } 61 | isRunning = true; 62 | } 63 | 64 | public void addGameObjectToScene(GameObject go) { 65 | if (!isRunning) { 66 | gameObjects.add(go); 67 | } else { 68 | pendingObjects.add(go); 69 | } 70 | } 71 | 72 | public void destroy() { 73 | for (GameObject go : gameObjects) { 74 | go.destroy(); 75 | } 76 | } 77 | 78 | public GameObject getGameObjectWith(Class clazz) { 79 | for (GameObject go : gameObjects) { 80 | if (go.getComponent(clazz) != null) { 81 | return go; 82 | } 83 | } 84 | 85 | return null; 86 | } 87 | 88 | public List getGameObjects() { 89 | return this.gameObjects; 90 | } 91 | 92 | public GameObject getGameObject(int gameObjectId) { 93 | Optional result = this.gameObjects.stream() 94 | .filter(gameObject -> gameObject.getUid() == gameObjectId) 95 | .findFirst(); 96 | return result.orElse(null); 97 | } 98 | 99 | public void editorUpdate(float dt) { 100 | this.camera.adjustProjection(); 101 | 102 | for (int i=0; i < gameObjects.size(); i++) { 103 | GameObject go = gameObjects.get(i); 104 | go.editorUpdate(dt); 105 | 106 | if (go.isDead()) { 107 | gameObjects.remove(i); 108 | this.renderer.destroyGameObject(go); 109 | this.physics2D.destroyGameObject(go); 110 | i--; 111 | } 112 | } 113 | 114 | for (GameObject go : pendingObjects) { 115 | gameObjects.add(go); 116 | go.start(); 117 | this.renderer.add(go); 118 | this.physics2D.add(go); 119 | } 120 | pendingObjects.clear(); 121 | } 122 | 123 | public GameObject getGameObject(String gameObjectName) { 124 | Optional result = this.gameObjects.stream() 125 | .filter(gameObject -> gameObject.name.equals(gameObjectName)) 126 | .findFirst(); 127 | return result.orElse(null); 128 | } 129 | 130 | public void update(float dt) { 131 | this.camera.adjustProjection(); 132 | this.physics2D.update(dt); 133 | 134 | for (int i=0; i < gameObjects.size(); i++) { 135 | GameObject go = gameObjects.get(i); 136 | go.update(dt); 137 | 138 | if (go.isDead()) { 139 | gameObjects.remove(i); 140 | this.renderer.destroyGameObject(go); 141 | this.physics2D.destroyGameObject(go); 142 | i--; 143 | } 144 | } 145 | 146 | for (GameObject go : pendingObjects) { 147 | gameObjects.add(go); 148 | go.start(); 149 | this.renderer.add(go); 150 | this.physics2D.add(go); 151 | } 152 | pendingObjects.clear(); 153 | } 154 | 155 | public void render() { 156 | this.renderer.render(); 157 | } 158 | 159 | public Camera camera() { 160 | return this.camera; 161 | } 162 | 163 | public void imgui() { 164 | this.sceneInitializer.imgui(); 165 | } 166 | 167 | public GameObject createGameObject(String name) { 168 | GameObject go = new GameObject(name); 169 | go.addComponent(new Transform()); 170 | go.transform = go.getComponent(Transform.class); 171 | return go; 172 | } 173 | 174 | public void save() { 175 | Gson gson = new GsonBuilder() 176 | .setPrettyPrinting() 177 | .registerTypeAdapter(Component.class, new ComponentDeserializer()) 178 | .registerTypeAdapter(GameObject.class, new GameObjectDeserializer()) 179 | .enableComplexMapKeySerialization() 180 | .create(); 181 | 182 | try { 183 | FileWriter writer = new FileWriter("level.txt"); 184 | List objsToSerialize = new ArrayList<>(); 185 | for (GameObject obj : this.gameObjects) { 186 | if (obj.doSerialization()) { 187 | objsToSerialize.add(obj); 188 | } 189 | } 190 | writer.write(gson.toJson(objsToSerialize)); 191 | writer.close(); 192 | } catch(IOException e) { 193 | e.printStackTrace(); 194 | } 195 | } 196 | 197 | public void load() { 198 | Gson gson = new GsonBuilder() 199 | .setPrettyPrinting() 200 | .registerTypeAdapter(Component.class, new ComponentDeserializer()) 201 | .registerTypeAdapter(GameObject.class, new GameObjectDeserializer()) 202 | .enableComplexMapKeySerialization() 203 | .create(); 204 | 205 | String inFile = ""; 206 | try { 207 | inFile = new String(Files.readAllBytes(Paths.get("level.txt"))); 208 | } catch (IOException e) { 209 | e.printStackTrace(); 210 | } 211 | 212 | if (!inFile.equals("")) { 213 | int maxGoId = -1; 214 | int maxCompId = -1; 215 | GameObject[] objs = gson.fromJson(inFile, GameObject[].class); 216 | for (int i=0; i < objs.length; i++) { 217 | addGameObjectToScene(objs[i]); 218 | 219 | for (Component c : objs[i].getAllComponents()) { 220 | if (c.getUid() > maxCompId) { 221 | maxCompId = c.getUid(); 222 | } 223 | } 224 | if (objs[i].getUid() > maxGoId) { 225 | maxGoId = objs[i].getUid(); 226 | } 227 | } 228 | 229 | maxGoId++; 230 | maxCompId++; 231 | GameObject.init(maxGoId); 232 | Component.init(maxCompId); 233 | } 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/main/java/components/MouseControls.java: -------------------------------------------------------------------------------- 1 | package components; 2 | 3 | import editor.PropertiesWindow; 4 | import jade.GameObject; 5 | import jade.KeyListener; 6 | import jade.MouseListener; 7 | import jade.Window; 8 | import org.joml.Vector2f; 9 | import org.joml.Vector2i; 10 | import org.joml.Vector4f; 11 | import renderer.DebugDraw; 12 | import renderer.PickingTexture; 13 | import scenes.Scene; 14 | import util.Settings; 15 | 16 | import java.util.HashSet; 17 | import java.util.Set; 18 | 19 | import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; 20 | import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT; 21 | 22 | public class MouseControls extends Component { 23 | GameObject holdingObject = null; 24 | private float debounceTime = 0.2f; 25 | private float debounce = debounceTime; 26 | 27 | private boolean boxSelectSet = false; 28 | private Vector2f boxSelectStart = new Vector2f(); 29 | private Vector2f boxSelectEnd = new Vector2f(); 30 | 31 | public void pickupObject(GameObject go) { 32 | if (this.holdingObject != null) { 33 | this.holdingObject.destroy(); 34 | } 35 | this.holdingObject = go; 36 | this.holdingObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0.8f, 0.8f, 0.8f, 0.5f)); 37 | this.holdingObject.addComponent(new NonPickable()); 38 | Window.getScene().addGameObjectToScene(go); 39 | } 40 | 41 | public void place() { 42 | GameObject newObj = holdingObject.copy(); 43 | if (newObj.getComponent(StateMachine.class) != null) { 44 | newObj.getComponent(StateMachine.class).refreshTextures(); 45 | } 46 | newObj.getComponent(SpriteRenderer.class).setColor(new Vector4f(1, 1, 1, 1)); 47 | newObj.removeComponent(NonPickable.class); 48 | Window.getScene().addGameObjectToScene(newObj); 49 | } 50 | 51 | @Override 52 | public void editorUpdate(float dt) { 53 | debounce -= dt; 54 | PickingTexture pickingTexture = Window.getImguiLayer().getPropertiesWindow().getPickingTexture(); 55 | Scene currentScene = Window.getScene(); 56 | 57 | if (holdingObject != null) { 58 | float x = MouseListener.getWorldX(); 59 | float y = MouseListener.getWorldY(); 60 | holdingObject.transform.position.x = ((int)Math.floor(x / Settings.GRID_WIDTH) * Settings.GRID_WIDTH) + Settings.GRID_WIDTH / 2.0f; 61 | holdingObject.transform.position.y = ((int)Math.floor(y / Settings.GRID_HEIGHT) * Settings.GRID_HEIGHT) + Settings.GRID_HEIGHT / 2.0f; 62 | 63 | if (MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) { 64 | float halfWidth = Settings.GRID_WIDTH / 2.0f; 65 | float halfHeight = Settings.GRID_HEIGHT / 2.0f; 66 | if (MouseListener.isDragging() && 67 | !blockInSquare(holdingObject.transform.position.x - halfWidth, 68 | holdingObject.transform.position.y - halfHeight)) { 69 | place(); 70 | } else if (!MouseListener.isDragging() && debounce < 0) { 71 | place(); 72 | debounce = debounceTime; 73 | } 74 | } 75 | 76 | if (KeyListener.isKeyPressed(GLFW_KEY_ESCAPE)) { 77 | holdingObject.destroy(); 78 | holdingObject = null; 79 | } 80 | } else if (!MouseListener.isDragging() && MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT) && debounce < 0) { 81 | int x = (int)MouseListener.getScreenX(); 82 | int y = (int)MouseListener.getScreenY(); 83 | int gameObjectId = pickingTexture.readPixel(x, y); 84 | GameObject pickedObj = currentScene.getGameObject(gameObjectId); 85 | if (pickedObj != null && pickedObj.getComponent(NonPickable.class) == null) { 86 | Window.getImguiLayer().getPropertiesWindow().setActiveGameObject(pickedObj); 87 | } else if (pickedObj == null && !MouseListener.isDragging()) { 88 | Window.getImguiLayer().getPropertiesWindow().clearSelected(); 89 | } 90 | this.debounce = 0.2f; 91 | } else if (MouseListener.isDragging() && MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) { 92 | if (!boxSelectSet) { 93 | Window.getImguiLayer().getPropertiesWindow().clearSelected(); 94 | boxSelectStart = MouseListener.getScreen(); 95 | boxSelectSet = true; 96 | } 97 | boxSelectEnd = MouseListener.getScreen(); 98 | Vector2f boxSelectStartWorld = MouseListener.screenToWorld(boxSelectStart); 99 | Vector2f boxSelectEndWorld = MouseListener.screenToWorld(boxSelectEnd); 100 | Vector2f halfSize = 101 | (new Vector2f(boxSelectEndWorld).sub(boxSelectStartWorld)).mul(0.5f); 102 | DebugDraw.addBox2D( 103 | (new Vector2f(boxSelectStartWorld)).add(halfSize), 104 | new Vector2f(halfSize).mul(2.0f), 105 | 0.0f); 106 | } else if (boxSelectSet) { 107 | boxSelectSet = false; 108 | int screenStartX = (int)boxSelectStart.x; 109 | int screenStartY = (int)boxSelectStart.y; 110 | int screenEndX = (int)boxSelectEnd.x; 111 | int screenEndY = (int)boxSelectEnd.y; 112 | boxSelectStart.zero(); 113 | boxSelectEnd.zero(); 114 | 115 | if (screenEndX < screenStartX) { 116 | int tmp = screenStartX; 117 | screenStartX = screenEndX; 118 | screenEndX = tmp; 119 | } 120 | if (screenEndY < screenStartY) { 121 | int tmp = screenStartY; 122 | screenStartY = screenEndY; 123 | screenEndY = tmp; 124 | } 125 | 126 | float[] gameObjectIds = pickingTexture.readPixels( 127 | new Vector2i(screenStartX, screenStartY), 128 | new Vector2i(screenEndX, screenEndY) 129 | ); 130 | Set uniqueGameObjectIds = new HashSet<>(); 131 | for (float objId : gameObjectIds) { 132 | uniqueGameObjectIds.add((int)objId); 133 | } 134 | 135 | for (Integer gameObjectId : uniqueGameObjectIds) { 136 | GameObject pickedObj = Window.getScene().getGameObject(gameObjectId); 137 | if (pickedObj != null && pickedObj.getComponent(NonPickable.class) == null) { 138 | Window.getImguiLayer().getPropertiesWindow().addActiveGameObject(pickedObj); 139 | } 140 | } 141 | } 142 | } 143 | 144 | private boolean blockInSquare(float x, float y) { 145 | PropertiesWindow propertiesWindow = Window.getImguiLayer().getPropertiesWindow(); 146 | Vector2f start = new Vector2f(x, y); 147 | Vector2f end = new Vector2f(start).add(new Vector2f(Settings.GRID_WIDTH, Settings.GRID_HEIGHT)); 148 | Vector2f startScreenf = MouseListener.worldToScreen(start); 149 | Vector2f endScreenf = MouseListener.worldToScreen(end); 150 | Vector2i startScreen = new Vector2i((int)startScreenf.x + 2, (int)startScreenf.y + 2); 151 | Vector2i endScreen = new Vector2i((int)endScreenf.x - 2, (int)endScreenf.y - 2); 152 | float[] gameObjectIds = propertiesWindow.getPickingTexture().readPixels(startScreen, endScreen); 153 | 154 | for (int i = 0; i < gameObjectIds.length; i++) { 155 | if (gameObjectIds[i] >= 0) { 156 | GameObject pickedObj = Window.getScene().getGameObject((int)gameObjectIds[i]); 157 | if (pickedObj.getComponent(NonPickable.class) == null) { 158 | return true; 159 | } 160 | } 161 | } 162 | 163 | return false; 164 | } 165 | } 166 | --------------------------------------------------------------------------------