Format code

master
Caroline Bell 2020-02-20 22:52:55 -08:00
parent 6ebcb42302
commit 75febd3fa5
102 changed files with 5237 additions and 6276 deletions

View File

@ -35,7 +35,6 @@ public class LiteCraftMain implements Runnable
public static int width = 640, height = 480, maxFPS = 60; // Don't change these values. They just initialize it in case we forget to set them later.
public static boolean spamLog = false, debug = false, limitFPS = false;
public String splashText = "";
@SuppressWarnings("unused")
private int fps, ups, tps;
private long frameTimer;
protected Timer timer;

View File

@ -13,11 +13,10 @@ public class TextFileReader
InputStream inputStream = ClassLoader.getSystemResourceAsStream(filename);
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader in = new BufferedReader(streamReader);
String[] output = new String[] {};
for (String line; (line = in.readLine()) != null;)
{
String[] bufferArray = new String[output.length + 1];
String[] bufferArray = new String[output.length + 1];
System.arraycopy(output, 0, bufferArray, 0, output.length);
bufferArray[output.length] = line;
output = bufferArray;

View File

@ -18,40 +18,33 @@ import io.github.hydos.ginger.engine.renderEngine.MasterRenderer;
import io.github.hydos.ginger.engine.terrain.Terrain;
import io.github.hydos.ginger.engine.utils.Loader;
import io.github.hydos.ginger.main.GingerMain;
/*
* The non kid friendly wrapper for your blocky game
*/
public class RenderWrapper {
public class RenderWrapper
{
private static MasterRenderer masterRenderer4D;
public static List<Entity> entities = new ArrayList<Entity>();
public static List<GuiTexture> guis = new ArrayList<GuiTexture>();
public static List<Light> lights = new ArrayList<Light>();
public static ThirdPersonCamera camera;
private static final List<Terrain> TERRAIN = new ArrayList<Terrain>();
private static final List<Entity> NORMAL_ENTITY = new ArrayList<Entity>();
private static String splash = "WILL ADD THIS LATER";
public static void init(String splash, RenderPlayer renderPlayer) {
camera = new ThirdPersonCamera(new Vector3f(0,0.1f,0), renderPlayer);
public static void init(String splash, RenderPlayer renderPlayer)
{
camera = new ThirdPersonCamera(new Vector3f(0, 0.1f, 0), renderPlayer);
RenderWrapper.splash = splash;
Window.setBackgroundColour(0.2f, 0.2f, 0.6f);
masterRenderer4D = new MasterRenderer(camera);
ParticleMaster.init(masterRenderer4D.getProjectionMatrix());
Window.setBackgroundColour(0.2f, 0.2f, 0.6f);
masterRenderer4D = new MasterRenderer(camera);
ParticleMaster.init(masterRenderer4D.getProjectionMatrix());
PostProcessing.init();
}
public static void cleanup() {
public static void cleanup()
{
Window.stop();
PostProcessing.cleanUp();
ParticleMaster.cleanUp();
@ -60,29 +53,29 @@ public class RenderWrapper {
Loader.cleanUp();
System.exit(0);
}
public static void render() {
public static void render()
{
Window.update();
GingerMain.update();
GingerMain.preRenderScene(masterRenderer4D);
masterRenderer4D.renderScene(entities, NORMAL_ENTITY, TERRAIN, lights, camera, new Vector4f(0, -1, 0, 100000));
ParticleMaster.renderParticles(camera);
ParticleMaster.renderParticles(camera);
masterRenderer4D.renderGuis(guis);
TextMaster.render();
Window.swapBuffers();
}
public static void preInit() {
public static void preInit()
{
Window.create(2000, 1200, "LiteCraft - " + splash, 60);
GingerMain.init();
}
public static void update() {
public static void update()
{
Window.update();
GingerMain.update();
ParticleMaster.update(camera);
}
}

View File

@ -55,7 +55,7 @@ public class Timer
}
return false;
}
public interface TickListener
{
void onTick(float deltaTime);

View File

@ -8,15 +8,19 @@ public interface SettingsConfig extends Config
@Key("render.screen_width")
@DefaultValue("640")
public int screenWidth();
@Key("render.screen_height")
@DefaultValue("480")
public int screenHeight();
@Key("render.max_fps")
@DefaultValue("60")
public int max_fps();
@Key("debug.debug_mode")
@DefaultValue("false")
public boolean debugMode();
@Key("debug.spam_log")
@DefaultValue("false")
public boolean spamLog();

View File

@ -7,11 +7,11 @@ public class SettingsHandler
{
public static Options createCommandLineOptions()
{
Options cmdOptions = new Options();
Options cmdOptions = new Options();
cmdOptions.addOption(new Option("w", "width", true, "Screen width"));
cmdOptions.addOption(new Option("h", "height", true, "Screen height"));
cmdOptions.addOption(new Option("debug", "debug", true, "Use debug features"));
cmdOptions.addOption(new Option("spam_log","spam_log", true, "Log sanity checks"));
cmdOptions.addOption(new Option("spam_log", "spam_log", true, "Log sanity checks"));
cmdOptions.addOption(new Option("limit_fps", "limit_fps", true, "Use the FPS limiter"));
cmdOptions.addOption(new Option("max_fps", "max_fps", true, "The maximum amount of FPS"));
return cmdOptions;

View File

@ -1,12 +1,11 @@
package com.github.halotroop.litecraft.registries;
public class BlockList{
// this is how you fix bugs :)
// public static List<Block> blocks;
// public static Block dirt;
// public static Block stone;
public class BlockList
{
// this is how you fix bugs :)
// public static List<Block> blocks;
// public static Block dirt;
// public static Block stone;
public BlockList()
{}
}

View File

@ -1,208 +0,0 @@
package io.github.hydos.ginger;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.glfw.GLFW;
import io.github.hydos.ginger.engine.cameras.ThirdPersonCamera;
import io.github.hydos.ginger.engine.elements.GuiTexture;
import io.github.hydos.ginger.engine.elements.buttons.TextureButton;
import io.github.hydos.ginger.engine.elements.objects.Entity;
import io.github.hydos.ginger.engine.elements.objects.Light;
import io.github.hydos.ginger.engine.elements.objects.RenderPlayer;
import io.github.hydos.ginger.engine.font.FontType;
import io.github.hydos.ginger.engine.font.GUIText;
import io.github.hydos.ginger.engine.font.TextMaster;
import io.github.hydos.ginger.engine.io.Window;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
import io.github.hydos.ginger.engine.obj.ModelLoader;
import io.github.hydos.ginger.engine.obj.normals.NormalMappedObjLoader;
import io.github.hydos.ginger.engine.particle.ParticleMaster;
import io.github.hydos.ginger.engine.particle.ParticleSystem;
import io.github.hydos.ginger.engine.particle.ParticleTexture;
import io.github.hydos.ginger.engine.postProcessing.Fbo;
import io.github.hydos.ginger.engine.postProcessing.PostProcessing;
import io.github.hydos.ginger.engine.renderEngine.MasterRenderer;
import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
import io.github.hydos.ginger.engine.renderEngine.tools.MousePicker;
import io.github.hydos.ginger.engine.terrain.Terrain;
import io.github.hydos.ginger.engine.terrain.TerrainTexture;
import io.github.hydos.ginger.engine.terrain.TerrainTexturePack;
import io.github.hydos.ginger.engine.utils.Loader;
import io.github.hydos.ginger.main.GingerMain;
import io.github.hydos.ginger.main.settings.Constants;
public class Example {
private MasterRenderer masterRenderer;
private List<Terrain> terrains = new ArrayList<Terrain>();
private List<GuiTexture> guis = new ArrayList<GuiTexture>();
private List<Light> lights = new ArrayList<Light>();
private List<Entity> entities = new ArrayList<Entity>();
private List<Entity> normalMapEntities = new ArrayList<Entity>();
public void main(String[] args) {
Window.create(2000, 1200, "Ginger Example", 60);
GingerMain.init();
Window.setBackgroundColour(0.2f, 0.2f, 0.8f);
TexturedModel tModel = ModelLoader.loadModel("stall.obj", "stallTexture.png");
tModel.getTexture().setReflectivity(1f);
tModel.getTexture().setShineDamper(7f);
RenderPlayer entity = new RenderPlayer(tModel, new Vector3f(0,0,-3),0,180f,0, new Vector3f(0.2f, 0.2f, 0.2f));
Constants.movementSpeed = 0.000005f;
Constants.turnSpeed = 0.00002f;
Constants.gravity = -0.000000000005f;
Constants.jumpPower = 0.000005f;
ThirdPersonCamera camera = new ThirdPersonCamera(new Vector3f(0,0.1f,0), entity);
masterRenderer = new MasterRenderer(camera);
FontType font = new FontType(Loader.loadFontAtlas("candara.png"), "candara.fnt");
GUIText text = new GUIText("hi, this is some sample text", 3, font, new Vector2f(0,0), 1f, true);
text.setColour(0, 1, 0);
text.setBorderWidth(0.7f);
text.setBorderEdge(0.4f);
text.setOffset(new Vector2f(0.003f, 0.003f));
ParticleMaster.init(masterRenderer.getProjectionMatrix());
TexturedModel dragonMdl = ModelLoader.loadModel("dragon.obj", "stallTexture.png");
dragonMdl.getTexture().setReflectivity(4f);
dragonMdl.getTexture().setShineDamper(2f);
Light sun = new Light(new Vector3f(100,105,-100), new Vector3f(1.3f, 1.3f, 1.3f), new Vector3f(0.0001f, 0.0001f, 0.0001f));
lights.add(sun);
TexturedModel tgrass = ModelLoader.loadModel("grass.obj", "grass.png");
tgrass.getTexture().setTransparency(true);
tgrass.getTexture().useFakeLighting(true);
TerrainTexture backgroundTexture = Loader.loadTerrainTexture("grass.png");
TerrainTexture rTexture = Loader.loadTerrainTexture("mud.png");
TerrainTexture gTexture = Loader.loadTerrainTexture("grassFlowers.png");
TerrainTexture bTexture = Loader.loadTerrainTexture("path.png");
TerrainTexturePack texturePack = new TerrainTexturePack(backgroundTexture, rTexture, gTexture, bTexture);
TerrainTexture blendMap = Loader.loadTerrainTexture("blendMap.png");
Terrain terrain = new Terrain(-0.5f, -0.5f, texturePack, blendMap, "heightmap.png");
Entity dragon = new Entity(dragonMdl, new Vector3f(3,terrain.getHeightOfTerrain(3, -3),-3),0,180f,0, new Vector3f(0.2f, 0.2f, 0.2f));
Entity grassEntity = new Entity(tgrass, new Vector3f(-3,terrain.getHeightOfTerrain(-3, -3),-3),0,180f,0, new Vector3f(0.2f, 0.2f, 0.2f));
entities.add(grassEntity);
MousePicker picker = new MousePicker(camera, masterRenderer.getProjectionMatrix(), terrain);
TexturedModel barrelModel = new TexturedModel(NormalMappedObjLoader.loadOBJ("barrel.obj"), new ModelTexture("barrel.png"));
barrelModel.getTexture().setNormalMap(new ModelTexture("modelNormals/barrelNormal.png").getTextureID());
barrelModel.getTexture().setShineDamper(10f);
barrelModel.getTexture().setReflectivity(0.5f);
Entity barrel = new Entity(barrelModel, new Vector3f(1,terrain.getHeightOfTerrain(1, 1),1), 0, 0, 0, new Vector3f(0.25f,0.25f,0.25f));
normalMapEntities.add(barrel);
entities.add(entity);
entities.add(dragon);
float colour = 0;
terrains.add(terrain);
ParticleTexture particleTexture = new ParticleTexture(Loader.loadTexture("particles/smoke.png"), 8);
TextureButton button = new TextureButton("/textures/guis/ginger.png", new Vector2f(0.8f, 0), new Vector2f(0.1f, 0.1f));
button.show(guis);
ParticleSystem system = new ParticleSystem(particleTexture, 100, 10f, 0.3f, 4, 3f);
system.randomizeRotation();
system.setDirection(new Vector3f(0,0.001f,0), 0.00001f);
system.setLifeError(0);
system.setSpeedError(0);
system.setScaleError(1f);
Fbo fbo = new Fbo(Window.width, Window.height, Fbo.DEPTH_RENDER_BUFFER);
PostProcessing.init();
while(!Window.closed()) {
if(Window.isUpdating()) {
Window.update();
GingerMain.update();
colour = colour + 0.001f;
picker.update();
ParticleMaster.update(camera);
masterRenderer.renderShadowMap(entities, sun);
camera.move();
entity.move(terrain);
text.setOutlineColour(new Vector3f(colour, colour /2, colour / 3));
Vector3f terrainPoint = picker.getCurrentTerrainPoint();
if(terrainPoint!=null) {
barrel.setPosition(terrainPoint);
if(Window.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_1)) {
normalMapEntities.add(new Entity(barrelModel, terrainPoint, 0, 0, 0, new Vector3f(0.25f,0.25f,0.25f)));
}
}
system.generateParticles(new Vector3f(0,-2,0));
dragon.increaseRotation(0,1,0);
barrel.increaseRotation(0, 1, 0);
GingerMain.preRenderScene(masterRenderer);
fbo.bindFrameBuffer();
masterRenderer.renderScene(entities, normalMapEntities, terrains, lights, camera, new Vector4f(0, -1, 0, 100000));
ParticleMaster.renderParticles(camera);
fbo.unbindFrameBuffer();
PostProcessing.doPostProcessing(fbo.getColourTexture());
// TODO: get fbo's working
button.update();
if(button.isClicked()) {
System.out.println("click");
button.hide(guis);
}
masterRenderer.renderScene(entities, normalMapEntities, terrains, lights, camera, new Vector4f(0, -1, 0, 100000));
masterRenderer.renderGuis(guis);
TextMaster.render();
Window.swapBuffers();
}
}
Window.stop();
PostProcessing.cleanUp();
fbo.cleanUp();
ParticleMaster.cleanUp();
masterRenderer.cleanUp();
TextMaster.cleanUp();
Loader.cleanUp();
System.exit(0);
}
}

View File

@ -1,11 +0,0 @@
package io.github.hydos.ginger;
public class Starter {
// private static final boolean usingEclipse = false;
public static void main(String[] args) {
new Example().main(args);
}
}

View File

@ -6,22 +6,18 @@ import io.github.hydos.ginger.UI.enums.UIDefaultClipSide;
import io.github.hydos.ginger.UI.enums.UIType;
import io.github.hydos.ginger.engine.elements.GuiTexture;
public abstract class UICanvas {
public abstract class UICanvas
{
UIDefaultClipSide clippingSide = UIDefaultClipSide.centre;
UIType type = UIType.tab;
String tabName = "Welcome";
public UICanvas() {
}
public UICanvas()
{}
public abstract void update();
public abstract void hide(List<GuiTexture> textures);
public abstract void show(List<GuiTexture> textures);
}

View File

@ -4,31 +4,25 @@ import io.github.hydos.ginger.UI.canvases.WelcomeScreen;
import io.github.hydos.ginger.UI.enums.UIColourType;
import io.github.hydos.ginger.engine.elements.GuiTexture;
public class UIManager {
public class UIManager
{
UIColourType colourMode = UIColourType.dark;
GuiTexture background;
UICanvas welcomeScreen;
public UIManager(UIColourType type) {
if(type == UIColourType.dark) {
// background = new GuiTexture(Loader.loadTextureDirectly("/engine/ui/dark/background/background.png"), new Vector2f(0,0), new Vector2f(10,10));
public UIManager(UIColourType type)
{
if (type == UIColourType.dark)
{
// background = new GuiTexture(Loader.loadTextureDirectly("/engine/ui/dark/background/background.png"), new Vector2f(0,0), new Vector2f(10,10));
}
this.colourMode = type;
welcomeScreen = new WelcomeScreen();
}
public void update() {
welcomeScreen.update();
}
public GuiTexture getBackgroundTexture() {
return background;
}
public void update()
{ welcomeScreen.update(); }
public GuiTexture getBackgroundTexture()
{ return background; }
}

View File

@ -5,29 +5,20 @@ import java.util.List;
import io.github.hydos.ginger.UI.UICanvas;
import io.github.hydos.ginger.engine.elements.GuiTexture;
public class WelcomeScreen extends UICanvas{
public WelcomeScreen() {
}
public class WelcomeScreen extends UICanvas
{
public WelcomeScreen()
{}
@Override
public void update() {
}
public void update()
{}
@Override
public void hide(List<GuiTexture> textures) {
}
public void hide(List<GuiTexture> textures)
{}
@Override
public void show(List<GuiTexture> textures) {
}
public void show(List<GuiTexture> textures)
{}
}

View File

@ -1,7 +1,6 @@
package io.github.hydos.ginger.UI.enums;
public enum UIColourType {
light,dark
public enum UIColourType
{
light, dark
}

View File

@ -1,6 +1,6 @@
package io.github.hydos.ginger.UI.enums;
public enum UIDefaultClipSide {
top,bottom,left,right,centre
public enum UIDefaultClipSide
{
top, bottom, left, right, centre
}

View File

@ -1,7 +1,6 @@
package io.github.hydos.ginger.UI.enums;
public enum UIType {
public enum UIType
{
tab, wholeScreen
}

View File

@ -5,69 +5,47 @@ import org.lwjgl.glfw.GLFW;
import io.github.hydos.ginger.engine.io.Window;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class FirstPersonCamera {
private Vector3f position = new Vector3f(0,0,0);
public class FirstPersonCamera
{
private Vector3f position = new Vector3f(0, 0, 0);
private float pitch, yaw;
private float roll;
public FirstPersonCamera() {
}
public FirstPersonCamera(Vector3f vector3f) {
this.position = vector3f;
public FirstPersonCamera()
{}
public FirstPersonCamera(Vector3f vector3f)
{ this.position = vector3f; }
public void move()
{
if (Window.isKeyDown(GLFW.GLFW_KEY_W))
{ position.z -= 0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_A))
{ position.x -= 0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_S))
{ position.z -= -0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_D))
{ position.x += 0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_SPACE))
{ position.y += 0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT))
{ position.y -= 0.05f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_LEFT))
{ yaw -= 0.5f; }
if (Window.isKeyDown(GLFW.GLFW_KEY_RIGHT))
{ yaw += 0.5f; }
}
public void move() {
if(Window.isKeyDown(GLFW.GLFW_KEY_W)){
position.z-=0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_A)){
position.x-=0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_S)){
position.z-=-0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_D)){
position.x+=0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_SPACE)){
position.y+=0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT)){
position.y-=0.05f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_LEFT)){
yaw-=0.5f;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_RIGHT)){
yaw+=0.5f;
}
}
public Vector3f getPosition()
{ return position; }
public Vector3f getPosition() {
return position;
}
public float getPitch()
{ return pitch; }
public float getYaw()
{ return yaw; }
public float getPitch() {
return pitch;
}
public float getYaw() {
return yaw;
}
public float getRoll() {
return roll;
}
public float getRoll()
{ return roll; }
}

View File

@ -7,32 +7,26 @@ import io.github.hydos.ginger.engine.elements.objects.RenderPlayer;
import io.github.hydos.ginger.engine.io.Window;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class ThirdPersonCamera {
public class ThirdPersonCamera
{
private float distanceFromPlayer = 5;
private float angleAroundPlayer = 0;
private Vector3f position = new Vector3f(0,0,0);
private Vector3f position = new Vector3f(0, 0, 0);
private float pitch, yaw;
private float roll;
private RenderPlayer player;
public ThirdPersonCamera(RenderPlayer player)
{ this.player = player; }
public ThirdPersonCamera(RenderPlayer player) {
this.player = player;
}
public ThirdPersonCamera(Vector3f vector3f, RenderPlayer player) {
public ThirdPersonCamera(Vector3f vector3f, RenderPlayer player)
{
this.position = vector3f;
this.player = player;
}
public void move(){
public void move()
{
calculateZoom();
calculatePitch();
calculateAngleAroundPlayer();
@ -41,28 +35,24 @@ public class ThirdPersonCamera {
calculateCameraPosition(horizontalDistance, verticalDistance);
this.yaw = 180 - (player.getRotY() + angleAroundPlayer);
}
public void invertPitch(){
this.pitch = -pitch;
}
public Vector3f getPosition() {
return position;
}
public void invertPitch()
{ this.pitch = -pitch; }
public float getPitch() {
return pitch;
}
public Vector3f getPosition()
{ return position; }
public float getYaw() {
return yaw;
}
public float getPitch()
{ return pitch; }
public float getRoll() {
return roll;
}
private void calculateCameraPosition(float horizDistance, float verticDistance){
public float getYaw()
{ return yaw; }
public float getRoll()
{ return roll; }
private void calculateCameraPosition(float horizDistance, float verticDistance)
{
float theta = player.getRotY() + angleAroundPlayer;
float offsetX = (float) (horizDistance * Math.sin(Math.toRadians(theta)));
float offsetZ = (float) (horizDistance * Math.cos(Math.toRadians(theta)));
@ -70,45 +60,52 @@ public class ThirdPersonCamera {
position.z = player.getPosition().z - offsetZ;
position.y = player.getPosition().y + verticDistance;
}
private float calculateHorizontalDistance(){
private float calculateHorizontalDistance()
{
float hD = (float) (distanceFromPlayer * Math.cos(Math.toRadians(pitch)));
if(hD < 0)
if (hD < 0)
hD = 0;
return hD;
}
private float calculateVerticalDistance(){
return (float) (distanceFromPlayer * Math.sin(Math.toRadians(pitch+4)));
}
private void calculateZoom(){
GLFW.glfwSetScrollCallback(Window.window, new GLFWScrollCallback() {
@Override public void invoke (long win, double dx, double dy) {
private float calculateVerticalDistance()
{ return (float) (distanceFromPlayer * Math.sin(Math.toRadians(pitch + 4))); }
private void calculateZoom()
{
GLFW.glfwSetScrollCallback(Window.window, new GLFWScrollCallback()
{
@Override
public void invoke(long win, double dx, double dy)
{
float zoomLevel = (float) dy * 0.1f;
distanceFromPlayer -= zoomLevel;
}
});
});
}
private void calculatePitch(){
if(Window.isMouseDown(1)) {
private void calculatePitch()
{
if (Window.isMouseDown(1))
{
float pitchChange = (float) (Window.dy * 0.2f);
pitch += pitchChange;
if(pitch < 0){
if (pitch < 0)
{
pitch = 0;
}else if(pitch > 90){
pitch = 90;
}
else if (pitch > 90)
{ pitch = 90; }
}
}
private void calculateAngleAroundPlayer(){
if(Window.isMouseDown(1)) {
private void calculateAngleAroundPlayer()
{
if (Window.isMouseDown(1))
{
float angleChange = (float) (Window.dx * 0.3f);
angleAroundPlayer -= angleChange;
}
}
}

View File

@ -2,39 +2,33 @@ package io.github.hydos.ginger.engine.elements;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
public class GuiTexture {
public class GuiTexture
{
private int texture;
private Vector2f position, scale;
public GuiTexture(int texture, Vector2f position, Vector2f scale) {
public GuiTexture(int texture, Vector2f position, Vector2f scale)
{
this.texture = texture;
this.position = position;
this.scale = scale;
}
public int getTexture() {
return texture;
}
public int getTexture()
{ return texture; }
public Vector2f getPosition() {
return position;
}
public Vector2f getPosition()
{ return position; }
public Vector2f getScale() {
return scale;
}
public Vector2f getScale()
{ return scale; }
public void setTexture(int texture) {
this.texture = texture;
}
public void setTexture(int texture)
{ this.texture = texture; }
public void setPosition(Vector2f position) {
this.position = position;
}
public void setPosition(Vector2f position)
{ this.position = position; }
public void setScale(Vector2f scale) {
this.scale = scale;
}
public void setScale(Vector2f scale)
{ this.scale = scale; }
}

View File

@ -9,79 +9,78 @@ import io.github.hydos.ginger.engine.io.Window;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.utils.Loader;
public class TextureButton{
public class TextureButton
{
private GuiTexture guiTexture;
private boolean shown = false;
private boolean clicked = false;
private boolean isHovering = false;
public TextureButton(String texture, Vector2f position, Vector2f scale) {
guiTexture = new GuiTexture(Loader.loadTextureDirectly(texture), position, scale);
}
public void update() {
if(shown) {
public TextureButton(String texture, Vector2f position, Vector2f scale)
{ guiTexture = new GuiTexture(Loader.loadTextureDirectly(texture), position, scale); }
public void update()
{
if (shown)
{
Vector2f location = guiTexture.getPosition();
Vector2f scale = guiTexture.getScale();
Vector2f mouseCoords = Window.getNormalizedMouseCoordinates();
if(location.y + scale.y > -mouseCoords.y && location.y - scale.y < -mouseCoords.y && location.x + scale.x > mouseCoords.x && location.x - scale.x < mouseCoords.x) {
if (location.y + scale.y > -mouseCoords.y && location.y - scale.y < -mouseCoords.y && location.x + scale.x > mouseCoords.x && location.x - scale.x < mouseCoords.x)
{
isHovering = true;
if(Window.isMousePressed(GLFW.GLFW_MOUSE_BUTTON_1)) {
if (Window.isMousePressed(GLFW.GLFW_MOUSE_BUTTON_1))
{
clicked = true;
}else {
}
else
{
clicked = false;
}
}else {
if(isHovering) {
isHovering = false;
}
}
}else {
else
{
if (isHovering)
{ isHovering = false; }
}
}
else
{
isHovering = false;
clicked = false;
}
}
public void show(List<GuiTexture> guiTexture) {
if(shown) {
}else {
public void show(List<GuiTexture> guiTexture)
{
if (shown)
{
}
else
{
guiTexture.add(this.guiTexture);
this.shown = true;
}
}
public void hide(List<GuiTexture> guiTexture) {
if(!shown) {
}else {
public void hide(List<GuiTexture> guiTexture)
{
if (!shown)
{
}
else
{
guiTexture.remove(this.guiTexture);
this.shown = false;
}
}
public boolean isShown() {
return shown;
}
public boolean isClicked() {
return clicked;
}
public boolean isHovering() {
return isHovering;
}
public boolean isShown()
{ return shown; }
public boolean isClicked()
{ return clicked; }
public boolean isHovering()
{ return isHovering; }
}

View File

@ -3,13 +3,15 @@ package io.github.hydos.ginger.engine.elements.objects;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
public class Entity {
public class Entity
{
private TexturedModel model;
private Vector3f position;
private float rotX = 0,rotY = 0,rotZ = 0;
private float rotX = 0, rotY = 0, rotZ = 0;
private Vector3f scale;
public Entity(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, Vector3f scale) {
public Entity(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, Vector3f scale)
{
this.model = model;
this.position = position;
this.rotX = rotX;
@ -17,64 +19,54 @@ public class Entity {
this.rotZ = rotZ;
this.scale = scale;
}
public void increasePosition(float dx, float dy, float dz) {
public void increasePosition(float dx, float dy, float dz)
{
this.position.x += dx;
this.position.y += dy;
this.position.z += dz;
}
public void increaseRotation(float dx, float dy, float dz) {
public void increaseRotation(float dx, float dy, float dz)
{
this.rotX += dx;
this.rotY += dy;
this.rotZ += dz;
}
public TexturedModel getModel() {
return model;
}
public TexturedModel getModel()
{ return model; }
public void setModel(TexturedModel model) {
this.model = model;
}
public void setModel(TexturedModel model)
{ this.model = model; }
public Vector3f getPosition() {
return position;
}
public Vector3f getPosition()
{ return position; }
public void setPosition(Vector3f position) {
this.position = position;
}
public void setPosition(Vector3f position)
{ this.position = position; }
public float getRotX() {
return rotX;
}
public float getRotX()
{ return rotX; }
public void setRotX(float rotX) {
this.rotX = rotX;
}
public void setRotX(float rotX)
{ this.rotX = rotX; }
public float getRotY() {
return rotY;
}
public float getRotY()
{ return rotY; }
public void setRotY(float rotY) {
this.rotY = rotY;
}
public void setRotY(float rotY)
{ this.rotY = rotY; }
public float getRotZ() {
return rotZ;
}
public float getRotZ()
{ return rotZ; }
public void setRotZ(float rotZ) {
this.rotZ = rotZ;
}
public void setRotZ(float rotZ)
{ this.rotZ = rotZ; }
public Vector3f getScale() {
return scale;
}
public void setScale(Vector3f scale) {
this.scale = scale;
}
public Vector3f getScale()
{ return scale; }
public void setScale(Vector3f scale)
{ this.scale = scale; }
}

View File

@ -2,43 +2,38 @@ package io.github.hydos.ginger.engine.elements.objects;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class Light {
public class Light
{
private Vector3f position, colour, attenuation;
public Light(Vector3f position, Vector3f colour) {
public Light(Vector3f position, Vector3f colour)
{
this.position = position;
this.colour = colour;
}
public Light(Vector3f position, Vector3f colour, Vector3f attenuation) {
public Light(Vector3f position, Vector3f colour, Vector3f attenuation)
{
this.position = position;
this.colour = colour;
this.attenuation = attenuation;
}
public void setAttenuation(Vector3f a) {
this.attenuation = a;
}
public void setAttenuation(Vector3f a)
{ this.attenuation = a; }
public Vector3f getPosition() {
return position;
}
public Vector3f getPosition()
{ return position; }
public Vector3f getColour() {
return colour;
}
public Vector3f getColour()
{ return colour; }
public void setPosition(Vector3f position) {
this.position = position;
}
public void setPosition(Vector3f position)
{ this.position = position; }
public void setColour(Vector3f colour) {
this.colour = colour;
}
public void setColour(Vector3f colour)
{ this.colour = colour; }
public Vector3f getAttenuation() {
return attenuation;
}
public Vector3f getAttenuation()
{ return attenuation; }
}

View File

@ -8,29 +8,25 @@ import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.terrain.Terrain;
import io.github.hydos.ginger.main.settings.Constants;
public class RenderPlayer extends Entity{
// private static float RUN_SPEED = 0.3f;
// private static float TURN_SPEED = 0.7f;
// public static float GRAVITY = -0.04f;
// private static float JUMP_POWER = 0.3f;
public class RenderPlayer extends Entity
{
// private static float RUN_SPEED = 0.3f;
// private static float TURN_SPEED = 0.7f;
// public static float GRAVITY = -0.04f;
// private static float JUMP_POWER = 0.3f;
private static float terrainHeight = 0;
private float currentSpeed = 0;
private float currentTurn = 0;
private float upwardsSpeed = 0;
private boolean isInAir = false;
public RenderPlayer(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, Vector3f scale) {
super(model, position, rotX, rotY, rotZ, scale);
}
public void move(Terrain t) {
public RenderPlayer(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, Vector3f scale)
{ super(model, position, rotX, rotY, rotZ, scale); }
public void move(Terrain t)
{
checkInputs();
super.increaseRotation(0, (float) ((currentTurn) * Window.getTime() ), 0);
super.increaseRotation(0, (float) ((currentTurn) * Window.getTime()), 0);
float distance = (float) ((currentSpeed) * (Window.getTime()));
float dx = (float) (distance * Math.sin(Math.toRadians(super.getRotY())));
float dz = (float) (distance * Math.cos(Math.toRadians(super.getRotY())));
@ -38,47 +34,51 @@ public class RenderPlayer extends Entity{
super.increasePosition(0, (float) (upwardsSpeed * (Window.getTime())), 0);
terrainHeight = t.getHeightOfTerrain(super.getPosition().x, super.getPosition().z);
upwardsSpeed += Constants.gravity * Window.getTime();
if(super.getPosition().y < terrainHeight) {
if (super.getPosition().y < terrainHeight)
{
isInAir = false;
upwardsSpeed = 0;
super.getPosition().y = terrainHeight;
}
}
private void jump() {
if(!isInAir) {
private void jump()
{
if (!isInAir)
{
isInAir = true;
this.upwardsSpeed = Constants.jumpPower;
}
}
private void checkInputs() {
if(Window.isKeyDown(GLFW.GLFW_KEY_W)) {
private void checkInputs()
{
if (Window.isKeyDown(GLFW.GLFW_KEY_W))
{
this.currentSpeed = Constants.movementSpeed;
}
else if(Window.isKeyDown(GLFW.GLFW_KEY_S)) {
else if (Window.isKeyDown(GLFW.GLFW_KEY_S))
{
this.currentSpeed = -Constants.movementSpeed;
}else {
}
else
{
this.currentSpeed = 0;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_A)) {
if (Window.isKeyDown(GLFW.GLFW_KEY_A))
{
this.currentTurn = Constants.turnSpeed;
}
else if(Window.isKeyDown(GLFW.GLFW_KEY_D)) {
this.currentTurn = -Constants.turnSpeed;
}
if(Window.isKeyReleased(68) || Window.isKeyReleased(65)){
this.currentTurn = 0;
}
if(Window.isKeyDown(GLFW.GLFW_KEY_SPACE)) {
else if (Window.isKeyDown(GLFW.GLFW_KEY_D))
{ this.currentTurn = -Constants.turnSpeed; }
if (Window.isKeyReleased(68) || Window.isKeyReleased(65))
{ this.currentTurn = 0; }
if (Window.isKeyDown(GLFW.GLFW_KEY_SPACE))
{
jump();
}else {
}
else
{
}
}
}

View File

@ -1,13 +1,9 @@
package io.github.hydos.ginger.engine.font;
/**
* Simple data structure class holding information about a certain glyph in the
* font texture atlas. All sizes are for a font-size of 1.
*
*
*/
public class Character {
/** Simple data structure class holding information about a certain glyph in the
* font texture atlas. All sizes are for a font-size of 1. */
public class Character
{
private int id;
private double xTextureCoord;
private double yTextureCoord;
@ -19,35 +15,34 @@ public class Character {
private double sizeY;
private double xAdvance;
/**
* @param id
* - the ASCII value of the character.
/** @param id
* - the ASCII value of the character.
* @param xTextureCoord
* - the x texture coordinate for the top left corner of the
* character in the texture atlas.
* - the x texture coordinate for the top left corner of the
* character in the texture atlas.
* @param yTextureCoord
* - the y texture coordinate for the top left corner of the
* character in the texture atlas.
* - the y texture coordinate for the top left corner of the
* character in the texture atlas.
* @param xTexSize
* - the width of the character in the texture atlas.
* - the width of the character in the texture atlas.
* @param yTexSize
* - the height of the character in the texture atlas.
* - the height of the character in the texture atlas.
* @param xOffset
* - the x distance from the curser to the left edge of the
* character's quad.
* - the x distance from the curser to the left edge of the
* character's quad.
* @param yOffset
* - the y distance from the curser to the top edge of the
* character's quad.
* - the y distance from the curser to the top edge of the
* character's quad.
* @param sizeX
* - the width of the character's quad in screen space.
* - the width of the character's quad in screen space.
* @param sizeY
* - the height of the character's quad in screen space.
* - the height of the character's quad in screen space.
* @param xAdvance
* - how far in pixels the cursor should advance after adding
* this character.
*/
* - how far in pixels the cursor should advance after adding
* this character. */
protected Character(int id, double xTextureCoord, double yTextureCoord, double xTexSize, double yTexSize,
double xOffset, double yOffset, double sizeX, double sizeY, double xAdvance) {
double xOffset, double yOffset, double sizeX, double sizeY, double xAdvance)
{
this.id = id;
this.xTextureCoord = xTextureCoord;
this.yTextureCoord = yTextureCoord;
@ -60,44 +55,33 @@ public class Character {
this.xAdvance = xAdvance;
}
protected int getId() {
return id;
}
protected int getId()
{ return id; }
protected double getxTextureCoord() {
return xTextureCoord;
}
protected double getxTextureCoord()
{ return xTextureCoord; }
protected double getyTextureCoord() {
return yTextureCoord;
}
protected double getyTextureCoord()
{ return yTextureCoord; }
protected double getXMaxTextureCoord() {
return xMaxTextureCoord;
}
protected double getXMaxTextureCoord()
{ return xMaxTextureCoord; }
protected double getYMaxTextureCoord() {
return yMaxTextureCoord;
}
protected double getYMaxTextureCoord()
{ return yMaxTextureCoord; }
protected double getxOffset() {
return xOffset;
}
protected double getxOffset()
{ return xOffset; }
protected double getyOffset() {
return yOffset;
}
protected double getyOffset()
{ return yOffset; }
protected double getSizeX() {
return sizeX;
}
protected double getSizeX()
{ return sizeX; }
protected double getSizeY() {
return sizeY;
}
protected double getxAdvance() {
return xAdvance;
}
protected double getSizeY()
{ return sizeY; }
protected double getxAdvance()
{ return xAdvance; }
}

View File

@ -1,49 +1,37 @@
package io.github.hydos.ginger.engine.font;
/**
* Represents a font. It holds the font's texture atlas as well as having the
* ability to create the quad vertices for any text using this font.
*
*
*/
public class FontType {
/** Represents a font. It holds the font's texture atlas as well as having the
* ability to create the quad vertices for any text using this font. */
public class FontType
{
private int textureAtlas;
private TextMeshCreator loader;
/**
* Creates a new font and loads up the data about each character from the
/** Creates a new font and loads up the data about each character from the
* font file.
*
* @param textureAtlas
* - the ID of the font atlas texture.
* - the ID of the font atlas texture.
* @param fontFile
* - the font file containing information about each character in
* the texture atlas.
*/
public FontType(int textureAtlas, String fontFile) {
* - the font file containing information about each character in
* the texture atlas. */
public FontType(int textureAtlas, String fontFile)
{
this.textureAtlas = textureAtlas;
this.loader = new TextMeshCreator(fontFile);
}
/**
* @return The font texture atlas.
*/
public int getTextureAtlas() {
return textureAtlas;
}
/** @return The font texture atlas. */
public int getTextureAtlas()
{ return textureAtlas; }
/**
* Takes in an unloaded text and calculate all of the vertices for the quads
/** Takes in an unloaded text and calculate all of the vertices for the quads
* on which this text will be rendered. The vertex positions and texture
* coords and calculated based on the information from the font file.
*
* @param text
* - the unloaded text.
* @return Information about the vertices of all the quads.
*/
public TextMeshData loadText(GUIText text) {
return loader.createTextMesh(text);
}
* @param text
* - the unloaded text.
* @return Information about the vertices of all the quads. */
public TextMeshData loadText(GUIText text)
{ return loader.createTextMesh(text); }
}

View File

@ -3,58 +3,48 @@ package io.github.hydos.ginger.engine.font;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
/**
* Represents a piece of text in the game.
*
*
*/
public class GUIText {
/** Represents a piece of text in the game. */
public class GUIText
{
private String textString;
private float fontSize;
private int textMeshVao;
private int vertexCount;
private Vector3f colour = new Vector3f(0f, 0f, 0f), outlineColour;
private float borderEdge = 0.1f, borderWidth = 0;
private Vector2f offset = new Vector2f(0, 0);
private Vector2f position;
private float lineMaxSize;
private int numberOfLines;
private FontType font;
private boolean centerText = false;
/**
* Creates a new text, loads the text's quads into a VAO, and adds the text
/** Creates a new text, loads the text's quads into a VAO, and adds the text
* to the screen.
*
* @param text
* - the text.
* - the text.
* @param fontSize
* - the font size of the text, where a font size of 1 is the
* default size.
* - the font size of the text, where a font size of 1 is the
* default size.
* @param font
* - the font that this text should use.
* - the font that this text should use.
* @param position
* - the position on the screen where the top left corner of the
* text should be rendered. The top left corner of the screen is
* (0, 0) and the bottom right is (1, 1).
* - the position on the screen where the top left corner of the
* text should be rendered. The top left corner of the screen is
* (0, 0) and the bottom right is (1, 1).
* @param maxLineLength
* - basically the width of the virtual page in terms of screen
* width (1 is full screen width, 0.5 is half the width of the
* screen, etc.) Text cannot go off the edge of the page, so if
* the text is longer than this length it will go onto the next
* line. When text is centered it is centered into the middle of
* the line, based on this line length value.
* - basically the width of the virtual page in terms of screen
* width (1 is full screen width, 0.5 is half the width of the
* screen, etc.) Text cannot go off the edge of the page, so if
* the text is longer than this length it will go onto the next
* line. When text is centered it is centered into the middle of
* the line, based on this line length value.
* @param centered
* - whether the text should be centered or not.
*/
* - whether the text should be centered or not. */
public GUIText(String text, float fontSize, FontType font, Vector2f position, float maxLineLength,
boolean centered) {
boolean centered)
{
this.textString = text;
this.fontSize = fontSize;
this.font = font;
@ -65,157 +55,107 @@ public class GUIText {
TextMaster.loadText(this);
}
/**
* Remove the text from the screen.
*/
public void remove() {
TextMaster.removeText(this);
}
/** Remove the text from the screen. */
public void remove()
{ TextMaster.removeText(this); }
/**
* @return The font used by this text.
*/
public FontType getFont() {
return font;
}
/** @return The font used by this text. */
public FontType getFont()
{ return font; }
/**
* Set the colour of the text.
/** Set the colour of the text.
*
* @param r
* - red value, between 0 and 1.
* - red value, between 0 and 1.
* @param g
* - green value, between 0 and 1.
* - green value, between 0 and 1.
* @param b
* - blue value, between 0 and 1.
*/
public void setColour(float r, float g, float b) {
colour.set(r, g, b);
}
* - blue value, between 0 and 1. */
public void setColour(float r, float g, float b)
{ colour.set(r, g, b); }
/**
* @return the colour of the text.
*/
public Vector3f getColour() {
return colour;
}
/** @return the colour of the text. */
public Vector3f getColour()
{ return colour; }
/**
* @return The number of lines of text. This is determined when the text is
/** @return The number of lines of text. This is determined when the text is
* loaded, based on the length of the text and the max line length
* that is set.
*/
public int getNumberOfLines() {
return numberOfLines;
}
* that is set. */
public int getNumberOfLines()
{ return numberOfLines; }
/**
* @return The position of the top-left corner of the text in screen-space.
/** @return The position of the top-left corner of the text in screen-space.
* (0, 0) is the top left corner of the screen, (1, 1) is the bottom
* right.
*/
public Vector2f getPosition() {
return position;
}
* right. */
public Vector2f getPosition()
{ return position; }
/**
* @return the ID of the text's VAO, which contains all the vertex data for
* the quads on which the text will be rendered.
*/
public int getMesh() {
return textMeshVao;
}
/** @return the ID of the text's VAO, which contains all the vertex data for
* the quads on which the text will be rendered. */
public int getMesh()
{ return textMeshVao; }
/**
* Set the VAO and vertex count for this text.
/** Set the VAO and vertex count for this text.
*
* @param vao
* - the VAO containing all the vertex data for the quads on
* which the text will be rendered.
* - the VAO containing all the vertex data for the quads on
* which the text will be rendered.
* @param verticesCount
* - the total number of vertices in all of the quads.
*/
public void setMeshInfo(int vao, int verticesCount) {
* - the total number of vertices in all of the quads. */
public void setMeshInfo(int vao, int verticesCount)
{
this.textMeshVao = vao;
this.vertexCount = verticesCount;
}
/**
* @return The total number of vertices of all the text's quads.
*/
public int getVertexCount() {
return this.vertexCount;
}
/** @return The total number of vertices of all the text's quads. */
public int getVertexCount()
{ return this.vertexCount; }
/**
* @return the font size of the text (a font size of 1 is normal).
*/
protected float getFontSize() {
return fontSize;
}
/** @return the font size of the text (a font size of 1 is normal). */
protected float getFontSize()
{ return fontSize; }
/**
* Sets the number of lines that this text covers (method used only in
/** Sets the number of lines that this text covers (method used only in
* loading).
*
* @param number
*/
protected void setNumberOfLines(int number) {
this.numberOfLines = number;
}
* @param number */
protected void setNumberOfLines(int number)
{ this.numberOfLines = number; }
/**
* @return {@code true} if the text should be centered.
*/
protected boolean isCentered() {
return centerText;
}
/** @return {@code true} if the text should be centered. */
protected boolean isCentered()
{ return centerText; }
/**
* @return The maximum length of a line of this text.
*/
protected float getMaxLineSize() {
return lineMaxSize;
}
/** @return The maximum length of a line of this text. */
protected float getMaxLineSize()
{ return lineMaxSize; }
/**
* @return The string of text.
*/
protected String getTextString() {
return textString;
}
/** @return The string of text. */
protected String getTextString()
{ return textString; }
public Vector3f getOutlineColour() {
return outlineColour;
}
public Vector3f getOutlineColour()
{ return outlineColour; }
public float getBorderEdge() {
return borderEdge;
}
public float getBorderEdge()
{ return borderEdge; }
public void setBorderEdge(float borderEdge) {
this.borderEdge = borderEdge;
}
public void setBorderEdge(float borderEdge)
{ this.borderEdge = borderEdge; }
public float getBorderWidth() {
return borderWidth;
}
public float getBorderWidth()
{ return borderWidth; }
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
public void setBorderWidth(float borderWidth)
{ this.borderWidth = borderWidth; }
public Vector2f getOffset() {
return offset;
}
public void setOffset(Vector2f offset) {
this.offset = offset;
}
public void setOutlineColour(Vector3f outlineColour) {
this.outlineColour = outlineColour;
}
public Vector2f getOffset()
{ return offset; }
public void setOffset(Vector2f offset)
{ this.offset = offset; }
public void setOutlineColour(Vector3f outlineColour)
{ this.outlineColour = outlineColour; }
}

View File

@ -3,75 +3,62 @@ package io.github.hydos.ginger.engine.font;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a line of text during the loading of a text.
/** Represents a line of text during the loading of a text.
*
* @author Karl
*
*/
public class Line {
* @author Karl */
public class Line
{
private double maxLength;
private double spaceSize;
private List<Word> words = new ArrayList<Word>();
private double currentLineLength = 0;
/**
* Creates an empty line.
/** Creates an empty line.
*
* @param spaceWidth
* - the screen-space width of a space character.
* - the screen-space width of a space character.
* @param fontSize
* - the size of font being used.
* - the size of font being used.
* @param maxLength
* - the screen-space maximum length of a line.
*/
protected Line(double spaceWidth, double fontSize, double maxLength) {
* - the screen-space maximum length of a line. */
protected Line(double spaceWidth, double fontSize, double maxLength)
{
this.spaceSize = spaceWidth * fontSize;
this.maxLength = maxLength;
}
/**
* Attempt to add a word to the line. If the line can fit the word in
/** Attempt to add a word to the line. If the line can fit the word in
* without reaching the maximum line length then the word is added and the
* line length increased.
*
* @param word
* - the word to try to add.
* @return {@code true} if the word has successfully been added to the line.
*/
protected boolean attemptToAddWord(Word word) {
* @param word
* - the word to try to add.
* @return {@code true} if the word has successfully been added to the line. */
protected boolean attemptToAddWord(Word word)
{
double additionalLength = word.getWordWidth();
additionalLength += !words.isEmpty() ? spaceSize : 0;
if (currentLineLength + additionalLength <= maxLength) {
if (currentLineLength + additionalLength <= maxLength)
{
words.add(word);
currentLineLength += additionalLength;
return true;
} else {
}
else
{
return false;
}
}
/**
* @return The max length of the line.
*/
protected double getMaxLength() {
return maxLength;
}
/** @return The max length of the line. */
protected double getMaxLength()
{ return maxLength; }
/**
* @return The current screen-space length of the line.
*/
protected double getLineLength() {
return currentLineLength;
}
/**
* @return The list of words in the line.
*/
protected List<Word> getWords() {
return words;
}
/** @return The current screen-space length of the line. */
protected double getLineLength()
{ return currentLineLength; }
/** @return The list of words in the line. */
protected List<Word> getWords()
{ return words; }
}

View File

@ -8,44 +8,33 @@ import java.util.Map;
import io.github.hydos.ginger.engine.io.Window;
/**
* Provides functionality for getting the values from a font file.
*
*
*/
public class MetaFile {
/** Provides functionality for getting the values from a font file. */
public class MetaFile
{
private static final int PAD_TOP = 0;
private static final int PAD_LEFT = 1;
private static final int PAD_BOTTOM = 2;
private static final int PAD_RIGHT = 3;
private static final int DESIRED_PADDING = 8;
private static final String SPLITTER = " ";
private static final String NUMBER_SEPARATOR = ",";
private double aspectRatio;
private double verticalPerPixelSize;
private double horizontalPerPixelSize;
private double spaceWidth;
private int[] padding;
private int paddingWidth;
private int paddingHeight;
private Map<Integer, Character> metaData = new HashMap<Integer, Character>();
private BufferedReader reader;
private Map<String, String> values = new HashMap<String, String>();
/**
* Opens a font file in preparation for reading.
/** Opens a font file in preparation for reading.
*
* @param file
* - the font file.
*/
protected MetaFile(String file) {
* - the font file. */
protected MetaFile(String file)
{
this.aspectRatio = (double) Window.width / (double) Window.height;
openFile(file);
loadPaddingData();
@ -55,145 +44,140 @@ public class MetaFile {
close();
}
protected double getSpaceWidth() {
return spaceWidth;
}
protected double getSpaceWidth()
{ return spaceWidth; }
protected Character getCharacter(int ascii) {
return metaData.get(ascii);
}
protected Character getCharacter(int ascii)
{ return metaData.get(ascii); }
/**
* Read in the next line and store the variable values.
/** Read in the next line and store the variable values.
*
* @return {@code true} if the end of the file hasn't been reached.
*/
private boolean processNextLine() {
* @return {@code true} if the end of the file hasn't been reached. */
private boolean processNextLine()
{
values.clear();
String line = null;
try {
try
{
line = reader.readLine();
} catch (IOException e1) {
}
if (line == null) {
return false;
catch (IOException e1)
{
}
for (String part : line.split(SPLITTER)) {
if (line == null)
{ return false; }
for (String part : line.split(SPLITTER))
{
String[] valuePairs = part.split("=");
if (valuePairs.length == 2) {
values.put(valuePairs[0], valuePairs[1]);
}
if (valuePairs.length == 2)
{ values.put(valuePairs[0], valuePairs[1]); }
}
return true;
}
/**
* Gets the {@code int} value of the variable with a certain name on the
/** Gets the {@code int} value of the variable with a certain name on the
* current line.
*
* @param variable
* - the name of the variable.
* @return The value of the variable.
*/
private int getValueOfVariable(String variable) {
return Integer.parseInt(values.get(variable));
}
* @param variable
* - the name of the variable.
* @return The value of the variable. */
private int getValueOfVariable(String variable)
{ return Integer.parseInt(values.get(variable)); }
/**
* Gets the array of ints associated with a variable on the current line.
/** Gets the array of ints associated with a variable on the current line.
*
* @param variable
* - the name of the variable.
* @return The int array of values associated with the variable.
*/
private int[] getValuesOfVariable(String variable) {
* @param variable
* - the name of the variable.
* @return The int array of values associated with the variable. */
private int[] getValuesOfVariable(String variable)
{
String[] numbers = values.get(variable).split(NUMBER_SEPARATOR);
int[] actualValues = new int[numbers.length];
for (int i = 0; i < actualValues.length; i++) {
actualValues[i] = Integer.parseInt(numbers[i]);
}
for (int i = 0; i < actualValues.length; i++)
{ actualValues[i] = Integer.parseInt(numbers[i]); }
return actualValues;
}
/**
* Closes the font file after finishing reading.
*/
private void close() {
try {
/** Closes the font file after finishing reading. */
private void close()
{
try
{
reader.close();
} catch (IOException e) {
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* Opens the font file, ready for reading.
/** Opens the font file, ready for reading.
*
* @param file
* - the font file.
*/
private void openFile(String file) {
try {
* - the font file. */
private void openFile(String file)
{
try
{
reader = new BufferedReader(new InputStreamReader(Class.class.getResourceAsStream("/fonts/" + file)));
} catch (Exception e) {
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Couldn't read font meta file!");
}
}
/**
* Loads the data about how much padding is used around each character in
* the texture atlas.
*/
private void loadPaddingData() {
/** Loads the data about how much padding is used around each character in
* the texture atlas. */
private void loadPaddingData()
{
processNextLine();
this.padding = getValuesOfVariable("padding");
this.paddingWidth = padding[PAD_LEFT] + padding[PAD_RIGHT];
this.paddingHeight = padding[PAD_TOP] + padding[PAD_BOTTOM];
}
/**
* Loads information about the line height for this font in pixels, and uses
/** Loads information about the line height for this font in pixels, and uses
* this as a way to find the conversion rate between pixels in the texture
* atlas and screen-space.
*/
private void loadLineSizes() {
* atlas and screen-space. */
private void loadLineSizes()
{
processNextLine();
int lineHeightPixels = getValueOfVariable("lineHeight") - paddingHeight;
verticalPerPixelSize = TextMeshCreator.LINE_HEIGHT / (double) lineHeightPixels;
verticalPerPixelSize = TextMeshCreator.LINE_HEIGHT / lineHeightPixels;
horizontalPerPixelSize = verticalPerPixelSize / aspectRatio;
}
/**
* Loads in data about each character and stores the data in the
/** Loads in data about each character and stores the data in the
* {@link Character} class.
*
* @param imageWidth
* - the width of the texture atlas in pixels.
*/
private void loadCharacterData(int imageWidth) {
* - the width of the texture atlas in pixels. */
private void loadCharacterData(int imageWidth)
{
processNextLine();
processNextLine();
while (processNextLine()) {
while (processNextLine())
{
Character c = loadCharacter(imageWidth);
if (c != null) {
metaData.put(c.getId(), c);
}
if (c != null)
{ metaData.put(c.getId(), c); }
}
}
/**
* Loads all the data about one character in the texture atlas and converts
/** Loads all the data about one character in the texture atlas and converts
* it all from 'pixels' to 'screen-space' before storing. The effects of
* padding are also removed from the data.
*
* @param imageSize
* - the size of the texture atlas in pixels.
* @return The data about the character.
*/
private Character loadCharacter(int imageSize) {
* @param imageSize
* - the size of the texture atlas in pixels.
* @return The data about the character. */
private Character loadCharacter(int imageSize)
{
int id = getValueOfVariable("id");
if (id == TextMeshCreator.SPACE_ASCII) {
if (id == TextMeshCreator.SPACE_ASCII)
{
this.spaceWidth = (getValueOfVariable("xadvance") - paddingWidth) * horizontalPerPixelSize;
return null;
}

View File

@ -8,42 +8,40 @@ import java.util.Map;
import io.github.hydos.ginger.engine.renderEngine.renderers.FontRenderer;
import io.github.hydos.ginger.engine.utils.Loader;
public class TextMaster {
public class TextMaster
{
private static Map<FontType, List<GUIText>> texts = new HashMap<FontType, List<GUIText>>();
private static FontRenderer renderer;
public static void init() {
renderer = new FontRenderer();
}
public static void loadText(GUIText text) {
public static void init()
{ renderer = new FontRenderer(); }
public static void loadText(GUIText text)
{
FontType font = text.getFont();
TextMeshData data = font.loadText(text);
int vao = Loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
text.setMeshInfo(vao, data.getVertexCount());
List<GUIText> textBatch = texts.get(font);
if(textBatch == null) {
if (textBatch == null)
{
textBatch = new ArrayList<GUIText>();
texts.put(font, textBatch);
}
textBatch.add(text);
}
public static void removeText(GUIText text) {
public static void removeText(GUIText text)
{
List<GUIText> textBatch = texts.get(text.getFont());
textBatch.remove(text);
if(textBatch.isEmpty()) {
texts.remove(text.getFont());
}
if (textBatch.isEmpty())
{ texts.remove(text.getFont()); }
}
public static void cleanUp() {
renderer.cleanUp();
}
public static void render() {
renderer.render(texts);
}
public static void cleanUp()
{ renderer.cleanUp(); }
public static void render()
{ renderer.render(texts); }
}

View File

@ -3,33 +3,36 @@ package io.github.hydos.ginger.engine.font;
import java.util.ArrayList;
import java.util.List;
public class TextMeshCreator {
public class TextMeshCreator
{
protected static final double LINE_HEIGHT = 0.03f;
protected static final int SPACE_ASCII = 32;
private MetaFile metaData;
protected TextMeshCreator(String metaFile) {
metaData = new MetaFile(metaFile);
}
protected TextMeshCreator(String metaFile)
{ metaData = new MetaFile(metaFile); }
protected TextMeshData createTextMesh(GUIText text) {
protected TextMeshData createTextMesh(GUIText text)
{
List<Line> lines = createStructure(text);
TextMeshData data = createQuadVertices(text, lines);
return data;
}
private List<Line> createStructure(GUIText text) {
private List<Line> createStructure(GUIText text)
{
char[] chars = text.getTextString().toCharArray();
List<Line> lines = new ArrayList<Line>();
Line currentLine = new Line(metaData.getSpaceWidth(), text.getFontSize(), text.getMaxLineSize());
Word currentWord = new Word(text.getFontSize());
for (char c : chars) {
int ascii = (int) c;
if (ascii == SPACE_ASCII) {
for (char c : chars)
{
int ascii = c;
if (ascii == SPACE_ASCII)
{
boolean added = currentLine.attemptToAddWord(currentWord);
if (!added) {
if (!added)
{
lines.add(currentLine);
currentLine = new Line(metaData.getSpaceWidth(), text.getFontSize(), text.getMaxLineSize());
currentLine.attemptToAddWord(currentWord);
@ -44,9 +47,11 @@ public class TextMeshCreator {
return lines;
}
private void completeStructure(List<Line> lines, Line currentLine, Word currentWord, GUIText text) {
private void completeStructure(List<Line> lines, Line currentLine, Word currentWord, GUIText text)
{
boolean added = currentLine.attemptToAddWord(currentWord);
if (!added) {
if (!added)
{
lines.add(currentLine);
currentLine = new Line(metaData.getSpaceWidth(), text.getFontSize(), text.getMaxLineSize());
currentLine.attemptToAddWord(currentWord);
@ -54,33 +59,37 @@ public class TextMeshCreator {
lines.add(currentLine);
}
private TextMeshData createQuadVertices(GUIText text, List<Line> lines) {
private TextMeshData createQuadVertices(GUIText text, List<Line> lines)
{
text.setNumberOfLines(lines.size());
double curserX = 0f;
double curserY = 0f;
List<Float> vertices = new ArrayList<Float>();
List<Float> textureCoords = new ArrayList<Float>();
for (Line line : lines) {
if (text.isCentered()) {
curserX = (line.getMaxLength() - line.getLineLength()) / 2;
}
for (Word word : line.getWords()) {
for (Character letter : word.getCharacters()) {
for (Line line : lines)
{
if (text.isCentered())
{ curserX = (line.getMaxLength() - line.getLineLength()) / 2; }
for (Word word : line.getWords())
{
for (Character letter : word.getCharacters())
{
addVerticesForCharacter(curserX, curserY, letter, text.getFontSize(), vertices);
addTexCoords(textureCoords, letter.getxTextureCoord(), letter.getyTextureCoord(),
letter.getXMaxTextureCoord(), letter.getYMaxTextureCoord());
letter.getXMaxTextureCoord(), letter.getYMaxTextureCoord());
curserX += letter.getxAdvance() * text.getFontSize();
}
curserX += metaData.getSpaceWidth() * text.getFontSize();
}
curserX = 0;
curserY += LINE_HEIGHT * text.getFontSize();
}
}
return new TextMeshData(listToArray(vertices), listToArray(textureCoords));
}
private void addVerticesForCharacter(double curserX, double curserY, Character character, double fontSize,
List<Float> vertices) {
List<Float> vertices)
{
double x = curserX + (character.getxOffset() * fontSize);
double y = curserY + (character.getyOffset() * fontSize);
double maxX = x + (character.getSizeX() * fontSize);
@ -92,7 +101,8 @@ public class TextMeshCreator {
addVertices(vertices, properX, properY, properMaxX, properMaxY);
}
private static void addVertices(List<Float> vertices, double x, double y, double maxX, double maxY) {
private static void addVertices(List<Float> vertices, double x, double y, double maxX, double maxY)
{
vertices.add((float) x);
vertices.add((float) y);
vertices.add((float) x);
@ -107,7 +117,8 @@ public class TextMeshCreator {
vertices.add((float) y);
}
private static void addTexCoords(List<Float> texCoords, double x, double y, double maxX, double maxY) {
private static void addTexCoords(List<Float> texCoords, double x, double y, double maxX, double maxY)
{
texCoords.add((float) x);
texCoords.add((float) y);
texCoords.add((float) x);
@ -122,13 +133,11 @@ public class TextMeshCreator {
texCoords.add((float) y);
}
private static float[] listToArray(List<Float> listOfFloats) {
private static float[] listToArray(List<Float> listOfFloats)
{
float[] array = new float[listOfFloats.size()];
for (int i = 0; i < array.length; i++) {
array[i] = listOfFloats.get(i);
}
for (int i = 0; i < array.length; i++)
{ array[i] = listOfFloats.get(i); }
return array;
}
}

View File

@ -1,29 +1,23 @@
package io.github.hydos.ginger.engine.font;
/**
* Stores the vertex data for all the quads on which a text will be rendered.
*
*/
public class TextMeshData {
/** Stores the vertex data for all the quads on which a text will be rendered. */
public class TextMeshData
{
private float[] vertexPositions;
private float[] textureCoords;
protected TextMeshData(float[] vertexPositions, float[] textureCoords){
protected TextMeshData(float[] vertexPositions, float[] textureCoords)
{
this.vertexPositions = vertexPositions;
this.textureCoords = textureCoords;
}
public float[] getVertexPositions() {
return vertexPositions;
}
public float[] getVertexPositions()
{ return vertexPositions; }
public float[] getTextureCoords() {
return textureCoords;
}
public int getVertexCount() {
return vertexPositions.length/2;
}
public float[] getTextureCoords()
{ return textureCoords; }
public int getVertexCount()
{ return vertexPositions.length / 2; }
}

View File

@ -3,45 +3,33 @@ package io.github.hydos.ginger.engine.font;
import java.util.ArrayList;
import java.util.List;
/**
* During the loading of a text this represents one word in the text.
*
*/
public class Word {
/** During the loading of a text this represents one word in the text. */
public class Word
{
private List<Character> characters = new ArrayList<Character>();
private double width = 0;
private double fontSize;
/**
* Create a new empty word.
* @param fontSize - the font size of the text which this word is in.
*/
protected Word(double fontSize){
this.fontSize = fontSize;
}
/**
* Adds a character to the end of the current word and increases the screen-space width of the word.
* @param character - the character to be added.
*/
protected void addCharacter(Character character){
/** Create a new empty word.
*
* @param fontSize - the font size of the text which this word is in. */
protected Word(double fontSize)
{ this.fontSize = fontSize; }
/** Adds a character to the end of the current word and increases the screen-space width of the word.
*
* @param character - the character to be added. */
protected void addCharacter(Character character)
{
characters.add(character);
width += character.getxAdvance() * fontSize;
}
/**
* @return The list of characters in the word.
*/
protected List<Character> getCharacters(){
return characters;
}
/**
* @return The width of the word in terms of screen size.
*/
protected double getWordWidth(){
return width;
}
/** @return The list of characters in the word. */
protected List<Character> getCharacters()
{ return characters; }
/** @return The width of the word in terms of screen size. */
protected double getWordWidth()
{ return width; }
}

View File

@ -1,6 +1,5 @@
package io.github.hydos.ginger.engine.io;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
@ -16,13 +15,13 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.renderEngine.texture.Image;
public class Window {
public class Window
{
public static int width;
public static int height;
private static String title;
public static long window;
private static Vector3f backgroundColour = new Vector3f(0.2f,0.2f,0.2f);
private static Vector3f backgroundColour = new Vector3f(0.2f, 0.2f, 0.2f);
private static boolean[] keys = new boolean[GLFW.GLFW_KEY_LAST];
private static boolean[] mouseButtons = new boolean[GLFW.GLFW_MOUSE_BUTTON_LAST];
private static GLFWImage.Buffer iconBuffer = null;
@ -30,14 +29,15 @@ public class Window {
private static boolean isFullscreen = false;
public static double dy = 0;
public static double dx = 0;
static double oldX = 0;
static double oldY = 0;
static double newX = 0;
static double newY = 0;
static double oldX = 0;
static double oldY = 0;
static double newX = 0;
static double newY = 0;
public static GLCapabilities glContext;
public static int actuallWidth, actuallHeight;
public static void create(int width, int height, String title, int fps) {
public static void create(int width, int height, String title, int fps)
{
Window.width = width / 2;
Window.height = height / 2;
Window.actuallHeight = height;
@ -46,49 +46,41 @@ public class Window {
fpsCap = fps;
create();
}
public static void create() {
if(!GLFW.glfwInit()) {
System.err.println("Error: Couldn't initialize GLFW");
System.exit(-1);
}
GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GL11.GL_TRUE);
GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_FALSE);
GLFWVidMode vidmode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
window = GLFW.glfwCreateWindow(actuallWidth, actuallHeight, title, (isFullscreen) ? GLFW.glfwGetPrimaryMonitor() : 0, window);
if(window == 0) {
System.err.println("Error: Couldnt initilize window");
System.exit(-1);
}
GLFW.glfwMakeContextCurrent(window);
glContext = GL.createCapabilities();
GL11.glEnable(GL11.GL_DEPTH_TEST);
GLFW.glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
GLFW.glfwShowWindow(window);
time = getTime();
getCurrentTime();
}
public static boolean closed() {
return GLFW.glfwWindowShouldClose(window);
public static void create()
{
if (!GLFW.glfwInit())
{
System.err.println("Error: Couldn't initialize GLFW");
System.exit(-1);
}
GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GL11.GL_TRUE);
GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_FALSE);
GLFWVidMode vidmode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
window = GLFW.glfwCreateWindow(actuallWidth, actuallHeight, title, (isFullscreen) ? GLFW.glfwGetPrimaryMonitor() : 0, window);
if (window == 0)
{
System.err.println("Error: Couldnt initilize window");
System.exit(-1);
}
GLFW.glfwMakeContextCurrent(window);
glContext = GL.createCapabilities();
GL11.glEnable(GL11.GL_DEPTH_TEST);
GLFW.glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
GLFW.glfwShowWindow(window);
time = getTime();
getCurrentTime();
}
public static void update() {
public static boolean closed()
{ return GLFW.glfwWindowShouldClose(window); }
public static void update()
{
IntBuffer widthBuffer = BufferUtils.createIntBuffer(1);
IntBuffer heightBuffer = BufferUtils.createIntBuffer(1);
GLFW.glfwGetWindowSize(window, widthBuffer, heightBuffer);
@ -98,127 +90,115 @@ public class Window {
GL11.glClearColor(backgroundColour.x, backgroundColour.y, backgroundColour.z, 1.0f);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GLFW.glfwPollEvents();
newX = Window.getMouseX();
newY = Window.getMouseY();
Window.dx = newX - oldX;
Window.dy = newY - oldY;
oldX = newX;
oldY = newY;
}
public static void swapBuffers() {
GLFW.glfwSwapBuffers(window);
}
public static boolean isKeyDown(int keycode) {
return GLFW.glfwGetKey(window, keycode) == 1;
}
public static boolean isMouseDown(int mouseButton) {
return GLFW.glfwGetMouseButton(window, mouseButton) == 1;
}
public static boolean isKeyPressed(int keyCode) {
return isKeyDown(keyCode) && !keys[keyCode];
}
public static boolean isKeyReleased(int keyCode) {
return !isKeyDown(keyCode) && keys[keyCode];
}
public static boolean isMousePressed(int keyCode) {
return isMouseDown(keyCode) && !mouseButtons[keyCode];
}
public static boolean isMouseReleased(int keyCode) {
return !isMouseDown(keyCode) && mouseButtons[keyCode];
}
public static double getMouseX() {
public static void swapBuffers()
{ GLFW.glfwSwapBuffers(window); }
public static boolean isKeyDown(int keycode)
{ return GLFW.glfwGetKey(window, keycode) == 1; }
public static boolean isMouseDown(int mouseButton)
{ return GLFW.glfwGetMouseButton(window, mouseButton) == 1; }
public static boolean isKeyPressed(int keyCode)
{ return isKeyDown(keyCode) && !keys[keyCode]; }
public static boolean isKeyReleased(int keyCode)
{ return !isKeyDown(keyCode) && keys[keyCode]; }
public static boolean isMousePressed(int keyCode)
{ return isMouseDown(keyCode) && !mouseButtons[keyCode]; }
public static boolean isMouseReleased(int keyCode)
{ return !isMouseDown(keyCode) && mouseButtons[keyCode]; }
public static double getMouseX()
{
DoubleBuffer buffer = BufferUtils.createDoubleBuffer(1);
GLFW.glfwGetCursorPos(window, buffer, null);
return buffer.get(0);
}
public static double getMouseY() {
public static double getMouseY()
{
DoubleBuffer buffer = BufferUtils.createDoubleBuffer(1);
GLFW.glfwGetCursorPos(window, null, buffer);
return buffer.get(0);
}
public static double getTime() {
public static double getTime()
{
double f = (double) System.nanoTime() / (double) 1000000000;
return f;
}
public static float getFloatTime() {
public static float getFloatTime()
{
float f = (System.nanoTime() / (float) 1000000000);
return f;
}
public static boolean isUpdating() {
public static boolean isUpdating()
{
double nextTime = getTime();
double passedTime = nextTime - time;
processedTime += passedTime;
time = nextTime;
while (processedTime > 1.0/fpsCap) {
processedTime -= 1.0/fpsCap;
while (processedTime > 1.0 / fpsCap)
{
processedTime -= 1.0 / fpsCap;
return true;
}
return false;
}
public static void stop() {
GLFW.glfwTerminate();
}
public static void setBackgroundColour(float r, float g, float b) {
backgroundColour = new Vector3f(r,g,b);
}
public static void setIcon(String path) {
public static void stop()
{ GLFW.glfwTerminate(); }
public static void setBackgroundColour(float r, float g, float b)
{ backgroundColour = new Vector3f(r, g, b); }
public static void setIcon(String path)
{
Image icon = Image.createImage("/res/textures/" + path);
GLFWImage iconImage = GLFWImage.malloc();
iconBuffer = GLFWImage.malloc(1);
iconImage.set(icon.getWidth(), icon.getHeight(), icon.getImage());
iconBuffer.put(0, iconImage);
}
public static void showIcon() {
if(iconBuffer != null) {
GLFW.glfwSetWindowIcon(window, iconBuffer);
}
}
public void setFullscreen(boolean t) {
Window.isFullscreen = t;
}
public static void lockMouse() {
GLFW.glfwSetInputMode(window, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED);
}
public static void unlockMouse() {
GLFW.glfwSetInputMode(window, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL);
public static void showIcon()
{
if (iconBuffer != null)
{ GLFW.glfwSetWindowIcon(window, iconBuffer); }
}
public static Vector3f getColour() {
return Window.backgroundColour;
}
private static long getCurrentTime() {
return (long) (GLFW.glfwGetTime()*1000/GLFW.glfwGetTimerFrequency());
}
public static Vector2f getNormalizedMouseCoordinates() {
public void setFullscreen(boolean t)
{ Window.isFullscreen = t; }
public static void lockMouse()
{ GLFW.glfwSetInputMode(window, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED); }
public static void unlockMouse()
{ GLFW.glfwSetInputMode(window, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL); }
public static Vector3f getColour()
{ return Window.backgroundColour; }
private static long getCurrentTime()
{ return (long) (GLFW.glfwGetTime() * 1000 / GLFW.glfwGetTimerFrequency()); }
public static Vector2f getNormalizedMouseCoordinates()
{
float normalX = -1.0f + 2.0f * (float) getMouseX() / width;
float normalY = 1.0f - 2.0f * (float) getMouseY() / height;
return new Vector2f(normalX, normalY);
}
}

View File

@ -5,40 +5,44 @@ import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class Maths {
public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry, float rz, Vector3f scale) {
public class Maths
{
public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry, float rz, Vector3f scale)
{
Matrix4f matrix = new Matrix4f();
matrix.setIdentity();
Matrix4f.translate(translation, matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1, 0, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0, 1, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0, 0, 1), matrix, matrix);
Matrix4f.scale(scale, matrix, matrix);
return matrix;
}
public static Matrix4f createViewMatrix(ThirdPersonCamera camera) {
Matrix4f viewMatrix = new Matrix4f();
viewMatrix.setIdentity();
Matrix4f.rotate((float) Math.toRadians(camera.getPitch()), new Vector3f(1, 0, 0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(camera.getYaw()), new Vector3f(0, 1, 0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(camera.getRoll()), new Vector3f(0, 0, 1), viewMatrix, viewMatrix);
Vector3f cameraPos = camera.getPosition();
Vector3f negativeCameraPos = new Vector3f(-cameraPos.x,-cameraPos.y,-cameraPos.z);
Matrix4f.translate(negativeCameraPos, viewMatrix, viewMatrix);
return viewMatrix;
}
public static float barryCentric(Vector3f p1, Vector3f p2, Vector3f p3, Vector2f pos) {
public static Matrix4f createViewMatrix(ThirdPersonCamera camera)
{
Matrix4f viewMatrix = new Matrix4f();
viewMatrix.setIdentity();
Matrix4f.rotate((float) Math.toRadians(camera.getPitch()), new Vector3f(1, 0, 0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(camera.getYaw()), new Vector3f(0, 1, 0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(camera.getRoll()), new Vector3f(0, 0, 1), viewMatrix, viewMatrix);
Vector3f cameraPos = camera.getPosition();
Vector3f negativeCameraPos = new Vector3f(-cameraPos.x, -cameraPos.y, -cameraPos.z);
Matrix4f.translate(negativeCameraPos, viewMatrix, viewMatrix);
return viewMatrix;
}
public static float barryCentric(Vector3f p1, Vector3f p2, Vector3f p3, Vector2f pos)
{
float det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z)) / det;
float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z)) / det;
float l3 = 1.0f - l1 - l2;
return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}
public static Matrix4f createTransformationMatrix(Vector2f translation, Vector2f scale) {
public static Matrix4f createTransformationMatrix(Vector2f translation, Vector2f scale)
{
Matrix4f matrix = new Matrix4f();
matrix.setIdentity();
Matrix4f.translate(translation, matrix, matrix);
@ -46,16 +50,16 @@ public class Maths {
return matrix;
}
public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry, float rz, float scale) {
public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry, float rz, float scale)
{
Matrix4f matrix = new Matrix4f();
matrix.setIdentity();
Matrix4f.translate(translation, matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix);
Vector3f newScale = new Vector3f(scale,scale,scale);
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1, 0, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0, 1, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0, 0, 1), matrix, matrix);
Vector3f newScale = new Vector3f(scale, scale, scale);
Matrix4f.scale(newScale, matrix, matrix);
return matrix;
}
}

View File

@ -39,7 +39,6 @@ package io.github.hydos.ginger.engine.mathEngine;
* @version $Revision$
* $Id$
*/
import java.nio.FloatBuffer;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix3f;
@ -48,42 +47,35 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.ReadableVector4f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
public class Quaternion extends Vector implements ReadableVector4f {
public class Quaternion extends Vector implements ReadableVector4f
{
private static final long serialVersionUID = 1L;
public float x, y, z, w;
/**
* C'tor. The quaternion will be initialized to the identity.
*/
public Quaternion() {
/** C'tor. The quaternion will be initialized to the identity. */
public Quaternion()
{
super();
setIdentity();
}
/**
* C'tor
/** C'tor
*
* @param src
*/
public Quaternion(ReadableVector4f src) {
set(src);
}
* @param src */
public Quaternion(ReadableVector4f src)
{ set(src); }
/**
* C'tor
*
*/
public Quaternion(float x, float y, float z, float w) {
set(x, y, z, w);
}
/** C'tor */
public Quaternion(float x, float y, float z, float w)
{ set(x, y, z, w); }
/*
* (non-Javadoc)
*
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
@ -93,7 +85,8 @@ public class Quaternion extends Vector implements ReadableVector4f {
*
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
public void set(float x, float y, float z) {
public void set(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
@ -105,21 +98,21 @@ public class Quaternion extends Vector implements ReadableVector4f {
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float,
* float)
*/
public void set(float x, float y, float z, float w) {
public void set(float x, float y, float z, float w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Load from another Vector4f
/** Load from another Vector4f
*
* @param src
* The source vector
* @return this
*/
public Quaternion set(ReadableVector4f src) {
* @param src
* The source vector
* @return this */
public Quaternion set(ReadableVector4f src)
{
x = src.getX();
y = src.getY();
z = src.getZ();
@ -127,20 +120,18 @@ public class Quaternion extends Vector implements ReadableVector4f {
return this;
}
/**
* Set this quaternion to the multiplication identity.
* @return this
*/
public Quaternion setIdentity() {
return setIdentity(this);
}
/** Set this quaternion to the multiplication identity.
*
* @return this */
public Quaternion setIdentity()
{ return setIdentity(this); }
/**
* Set the given quaternion to the multiplication identity.
* @param q The quaternion
* @return q
*/
public static Quaternion setIdentity(Quaternion q) {
/** Set the given quaternion to the multiplication identity.
*
* @param q The quaternion
* @return q */
public static Quaternion setIdentity(Quaternion q)
{
q.x = 0;
q.y = 0;
q.z = 0;
@ -148,106 +139,85 @@ public class Quaternion extends Vector implements ReadableVector4f {
return q;
}
/**
* @return the length squared of the quaternion
*/
/** @return the length squared of the quaternion */
@Override
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
public float lengthSquared()
{ return x * x + y * y + z * z + w * w; }
/**
* Normalise the source quaternion and place the result in another quaternion.
/** Normalise the source quaternion and place the result in another quaternion.
*
* @param src
* The source quaternion
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return The normalised quaternion
*/
public static Quaternion normalise(Quaternion src, Quaternion dest) {
float inv_l = 1f/src.length();
* @param src
* The source quaternion
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return The normalised quaternion */
public static Quaternion normalise(Quaternion src, Quaternion dest)
{
float inv_l = 1f / src.length();
if (dest == null)
dest = new Quaternion();
dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l);
return dest;
}
/**
* Normalise this quaternion and place the result in another quaternion.
/** Normalise this quaternion and place the result in another quaternion.
*
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return the normalised quaternion */
public Quaternion normalise(Quaternion dest)
{ return normalise(this, dest); }
/** The dot product of two quaternions
*
* @param left
* The LHS quat
* @param right
* The RHS quat
* @return left dot right */
public static float dot(Quaternion left, Quaternion right)
{ return left.x * right.x + left.y * right.y + left.z * right.z + left.w
* right.w; }
/** Calculate the conjugate of this quaternion and put it into the given one
*
* @param dest
* The destination quaternion, or null if a new quaternion is to be
* created
* @return the normalised quaternion
*/
public Quaternion normalise(Quaternion dest) {
return normalise(this, dest);
}
* The quaternion which should be set to the conjugate of this
* quaternion */
public Quaternion negate(Quaternion dest)
{ return negate(this, dest); }
/**
* The dot product of two quaternions
*
* @param left
* The LHS quat
* @param right
* The RHS quat
* @return left dot right
*/
public static float dot(Quaternion left, Quaternion right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w
* right.w;
}
/**
* Calculate the conjugate of this quaternion and put it into the given one
*
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public Quaternion negate(Quaternion dest) {
return negate(this, dest);
}
/**
* Calculate the conjugate of this quaternion and put it into the given one
/** Calculate the conjugate of this quaternion and put it into the given one
*
* @param src
* The source quaternion
* The source quaternion
* @param dest
* The quaternion which should be set to the conjugate of this
* quaternion
*/
public static Quaternion negate(Quaternion src, Quaternion dest) {
* The quaternion which should be set to the conjugate of this
* quaternion */
public static Quaternion negate(Quaternion src, Quaternion dest)
{
if (dest == null)
dest = new Quaternion();
dest.x = -src.x;
dest.y = -src.y;
dest.z = -src.z;
dest.w = src.w;
return dest;
}
/**
* Calculate the conjugate of this quaternion
*/
/** Calculate the conjugate of this quaternion */
@Override
public Vector negate() {
return negate(this, this);
}
public Vector negate()
{ return negate(this, this); }
/* (non-Javadoc)
* @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer)
*/
@Override
public Vector load(FloatBuffer buf) {
public Vector load(FloatBuffer buf)
{
x = buf.get();
y = buf.get();
z = buf.get();
@ -261,18 +231,17 @@ public class Quaternion extends Vector implements ReadableVector4f {
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale) {
return scale(scale, this, this);
}
public Vector scale(float scale)
{ return scale(scale, this, this); }
/**
* Scale the source quaternion by scale and put the result in the destination
* @param scale The amount to scale by
* @param src The source quaternion
* @param dest The destination quaternion, or null if a new quaternion is to be created
* @return The scaled quaternion
*/
public static Quaternion scale(float scale, Quaternion src, Quaternion dest) {
/** Scale the source quaternion by scale and put the result in the destination
*
* @param scale The amount to scale by
* @param src The source quaternion
* @param dest The destination quaternion, or null if a new quaternion is to be created
* @return The scaled quaternion */
public static Quaternion scale(float scale, Quaternion src, Quaternion dest)
{
if (dest == null)
dest = new Quaternion();
dest.x = src.x * scale;
@ -286,57 +255,42 @@ public class Quaternion extends Vector implements ReadableVector4f {
* @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer)
*/
@Override
public Vector store(FloatBuffer buf) {
public Vector store(FloatBuffer buf)
{
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
return this;
}
/**
* @return x
*/
/** @return x */
@Override
public final float getX() {
return x;
}
public final float getX()
{ return x; }
/**
* @return y
*/
/** @return y */
@Override
public final float getY() {
return y;
}
public final float getY()
{ return y; }
/**
* Set X
/** Set X
*
* @param x
*/
public final void setX(float x) {
this.x = x;
}
* @param x */
public final void setX(float x)
{ this.x = x; }
/**
* Set Y
/** Set Y
*
* @param y
*/
public final void setY(float y) {
this.y = y;
}
* @param y */
public final void setY(float y)
{ this.y = y; }
/**
* Set Z
/** Set Z
*
* @param z
*/
public void setZ(float z) {
this.z = z;
}
* @param z */
public void setZ(float z)
{ this.z = z; }
/*
* (Overrides)
@ -344,18 +298,14 @@ public class Quaternion extends Vector implements ReadableVector4f {
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getZ() {
return z;
}
public float getZ()
{ return z; }
/**
* Set W
/** Set W
*
* @param w
*/
public void setW(float w) {
this.w = w;
}
* @param w */
public void setW(float w)
{ this.w = w; }
/*
* (Overrides)
@ -363,51 +313,48 @@ public class Quaternion extends Vector implements ReadableVector4f {
* @see org.lwjgl.vector.ReadableVector3f#getW()
*/
@Override
public float getW() {
return w;
}
public float getW()
{ return w; }
@Override
public String toString() {
return "Quaternion: " + x + " " + y + " " + z + " " + w;
}
public String toString()
{ return "Quaternion: " + x + " " + y + " " + z + " " + w; }
/**
* Sets the value of this quaternion to the quaternion product of
/** Sets the value of this quaternion to the quaternion product of
* quaternions left and right (this = left * right). Note that this is safe
* for aliasing (e.g. this can be left or right).
*
* @param left
* the first quaternion
* the first quaternion
* @param right
* the second quaternion
*/
* the second quaternion */
public static Quaternion mul(Quaternion left, Quaternion right,
Quaternion dest) {
Quaternion dest)
{
if (dest == null)
dest = new Quaternion();
dest.set(left.x * right.w + left.w * right.x + left.y * right.z
- left.z * right.y, left.y * right.w + left.w * right.y
+ left.z * right.x - left.x * right.z, left.z * right.w
- left.z * right.y,
left.y * right.w + left.w * right.y
+ left.z * right.x - left.x * right.z,
left.z * right.w
+ left.w * right.z + left.x * right.y - left.y * right.x,
left.w * right.w - left.x * right.x - left.y * right.y
left.w * right.w - left.x * right.x - left.y * right.y
- left.z * right.z);
return dest;
}
/**
*
* Multiplies quaternion left by the inverse of quaternion right and places
/** Multiplies quaternion left by the inverse of quaternion right and places
* the value into this quaternion. The value of both argument quaternions is
* preservered (this = left * right^-1).
*
* @param left
* the left quaternion
* the left quaternion
* @param right
* the right quaternion
*/
* the right quaternion */
public static Quaternion mulInverse(Quaternion left, Quaternion right,
Quaternion dest) {
Quaternion dest)
{
float n = right.lengthSquared();
// zero-div may occur.
n = (n == 0.0 ? n : 1 / n);
@ -416,26 +363,27 @@ public class Quaternion extends Vector implements ReadableVector4f {
dest = new Quaternion();
dest
.set((left.x * right.w - left.w * right.x - left.y
* right.z + left.z * right.y)
* n, (left.y * right.w - left.w * right.y - left.z
* right.x + left.x * right.z)
* n, (left.z * right.w - left.w * right.z - left.x
* right.y + left.y * right.x)
* n, (left.w * right.w + left.x * right.x + left.y
* right.y + left.z * right.z)
* right.z + left.z * right.y)
* n,
(left.y * right.w - left.w * right.y - left.z
* right.x + left.x * right.z)
* n,
(left.z * right.w - left.w * right.z - left.x
* right.y + left.y * right.x)
* n,
(left.w * right.w + left.x * right.x + left.y
* right.y + left.z * right.z)
* n);
return dest;
}
/**
* Sets the value of this quaternion to the equivalent rotation of the
/** Sets the value of this quaternion to the equivalent rotation of the
* Axis-Angle argument.
*
* @param a1
* the axis-angle: (x,y,z) is the axis and w is the angle
*/
public final void setFromAxisAngle(Vector4f a1) {
* the axis-angle: (x,y,z) is the axis and w is the angle */
public final void setFromAxisAngle(Vector4f a1)
{
x = a1.x;
y = a1.y;
z = a1.z;
@ -448,91 +396,85 @@ public class Quaternion extends Vector implements ReadableVector4f {
w = (float) Math.cos(0.5 * a1.w);
}
/**
* Sets the value of this quaternion using the rotational component of the
/** Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The matrix
* @return this */
public final Quaternion setFromMatrix(Matrix4f m)
{ return setFromMatrix(m, this); }
/** Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q */
public static Quaternion setFromMatrix(Matrix4f m, Quaternion q)
{ return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22); }
/** Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The matrix
* @return this
*/
public final Quaternion setFromMatrix(Matrix4f m) {
return setFromMatrix(m, this);
}
* The source matrix */
public final Quaternion setFromMatrix(Matrix3f m)
{ return setFromMatrix(m, this); }
/**
* Sets the value of the source quaternion using the rotational component of the
/** Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22);
}
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q */
public static Quaternion setFromMatrix(Matrix3f m, Quaternion q)
{ return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22); }
/**
* Sets the value of this quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
*/
public final Quaternion setFromMatrix(Matrix3f m) {
return setFromMatrix(m, this);
}
/**
* Sets the value of the source quaternion using the rotational component of the
* passed matrix.
*
* @param m
* The source matrix
* @param q
* The destination quaternion, or null if a new quaternion is to be created
* @return q
*/
public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) {
return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20,
m.m21, m.m22);
}
/**
* Private method to perform the matrix-to-quaternion conversion
*/
/** Private method to perform the matrix-to-quaternion conversion */
private Quaternion setFromMat(float m00, float m01, float m02, float m10,
float m11, float m12, float m20, float m21, float m22) {
float m11, float m12, float m20, float m21, float m22)
{
float s;
float tr = m00 + m11 + m22;
if (tr >= 0.0) {
if (tr >= 0.0)
{
s = (float) Math.sqrt(tr + 1.0);
w = s * 0.5f;
s = 0.5f / s;
x = (m21 - m12) * s;
y = (m02 - m20) * s;
z = (m10 - m01) * s;
} else {
}
else
{
float max = Math.max(Math.max(m00, m11), m22);
if (max == m00) {
if (max == m00)
{
s = (float) Math.sqrt(m00 - (m11 + m22) + 1.0);
x = s * 0.5f;
s = 0.5f / s;
y = (m01 + m10) * s;
z = (m20 + m02) * s;
w = (m21 - m12) * s;
} else if (max == m11) {
}
else if (max == m11)
{
s = (float) Math.sqrt(m11 - (m22 + m00) + 1.0);
y = s * 0.5f;
s = 0.5f / s;
z = (m12 + m21) * s;
x = (m01 + m10) * s;
w = (m02 - m20) * s;
} else {
}
else
{
s = (float) Math.sqrt(m22 - (m00 + m11) + 1.0);
z = s * 0.5f;
s = 0.5f / s;

View File

@ -34,104 +34,73 @@ package io.github.hydos.ginger.engine.mathEngine.matrixes;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Base class for matrices. When a matrix is constructed it will be the identity
/** Base class for matrices. When a matrix is constructed it will be the identity
* matrix unless otherwise stated.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public abstract class Matrix implements Serializable {
* $Id$ */
public abstract class Matrix implements Serializable
{
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/** Constructor for Matrix. */
protected Matrix()
{ super(); }
/** Set this matrix to be the identity matrix.
*
* @return this */
public abstract Matrix setIdentity();
/**
* Constructor for Matrix.
*/
protected Matrix() {
super();
}
/** Invert this matrix
*
* @return this */
public abstract Matrix invert();
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public abstract Matrix setIdentity();
/** Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this */
public abstract Matrix load(FloatBuffer buf);
/** Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this */
public abstract Matrix loadTranspose(FloatBuffer buf);
/**
* Invert this matrix
* @return this
*/
public abstract Matrix invert();
/** Negate this matrix
*
* @return this */
public abstract Matrix negate();
/** Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
*
* @param buf The buffer to store this matrix in
* @return this */
public abstract Matrix store(FloatBuffer buf);
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix load(FloatBuffer buf);
/** Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
*
* @param buf The buffer to store this matrix in
* @return this */
public abstract Matrix storeTranspose(FloatBuffer buf);
/** Transpose this matrix
*
* @return this */
public abstract Matrix transpose();
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix loadTranspose(FloatBuffer buf);
/**
* Negate this matrix
* @return this
*/
public abstract Matrix negate();
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix store(FloatBuffer buf);
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix storeTranspose(FloatBuffer buf);
/**
* Transpose this matrix
* @return this
*/
public abstract Matrix transpose();
/**
* Set this matrix to 0.
* @return this
*/
public abstract Matrix setZero();
/**
* @return the determinant of the matrix
*/
public abstract float determinant();
/** Set this matrix to 0.
*
* @return this */
public abstract Matrix setZero();
/** @return the determinant of the matrix */
public abstract float determinant();
}

View File

@ -36,378 +36,325 @@ import java.nio.FloatBuffer;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
/**
/** Holds a 2x2 matrix
*
* Holds a 2x2 matrix
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
* $Id$ */
public class Matrix2f extends Matrix implements Serializable
{
private static final long serialVersionUID = 1L;
public float m00, m01, m10, m11;
public class Matrix2f extends Matrix implements Serializable {
/** Constructor for Matrix2f. The matrix is initialised to the identity. */
public Matrix2f()
{ setIdentity(); }
private static final long serialVersionUID = 1L;
/** Constructor */
public Matrix2f(Matrix2f src)
{ load(src); }
public float m00, m01, m10, m11;
/** Load from another matrix
*
* @param src The source matrix
* @return this */
public Matrix2f load(Matrix2f src)
{ return load(src, this); }
/**
* Constructor for Matrix2f. The matrix is initialised to the identity.
*/
public Matrix2f() {
setIdentity();
}
/** Copy the source matrix to the destination matrix.
*
* @param src The source matrix
* @param dest The destination matrix, or null if a new one should be created.
* @return The copied matrix */
public static Matrix2f load(Matrix2f src, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m10 = src.m10;
dest.m11 = src.m11;
return dest;
}
/**
* Constructor
*/
public Matrix2f(Matrix2f src) {
load(src);
}
/** Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this */
@Override
public Matrix load(FloatBuffer buf)
{
m00 = buf.get();
m01 = buf.get();
m10 = buf.get();
m11 = buf.get();
return this;
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix2f load(Matrix2f src) {
return load(src, this);
}
/** Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this */
@Override
public Matrix loadTranspose(FloatBuffer buf)
{
m00 = buf.get();
m10 = buf.get();
m01 = buf.get();
m11 = buf.get();
return this;
}
/**
* Copy the source matrix to the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new one should be created.
* @return The copied matrix
*/
public static Matrix2f load(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
/** Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
*
* @param buf The buffer to store this matrix in */
@Override
public Matrix store(FloatBuffer buf)
{
buf.put(m00);
buf.put(m01);
buf.put(m10);
buf.put(m11);
return this;
}
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m10 = src.m10;
dest.m11 = src.m11;
/** Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
*
* @param buf The buffer to store this matrix in */
@Override
public Matrix storeTranspose(FloatBuffer buf)
{
buf.put(m00);
buf.put(m10);
buf.put(m01);
buf.put(m11);
return this;
}
return dest;
}
/** Add two matrices together and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
@Override
public Matrix load(FloatBuffer buf) {
/** Subtract the right matrix from the left and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
return dest;
}
m00 = buf.get();
m01 = buf.get();
m10 = buf.get();
m11 = buf.get();
/** Multiply the right matrix by the left and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
float m00 = left.m00 * right.m00 + left.m10 * right.m01;
float m01 = left.m01 * right.m00 + left.m11 * right.m01;
float m10 = left.m00 * right.m10 + left.m10 * right.m11;
float m11 = left.m01 * right.m10 + left.m11 * right.m11;
dest.m00 = m00;
dest.m01 = m01;
dest.m10 = m10;
dest.m11 = m11;
return dest;
}
return this;
}
/** Transform a Vector by a matrix and return the result in a destination
* vector.
*
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector */
public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest)
{
if (dest == null)
dest = new Vector2f();
float x = left.m00 * right.x + left.m10 * right.y;
float y = left.m01 * right.x + left.m11 * right.y;
dest.x = x;
dest.y = y;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
@Override
public Matrix loadTranspose(FloatBuffer buf) {
/** Transpose this matrix
*
* @return this */
@Override
public Matrix transpose()
{ return transpose(this); }
m00 = buf.get();
m10 = buf.get();
m01 = buf.get();
m11 = buf.get();
/** Transpose this matrix and place the result in another matrix.
*
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix */
public Matrix2f transpose(Matrix2f dest)
{ return transpose(this, dest); }
return this;
}
/** Transpose the source matrix and place the result in the destination matrix.
*
* @param src The source matrix or null if a new matrix is to be created
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix */
public static Matrix2f transpose(Matrix2f src, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
float m01 = src.m10;
float m10 = src.m01;
dest.m01 = m01;
dest.m10 = m10;
return dest;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
@Override
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m10);
buf.put(m11);
return this;
}
/** Invert this matrix
*
* @return this if successful, null otherwise */
@Override
public Matrix invert()
{ return invert(this, this); }
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
@Override
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m01);
buf.put(m11);
return this;
}
/** Invert the source matrix and place the result in the destination matrix.
*
* @param src The source matrix to be inverted
* @param dest The destination matrix or null if a new matrix is to be created
* @return The inverted matrix, or null if source can't be reverted. */
public static Matrix2f invert(Matrix2f src, Matrix2f dest)
{
/*
*inv(A) = 1/det(A) * adj(A);
*/
float determinant = src.determinant();
if (determinant != 0)
{
if (dest == null)
dest = new Matrix2f();
float determinant_inv = 1f / determinant;
float t00 = src.m11 * determinant_inv;
float t01 = -src.m01 * determinant_inv;
float t11 = src.m00 * determinant_inv;
float t10 = -src.m10 * determinant_inv;
dest.m00 = t00;
dest.m01 = t01;
dest.m10 = t10;
dest.m11 = t11;
return dest;
}
else
return null;
}
/** Returns a string representation of this matrix */
@Override
public String toString()
{
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append('\n');
return buf.toString();
}
/** Negate this matrix
*
* @return this */
@Override
public Matrix negate()
{ return negate(this); }
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
/** Negate this matrix and stash the result in another matrix.
*
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix */
public Matrix2f negate(Matrix2f dest)
{ return negate(this, dest); }
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
/** Negate the source matrix and stash the result in the destination matrix.
*
* @param src The source matrix to be negated
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix */
public static Matrix2f negate(Matrix2f src, Matrix2f dest)
{
if (dest == null)
dest = new Matrix2f();
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
return dest;
}
return dest;
}
/** Set this matrix to be the identity matrix.
*
* @return this */
@Override
public Matrix setIdentity()
{ return setIdentity(this); }
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
/** Set the source matrix to be the identity matrix.
*
* @param src The matrix to set to the identity.
* @return The source matrix */
public static Matrix2f setIdentity(Matrix2f src)
{
src.m00 = 1.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 1.0f;
return src;
}
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
/** Set this matrix to 0.
*
* @return this */
@Override
public Matrix setZero()
{ return setZero(this); }
return dest;
}
public static Matrix2f setZero(Matrix2f src)
{
src.m00 = 0.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 0.0f;
return src;
}
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
float m00 = left.m00 * right.m00 + left.m10 * right.m01;
float m01 = left.m01 * right.m00 + left.m11 * right.m01;
float m10 = left.m00 * right.m10 + left.m10 * right.m11;
float m11 = left.m01 * right.m10 + left.m11 * right.m11;
dest.m00 = m00;
dest.m01 = m01;
dest.m10 = m10;
dest.m11 = m11;
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) {
if (dest == null)
dest = new Vector2f();
float x = left.m00 * right.x + left.m10 * right.y;
float y = left.m01 * right.x + left.m11 * right.y;
dest.x = x;
dest.y = y;
return dest;
}
/**
* Transpose this matrix
* @return this
*/
@Override
public Matrix transpose() {
return transpose(this);
}
/**
* Transpose this matrix and place the result in another matrix.
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix2f transpose(Matrix2f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result in the destination matrix.
* @param src The source matrix or null if a new matrix is to be created
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix2f transpose(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
float m01 = src.m10;
float m10 = src.m01;
dest.m01 = m01;
dest.m10 = m10;
return dest;
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
@Override
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and place the result in the destination matrix.
* @param src The source matrix to be inverted
* @param dest The destination matrix or null if a new matrix is to be created
* @return The inverted matrix, or null if source can't be reverted.
*/
public static Matrix2f invert(Matrix2f src, Matrix2f dest) {
/*
*inv(A) = 1/det(A) * adj(A);
*/
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix2f();
float determinant_inv = 1f/determinant;
float t00 = src.m11*determinant_inv;
float t01 = -src.m01*determinant_inv;
float t11 = src.m00*determinant_inv;
float t10 = -src.m10*determinant_inv;
dest.m00 = t00;
dest.m01 = t01;
dest.m10 = t10;
dest.m11 = t11;
return dest;
} else
return null;
}
/**
* Returns a string representation of this matrix
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append('\n');
return buf.toString();
}
/**
* Negate this matrix
* @return this
*/
@Override
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and stash the result in another matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix2f negate(Matrix2f dest) {
return negate(this, dest);
}
/**
* Negate the source matrix and stash the result in the destination matrix.
* @param src The source matrix to be negated
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix2f negate(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
return dest;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
@Override
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the source matrix to be the identity matrix.
* @param src The matrix to set to the identity.
* @return The source matrix
*/
public static Matrix2f setIdentity(Matrix2f src) {
src.m00 = 1.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 1.0f;
return src;
}
/**
* Set this matrix to 0.
* @return this
*/
@Override
public Matrix setZero() {
return setZero(this);
}
public static Matrix2f setZero(Matrix2f src) {
src.m00 = 0.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 0.0f;
return src;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Matrix#determinant()
*/
@Override
public float determinant() {
return m00 * m11 - m01*m10;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Matrix#determinant()
*/
@Override
public float determinant()
{ return m00 * m11 - m01 * m10; }
}

View File

@ -1,5 +1,3 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
@ -38,488 +36,432 @@ import java.nio.FloatBuffer;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
/**
/** Holds a 3x3 matrix.
*
* Holds a 3x3 matrix.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
* $Id$ */
public class Matrix3f extends Matrix implements Serializable
{
private static final long serialVersionUID = 1L;
public float m00,
m01,
m02,
m10,
m11,
m12,
m20,
m21,
m22;
public class Matrix3f extends Matrix implements Serializable {
/** Constructor for Matrix3f. Matrix is initialised to the identity. */
public Matrix3f()
{
super();
setIdentity();
}
private static final long serialVersionUID = 1L;
/** Load from another matrix
*
* @param src The source matrix
* @return this */
public Matrix3f load(Matrix3f src)
{ return load(src, this); }
public float m00,
m01,
m02,
m10,
m11,
m12,
m20,
m21,
m22;
/** Copy source matrix to destination matrix
*
* @param src The source matrix
* @param dest The destination matrix, or null of a new matrix is to be created
* @return The copied matrix */
public static Matrix3f load(Matrix3f src, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
dest.m00 = src.m00;
dest.m10 = src.m10;
dest.m20 = src.m20;
dest.m01 = src.m01;
dest.m11 = src.m11;
dest.m21 = src.m21;
dest.m02 = src.m02;
dest.m12 = src.m12;
dest.m22 = src.m22;
return dest;
}
/**
* Constructor for Matrix3f. Matrix is initialised to the identity.
*/
public Matrix3f() {
super();
setIdentity();
}
/** Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this */
@Override
public Matrix load(FloatBuffer buf)
{
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
return this;
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix3f load(Matrix3f src) {
return load(src, this);
}
/** Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this */
@Override
public Matrix loadTranspose(FloatBuffer buf)
{
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
return this;
}
/**
* Copy source matrix to destination matrix
* @param src The source matrix
* @param dest The destination matrix, or null of a new matrix is to be created
* @return The copied matrix
*/
public static Matrix3f load(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/** Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
*
* @param buf The buffer to store this matrix in */
@Override
public Matrix store(FloatBuffer buf)
{
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
dest.m00 = src.m00;
dest.m10 = src.m10;
dest.m20 = src.m20;
dest.m01 = src.m01;
dest.m11 = src.m11;
dest.m21 = src.m21;
dest.m02 = src.m02;
dest.m12 = src.m12;
dest.m22 = src.m22;
/** Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
*
* @param buf The buffer to store this matrix in */
@Override
public Matrix storeTranspose(FloatBuffer buf)
{
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m02);
buf.put(m12);
buf.put(m22);
return this;
}
return dest;
}
/** Add two matrices together and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
@Override
public Matrix load(FloatBuffer buf) {
/** Subtract the right matrix from the left and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
return dest;
}
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
/** Multiply the right matrix by the left and place the result in a third matrix.
*
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix */
public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
float m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02;
float m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02;
float m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02;
float m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12;
float m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12;
float m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12;
float m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22;
float m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22;
float m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
return this;
}
/** Transform a Vector by a matrix and return the result in a destination
* vector.
*
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector */
public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest)
{
if (dest == null)
dest = new Vector3f();
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z;
dest.x = x;
dest.y = y;
dest.z = z;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this
*/
@Override
public Matrix loadTranspose(FloatBuffer buf) {
/** Transpose this matrix
*
* @return this */
@Override
public Matrix transpose()
{ return transpose(this, this); }
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
/** Transpose this matrix and place the result in another matrix
*
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix */
public Matrix3f transpose(Matrix3f dest)
{ return transpose(this, dest); }
return this;
}
/** Transpose the source matrix and place the result into the destination matrix
*
* @param src The source matrix to be transposed
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix */
public static Matrix3f transpose(Matrix3f src, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
@Override
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
/** @return the determinant of the matrix */
@Override
public float determinant()
{
float f = m00 * (m11 * m22 - m12 * m21)
+ m01 * (m12 * m20 - m10 * m22)
+ m02 * (m10 * m21 - m11 * m20);
return f;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
@Override
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m02);
buf.put(m12);
buf.put(m22);
return this;
}
/** Returns a string representation of this matrix */
@Override
public String toString()
{
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append('\n');
buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append('\n');
return buf.toString();
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/** Invert this matrix
*
* @return this if successful, null otherwise */
@Override
public Matrix invert()
{ return invert(this, this); }
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
/** Invert the source matrix and put the result into the destination matrix
*
* @param src The source matrix to be inverted
* @param dest The destination matrix, or null if a new one is to be created
* @return The inverted matrix if successful, null otherwise */
public static Matrix3f invert(Matrix3f src, Matrix3f dest)
{
float determinant = src.determinant();
if (determinant != 0)
{
if (dest == null)
dest = new Matrix3f();
/* do it the ordinary way
*
* inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix)
*
* m00 m01 m02
* m10 m11 m12
* m20 m21 m22
*/
float determinant_inv = 1f / determinant;
// get the conjugate matrix
float t00 = src.m11 * src.m22 - src.m12 * src.m21;
float t01 = -src.m10 * src.m22 + src.m12 * src.m20;
float t02 = src.m10 * src.m21 - src.m11 * src.m20;
float t10 = -src.m01 * src.m22 + src.m02 * src.m21;
float t11 = src.m00 * src.m22 - src.m02 * src.m20;
float t12 = -src.m00 * src.m21 + src.m01 * src.m20;
float t20 = src.m01 * src.m12 - src.m02 * src.m11;
float t21 = -src.m00 * src.m12 + src.m02 * src.m10;
float t22 = src.m00 * src.m11 - src.m01 * src.m10;
dest.m00 = t00 * determinant_inv;
dest.m11 = t11 * determinant_inv;
dest.m22 = t22 * determinant_inv;
dest.m01 = t10 * determinant_inv;
dest.m10 = t01 * determinant_inv;
dest.m20 = t02 * determinant_inv;
dest.m02 = t20 * determinant_inv;
dest.m12 = t21 * determinant_inv;
dest.m21 = t12 * determinant_inv;
return dest;
}
else
return null;
}
return dest;
}
/** Negate this matrix
*
* @return this */
@Override
public Matrix negate()
{ return negate(this); }
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/** Negate this matrix and place the result in a destination matrix.
*
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix */
public Matrix3f negate(Matrix3f dest)
{ return negate(this, dest); }
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
/** Negate the source matrix and place the result in the destination matrix.
*
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix */
public static Matrix3f negate(Matrix3f src, Matrix3f dest)
{
if (dest == null)
dest = new Matrix3f();
dest.m00 = -src.m00;
dest.m01 = -src.m02;
dest.m02 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m12;
dest.m12 = -src.m11;
dest.m20 = -src.m20;
dest.m21 = -src.m22;
dest.m22 = -src.m21;
return dest;
}
return dest;
}
/** Set this matrix to be the identity matrix.
*
* @return this */
@Override
public Matrix setIdentity()
{ return setIdentity(this); }
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
/** Set the matrix to be the identity matrix.
*
* @param m The matrix to be set to the identity
* @return m */
public static Matrix3f setIdentity(Matrix3f m)
{
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
return m;
}
float m00 =
left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02;
float m01 =
left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02;
float m02 =
left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02;
float m10 =
left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12;
float m11 =
left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12;
float m12 =
left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12;
float m20 =
left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22;
float m21 =
left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22;
float m22 =
left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22;
/** Set this matrix to 0.
*
* @return this */
@Override
public Matrix setZero()
{ return setZero(this); }
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) {
if (dest == null)
dest = new Vector3f();
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z;
dest.x = x;
dest.y = y;
dest.z = z;
return dest;
}
/**
* Transpose this matrix
* @return this
*/
@Override
public Matrix transpose() {
return transpose(this, this);
}
/**
* Transpose this matrix and place the result in another matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix3f transpose(Matrix3f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result into the destination matrix
* @param src The source matrix to be transposed
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix3f transpose(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* @return the determinant of the matrix
*/
@Override
public float determinant() {
float f =
m00 * (m11 * m22 - m12 * m21)
+ m01 * (m12 * m20 - m10 * m22)
+ m02 * (m10 * m21 - m11 * m20);
return f;
}
/**
* Returns a string representation of this matrix
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append('\n');
buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append('\n');
return buf.toString();
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
@Override
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and put the result into the destination matrix
* @param src The source matrix to be inverted
* @param dest The destination matrix, or null if a new one is to be created
* @return The inverted matrix if successful, null otherwise
*/
public static Matrix3f invert(Matrix3f src, Matrix3f dest) {
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix3f();
/* do it the ordinary way
*
* inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix)
*
* m00 m01 m02
* m10 m11 m12
* m20 m21 m22
*/
float determinant_inv = 1f/determinant;
// get the conjugate matrix
float t00 = src.m11 * src.m22 - src.m12* src.m21;
float t01 = - src.m10 * src.m22 + src.m12 * src.m20;
float t02 = src.m10 * src.m21 - src.m11 * src.m20;
float t10 = - src.m01 * src.m22 + src.m02 * src.m21;
float t11 = src.m00 * src.m22 - src.m02 * src.m20;
float t12 = - src.m00 * src.m21 + src.m01 * src.m20;
float t20 = src.m01 * src.m12 - src.m02 * src.m11;
float t21 = -src.m00 * src.m12 + src.m02 * src.m10;
float t22 = src.m00 * src.m11 - src.m01 * src.m10;
dest.m00 = t00*determinant_inv;
dest.m11 = t11*determinant_inv;
dest.m22 = t22*determinant_inv;
dest.m01 = t10*determinant_inv;
dest.m10 = t01*determinant_inv;
dest.m20 = t02*determinant_inv;
dest.m02 = t20*determinant_inv;
dest.m12 = t21*determinant_inv;
dest.m21 = t12*determinant_inv;
return dest;
} else
return null;
}
/**
* Negate this matrix
* @return this
*/
@Override
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix3f negate(Matrix3f dest) {
return negate(this, dest);
}
/**
* Negate the source matrix and place the result in the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix3f negate(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = -src.m00;
dest.m01 = -src.m02;
dest.m02 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m12;
dest.m12 = -src.m11;
dest.m20 = -src.m20;
dest.m21 = -src.m22;
dest.m22 = -src.m21;
return dest;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
@Override
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the matrix to be the identity matrix.
* @param m The matrix to be set to the identity
* @return m
*/
public static Matrix3f setIdentity(Matrix3f m) {
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
return m;
}
/**
* Set this matrix to 0.
* @return this
*/
@Override
public Matrix setZero() {
return setZero(this);
}
/**
* Set the matrix matrix to 0.
* @param m The matrix to be set to 0
* @return m
*/
public static Matrix3f setZero(Matrix3f m) {
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
return m;
}
/** Set the matrix matrix to 0.
*
* @param m The matrix to be set to 0
* @return m */
public static Matrix3f setZero(Matrix3f m)
{
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
return m;
}
}

View File

@ -33,22 +33,18 @@ package io.github.hydos.ginger.engine.mathEngine.vectors;
import java.nio.FloatBuffer;
/**
* @author foo
*/
public interface ReadableVector {
/**
* @return the length of the vector
*/
float length();
/**
* @return the length squared of the vector
*/
float lengthSquared();
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
Vector store(FloatBuffer buf);
/** @author foo */
public interface ReadableVector
{
/** @return the length of the vector */
float length();
/** @return the length squared of the vector */
float lengthSquared();
/** Store this vector in a FloatBuffer
*
* @param buf The buffer to store it in, at the current position
* @return this */
Vector store(FloatBuffer buf);
}

View File

@ -31,16 +31,12 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* @author foo
*/
public interface ReadableVector2f extends ReadableVector {
/**
* @return x
*/
float getX();
/**
* @return y
*/
float getY();
/** @author foo */
public interface ReadableVector2f extends ReadableVector
{
/** @return x */
float getX();
/** @return y */
float getY();
}

View File

@ -31,12 +31,9 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* @author foo
*/
public interface ReadableVector3f extends ReadableVector2f {
/**
* @return z
*/
float getZ();
/** @author foo */
public interface ReadableVector3f extends ReadableVector2f
{
/** @return z */
float getZ();
}

View File

@ -31,14 +31,9 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* @author foo
*/
public interface ReadableVector4f extends ReadableVector3f {
/**
* @return w
*/
float getW();
/** @author foo */
public interface ReadableVector4f extends ReadableVector3f
{
/** @return w */
float getW();
}

View File

@ -34,85 +34,64 @@ package io.github.hydos.ginger.engine.mathEngine.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
/** Base class for vectors.
*
* Base class for vectors.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public abstract class Vector implements Serializable, ReadableVector {
* $Id$ */
public abstract class Vector implements Serializable, ReadableVector
{
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/** Constructor for Vector. */
protected Vector()
{ super(); }
/** @return the length of the vector */
@Override
public final float length()
{ return (float) Math.sqrt(lengthSquared()); }
/**
* Constructor for Vector.
*/
protected Vector() {
super();
}
/**
* @return the length of the vector
*/
@Override
public final float length() {
return (float) Math.sqrt(lengthSquared());
}
/**
* @return the length squared of the vector
*/
@Override
/** @return the length squared of the vector */
@Override
public abstract float lengthSquared();
/**
* Load this vector from a FloatBuffer
* @param buf The buffer to load it from, at the current position
* @return this
*/
public abstract Vector load(FloatBuffer buf);
/** Load this vector from a FloatBuffer
*
* @param buf The buffer to load it from, at the current position
* @return this */
public abstract Vector load(FloatBuffer buf);
/**
* Negate a vector
* @return this
*/
public abstract Vector negate();
/** Negate a vector
*
* @return this */
public abstract Vector negate();
/** Normalise this vector
*
* @return this */
public final Vector normalise()
{
float len = length();
if (len != 0.0f)
{
float l = 1.0f / len;
return scale(l);
}
else
throw new IllegalStateException("Zero length vector");
}
/**
* Normalise this vector
* @return this
*/
public final Vector normalise() {
float len = length();
if (len != 0.0f) {
float l = 1.0f / len;
return scale(l);
} else
throw new IllegalStateException("Zero length vector");
}
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
@Override
/** Store this vector in a FloatBuffer
*
* @param buf The buffer to store it in, at the current position
* @return this */
@Override
public abstract Vector store(FloatBuffer buf);
/**
* Scale this vector
* @param scale The scale factor
* @return this
*/
public abstract Vector scale(float scale);
/** Scale this vector
*
* @param scale The scale factor
* @return this */
public abstract Vector scale(float scale);
}

View File

@ -34,280 +34,246 @@ package io.github.hydos.ginger.engine.mathEngine.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
/** Holds a 2-tuple vector.
*
* Holds a 2-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
* $Id$ */
public class Vector2f extends Vector implements Serializable, ReadableVector2f, WritableVector2f
{
private static final long serialVersionUID = 1L;
public float x, y;
public class Vector2f extends Vector implements Serializable, ReadableVector2f, WritableVector2f {
/** Constructor for Vector2f. */
public Vector2f()
{ super(); }
private static final long serialVersionUID = 1L;
/** Constructor. */
public Vector2f(ReadableVector2f src)
{ set(src); }
public float x, y;
/** Constructor. */
public Vector2f(float x, float y)
{ set(x, y); }
/**
* Constructor for Vector2f.
*/
public Vector2f() {
super();
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
/**
* Constructor.
*/
public Vector2f(ReadableVector2f src) {
set(src);
}
/** Load from another Vector2f
*
* @param src The source vector
* @return this */
public Vector2f set(ReadableVector2f src)
{
x = src.getX();
y = src.getY();
return this;
}
/**
* Constructor.
*/
public Vector2f(float x, float y) {
set(x, y);
}
/** @return the length squared of the vector */
@Override
public float lengthSquared()
{ return x * x + y * y; }
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/** Translate a vector
*
* @param x The translation in x
* @param y the translation in y
* @return this */
public Vector2f translate(float x, float y)
{
this.x += x;
this.y += y;
return this;
}
/**
* Load from another Vector2f
* @param src The source vector
* @return this
*/
public Vector2f set(ReadableVector2f src) {
x = src.getX();
y = src.getY();
return this;
}
/** Negate a vector
*
* @return this */
@Override
public Vector negate()
{
x = -x;
y = -y;
return this;
}
/**
* @return the length squared of the vector
*/
@Override
public float lengthSquared() {
return x * x + y * y;
}
/** Negate a vector and place the result in a destination vector.
*
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector */
public Vector2f negate(Vector2f dest)
{
if (dest == null)
dest = new Vector2f();
dest.x = -x;
dest.y = -y;
return dest;
}
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector2f translate(float x, float y) {
this.x += x;
this.y += y;
return this;
}
/** Normalise this vector and place the result in another vector.
*
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector */
public Vector2f normalise(Vector2f dest)
{
float l = length();
if (dest == null)
dest = new Vector2f(x / l, y / l);
else
dest.set(x / l, y / l);
return dest;
}
/**
* Negate a vector
* @return this
*/
@Override
public Vector negate() {
x = -x;
y = -y;
return this;
}
/** The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
*
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right */
public static float dot(Vector2f left, Vector2f right)
{ return left.x * right.x + left.y * right.y; }
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector2f negate(Vector2f dest) {
if (dest == null)
dest = new Vector2f();
dest.x = -x;
dest.y = -y;
return dest;
}
/** Calculate the angle between two vectors, in radians
*
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians */
public static float angle(Vector2f a, Vector2f b)
{
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float) Math.acos(dls);
}
/** Add a vector to another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest */
public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest)
{
if (dest == null)
return new Vector2f(left.x + right.x, left.y + right.y);
else
{
dest.set(left.x + right.x, left.y + right.y);
return dest;
}
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector2f normalise(Vector2f dest) {
float l = length();
/** Subtract a vector from another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest */
public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest)
{
if (dest == null)
return new Vector2f(left.x - right.x, left.y - right.y);
else
{
dest.set(left.x - right.x, left.y - right.y);
return dest;
}
}
if (dest == null)
dest = new Vector2f(x / l, y / l);
else
dest.set(x / l, y / l);
/** Store this vector in a FloatBuffer
*
* @param buf The buffer to store it in, at the current position
* @return this */
@Override
public Vector store(FloatBuffer buf)
{
buf.put(x);
buf.put(y);
return this;
}
return dest;
}
/** Load this vector from a FloatBuffer
*
* @param buf The buffer to load it from, at the current position
* @return this */
@Override
public Vector load(FloatBuffer buf)
{
x = buf.get();
y = buf.get();
return this;
}
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector2f left, Vector2f right) {
return left.x * right.x + left.y * right.y;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale)
{
x *= scale;
y *= scale;
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(64);
sb.append("Vector2f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(']');
return sb.toString();
}
/** @return x */
@Override
public final float getX()
{ return x; }
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector2f a, Vector2f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/** @return y */
@Override
public final float getY()
{ return y; }
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest) {
if (dest == null)
return new Vector2f(left.x + right.x, left.y + right.y);
else {
dest.set(left.x + right.x, left.y + right.y);
return dest;
}
}
/** Set X
*
* @param x */
@Override
public final void setX(float x)
{ this.x = x; }
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest) {
if (dest == null)
return new Vector2f(left.x - right.x, left.y - right.y);
else {
dest.set(left.x - right.x, left.y - right.y);
return dest;
}
}
/** Set Y
*
* @param y */
@Override
public final void setY(float y)
{ this.y = y; }
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
@Override
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
return this;
}
/**
* Load this vector from a FloatBuffer
* @param buf The buffer to load it from, at the current position
* @return this
*/
@Override
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale) {
x *= scale;
y *= scale;
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("Vector2f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(']');
return sb.toString();
}
/**
* @return x
*/
@Override
public final float getX() {
return x;
}
/**
* @return y
*/
@Override
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
@Override
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
@Override
public final void setY(float y) {
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector2f other = (Vector2f)obj;
if (x == other.x && y == other.y) return true;
return false;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector2f other = (Vector2f) obj;
if (x == other.x && y == other.y) return true;
return false;
}
}

View File

@ -34,354 +34,307 @@ package io.github.hydos.ginger.engine.mathEngine.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
/** Holds a 3-tuple vector.
*
* Holds a 3-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
* $Id$ */
public class Vector3f extends Vector implements Serializable, ReadableVector3f, WritableVector3f
{
private static final long serialVersionUID = 1L;
public float x, y, z;
public class Vector3f extends Vector implements Serializable, ReadableVector3f, WritableVector3f {
/** Constructor for Vector3f. */
public Vector3f()
{ super(); }
private static final long serialVersionUID = 1L;
/** Constructor */
public Vector3f(ReadableVector3f src)
{ set(src); }
public float x, y, z;
/** Constructor */
public Vector3f(float x, float y, float z)
{ set(x, y, z); }
/**
* Constructor for Vector3f.
*/
public Vector3f() {
super();
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
/**
* Constructor
*/
public Vector3f(ReadableVector3f src) {
set(src);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
@Override
public void set(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
/**
* Constructor
*/
public Vector3f(float x, float y, float z) {
set(x, y, z);
}
/** Load from another Vector3f
*
* @param src The source vector
* @return this */
public Vector3f set(ReadableVector3f src)
{
x = src.getX();
y = src.getY();
z = src.getZ();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/** @return the length squared of the vector */
@Override
public float lengthSquared()
{ return x * x + y * y + z * z; }
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
@Override
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/** Translate a vector
*
* @param x The translation in x
* @param y the translation in y
* @return this */
public Vector3f translate(float x, float y, float z)
{
this.x += x;
this.y += y;
this.z += z;
return this;
}
/**
* Load from another Vector3f
* @param src The source vector
* @return this
*/
public Vector3f set(ReadableVector3f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
return this;
}
/** Add a vector to another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest */
public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest)
{
if (dest == null)
return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z);
else
{
dest.set(left.x + right.x, left.y + right.y, left.z + right.z);
return dest;
}
}
/**
* @return the length squared of the vector
*/
@Override
public float lengthSquared() {
return x * x + y * y + z * z;
}
public Vector3f add(Vector3f vector)
{ return new Vector3f(x + vector.x, y + vector.y, z + vector.z); }
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector3f translate(float x, float y, float z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
/** Subtract a vector from another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest */
public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest)
{
if (dest == null)
return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z);
else
{
dest.set(left.x - right.x, left.y - right.y, left.z - right.z);
return dest;
}
}
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) {
if (dest == null)
return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z);
else {
dest.set(left.x + right.x, left.y + right.y, left.z + right.z);
return dest;
}
}
public Vector3f add(Vector3f vector)
{
return new Vector3f(x + vector.x, y + vector.y, z + vector.z);
}
/** The cross product of two vectors.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination result, or null if a new vector is to be created
* @return left cross right */
public static Vector3f cross(
Vector3f left,
Vector3f right,
Vector3f dest)
{
if (dest == null)
dest = new Vector3f();
dest.set(
left.y * right.z - left.z * right.y,
right.x * left.z - right.z * left.x,
left.x * right.y - left.y * right.x);
return dest;
}
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) {
if (dest == null)
return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z);
else {
dest.set(left.x - right.x, left.y - right.y, left.z - right.z);
return dest;
}
}
/** Negate a vector
*
* @return this */
@Override
public Vector negate()
{
x = -x;
y = -y;
z = -z;
return this;
}
/**
* The cross product of two vectors.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination result, or null if a new vector is to be created
* @return left cross right
*/
public static Vector3f cross(
Vector3f left,
Vector3f right,
Vector3f dest)
{
/** Negate a vector and place the result in a destination vector.
*
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector */
public Vector3f negate(Vector3f dest)
{
if (dest == null)
dest = new Vector3f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
return dest;
}
if (dest == null)
dest = new Vector3f();
public Vector3f mul(float value)
{ return new Vector3f(x * value, y * value, z * value); }
dest.set(
left.y * right.z - left.z * right.y,
right.x * left.z - right.z * left.x,
left.x * right.y - left.y * right.x
);
public Vector3f mul(Vector3f vector)
{ return new Vector3f(x * vector.x, y * vector.y, z * vector.z); }
return dest;
}
/** Normalise this vector and place the result in another vector.
*
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector */
public Vector3f normalise(Vector3f dest)
{
float l = length();
if (dest == null)
dest = new Vector3f(x / l, y / l, z / l);
else
dest.set(x / l, y / l, z / l);
return dest;
}
/** The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
*
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right */
public static float dot(Vector3f left, Vector3f right)
{ return left.x * right.x + left.y * right.y + left.z * right.z; }
/** Calculate the angle between two vectors, in radians
*
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians */
public static float angle(Vector3f a, Vector3f b)
{
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float) Math.acos(dls);
}
/**
* Negate a vector
* @return this
*/
@Override
public Vector negate() {
x = -x;
y = -y;
z = -z;
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
@Override
public Vector load(FloatBuffer buf)
{
x = buf.get();
y = buf.get();
z = buf.get();
return this;
}
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector3f negate(Vector3f dest) {
if (dest == null)
dest = new Vector3f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
return dest;
}
public Vector3f mul(float value)
{
return new Vector3f(x * value, y * value, z * value);
}
public Vector3f mul(Vector3f vector)
{
return new Vector3f(x * vector.x, y * vector.y, z * vector.z);
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale)
{
x *= scale;
y *= scale;
z *= scale;
return this;
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector3f normalise(Vector3f dest) {
float l = length();
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
@Override
public Vector store(FloatBuffer buf)
{
buf.put(x);
buf.put(y);
buf.put(z);
return this;
}
if (dest == null)
dest = new Vector3f(x / l, y / l, z / l);
else
dest.set(x / l, y / l, z / l);
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(64);
sb.append("Vector3f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(", ");
sb.append(z);
sb.append(']');
return sb.toString();
}
return dest;
}
/** @return x */
@Override
public final float getX()
{ return x; }
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector3f left, Vector3f right) {
return left.x * right.x + left.y * right.y + left.z * right.z;
}
/** @return y */
@Override
public final float getY()
{ return y; }
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector3f a, Vector3f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/** Set X
*
* @param x */
@Override
public final void setX(float x)
{ this.x = x; }
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
@Override
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
return this;
}
/** Set Y
*
* @param y */
@Override
public final void setY(float y)
{ this.y = y; }
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale) {
/** Set Z
*
* @param z */
@Override
public void setZ(float z)
{ this.z = z; }
x *= scale;
y *= scale;
z *= scale;
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getZ()
{ return z; }
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
@Override
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
buf.put(z);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("Vector3f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(", ");
sb.append(z);
sb.append(']');
return sb.toString();
}
/**
* @return x
*/
@Override
public final float getX() {
return x;
}
/**
* @return y
*/
@Override
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
@Override
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
@Override
public final void setY(float y) {
this.y = y;
}
/**
* Set Z
* @param z
*/
@Override
public void setZ(float z) {
this.z = z;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getZ() {
return z;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector3f other = (Vector3f)obj;
if (x == other.x && y == other.y && z == other.z) return true;
return false;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector3f other = (Vector3f) obj;
if (x == other.x && y == other.y && z == other.z) return true;
return false;
}
}

View File

@ -34,334 +34,298 @@ package io.github.hydos.ginger.engine.mathEngine.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 4-tuple vector.
/** Holds a 4-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
* $Id$ */
public class Vector4f extends Vector implements Serializable, ReadableVector4f, WritableVector4f
{
private static final long serialVersionUID = 1L;
public float x, y, z, w;
public class Vector4f extends Vector implements Serializable, ReadableVector4f, WritableVector4f {
/** Constructor for Vector4f. */
public Vector4f()
{ super(); }
private static final long serialVersionUID = 1L;
/** Constructor */
public Vector4f(ReadableVector4f src)
{ set(src); }
public float x, y, z, w;
/** Constructor */
public Vector4f(float x, float y, float z, float w)
{ set(x, y, z, w); }
/**
* Constructor for Vector4f.
*/
public Vector4f() {
super();
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
/**
* Constructor
*/
public Vector4f(ReadableVector4f src) {
set(src);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
@Override
public void set(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
/**
* Constructor
*/
public Vector4f(float x, float y, float z, float w) {
set(x, y, z, w);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float)
*/
@Override
public void set(float x, float y, float z, float w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
@Override
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/** Load from another Vector4f
*
* @param src The source vector
* @return this */
public Vector4f set(ReadableVector4f src)
{
x = src.getX();
y = src.getY();
z = src.getZ();
w = src.getW();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
@Override
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/** @return the length squared of the vector */
@Override
public float lengthSquared()
{ return x * x + y * y + z * z + w * w; }
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float)
*/
@Override
public void set(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/** Translate a vector
*
* @param x The translation in x
* @param y the translation in y
* @return this */
public Vector4f translate(float x, float y, float z, float w)
{
this.x += x;
this.y += y;
this.z += z;
this.w += w;
return this;
}
/**
* Load from another Vector4f
* @param src The source vector
* @return this
*/
public Vector4f set(ReadableVector4f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
w = src.getW();
return this;
}
/** Add a vector to another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest */
public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest)
{
if (dest == null)
return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
else
{
dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
return dest;
}
}
/**
* @return the length squared of the vector
*/
@Override
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
/** Subtract a vector from another vector and place the result in a destination
* vector.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest */
public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest)
{
if (dest == null)
return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
else
{
dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
return dest;
}
}
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector4f translate(float x, float y, float z, float w) {
this.x += x;
this.y += y;
this.z += z;
this.w += w;
return this;
}
/** Negate a vector
*
* @return this */
@Override
public Vector negate()
{
x = -x;
y = -y;
z = -z;
w = -w;
return this;
}
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest) {
if (dest == null)
return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
else {
dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
return dest;
}
}
/** Negate a vector and place the result in a destination vector.
*
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector */
public Vector4f negate(Vector4f dest)
{
if (dest == null)
dest = new Vector4f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
dest.w = -w;
return dest;
}
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest) {
if (dest == null)
return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
else {
dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
return dest;
}
}
/** Normalise this vector and place the result in another vector.
*
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector */
public Vector4f normalise(Vector4f dest)
{
float l = length();
if (dest == null)
dest = new Vector4f(x / l, y / l, z / l, w / l);
else
dest.set(x / l, y / l, z / l, w / l);
return dest;
}
/** The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w
*
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right */
public static float dot(Vector4f left, Vector4f right)
{ return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; }
/**
* Negate a vector
* @return this
*/
@Override
public Vector negate() {
x = -x;
y = -y;
z = -z;
w = -w;
return this;
}
/** Calculate the angle between two vectors, in radians
*
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians */
public static float angle(Vector4f a, Vector4f b)
{
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float) Math.acos(dls);
}
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector4f negate(Vector4f dest) {
if (dest == null)
dest = new Vector4f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
dest.w = -w;
return dest;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
@Override
public Vector load(FloatBuffer buf)
{
x = buf.get();
y = buf.get();
z = buf.get();
w = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale)
{
x *= scale;
y *= scale;
z *= scale;
w *= scale;
return this;
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector4f normalise(Vector4f dest) {
float l = length();
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
@Override
public Vector store(FloatBuffer buf)
{
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
return this;
}
if (dest == null)
dest = new Vector4f(x / l, y / l, z / l, w / l);
else
dest.set(x / l, y / l, z / l, w / l);
@Override
public String toString()
{ return "Vector4f: " + x + " " + y + " " + z + " " + w; }
return dest;
}
/** @return x */
@Override
public final float getX()
{ return x; }
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector4f left, Vector4f right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
}
/** @return y */
@Override
public final float getY()
{ return y; }
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector4f a, Vector4f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/** Set X
*
* @param x */
@Override
public final void setX(float x)
{ this.x = x; }
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
@Override
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
w = buf.get();
return this;
}
/** Set Y
*
* @param y */
@Override
public final void setY(float y)
{ this.y = y; }
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
@Override
public Vector scale(float scale) {
x *= scale;
y *= scale;
z *= scale;
w *= scale;
return this;
}
/** Set Z
*
* @param z */
@Override
public void setZ(float z)
{ this.z = z; }
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
@Override
public Vector store(FloatBuffer buf) {
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getZ()
{ return z; }
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
/** Set W
*
* @param w */
@Override
public void setW(float w)
{ this.w = w; }
return this;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getW()
{ return w; }
@Override
public String toString() {
return "Vector4f: " + x + " " + y + " " + z + " " + w;
}
/**
* @return x
*/
@Override
public final float getX() {
return x;
}
/**
* @return y
*/
@Override
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
@Override
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
@Override
public final void setY(float y) {
this.y = y;
}
/**
* Set Z
* @param z
*/
@Override
public void setZ(float z) {
this.z = z;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getZ() {
return z;
}
/**
* Set W
* @param w
*/
@Override
public void setW(float w) {
this.w = w;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
@Override
public float getW() {
return w;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector4f other = (Vector4f)obj;
if (x == other.x && y == other.y && z == other.z && w == other.w) return true;
return false;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector4f other = (Vector4f) obj;
if (x == other.x && y == other.y && z == other.z && w == other.w) return true;
return false;
}
}

View File

@ -31,31 +31,26 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* Writable interface to Vector2fs
* @author $author$
/** Writable interface to Vector2fs
*
* @author $author$
* @version $revision$
* $Id$
*/
public interface WritableVector2f {
* $Id$ */
public interface WritableVector2f
{
/** Set the X value
*
* @param x */
void setX(float x);
/**
* Set the X value
* @param x
*/
void setX(float x);
/**
* Set the Y value
* @param y
*/
void setY(float y);
/**
* Set the X,Y values
* @param x
* @param y
*/
void set(float x, float y);
/** Set the Y value
*
* @param y */
void setY(float y);
/** Set the X,Y values
*
* @param x
* @param y */
void set(float x, float y);
}

View File

@ -31,26 +31,22 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* Writable interface to Vector3fs
* @author $author$
/** Writable interface to Vector3fs
*
* @author $author$
* @version $revision$
* $Id$
*/
public interface WritableVector3f extends WritableVector2f {
/**
* Set the Z value
* @param z
*/
void setZ(float z);
/**
* Set the X,Y,Z values
* @param x
* @param y
* @param z
*/
void set(float x, float y, float z);
* $Id$ */
public interface WritableVector3f extends WritableVector2f
{
/** Set the Z value
*
* @param z */
void setZ(float z);
/** Set the X,Y,Z values
*
* @param x
* @param y
* @param z */
void set(float x, float y, float z);
}

View File

@ -31,27 +31,23 @@
*/
package io.github.hydos.ginger.engine.mathEngine.vectors;
/**
* Writable interface to Vector4fs
* @author $author$
/** Writable interface to Vector4fs
*
* @author $author$
* @version $revision$
* $Id$
*/
public interface WritableVector4f extends WritableVector3f {
/**
* Set the W value
* @param w
*/
void setW(float w);
/**
* Set the X,Y,Z,W values
* @param x
* @param y
* @param z
* @param w
*/
void set(float x, float y, float z, float w);
* $Id$ */
public interface WritableVector4f extends WritableVector3f
{
/** Set the W value
*
* @param w */
void setW(float w);
/** Set the X,Y,Z,W values
*
* @param x
* @param y
* @param z
* @param w */
void set(float x, float y, float z, float w);
}

View File

@ -1,7 +1,7 @@
package io.github.hydos.ginger.engine.obj;
public class ModelData {
public class ModelData
{
private float[] vertices;
private float[] textureCoords;
private float[] normals;
@ -9,7 +9,8 @@ public class ModelData {
private float furthestPoint;
public ModelData(float[] vertices, float[] textureCoords, float[] normals, int[] indices,
float furthestPoint) {
float furthestPoint)
{
this.vertices = vertices;
this.textureCoords = textureCoords;
this.normals = normals;
@ -17,24 +18,18 @@ public class ModelData {
this.furthestPoint = furthestPoint;
}
public float[] getVertices() {
return vertices;
}
public float[] getVertices()
{ return vertices; }
public float[] getTextureCoords() {
return textureCoords;
}
public float[] getTextureCoords()
{ return textureCoords; }
public float[] getNormals() {
return normals;
}
public float[] getNormals()
{ return normals; }
public int[] getIndices() {
return indices;
}
public float getFurthestPoint() {
return furthestPoint;
}
public int[] getIndices()
{ return indices; }
public float getFurthestPoint()
{ return furthestPoint; }
}

View File

@ -4,12 +4,12 @@ import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
import io.github.hydos.ginger.engine.utils.Loader;
public class ModelLoader {
public static TexturedModel loadModel(String objPath, String texturePath) {
public class ModelLoader
{
public static TexturedModel loadModel(String objPath, String texturePath)
{
ModelData data = OBJFileLoader.loadOBJ(objPath);
TexturedModel tm = new TexturedModel(Loader.loadToVAO(data.getVertices(), data.getIndices(), data.getNormals(), data.getTextureCoords()), new ModelTexture(texturePath));
return tm;
}
}

View File

@ -9,11 +9,12 @@ import java.util.List;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class OBJFileLoader {
public class OBJFileLoader
{
private static final String RES_LOC = "/models/";
public static ModelData loadOBJ(String objFileName) {
public static ModelData loadOBJ(String objFileName)
{
String objFile = RES_LOC + objFileName;
System.out.println(objFile);
System.out.println(objFile);
@ -24,33 +25,40 @@ public class OBJFileLoader {
List<Vector2f> textures = new ArrayList<Vector2f>();
List<Vector3f> normals = new ArrayList<Vector3f>();
List<Integer> indices = new ArrayList<Integer>();
try {
while (true) {
try
{
while (true)
{
line = reader.readLine();
if (line.startsWith("v ")) {
if (line.startsWith("v "))
{
String[] currentLine = line.split(" ");
Vector3f vertex = new Vector3f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
Vertex newVertex = new Vertex(vertices.size(), vertex);
vertices.add(newVertex);
} else if (line.startsWith("vt ")) {
}
else if (line.startsWith("vt "))
{
String[] currentLine = line.split(" ");
Vector2f texture = new Vector2f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]));
Float.valueOf(currentLine[2]));
textures.add(texture);
} else if (line.startsWith("vn ")) {
}
else if (line.startsWith("vn "))
{
String[] currentLine = line.split(" ");
Vector3f normal = new Vector3f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
normals.add(normal);
} else if (line.startsWith("f ")) {
break;
}
else if (line.startsWith("f "))
{ break; }
}
while (line != null && line.startsWith("f ")) {
while (line != null && line.startsWith("f "))
{
String[] currentLine = line.split(" ");
String[] vertex1 = currentLine[1].split("/");
String[] vertex2 = currentLine[2].split("/");
@ -61,7 +69,9 @@ public class OBJFileLoader {
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
}
catch (IOException e)
{
System.err.println("Error reading the file");
}
removeUnusedVertices(vertices);
@ -69,45 +79,50 @@ public class OBJFileLoader {
float[] texturesArray = new float[vertices.size() * 2];
float[] normalsArray = new float[vertices.size() * 3];
float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
texturesArray, normalsArray);
texturesArray, normalsArray);
int[] indicesArray = convertIndicesListToArray(indices);
ModelData data = new ModelData(verticesArray, texturesArray, normalsArray, indicesArray,
furthest);
furthest);
return data;
}
private static void processVertex(String[] vertex, List<Vertex> vertices, List<Integer> indices) {
private static void processVertex(String[] vertex, List<Vertex> vertices, List<Integer> indices)
{
int index = Integer.parseInt(vertex[0]) - 1;
Vertex currentVertex = vertices.get(index);
int textureIndex = Integer.parseInt(vertex[1]) - 1;
int normalIndex = Integer.parseInt(vertex[2]) - 1;
if (!currentVertex.isSet()) {
if (!currentVertex.isSet())
{
currentVertex.setTextureIndex(textureIndex);
currentVertex.setNormalIndex(normalIndex);
indices.add(index);
} else {
}
else
{
dealWithAlreadyProcessedVertex(currentVertex, textureIndex, normalIndex, indices,
vertices);
vertices);
}
}
private static int[] convertIndicesListToArray(List<Integer> indices) {
private static int[] convertIndicesListToArray(List<Integer> indices)
{
int[] indicesArray = new int[indices.size()];
for (int i = 0; i < indicesArray.length; i++) {
indicesArray[i] = indices.get(i);
}
for (int i = 0; i < indicesArray.length; i++)
{ indicesArray[i] = indices.get(i); }
return indicesArray;
}
private static float convertDataToArrays(List<Vertex> vertices, List<Vector2f> textures,
List<Vector3f> normals, float[] verticesArray, float[] texturesArray,
float[] normalsArray) {
List<Vector3f> normals, float[] verticesArray, float[] texturesArray,
float[] normalsArray)
{
float furthestPoint = 0;
for (int i = 0; i < vertices.size(); i++) {
for (int i = 0; i < vertices.size(); i++)
{
Vertex currentVertex = vertices.get(i);
if (currentVertex.getLength() > furthestPoint) {
furthestPoint = currentVertex.getLength();
}
if (currentVertex.getLength() > furthestPoint)
{ furthestPoint = currentVertex.getLength(); }
Vector3f position = currentVertex.getPosition();
Vector2f textureCoord = textures.get(currentVertex.getTextureIndex());
Vector3f normalVector = normals.get(currentVertex.getNormalIndex());
@ -124,15 +139,22 @@ public class OBJFileLoader {
}
private static void dealWithAlreadyProcessedVertex(Vertex previousVertex, int newTextureIndex,
int newNormalIndex, List<Integer> indices, List<Vertex> vertices) {
if (previousVertex.hasSameTextureAndNormal(newTextureIndex, newNormalIndex)) {
int newNormalIndex, List<Integer> indices, List<Vertex> vertices)
{
if (previousVertex.hasSameTextureAndNormal(newTextureIndex, newNormalIndex))
{
indices.add(previousVertex.getIndex());
} else {
}
else
{
Vertex anotherVertex = previousVertex.getDuplicateVertex();
if (anotherVertex != null) {
if (anotherVertex != null)
{
dealWithAlreadyProcessedVertex(anotherVertex, newTextureIndex, newNormalIndex,
indices, vertices);
} else {
indices, vertices);
}
else
{
Vertex duplicateVertex = new Vertex(vertices.size(), previousVertex.getPosition());
duplicateVertex.setTextureIndex(newTextureIndex);
duplicateVertex.setNormalIndex(newNormalIndex);
@ -140,17 +162,18 @@ public class OBJFileLoader {
vertices.add(duplicateVertex);
indices.add(duplicateVertex.getIndex());
}
}
}
private static void removeUnusedVertices(List<Vertex> vertices){
for(Vertex vertex:vertices){
if(!vertex.isSet()){
private static void removeUnusedVertices(List<Vertex> vertices)
{
for (Vertex vertex : vertices)
{
if (!vertex.isSet())
{
vertex.setTextureIndex(0);
vertex.setNormalIndex(0);
}
}
}
}

View File

@ -2,65 +2,53 @@ package io.github.hydos.ginger.engine.obj;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class Vertex {
public class Vertex
{
private static final int NO_INDEX = -1;
private Vector3f position;
private int textureIndex = NO_INDEX;
private int normalIndex = NO_INDEX;
private Vertex duplicateVertex = null;
private int index;
private float length;
public Vertex(int index,Vector3f position){
public Vertex(int index, Vector3f position)
{
this.index = index;
this.position = position;
this.length = position.length();
}
public int getIndex(){
return index;
}
public float getLength(){
return length;
}
public boolean isSet(){
return textureIndex!=NO_INDEX && normalIndex!=NO_INDEX;
}
public boolean hasSameTextureAndNormal(int textureIndexOther,int normalIndexOther){
return textureIndexOther==textureIndex && normalIndexOther==normalIndex;
}
public void setTextureIndex(int textureIndex){
this.textureIndex = textureIndex;
}
public void setNormalIndex(int normalIndex){
this.normalIndex = normalIndex;
}
public Vector3f getPosition() {
return position;
}
public int getIndex()
{ return index; }
public int getTextureIndex() {
return textureIndex;
}
public float getLength()
{ return length; }
public int getNormalIndex() {
return normalIndex;
}
public boolean isSet()
{ return textureIndex != NO_INDEX && normalIndex != NO_INDEX; }
public Vertex getDuplicateVertex() {
return duplicateVertex;
}
public boolean hasSameTextureAndNormal(int textureIndexOther, int normalIndexOther)
{ return textureIndexOther == textureIndex && normalIndexOther == normalIndex; }
public void setDuplicateVertex(Vertex duplicateVertex) {
this.duplicateVertex = duplicateVertex;
}
public void setTextureIndex(int textureIndex)
{ this.textureIndex = textureIndex; }
public void setNormalIndex(int normalIndex)
{ this.normalIndex = normalIndex; }
public Vector3f getPosition()
{ return position; }
public int getTextureIndex()
{ return textureIndex; }
public int getNormalIndex()
{ return normalIndex; }
public Vertex getDuplicateVertex()
{ return duplicateVertex; }
public void setDuplicateVertex(Vertex duplicateVertex)
{ this.duplicateVertex = duplicateVertex; }
}

View File

@ -1,7 +1,7 @@
package io.github.hydos.ginger.engine.obj.normals;
public class ModelDataNM {
public class ModelDataNM
{
private float[] vertices;
private float[] textureCoords;
private float[] normals;
@ -10,7 +10,8 @@ public class ModelDataNM {
private float furthestPoint;
public ModelDataNM(float[] vertices, float[] textureCoords, float[] normals, float[] tangents, int[] indices,
float furthestPoint) {
float furthestPoint)
{
this.vertices = vertices;
this.textureCoords = textureCoords;
this.normals = normals;
@ -19,28 +20,21 @@ public class ModelDataNM {
this.tangents = tangents;
}
public float[] getVertices() {
return vertices;
}
public float[] getVertices()
{ return vertices; }
public float[] getTextureCoords() {
return textureCoords;
}
public float[] getTangents(){
return tangents;
}
public float[] getTextureCoords()
{ return textureCoords; }
public float[] getNormals() {
return normals;
}
public float[] getTangents()
{ return tangents; }
public int[] getIndices() {
return indices;
}
public float[] getNormals()
{ return normals; }
public float getFurthestPoint() {
return furthestPoint;
}
public int[] getIndices()
{ return indices; }
public float getFurthestPoint()
{ return furthestPoint; }
}

View File

@ -11,10 +11,10 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.utils.Loader;
public class NormalMappedObjLoader {
public static RawModel loadOBJ(String objFileName) {
public class NormalMappedObjLoader
{
public static RawModel loadOBJ(String objFileName)
{
BufferedReader isr = null;
isr = new BufferedReader(new InputStreamReader(Class.class.getResourceAsStream("/models/" + objFileName)));
BufferedReader reader = new BufferedReader(isr);
@ -23,33 +23,40 @@ public class NormalMappedObjLoader {
List<Vector2f> textures = new ArrayList<Vector2f>();
List<Vector3f> normals = new ArrayList<Vector3f>();
List<Integer> indices = new ArrayList<Integer>();
try {
while (true) {
try
{
while (true)
{
line = reader.readLine();
if (line.startsWith("v ")) {
if (line.startsWith("v "))
{
String[] currentLine = line.split(" ");
Vector3f vertex = new Vector3f((float) Float.valueOf(currentLine[1]),
(float) Float.valueOf(currentLine[2]),
(float) Float.valueOf(currentLine[3]));
Vector3f vertex = new Vector3f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
VertexNM newVertex = new VertexNM(vertices.size(), vertex);
vertices.add(newVertex);
} else if (line.startsWith("vt ")) {
String[] currentLine = line.split(" ");
Vector2f texture = new Vector2f((float) Float.valueOf(currentLine[1]),
(float) Float.valueOf(currentLine[2]));
textures.add(texture);
} else if (line.startsWith("vn ")) {
String[] currentLine = line.split(" ");
Vector3f normal = new Vector3f((float) Float.valueOf(currentLine[1]),
(float) Float.valueOf(currentLine[2]),
(float) Float.valueOf(currentLine[3]));
normals.add(normal);
} else if (line.startsWith("f ")) {
break;
}
else if (line.startsWith("vt "))
{
String[] currentLine = line.split(" ");
Vector2f texture = new Vector2f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]));
textures.add(texture);
}
else if (line.startsWith("vn "))
{
String[] currentLine = line.split(" ");
Vector3f normal = new Vector3f(Float.valueOf(currentLine[1]),
Float.valueOf(currentLine[2]),
Float.valueOf(currentLine[3]));
normals.add(normal);
}
else if (line.startsWith("f "))
{ break; }
}
while (line != null && line.startsWith("f ")) {
while (line != null && line.startsWith("f "))
{
String[] currentLine = line.split(" ");
String[] vertex1 = currentLine[1].split("/");
String[] vertex2 = currentLine[2].split("/");
@ -61,7 +68,9 @@ public class NormalMappedObjLoader {
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
}
catch (IOException e)
{
System.err.println("Error reading the file");
}
removeUnusedVertices(vertices);
@ -72,14 +81,13 @@ public class NormalMappedObjLoader {
@SuppressWarnings("unused")
//some weird eclipse only error here i think
float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
texturesArray, normalsArray, tangentsArray);
texturesArray, normalsArray, tangentsArray);
int[] indicesArray = convertIndicesListToArray(indices);
return Loader.loadToVAO(verticesArray, indicesArray, normalsArray, tangentsArray, texturesArray);
}
private static void calculateTangents(VertexNM v0, VertexNM v1, VertexNM v2,
List<Vector2f> textures) {
private static void calculateTangents(VertexNM v0, VertexNM v1, VertexNM v2, List<Vector2f> textures)
{
Vector3f delatPos1 = Vector3f.sub(v1.getPosition(), v0.getPosition(), null);
Vector3f delatPos2 = Vector3f.sub(v2.getPosition(), v0.getPosition(), null);
Vector2f uv0 = textures.get(v0.getTextureIndex());
@ -87,7 +95,6 @@ public class NormalMappedObjLoader {
Vector2f uv2 = textures.get(v2.getTextureIndex());
Vector2f deltaUv1 = Vector2f.sub(uv1, uv0, null);
Vector2f deltaUv2 = Vector2f.sub(uv2, uv0, null);
float r = 1.0f / (deltaUv1.x * deltaUv2.y - deltaUv1.y * deltaUv2.x);
delatPos1.scale(deltaUv2.y);
delatPos2.scale(deltaUv1.y);
@ -98,40 +105,44 @@ public class NormalMappedObjLoader {
v2.addTangent(tangent);
}
private static VertexNM processVertex(String[] vertex, List<VertexNM> vertices,
List<Integer> indices) {
private static VertexNM processVertex(String[] vertex, List<VertexNM> vertices, List<Integer> indices)
{
int index = Integer.parseInt(vertex[0]) - 1;
VertexNM currentVertex = vertices.get(index);
int textureIndex = Integer.parseInt(vertex[1]) - 1;
int normalIndex = Integer.parseInt(vertex[2]) - 1;
if (!currentVertex.isSet()) {
if (!currentVertex.isSet())
{
currentVertex.setTextureIndex(textureIndex);
currentVertex.setNormalIndex(normalIndex);
indices.add(index);
return currentVertex;
} else {
}
else
{
return dealWithAlreadyProcessedVertex(currentVertex, textureIndex, normalIndex, indices,
vertices);
vertices);
}
}
private static int[] convertIndicesListToArray(List<Integer> indices) {
private static int[] convertIndicesListToArray(List<Integer> indices)
{
int[] indicesArray = new int[indices.size()];
for (int i = 0; i < indicesArray.length; i++) {
indicesArray[i] = indices.get(i);
}
for (int i = 0; i < indicesArray.length; i++)
{ indicesArray[i] = indices.get(i); }
return indicesArray;
}
private static float convertDataToArrays(List<VertexNM> vertices, List<Vector2f> textures,
List<Vector3f> normals, float[] verticesArray, float[] texturesArray,
float[] normalsArray, float[] tangentsArray) {
List<Vector3f> normals, float[] verticesArray, float[] texturesArray,
float[] normalsArray, float[] tangentsArray)
{
float furthestPoint = 0;
for (int i = 0; i < vertices.size(); i++) {
for (int i = 0; i < vertices.size(); i++)
{
VertexNM currentVertex = vertices.get(i);
if (currentVertex.getLength() > furthestPoint) {
furthestPoint = currentVertex.getLength();
}
if (currentVertex.getLength() > furthestPoint)
{ furthestPoint = currentVertex.getLength(); }
Vector3f position = currentVertex.getPosition();
Vector2f textureCoord = textures.get(currentVertex.getTextureIndex());
Vector3f normalVector = normals.get(currentVertex.getNormalIndex());
@ -147,22 +158,28 @@ public class NormalMappedObjLoader {
tangentsArray[i * 3] = tangent.x;
tangentsArray[i * 3 + 1] = tangent.y;
tangentsArray[i * 3 + 2] = tangent.z;
}
return furthestPoint;
}
private static VertexNM dealWithAlreadyProcessedVertex(VertexNM previousVertex, int newTextureIndex,
int newNormalIndex, List<Integer> indices, List<VertexNM> vertices) {
if (previousVertex.hasSameTextureAndNormal(newTextureIndex, newNormalIndex)) {
int newNormalIndex, List<Integer> indices, List<VertexNM> vertices)
{
if (previousVertex.hasSameTextureAndNormal(newTextureIndex, newNormalIndex))
{
indices.add(previousVertex.getIndex());
return previousVertex;
} else {
}
else
{
VertexNM anotherVertex = previousVertex.getDuplicateVertex();
if (anotherVertex != null) {
if (anotherVertex != null)
{
return dealWithAlreadyProcessedVertex(anotherVertex, newTextureIndex,
newNormalIndex, indices, vertices);
} else {
newNormalIndex, indices, vertices);
}
else
{
VertexNM duplicateVertex = previousVertex.duplicate(vertices.size());
duplicateVertex.setTextureIndex(newTextureIndex);
duplicateVertex.setNormalIndex(newNormalIndex);
@ -174,14 +191,16 @@ public class NormalMappedObjLoader {
}
}
private static void removeUnusedVertices(List<VertexNM> vertices) {
for (VertexNM vertex : vertices) {
private static void removeUnusedVertices(List<VertexNM> vertices)
{
for (VertexNM vertex : vertices)
{
vertex.averageTangents();
if (!vertex.isSet()) {
if (!vertex.isSet())
{
vertex.setTextureIndex(0);
vertex.setNormalIndex(0);
}
}
}
}

View File

@ -5,10 +5,9 @@ import java.util.List;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class VertexNM {
public class VertexNM
{
private static final int NO_INDEX = -1;
private Vector3f position;
private int textureIndex = NO_INDEX;
private int normalIndex = NO_INDEX;
@ -17,80 +16,67 @@ public class VertexNM {
private float length;
private List<Vector3f> tangents = new ArrayList<Vector3f>();
private Vector3f averagedTangent = new Vector3f(0, 0, 0);
protected VertexNM(int index, Vector3f position){
protected VertexNM(int index, Vector3f position)
{
this.index = index;
this.position = position;
this.length = position.length();
}
protected void addTangent(Vector3f tangent){
tangents.add(tangent);
}
protected void addTangent(Vector3f tangent)
{ tangents.add(tangent); }
//NEW
protected VertexNM duplicate(int newIndex){
protected VertexNM duplicate(int newIndex)
{
VertexNM vertex = new VertexNM(newIndex, position);
vertex.tangents = this.tangents;
return vertex;
}
protected void averageTangents(){
if(tangents.isEmpty()){
return;
}
for(Vector3f tangent : tangents){
Vector3f.add(averagedTangent, tangent, averagedTangent);
}
protected void averageTangents()
{
if (tangents.isEmpty())
{ return; }
for (Vector3f tangent : tangents)
{ Vector3f.add(averagedTangent, tangent, averagedTangent); }
averagedTangent.normalise();
}
protected Vector3f getAverageTangent(){
return averagedTangent;
}
protected int getIndex(){
return index;
}
protected float getLength(){
return length;
}
protected boolean isSet(){
return textureIndex!=NO_INDEX && normalIndex!=NO_INDEX;
}
protected boolean hasSameTextureAndNormal(int textureIndexOther,int normalIndexOther){
return textureIndexOther==textureIndex && normalIndexOther==normalIndex;
}
protected void setTextureIndex(int textureIndex){
this.textureIndex = textureIndex;
}
protected void setNormalIndex(int normalIndex){
this.normalIndex = normalIndex;
}
protected Vector3f getPosition() {
return position;
}
protected Vector3f getAverageTangent()
{ return averagedTangent; }
protected int getTextureIndex() {
return textureIndex;
}
protected int getIndex()
{ return index; }
protected int getNormalIndex() {
return normalIndex;
}
protected float getLength()
{ return length; }
protected VertexNM getDuplicateVertex() {
return duplicateVertex;
}
protected boolean isSet()
{ return textureIndex != NO_INDEX && normalIndex != NO_INDEX; }
protected void setDuplicateVertex(VertexNM duplicateVertex) {
this.duplicateVertex = duplicateVertex;
}
protected boolean hasSameTextureAndNormal(int textureIndexOther, int normalIndexOther)
{ return textureIndexOther == textureIndex && normalIndexOther == normalIndex; }
protected void setTextureIndex(int textureIndex)
{ this.textureIndex = textureIndex; }
protected void setNormalIndex(int normalIndex)
{ this.normalIndex = normalIndex; }
protected Vector3f getPosition()
{ return position; }
protected int getTextureIndex()
{ return textureIndex; }
protected int getNormalIndex()
{ return normalIndex; }
protected VertexNM getDuplicateVertex()
{ return duplicateVertex; }
protected void setDuplicateVertex(VertexNM duplicateVertex)
{ this.duplicateVertex = duplicateVertex; }
}

View File

@ -2,33 +2,31 @@ package io.github.hydos.ginger.engine.particle;
import java.util.List;
public class InsertionSort {
/**
* Sorts a list of particles so that the particles with the highest distance
* from the camera are first, and the particles with the shortest distance
* are last.
*
* @param list
* - the list of particles needing sorting.
*/
public static void sortHighToLow(List<Particle> list) {
for (int i = 1; i < list.size(); i++) {
Particle item = list.get(i);
if (item.getDistance() > list.get(i - 1).getDistance()) {
sortUpHighToLow(list, i);
}
}
}
private static void sortUpHighToLow(List<Particle> list, int i) {
Particle item = list.get(i);
int attemptPos = i - 1;
while (attemptPos != 0 && list.get(attemptPos - 1).getDistance() < item.getDistance()) {
attemptPos--;
}
list.remove(i);
list.add(attemptPos, item);
}
public class InsertionSort
{
/** Sorts a list of particles so that the particles with the highest distance
* from the camera are first, and the particles with the shortest distance
* are last.
*
* @param list
* - the list of particles needing sorting. */
public static void sortHighToLow(List<Particle> list)
{
for (int i = 1; i < list.size(); i++)
{
Particle item = list.get(i);
if (item.getDistance() > list.get(i - 1).getDistance())
{ sortUpHighToLow(list, i); }
}
}
private static void sortUpHighToLow(List<Particle> list, int i)
{
Particle item = list.get(i);
int attemptPos = i - 1;
while (attemptPos != 0 && list.get(attemptPos - 1).getDistance() < item.getDistance())
{ attemptPos--; }
list.remove(i);
list.add(attemptPos, item);
}
}

View File

@ -6,27 +6,24 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.main.settings.Constants;
public class Particle {
public class Particle
{
private Vector3f position;
private Vector3f velocity;
private float gravityEffect;
private float lifeLength;
private float rotation;
private Vector3f scale;
private Vector2f texOffset1 = new Vector2f();
private Vector2f texOffset2 = new Vector2f();
private float blend;
private ParticleTexture texture;
private float elapsedTime = 0;
private float distance;
public Particle(ParticleTexture texture, Vector3f position, Vector3f velocity, float gravityEffect, float lifeLength, float rotation,
Vector3f scale) {
Vector3f scale)
{
super();
this.position = position;
this.velocity = velocity;
@ -37,52 +34,46 @@ public class Particle {
this.texture = texture;
ParticleMaster.addParticle(this);
}
public ParticleTexture getTexture() {
return texture;
}
public Vector3f getPosition() {
return position;
}
public float getDistance() {
return distance;
}
public ParticleTexture getTexture()
{ return texture; }
public float getRotation() {
return rotation;
}
public Vector3f getPosition()
{ return position; }
public Vector3f getScale() {
return scale;
}
public Vector2f getTexOffset1() {
return texOffset1;
}
public float getDistance()
{ return distance; }
public Vector2f getTexOffset2() {
return texOffset2;
}
public float getRotation()
{ return rotation; }
public float getBlend() {
return blend;
}
public Vector3f getScale()
{ return scale; }
public boolean update(ThirdPersonCamera camera) {
public Vector2f getTexOffset1()
{ return texOffset1; }
public Vector2f getTexOffset2()
{ return texOffset2; }
public float getBlend()
{ return blend; }
public boolean update(ThirdPersonCamera camera)
{
float time = (float) Window.getTime() / 1000000;
velocity.y += Constants.gravity * gravityEffect * time;
Vector3f change = new Vector3f(velocity);
change.scale((float) time);
change.scale(time);
Vector3f.add(change, position, position);
distance = Vector3f.sub(camera.getPosition(), position, null).lengthSquared();
elapsedTime += time;
updateTextureCoordInfo();
return elapsedTime < lifeLength;
}
private void updateTextureCoordInfo() {
private void updateTextureCoordInfo()
{
float lifeFactor = elapsedTime / lifeLength;
int stageCount = texture.getNumberOfRows() * texture.getNumberOfRows();
float atlasProgression = lifeFactor * stageCount;
@ -92,13 +83,12 @@ public class Particle {
setTextureOffset(texOffset1, index1);
setTextureOffset(texOffset2, index2);
}
private void setTextureOffset(Vector2f offset, int index) {
private void setTextureOffset(Vector2f offset, int index)
{
int column = index % texture.getNumberOfRows();
int row = index / texture.getNumberOfRows();
offset.x = (float) column / texture.getNumberOfRows();
offset.y = (float) row / texture.getNumberOfRows();
}
}

View File

@ -11,53 +11,50 @@ import io.github.hydos.ginger.engine.cameras.ThirdPersonCamera;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.renderEngine.renderers.ParticleRenderer;
public class ParticleMaster {
private static Map<ParticleTexture,List<Particle>> particles = new HashMap<ParticleTexture, List<Particle>>();
public class ParticleMaster
{
private static Map<ParticleTexture, List<Particle>> particles = new HashMap<ParticleTexture, List<Particle>>();
private static ParticleRenderer particleRenderer;
public static void init(Matrix4f projectionMatrix) {
particleRenderer = new ParticleRenderer(projectionMatrix);
}
public static void update(ThirdPersonCamera camera) {
public static void init(Matrix4f projectionMatrix)
{ particleRenderer = new ParticleRenderer(projectionMatrix); }
public static void update(ThirdPersonCamera camera)
{
Iterator<Entry<ParticleTexture, List<Particle>>> mapIterator = particles.entrySet().iterator();
while(mapIterator.hasNext()) {
while (mapIterator.hasNext())
{
List<Particle> list = mapIterator.next().getValue();
Iterator<Particle> iterator= list.iterator();
while(iterator.hasNext()) {
Iterator<Particle> iterator = list.iterator();
while (iterator.hasNext())
{
Particle p = iterator.next();
boolean stillAlive = p.update(camera);
if(!stillAlive) {
if (!stillAlive)
{
iterator.remove();
if(list.isEmpty()) {
mapIterator.remove();
}
if (list.isEmpty())
{ mapIterator.remove(); }
}
}
InsertionSort.sortHighToLow(list);
}
}
public static void renderParticles(ThirdPersonCamera camera) {
particleRenderer.render(particles, camera);
}
public static void cleanUp() {
particleRenderer.cleanUp();
}
public static void addParticle(Particle particle) {
public static void renderParticles(ThirdPersonCamera camera)
{ particleRenderer.render(particles, camera); }
public static void cleanUp()
{ particleRenderer.cleanUp(); }
public static void addParticle(Particle particle)
{
List<Particle> list = particles.get(particle.getTexture());
if(list==null) {
if (list == null)
{
list = new ArrayList<Particle>();
particles.put(particle.getTexture(), list);
}
list.add(particle);
}
}

View File

@ -7,20 +7,18 @@ import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
public class ParticleSystem {
public class ParticleSystem
{
private float pps, averageSpeed, gravityComplient, averageLifeLength, averageScale;
private float speedError, lifeError, scaleError = 0;
private boolean randomRotation = false;
private Vector3f direction;
private float directionDeviation = 0;
private ParticleTexture texture;
private Random random = new Random();
public ParticleSystem(ParticleTexture texture, float pps, float speed, float gravityComplient, float lifeLength, float scale) {
public ParticleSystem(ParticleTexture texture, float pps, float speed, float gravityComplient, float lifeLength, float scale)
{
this.pps = pps / 100000;
this.averageSpeed = speed;
this.gravityComplient = gravityComplient;
@ -29,85 +27,82 @@ public class ParticleSystem {
this.texture = texture;
}
/**
* @param direction - The average direction in which particles are emitted.
* @param deviation - A value between 0 and 1 indicating how far from the chosen direction particles can deviate.
*/
public void setDirection(Vector3f direction, float deviation) {
/** @param direction - The average direction in which particles are emitted.
* @param deviation - A value between 0 and 1 indicating how far from the chosen direction particles can deviate. */
public void setDirection(Vector3f direction, float deviation)
{
this.direction = new Vector3f(direction);
this.directionDeviation = (float) (deviation * Math.PI);
}
public void randomizeRotation() {
randomRotation = true;
}
public void randomizeRotation()
{ randomRotation = true; }
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setSpeedError(float error) {
this.speedError = error * averageSpeed;
}
/** @param error
* - A number between 0 and 1, where 0 means no error margin. */
public void setSpeedError(float error)
{ this.speedError = error * averageSpeed; }
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setLifeError(float error) {
this.lifeError = error * averageLifeLength;
}
/** @param error
* - A number between 0 and 1, where 0 means no error margin. */
public void setLifeError(float error)
{ this.lifeError = error * averageLifeLength; }
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setScaleError(float error) {
this.scaleError = error * averageScale;
}
/** @param error
* - A number between 0 and 1, where 0 means no error margin. */
public void setScaleError(float error)
{ this.scaleError = error * averageScale; }
public void generateParticles(Vector3f systemCenter) {
public void generateParticles(Vector3f systemCenter)
{
float delta = (float) Window.getTime();
float particlesToCreate = pps * delta;
int count = (int) Math.floor(particlesToCreate);
float partialParticle = particlesToCreate % 1;
for (int i = 0; i < count; i++) {
emitParticle(systemCenter);
}
if (Math.random() < partialParticle) {
emitParticle(systemCenter);
}
for (int i = 0; i < count; i++)
{ emitParticle(systemCenter); }
if (Math.random() < partialParticle)
{ emitParticle(systemCenter); }
}
private void emitParticle(Vector3f center) {
private void emitParticle(Vector3f center)
{
Vector3f velocity = null;
if(direction!=null){
if (direction != null)
{
velocity = generateRandomUnitVectorWithinCone(direction, directionDeviation);
}else{
}
else
{
velocity = generateRandomUnitVector();
}
velocity.normalise();
velocity.scale(generateValue(averageSpeed, speedError));
float scale = generateValue(averageScale, scaleError);
float lifeLength = generateValue(averageLifeLength, lifeError);
new Particle(texture, new Vector3f(center), velocity, gravityComplient, lifeLength, generateRotation(), new Vector3f(scale,scale,scale));
new Particle(texture, new Vector3f(center), velocity, gravityComplient, lifeLength, generateRotation(), new Vector3f(scale, scale, scale));
}
private float generateValue(float average, float errorMargin) {
private float generateValue(float average, float errorMargin)
{
float offset = (random.nextFloat() - 0.5f) * 2f * errorMargin;
return average + offset;
}
private float generateRotation() {
if (randomRotation) {
private float generateRotation()
{
if (randomRotation)
{
return random.nextFloat() * 360f;
} else {
}
else
{
return 0;
}
}
private static Vector3f generateRandomUnitVectorWithinCone(Vector3f coneDirection, float angle) {
private static Vector3f generateRandomUnitVectorWithinCone(Vector3f coneDirection, float angle)
{
float cosAngle = (float) Math.cos(angle);
Random random = new Random();
float theta = (float) (random.nextFloat() * 2f * Math.PI);
@ -115,22 +110,23 @@ public class ParticleSystem {
float rootOneMinusZSquared = (float) Math.sqrt(1 - z * z);
float x = (float) (rootOneMinusZSquared * Math.cos(theta));
float y = (float) (rootOneMinusZSquared * Math.sin(theta));
Vector4f direction = new Vector4f(x, y, z, 1);
if (coneDirection.x != 0 || coneDirection.y != 0 || (coneDirection.z != 1 && coneDirection.z != -1)) {
if (coneDirection.x != 0 || coneDirection.y != 0 || (coneDirection.z != 1 && coneDirection.z != -1))
{
Vector3f rotateAxis = Vector3f.cross(coneDirection, new Vector3f(0, 0, 1), null);
rotateAxis.normalise();
float rotateAngle = (float) Math.acos(Vector3f.dot(coneDirection, new Vector3f(0, 0, 1)));
Matrix4f rotationMatrix = new Matrix4f();
rotationMatrix.rotate(-rotateAngle, rotateAxis);
Matrix4f.transform(rotationMatrix, direction, direction);
} else if (coneDirection.z == -1) {
direction.z *= -1;
}
else if (coneDirection.z == -1)
{ direction.z *= -1; }
return new Vector3f(direction);
}
private Vector3f generateRandomUnitVector() {
private Vector3f generateRandomUnitVector()
{
float theta = (float) (random.nextFloat() * 2f * Math.PI);
float z = (random.nextFloat() * 2) - 1;
float rootOneMinusZSquared = (float) Math.sqrt(1 - z * z);
@ -138,5 +134,4 @@ public class ParticleSystem {
float y = (float) (rootOneMinusZSquared * Math.sin(theta));
return new Vector3f(x, y, z);
}
}

View File

@ -1,19 +1,20 @@
package io.github.hydos.ginger.engine.particle;
public class ParticleTexture {
public class ParticleTexture
{
private int textureID;
private int numberOfRows;
public ParticleTexture(int textureID, int numberOfRows) {
public ParticleTexture(int textureID, int numberOfRows)
{
super();
this.textureID = textureID;
this.numberOfRows = numberOfRows;
}
public int getTextureID() {
return textureID;
}
public int getNumberOfRows() {
return numberOfRows;
}
public int getTextureID()
{ return textureID; }
public int getNumberOfRows()
{ return numberOfRows; }
}

View File

@ -3,17 +3,19 @@ package io.github.hydos.ginger.engine.postProcessing;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
public class ContrastChanger {
public class ContrastChanger
{
private ImageRenderer renderer;
private ContrastShader shader;
public ContrastChanger() {
public ContrastChanger()
{
shader = new ContrastShader();
renderer = new ImageRenderer();
}
public void render(int texture) {
public void render(int texture)
{
shader.start();
GL13.glActiveTexture(GL13.GL_TEXTURE0);
System.out.println(texture);
@ -21,10 +23,10 @@ public class ContrastChanger {
renderer.renderQuad();
shader.stop();
}
public void cleanUp() {
public void cleanUp()
{
renderer.cleanUp();
shader.cleanUp();
}
}

View File

@ -2,22 +2,19 @@ package io.github.hydos.ginger.engine.postProcessing;
import io.github.hydos.ginger.engine.renderEngine.shaders.ShaderProgram;
public class ContrastShader extends ShaderProgram {
public class ContrastShader extends ShaderProgram
{
private static final String VERTEX_FILE = "contrastVertex.glsl";
private static final String FRAGMENT_FILE = "contrastFragment.glsl";
public ContrastShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public ContrastShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
@Override
protected void getAllUniformLocations() {
}
protected void getAllUniformLocations()
{}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
protected void bindAttributes()
{ super.bindAttribute(0, "position"); }
}

View File

@ -1,4 +1,3 @@
package io.github.hydos.ginger.engine.postProcessing;
import java.nio.ByteBuffer;
@ -10,45 +9,39 @@ import org.lwjgl.opengl.GL30;
import io.github.hydos.ginger.engine.io.Window;
public class Fbo {
public class Fbo
{
public static final int NONE = 0;
public static final int DEPTH_TEXTURE = 1;
public static final int DEPTH_RENDER_BUFFER = 2;
private final int width;
private final int height;
private int frameBuffer;
private int colourTexture;
private int depthTexture;
private int depthBuffer;
private int colourBuffer;
/**
* Creates an FBO of a specified width and height, with the desired type of
/** Creates an FBO of a specified width and height, with the desired type of
* depth buffer attachment.
*
* @param width
* - the width of the FBO.
* - the width of the FBO.
* @param height
* - the height of the FBO.
* - the height of the FBO.
* @param depthBufferType
* - an int indicating the type of depth buffer attachment that
* this FBO should use.
*/
public Fbo(int width, int height, int depthBufferType) {
* - an int indicating the type of depth buffer attachment that
* this FBO should use. */
public Fbo(int width, int height, int depthBufferType)
{
this.width = width;
this.height = height;
initialiseFrameBuffer(depthBufferType);
}
/**
* Deletes the frame buffer and its attachments when the game closes.
*/
public void cleanUp() {
/** Deletes the frame buffer and its attachments when the game closes. */
public void cleanUp()
{
GL30.glDeleteFramebuffers(frameBuffer);
GL11.glDeleteTextures(colourTexture);
GL11.glDeleteTextures(depthTexture);
@ -56,120 +49,105 @@ public class Fbo {
GL30.glDeleteRenderbuffers(colourBuffer);
}
/**
* Binds the frame buffer, setting it as the current render target. Anything
* rendered after this will be rendered to this FBO, and not to the screen.
*/
public void bindFrameBuffer() {
/** Binds the frame buffer, setting it as the current render target. Anything
* rendered after this will be rendered to this FBO, and not to the screen. */
public void bindFrameBuffer()
{
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, frameBuffer);
GL11.glViewport(0, 0, width, height);
}
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
/** Unbinds the frame buffer, setting the default frame buffer as the current
* render target. Anything rendered after this will be rendered to the
* screen, and not this FBO.
*/
public void unbindFrameBuffer() {
* screen, and not this FBO. */
public void unbindFrameBuffer()
{
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
GL11.glViewport(0, 0, Window.width, Window.height);
}
/**
* Binds the current FBO to be read from (not used in tutorial 43).
*/
public void bindToRead() {
/** Binds the current FBO to be read from (not used in tutorial 43). */
public void bindToRead()
{
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, frameBuffer);
GL11.glReadBuffer(GL30.GL_COLOR_ATTACHMENT0);
}
/**
* @return The ID of the texture containing the colour buffer of the FBO.
*/
public int getColourTexture() {
return colourTexture;
}
/** @return The ID of the texture containing the colour buffer of the FBO. */
public int getColourTexture()
{ return colourTexture; }
/**
* @return The texture containing the FBOs depth buffer.
*/
public int getDepthTexture() {
return depthTexture;
}
/** @return The texture containing the FBOs depth buffer. */
public int getDepthTexture()
{ return depthTexture; }
/**
* Creates the FBO along with a colour buffer texture attachment, and
/** Creates the FBO along with a colour buffer texture attachment, and
* possibly a depth buffer.
*
* @param type
* - the type of depth buffer attachment to be attached to the
* FBO.
*/
private void initialiseFrameBuffer(int type) {
* - the type of depth buffer attachment to be attached to the
* FBO. */
private void initialiseFrameBuffer(int type)
{
createFrameBuffer();
createTextureAttachment();
if (type == DEPTH_RENDER_BUFFER) {
if (type == DEPTH_RENDER_BUFFER)
{
createDepthBufferAttachment();
} else if (type == DEPTH_TEXTURE) {
createDepthTextureAttachment();
}
else if (type == DEPTH_TEXTURE)
{ createDepthTextureAttachment(); }
unbindFrameBuffer();
}
/**
* Creates a new frame buffer object and sets the buffer to which drawing
/** Creates a new frame buffer object and sets the buffer to which drawing
* will occur - colour attachment 0. This is the attachment where the colour
* buffer texture is.
*
*/
private void createFrameBuffer() {
* buffer texture is. */
private void createFrameBuffer()
{
frameBuffer = GL30.glGenFramebuffers();
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frameBuffer);
GL11.glDrawBuffer(GL30.GL_COLOR_ATTACHMENT0);
}
/**
* Creates a texture and sets it as the colour buffer attachment for this
* FBO.
*/
private void createTextureAttachment() {
/** Creates a texture and sets it as the colour buffer attachment for this
* FBO. */
private void createTextureAttachment()
{
colourTexture = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, colourTexture);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE,
(ByteBuffer) null);
(ByteBuffer) null);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colourTexture,
0);
0);
}
/**
* Adds a depth buffer to the FBO in the form of a texture, which can later
* be sampled.
*/
private void createDepthTextureAttachment() {
/** Adds a depth buffer to the FBO in the form of a texture, which can later
* be sampled. */
private void createDepthTextureAttachment()
{
depthTexture = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, depthTexture);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT24, width, height, 0, GL11.GL_DEPTH_COMPONENT,
GL11.GL_FLOAT, (ByteBuffer) null);
GL11.GL_FLOAT, (ByteBuffer) null);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTexture, 0);
}
/**
* Adds a depth buffer to the FBO in the form of a render buffer. This can't
* be used for sampling in the shaders.
*/
private void createDepthBufferAttachment() {
/** Adds a depth buffer to the FBO in the form of a render buffer. This can't
* be used for sampling in the shaders. */
private void createDepthBufferAttachment()
{
depthBuffer = GL30.glGenRenderbuffers();
GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depthBuffer);
GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL14.GL_DEPTH_COMPONENT24, width, height);
GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER,
depthBuffer);
depthBuffer);
}
}

View File

@ -2,35 +2,32 @@ package io.github.hydos.ginger.engine.postProcessing;
import org.lwjgl.opengl.GL11;
public class ImageRenderer {
public class ImageRenderer
{
private Fbo fbo;
protected ImageRenderer(int width, int height) {
this.fbo = new Fbo(width, height, Fbo.NONE);
}
protected ImageRenderer(int width, int height)
{ this.fbo = new Fbo(width, height, Fbo.NONE); }
protected ImageRenderer() {}
protected ImageRenderer()
{}
protected void renderQuad() {
if (fbo != null) {
fbo.bindFrameBuffer();
}
protected void renderQuad()
{
if (fbo != null)
{ fbo.bindFrameBuffer(); }
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4);
if (fbo != null) {
fbo.unbindFrameBuffer();
}
if (fbo != null)
{ fbo.unbindFrameBuffer(); }
}
protected int getOutputTexture() {
return fbo.getColourTexture();
}
protected int getOutputTexture()
{ return fbo.getColourTexture(); }
protected void cleanUp() {
if (fbo != null) {
fbo.cleanUp();
}
protected void cleanUp()
{
if (fbo != null)
{ fbo.cleanUp(); }
}
}

View File

@ -7,38 +7,42 @@ import org.lwjgl.opengl.GL30;
import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.utils.Loader;
public class PostProcessing {
private static final float[] POSITIONS = { -1, 1, -1, -1, 1, 1, 1, -1 };
public class PostProcessing
{
private static final float[] POSITIONS =
{
-1, 1, -1, -1, 1, 1, 1, -1
};
private static RawModel quad;
private static ContrastChanger contrastChanger;
public static void init(){
public static void init()
{
quad = Loader.loadToVAO(POSITIONS, 2);
contrastChanger = new ContrastChanger();
}
public static void doPostProcessing(int colourTexture){
public static void doPostProcessing(int colourTexture)
{
start();
contrastChanger.render(colourTexture);
end();
}
public static void cleanUp(){
contrastChanger.cleanUp();
}
private static void start(){
public static void cleanUp()
{ contrastChanger.cleanUp(); }
private static void start()
{
GL30.glBindVertexArray(quad.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL11.glDisable(GL11.GL_DEPTH_TEST);
}
private static void end(){
private static void end()
{
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL20.glDisableVertexAttribArray(0);
GL30.glBindVertexArray(0);
}
}

View File

@ -27,176 +27,170 @@ import io.github.hydos.ginger.engine.renderEngine.shaders.TerrainShader;
import io.github.hydos.ginger.engine.shadow.ShadowMapMasterRenderer;
import io.github.hydos.ginger.engine.terrain.Terrain;
public class MasterRenderer {
public class MasterRenderer
{
private StaticShader entityShader;
private EntityRenderer entityRenderer;
private TerrainShader terrainShader;
private TerrainRenderer terrainRenderer;
private GuiShader guiShader;
private GuiRenderer guiRenderer;
private SkyboxRenderer skyboxRenderer;
private NormalMappingRenderer normalRenderer;
private Matrix4f projectionMatrix;
private ShadowMapMasterRenderer shadowMapRenderer;
private Map<TexturedModel, List<Entity>> entities = new HashMap<TexturedModel, List<Entity>>();
private Map<TexturedModel, List<Entity>> normalMapEntities = new HashMap<TexturedModel, List<Entity>>();
public static final float FOV = 70f;
public static final float NEAR_PLANE = 0.1f;
private static final float FAR_PLANE = 1000f;
public MasterRenderer(ThirdPersonCamera camera) {
public MasterRenderer(ThirdPersonCamera camera)
{
createProjectionMatrix();
entityShader = new StaticShader();
entityRenderer = new EntityRenderer(entityShader, projectionMatrix);
skyboxRenderer = new SkyboxRenderer(projectionMatrix);
guiShader = new GuiShader();
guiRenderer = new GuiRenderer(guiShader);
normalRenderer = new NormalMappingRenderer(projectionMatrix);
terrainShader = new TerrainShader();
terrainRenderer = new TerrainRenderer(terrainShader, projectionMatrix);
shadowMapRenderer = new ShadowMapMasterRenderer(camera);
}
public static void enableCulling() {
public static void enableCulling()
{
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glCullFace(GL11.GL_BACK);
}
public static void disableCulling() {
GL11.glDisable(GL11.GL_CULL_FACE);
}
public void prepare() {
public static void disableCulling()
{ GL11.glDisable(GL11.GL_CULL_FACE); }
public void prepare()
{
GL13.glActiveTexture(GL13.GL_TEXTURE5);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, shadowMapRenderer.getShadowMap());
}
public void renderScene(List<Entity> entities, List<Entity> normalEntities, List<Terrain> terrains, List<Light> lights, ThirdPersonCamera camera, Vector4f clipPlane) {
public void renderScene(List<Entity> entities, List<Entity> normalEntities, List<Terrain> terrains, List<Light> lights, ThirdPersonCamera camera, Vector4f clipPlane)
{
prepare();
renderEntities(entities, camera, lights);
renderNormalEntities(normalEntities, lights, camera, clipPlane);
renderTerrains(terrains, lights, camera);
skyboxRenderer.render(camera);
}
private void renderNormalEntities(List<Entity> normalEntities, List<Light> lights, ThirdPersonCamera camera, Vector4f clipPlane) {
for(Entity entity: normalEntities) {
processEntityWithNormal(entity);
}
private void renderNormalEntities(List<Entity> normalEntities, List<Light> lights, ThirdPersonCamera camera, Vector4f clipPlane)
{
for (Entity entity : normalEntities)
{ processEntityWithNormal(entity); }
normalRenderer.render(normalMapEntities, clipPlane, lights, camera);
}
public void renderGuis(List<GuiTexture> guis) {
guiRenderer.render(guis);
}
private void renderTerrains(List<Terrain> terrains, List<Light> lights, ThirdPersonCamera camera) {
public void renderGuis(List<GuiTexture> guis)
{ guiRenderer.render(guis); }
private void renderTerrains(List<Terrain> terrains, List<Light> lights, ThirdPersonCamera camera)
{
terrainShader.start();
terrainShader.loadSkyColour(Window.getColour());
terrainShader.loadLights(lights);
terrainShader.loadViewMatrix(camera);
terrainRenderer.render(terrains, shadowMapRenderer.getToShadowMapSpaceMatrix());
terrainShader.stop();
terrainShader.stop();
}
private void renderEntities(List<Entity> entities, ThirdPersonCamera camera, List<Light> lights) {
for(Entity entity: entities) {
processEntity(entity);
}
private void renderEntities(List<Entity> entities, ThirdPersonCamera camera, List<Light> lights)
{
for (Entity entity : entities)
{ processEntity(entity); }
entityRenderer.prepare();
entityShader.start();
entityShader.loadSkyColour(Window.getColour());
entityShader.loadLights(lights);
entityShader.loadViewMatrix(camera);
entityRenderer.render(this.entities);
entityRenderer.render(this.entities);
entityShader.stop();
this.entities.clear();
}
private void processEntity(Entity entity) {
private void processEntity(Entity entity)
{
TexturedModel entityModel = entity.getModel();
List<Entity> batch = entities.get(entityModel);
if(batch!=null) {
if (batch != null)
{
batch.add(entity);
}else {
}
else
{
List<Entity> newBatch = new ArrayList<Entity>();
newBatch.add(entity);
entities.put(entityModel, newBatch);
}
}
private void processEntityWithNormal(Entity entity) {
private void processEntityWithNormal(Entity entity)
{
TexturedModel entityModel = entity.getModel();
List<Entity> batch = normalMapEntities.get(entityModel);
if(batch!=null) {
if (batch != null)
{
batch.add(entity);
}else {
}
else
{
List<Entity> newBatch = new ArrayList<Entity>();
newBatch.add(entity);
normalMapEntities.put(entityModel, newBatch);
}
}
public void renderShadowMap(List<Entity> entityList, Light sun) {
for(Entity entity : entityList) {
processEntity(entity);
}
public void renderShadowMap(List<Entity> entityList, Light sun)
{
for (Entity entity : entityList)
{ processEntity(entity); }
shadowMapRenderer.render(entities, sun);
entities.clear();
}
public int getShadowMapTexture() {
return shadowMapRenderer.getShadowMap();
}
public void cleanUp() {
public int getShadowMapTexture()
{ return shadowMapRenderer.getShadowMap(); }
public void cleanUp()
{
entityShader.cleanUp();
terrainShader.cleanUp();
guiRenderer.cleanUp();
shadowMapRenderer.cleanUp();
normalRenderer.cleanUp();
}
public Matrix4f getProjectionMatrix() {
return this.projectionMatrix;
}
private void createProjectionMatrix(){
projectionMatrix = new Matrix4f();
public Matrix4f getProjectionMatrix()
{ return this.projectionMatrix; }
private void createProjectionMatrix()
{
projectionMatrix = new Matrix4f();
float aspectRatio = (float) Window.width / (float) Window.height;
float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))));
float x_scale = y_scale / aspectRatio;
float frustum_length = FAR_PLANE - NEAR_PLANE;
projectionMatrix.m00 = x_scale;
projectionMatrix.m11 = y_scale;
projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
projectionMatrix.m23 = -1;
projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
projectionMatrix.m33 = 0;
}
}
public void renderGui(GuiTexture guiTexture) {
if(guiTexture == null) return;
if(guiTexture.getTexture() == 0) return;
public void renderGui(GuiTexture guiTexture)
{
if (guiTexture == null) return;
if (guiTexture.getTexture() == 0) return;
List<GuiTexture> texture = new ArrayList<GuiTexture>();
texture.add(guiTexture);
guiRenderer.render(texture);

View File

@ -1,26 +1,19 @@
package io.github.hydos.ginger.engine.renderEngine.models;
public class RawModel {
public class RawModel
{
private int vaoID;
private int vertexCount;
public RawModel(int vaoID, int vertexCount) {
public RawModel(int vaoID, int vertexCount)
{
this.vaoID = vaoID;
this.vertexCount = vertexCount;
}
public int getVaoID() {
return vaoID;
}
public int getVaoID()
{ return vaoID; }
public int getVertexCount() {
return vertexCount;
}
public int getVertexCount()
{ return vertexCount; }
}

View File

@ -2,26 +2,20 @@ package io.github.hydos.ginger.engine.renderEngine.models;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
public class TexturedModel {
public class TexturedModel
{
private RawModel rawModel;
private ModelTexture texture;
public TexturedModel(RawModel model, ModelTexture texture) {
public TexturedModel(RawModel model, ModelTexture texture)
{
this.rawModel = model;
this.texture = texture;
}
public RawModel getRawModel() {
return rawModel;
}
public RawModel getRawModel()
{ return rawModel; }
public ModelTexture getTexture() {
return texture;
}
public ModelTexture getTexture()
{ return texture; }
}

View File

@ -17,39 +17,47 @@ import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.renderEngine.shaders.StaticShader;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
public class EntityRenderer {
public class EntityRenderer
{
private StaticShader shader;
public EntityRenderer(StaticShader shader, Matrix4f projectionMatrix) {
public EntityRenderer(StaticShader shader, Matrix4f projectionMatrix)
{
this.shader = shader;
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void render(Map<TexturedModel,List<Entity>> entities) {
for(TexturedModel model: entities.keySet()) {
public void render(Map<TexturedModel, List<Entity>> entities)
{
for (TexturedModel model : entities.keySet())
{
prepareTexturedModel(model);
List<Entity> batch = entities.get(model);
for(Entity entity:batch) {
for (Entity entity : batch)
{
prepareInstance(entity);
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
}
unbindTexturedModel();
}
}
private void prepareTexturedModel(TexturedModel model) {
private void prepareTexturedModel(TexturedModel model)
{
RawModel rawModel = model.getRawModel();
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL20.glEnableVertexAttribArray(2);
ModelTexture texture = model.getTexture();
if(texture.isTransparent()) {
if (texture.isTransparent())
{
MasterRenderer.disableCulling();
}else {
}
else
{
MasterRenderer.enableCulling();
}
shader.loadFakeLightingVariable(texture.isUseFakeLighting());
@ -57,22 +65,21 @@ public class EntityRenderer {
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getTexture().getTextureID());
}
private void unbindTexturedModel() {
private void unbindTexturedModel()
{
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
}
private void prepareInstance(Entity entity) {
private void prepareInstance(Entity entity)
{
Matrix4f transformationMatrix = Maths.createTransformationMatrix(entity.getPosition(), entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale());
shader.loadTransformationMatrix(transformationMatrix);
}
}
public void prepare() {
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
public void prepare()
{ GL11.glEnable(GL11.GL_DEPTH_TEST); }
}

View File

@ -5,7 +5,6 @@ import java.util.Map;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
@ -13,38 +12,39 @@ import io.github.hydos.ginger.engine.font.FontType;
import io.github.hydos.ginger.engine.font.GUIText;
import io.github.hydos.ginger.engine.renderEngine.shaders.FontShader;
public class FontRenderer {
public class FontRenderer
{
private FontShader shader;
public FontRenderer() {
shader = new FontShader();
}
public void render(Map<FontType, List<GUIText>> texts) {
public FontRenderer()
{ shader = new FontShader(); }
public void render(Map<FontType, List<GUIText>> texts)
{
prepare();
for(FontType font : texts.keySet()) {
GL14.glActiveTexture(GL13.GL_TEXTURE0);
for (FontType font : texts.keySet())
{
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, font.getTextureAtlas());
for(GUIText text : texts.get(font)) {
renderText(text);
}
for (GUIText text : texts.get(font))
{ renderText(text); }
}
endRendering();
}
public void cleanUp(){
shader.cleanUp();
}
private void prepare(){
public void cleanUp()
{ shader.cleanUp(); }
private void prepare()
{
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_DEPTH_TEST);
shader.start();
}
private void renderText(GUIText text){
private void renderText(GUIText text)
{
GL30.glBindVertexArray(text.getMesh());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
@ -56,12 +56,11 @@ public class FontRenderer {
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
}
private void endRendering(){
private void endRendering()
{
shader.stop();
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_BLEND);
}
}

View File

@ -14,27 +14,31 @@ import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.renderEngine.shaders.GuiShader;
import io.github.hydos.ginger.engine.utils.Loader;
public class GuiRenderer {
public class GuiRenderer
{
private final RawModel quad;
private GuiShader shader;
public GuiRenderer(GuiShader shader) {
public GuiRenderer(GuiShader shader)
{
this.shader = shader;
float[] positions = {-1, 1, -1, -1, 1, 1, 1, -1};
float[] positions =
{
-1, 1, -1, -1, 1, 1, 1, -1
};
quad = Loader.loadToVAO(positions, 2);
}
public void render(List<GuiTexture> guis) {
public void render(List<GuiTexture> guis)
{
shader.start();
GL30.glBindVertexArray(quad.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
for(GuiTexture gui: guis) {
for (GuiTexture gui : guis)
{
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, gui.getTexture());
Matrix4f matrix = Maths.createTransformationMatrix(gui.getPosition(), gui.getScale());
@ -47,9 +51,7 @@ public class GuiRenderer {
GL30.glBindVertexArray(0);
shader.stop();
}
public void cleanUp() {
shader.cleanUp();
}
public void cleanUp()
{ shader.cleanUp(); }
}

View File

@ -21,11 +21,12 @@ import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.renderEngine.shaders.NormalMappingShader;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
public class NormalMappingRenderer {
public class NormalMappingRenderer
{
private NormalMappingShader shader;
public NormalMappingRenderer(Matrix4f projectionMatrix) {
public NormalMappingRenderer(Matrix4f projectionMatrix)
{
this.shader = new NormalMappingShader();
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
@ -33,13 +34,16 @@ public class NormalMappingRenderer {
shader.stop();
}
public void render(Map<TexturedModel, List<Entity>> entities, Vector4f clipPlane, List<Light> lights, ThirdPersonCamera camera) {
public void render(Map<TexturedModel, List<Entity>> entities, Vector4f clipPlane, List<Light> lights, ThirdPersonCamera camera)
{
shader.start();
prepare(clipPlane, lights, camera);
for (TexturedModel model : entities.keySet()) {
for (TexturedModel model : entities.keySet())
{
prepareTexturedModel(model);
List<Entity> batch = entities.get(model);
for (Entity entity : batch) {
for (Entity entity : batch)
{
prepareInstance(entity);
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
}
@ -48,12 +52,12 @@ public class NormalMappingRenderer {
shader.stop();
entities.clear();
}
public void cleanUp(){
shader.cleanUp();
}
private void prepareTexturedModel(TexturedModel model) {
public void cleanUp()
{ shader.cleanUp(); }
private void prepareTexturedModel(TexturedModel model)
{
RawModel rawModel = model.getRawModel();
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
@ -61,9 +65,8 @@ public class NormalMappingRenderer {
GL20.glEnableVertexAttribArray(2);
GL20.glEnableVertexAttribArray(3);
ModelTexture texture = model.getTexture();
if (texture.isTransparent()) {
MasterRenderer.disableCulling();
}
if (texture.isTransparent())
{ MasterRenderer.disableCulling(); }
shader.loadShineVariables(texture.getShineDamper(), texture.getReflectivity());
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getTexture().getTextureID());
@ -71,7 +74,8 @@ public class NormalMappingRenderer {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getTexture().getNormalMap());
}
private void unbindTexturedModel() {
private void unbindTexturedModel()
{
MasterRenderer.enableCulling();
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
@ -80,21 +84,21 @@ public class NormalMappingRenderer {
GL30.glBindVertexArray(0);
}
private void prepareInstance(Entity entity) {
private void prepareInstance(Entity entity)
{
Matrix4f transformationMatrix = Maths.createTransformationMatrix(entity.getPosition(), entity.getRotX(),
entity.getRotY(), entity.getRotZ(), entity.getScale());
entity.getRotY(), entity.getRotZ(), entity.getScale());
shader.loadTransformationMatrix(transformationMatrix);
shader.loadOffset(0, 0);
}
private void prepare(Vector4f clipPlane, List<Light> lights, ThirdPersonCamera camera) {
private void prepare(Vector4f clipPlane, List<Light> lights, ThirdPersonCamera camera)
{
shader.loadClipPlane(clipPlane);
//need to be public variables in MasterRenderer
shader.loadSkyColour(Window.getColour());
Matrix4f viewMatrix = Maths.createViewMatrix(camera);
shader.loadLights(lights, viewMatrix);
shader.loadViewMatrix(viewMatrix);
}
}

View File

@ -21,21 +21,22 @@ import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.renderEngine.shaders.ParticleShader;
import io.github.hydos.ginger.engine.utils.Loader;
public class ParticleRenderer {
private static final float[] VERTICES = {-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f};
public class ParticleRenderer
{
private static final float[] VERTICES =
{
-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f
};
private static final int MAX_INSTANCES = 10000;
private static final int INSTANCE_DATA_LENGTH = 21;
private static final FloatBuffer buffer = BufferUtils.createFloatBuffer(MAX_INSTANCES * INSTANCE_DATA_LENGTH);
private RawModel quad;
private ParticleShader shader;
private int vbo;
private int pointer;
public ParticleRenderer(Matrix4f projectionMatrix){
public ParticleRenderer(Matrix4f projectionMatrix)
{
quad = Loader.loadToVAO(VERTICES, 2);
this.vbo = Loader.createEmptyVbo(INSTANCE_DATA_LENGTH * MAX_INSTANCES);
Loader.addInstancedAttribute(quad.getVaoID(), vbo, 1, 4, INSTANCE_DATA_LENGTH, 0);
@ -49,47 +50,49 @@ public class ParticleRenderer {
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void render(Map<ParticleTexture, List<Particle>> particles, ThirdPersonCamera camera){
public void render(Map<ParticleTexture, List<Particle>> particles, ThirdPersonCamera camera)
{
Matrix4f viewMatrix = Maths.createViewMatrix(camera);
prepare();
for(ParticleTexture texture : particles.keySet()) {
for (ParticleTexture texture : particles.keySet())
{
bindTexture(texture);
List<Particle> particleList = particles.get(texture);
pointer = 0;
float[] vboData = new float[particleList.size() * INSTANCE_DATA_LENGTH];
for(Particle particle : particleList) {
for (Particle particle : particleList)
{
updateModelViewMatrix(particle.getPosition(), particle.getRotation(), particle.getScale().x, viewMatrix, vboData);
updateTexCoordInfo(particle, vboData);
}
Loader.updateVbo(vbo, vboData, buffer);
GL31.glDrawArraysInstanced(GL11.GL_TRIANGLE_STRIP, 0, quad.getVertexCount(), particleList.size());
}
finishRendering();
}
public void cleanUp()
{ shader.cleanUp(); }
public void cleanUp(){
shader.cleanUp();
}
private void updateTexCoordInfo(Particle particle, float[] data) {
private void updateTexCoordInfo(Particle particle, float[] data)
{
data[pointer++] = particle.getTexOffset1().x;
data[pointer++] = particle.getTexOffset1().y;
data[pointer++] = particle.getTexOffset2().x;
data[pointer++] = particle.getTexOffset2().y;
data[pointer++] = particle.getBlend();
}
private void bindTexture(ParticleTexture texture) {
private void bindTexture(ParticleTexture texture)
{
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
shader.loadNumberOfRows(texture.getNumberOfRows());
}
private void updateModelViewMatrix(Vector3f position, float rotation, float scale, Matrix4f viewMatrix, float[] vboData) {
private void updateModelViewMatrix(Vector3f position, float rotation, float scale, Matrix4f viewMatrix, float[] vboData)
{
Matrix4f modelMatrix = new Matrix4f();
Matrix4f.translate(position, modelMatrix, modelMatrix);
modelMatrix.m00 = viewMatrix.m00;
@ -101,33 +104,34 @@ public class ParticleRenderer {
modelMatrix.m20 = viewMatrix.m02;
modelMatrix.m21 = viewMatrix.m12;
modelMatrix.m22 = viewMatrix.m22;
Matrix4f.rotate((float)Math.toRadians(rotation), new Vector3f(0,0,1), modelMatrix, modelMatrix);
Matrix4f.scale(new Vector3f(scale,scale,scale), modelMatrix, modelMatrix);
Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0, 0, 1), modelMatrix, modelMatrix);
Matrix4f.scale(new Vector3f(scale, scale, scale), modelMatrix, modelMatrix);
Matrix4f modelViewMatrix = Matrix4f.mul(viewMatrix, modelMatrix, null);
storeMatrixData(modelViewMatrix, vboData);
}
private void storeMatrixData(Matrix4f matrix, float[] vboData) {
vboData[pointer++] = matrix.m00;
vboData[pointer++] = matrix.m01;
vboData[pointer++] = matrix.m02;
vboData[pointer++] = matrix.m03;
vboData[pointer++] = matrix.m10;
vboData[pointer++] = matrix.m11;
vboData[pointer++] = matrix.m12;
vboData[pointer++] = matrix.m13;
vboData[pointer++] = matrix.m20;
vboData[pointer++] = matrix.m21;
vboData[pointer++] = matrix.m22;
vboData[pointer++] = matrix.m23;
vboData[pointer++] = matrix.m30;
vboData[pointer++] = matrix.m31;
vboData[pointer++] = matrix.m32;
vboData[pointer++] = matrix.m33;
private void storeMatrixData(Matrix4f matrix, float[] vboData)
{
vboData[pointer++] = matrix.m00;
vboData[pointer++] = matrix.m01;
vboData[pointer++] = matrix.m02;
vboData[pointer++] = matrix.m03;
vboData[pointer++] = matrix.m10;
vboData[pointer++] = matrix.m11;
vboData[pointer++] = matrix.m12;
vboData[pointer++] = matrix.m13;
vboData[pointer++] = matrix.m20;
vboData[pointer++] = matrix.m21;
vboData[pointer++] = matrix.m22;
vboData[pointer++] = matrix.m23;
vboData[pointer++] = matrix.m30;
vboData[pointer++] = matrix.m31;
vboData[pointer++] = matrix.m32;
vboData[pointer++] = matrix.m33;
}
private void prepare(){
private void prepare()
{
shader.start();
GL30.glBindVertexArray(quad.getVaoID());
GL20.glEnableVertexAttribArray(0);
@ -137,12 +141,12 @@ public class ParticleRenderer {
GL20.glEnableVertexAttribArray(4);
GL20.glEnableVertexAttribArray(5);
GL20.glEnableVertexAttribArray(6);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);//TODO: add all particle effects into 1 texture to fix overlapping
}
private void finishRendering(){
private void finishRendering()
{
shader.stop();
GL30.glBindVertexArray(0);
GL11.glDisable(GL11.GL_BLEND);
@ -154,5 +158,4 @@ public class ParticleRenderer {
GL20.glDisableVertexAttribArray(5);
GL20.glDisableVertexAttribArray(6);
}
}

View File

@ -11,62 +11,58 @@ import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.renderEngine.shaders.SkyboxShader;
import io.github.hydos.ginger.engine.utils.Loader;
public class SkyboxRenderer {
public class SkyboxRenderer
{
private static final float SIZE = 50f;
private static final float[] VERTICES = {
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
SIZE, SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, -SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, SIZE, SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, -SIZE, SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, SIZE, -SIZE,
SIZE, SIZE, -SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
-SIZE, SIZE, SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, SIZE
private static final float[] VERTICES =
{
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
SIZE, SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, -SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, SIZE, SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
SIZE, -SIZE, SIZE,
-SIZE, -SIZE, SIZE,
-SIZE, SIZE, -SIZE,
SIZE, SIZE, -SIZE,
SIZE, SIZE, SIZE,
SIZE, SIZE, SIZE,
-SIZE, SIZE, SIZE,
-SIZE, SIZE, -SIZE,
-SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, -SIZE,
SIZE, -SIZE, -SIZE,
-SIZE, -SIZE, SIZE,
SIZE, -SIZE, SIZE
};
private static String[] TEXTURE_FILES =
{
"right.png", "left.png", "up.png", "down.png", "back.png", "front.png"
};
private static String[] TEXTURE_FILES = {"right.png", "left.png", "up.png", "down.png", "back.png", "front.png"};
private RawModel cube;
private int texture;
private SkyboxShader shader;
public SkyboxRenderer(Matrix4f projectionMatrix) {
public SkyboxRenderer(Matrix4f projectionMatrix)
{
cube = Loader.loadToVAO(VERTICES, 3);
texture = Loader.loadCubeMap(TEXTURE_FILES);
shader = new SkyboxShader();
@ -74,8 +70,9 @@ public class SkyboxRenderer {
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void render(ThirdPersonCamera camera) {
public void render(ThirdPersonCamera camera)
{
shader.start();
shader.loadViewMatrix(camera);
GL30.glBindVertexArray(cube.getVaoID());
@ -87,9 +84,7 @@ public class SkyboxRenderer {
GL30.glBindVertexArray(0);
shader.stop();
}
public void cleanUp() {
shader.cleanUp();
}
public void cleanUp()
{ shader.cleanUp(); }
}

View File

@ -16,30 +16,33 @@ import io.github.hydos.ginger.engine.terrain.Terrain;
import io.github.hydos.ginger.engine.terrain.TerrainTexture;
import io.github.hydos.ginger.engine.terrain.TerrainTexturePack;
public class TerrainRenderer {
public class TerrainRenderer
{
private TerrainShader shader;
public TerrainRenderer(TerrainShader shader, Matrix4f projectionMatrix) {
public TerrainRenderer(TerrainShader shader, Matrix4f projectionMatrix)
{
this.shader = shader;
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
shader.connectTextureUnits();
shader.stop();
}
public void render(List<Terrain> terrains, Matrix4f toShadowSpace) {
public void render(List<Terrain> terrains, Matrix4f toShadowSpace)
{
shader.loadToShadowMapSpace(toShadowSpace);
for(Terrain t : terrains) {
for (Terrain t : terrains)
{
prepareTerrain(t);
loadModelMatrix(t);
GL11.glDrawElements(GL11.GL_TRIANGLES, t.getModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
unbindTerrain();
}
}
private void prepareTerrain(Terrain terrain) {
private void prepareTerrain(Terrain terrain)
{
RawModel rawModel = terrain.getModel();
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
@ -47,41 +50,35 @@ public class TerrainRenderer {
GL20.glEnableVertexAttribArray(2);
bindTextures(terrain);
shader.loadShine(1, 0);
}
private void bindTextures(Terrain terrain) {
private void bindTextures(Terrain terrain)
{
TerrainTexturePack texturePack = terrain.getTexturePack();
TerrainTexture blendMap = terrain.getBlendMap();
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texturePack.getBackgroundTexture().getTextureID());
GL13.glActiveTexture(GL13.GL_TEXTURE1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texturePack.getrTexture().getTextureID());
GL13.glActiveTexture(GL13.GL_TEXTURE2);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texturePack.getgTexture().getTextureID());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texturePack.getgTexture().getTextureID());
GL13.glActiveTexture(GL13.GL_TEXTURE3);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texturePack.getbTexture().getTextureID());
GL13.glActiveTexture(GL13.GL_TEXTURE4);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, blendMap.getTextureID());
}
private void unbindTerrain() {
private void unbindTerrain()
{
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
}
private void loadModelMatrix(Terrain terrain) {
Matrix4f transformationMatrix = Maths.createTransformationMatrix(new Vector3f(terrain.getX(), 0, terrain.getZ()), 0, 0, 0, new Vector3f(1,1,1));
shader.loadTransformationMatrix(transformationMatrix);
private void loadModelMatrix(Terrain terrain)
{
Matrix4f transformationMatrix = Maths.createTransformationMatrix(new Vector3f(terrain.getX(), 0, terrain.getZ()), 0, 0, 0, new Vector3f(1, 1, 1));
shader.loadTransformationMatrix(transformationMatrix);
}
}

View File

@ -4,24 +4,23 @@ import io.github.hydos.ginger.engine.font.GUIText;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class FontShader extends ShaderProgram{
public class FontShader extends ShaderProgram
{
private static final String VERTEX_FILE = "fontVertexShader.glsl";
private static final String FRAGMENT_FILE = "fontFragmentShader.glsl";
private int location_colour;
private int location_translation;
private int location_borderWidth;
private int location_borderEdge;
private int location_offset;
private int location_outlineColour;
public FontShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public FontShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
@Override
protected void getAllUniformLocations() {
protected void getAllUniformLocations()
{
location_colour = super.getUniformLocation("colour");
location_translation = super.getUniformLocation("translation");
location_borderWidth = super.getUniformLocation("borderWidth");
@ -31,25 +30,23 @@ public class FontShader extends ShaderProgram{
}
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoords");
}
public void loadColour(Vector3f colour) {
super.loadVector(location_colour, colour);
}
public void loadTranslation(Vector2f translation) {
super.load2DVector(location_translation, translation);
}
public void loadText(GUIText text) {
public void loadColour(Vector3f colour)
{ super.loadVector(location_colour, colour); }
public void loadTranslation(Vector2f translation)
{ super.load2DVector(location_translation, translation); }
public void loadText(GUIText text)
{
super.load2DVector(location_offset, text.getOffset());
super.loadFloat(location_borderEdge, text.getBorderEdge());
super.loadFloat(location_borderWidth, text.getBorderWidth());
super.loadVector(location_outlineColour, text.getOutlineColour());
}
}

View File

@ -2,32 +2,23 @@ package io.github.hydos.ginger.engine.renderEngine.shaders;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
public class GuiShader extends ShaderProgram{
private static final String VERTEX_FILE = "guiVertexShader.glsl";
private static final String FRAGMENT_FILE = "guiFragmentShader.glsl";
private int location_transformationMatrix;
public GuiShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public void loadTransformation(Matrix4f matrix){
super.loadMatrix(location_transformationMatrix, matrix);
}
@Override
protected void getAllUniformLocations() {
location_transformationMatrix = super.getUniformLocation("transformationMatrix");
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
public class GuiShader extends ShaderProgram
{
private static final String VERTEX_FILE = "guiVertexShader.glsl";
private static final String FRAGMENT_FILE = "guiFragmentShader.glsl";
private int location_transformationMatrix;
public GuiShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
public void loadTransformation(Matrix4f matrix)
{ super.loadMatrix(location_transformationMatrix, matrix); }
@Override
protected void getAllUniformLocations()
{ location_transformationMatrix = super.getUniformLocation("transformationMatrix"); }
@Override
protected void bindAttributes()
{ super.bindAttribute(0, "position"); }
}

View File

@ -8,13 +8,11 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
public class NormalMappingShader extends ShaderProgram{
public class NormalMappingShader extends ShaderProgram
{
private static final int MAX_LIGHTS = 4;
private static final String VERTEX_FILE = "normalMapVertexShader.glsl";
private static final String FRAGMENT_FILE = "normalMapFragmentShader.glsl";
private int location_transformationMatrix;
private int location_projectionMatrix;
private int location_viewMatrix;
@ -30,12 +28,12 @@ public class NormalMappingShader extends ShaderProgram{
private int location_modelTexture;
private int location_normalMap;
public NormalMappingShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public NormalMappingShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoordinates");
super.bindAttribute(2, "normal");
@ -43,7 +41,8 @@ public class NormalMappingShader extends ShaderProgram{
}
@Override
protected void getAllUniformLocations() {
protected void getAllUniformLocations()
{
location_transformationMatrix = super.getUniformLocation("transformationMatrix");
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
@ -55,81 +54,77 @@ public class NormalMappingShader extends ShaderProgram{
location_plane = super.getUniformLocation("plane");
location_modelTexture = super.getUniformLocation("modelTexture");
location_normalMap = super.getUniformLocation("normalMap");
location_lightPositionEyeSpace = new int[MAX_LIGHTS];
location_lightColour = new int[MAX_LIGHTS];
location_attenuation = new int[MAX_LIGHTS];
for(int i=0;i<MAX_LIGHTS;i++){
for (int i = 0; i < MAX_LIGHTS; i++)
{
location_lightPositionEyeSpace[i] = super.getUniformLocation("lightPositionEyeSpace[" + i + "]");
location_lightColour[i] = super.getUniformLocation("lightColour[" + i + "]");
location_attenuation[i] = super.getUniformLocation("attenuation[" + i + "]");
}
}
public void connectTextureUnits(){
public void connectTextureUnits()
{
super.loadInt(location_modelTexture, 0);
super.loadInt(location_normalMap, 1);
}
public void loadClipPlane(Vector4f plane){
super.loadVector(location_plane, plane);
}
public void loadNumberOfRows(int numberOfRows){
super.loadFloat(location_numberOfRows, numberOfRows);
}
public void loadOffset(float x, float y){
super.load2DVector(location_offset, new Vector2f(x,y));
}
public void loadSkyColour(float r, float g, float b){
super.loadVector(location_skyColour, new Vector3f(r,g,b));
}
public void loadShineVariables(float damper,float reflectivity){
public void loadClipPlane(Vector4f plane)
{ super.loadVector(location_plane, plane); }
public void loadNumberOfRows(int numberOfRows)
{ super.loadFloat(location_numberOfRows, numberOfRows); }
public void loadOffset(float x, float y)
{ super.load2DVector(location_offset, new Vector2f(x, y)); }
public void loadSkyColour(float r, float g, float b)
{ super.loadVector(location_skyColour, new Vector3f(r, g, b)); }
public void loadShineVariables(float damper, float reflectivity)
{
super.loadFloat(location_shineDamper, damper);
super.loadFloat(location_reflectivity, reflectivity);
}
public void loadTransformationMatrix(Matrix4f matrix){
super.loadMatrix(location_transformationMatrix, matrix);
}
public void loadLights(List<Light> lights, Matrix4f viewMatrix){
for(int i=0;i<MAX_LIGHTS;i++){
if(i<lights.size()){
public void loadTransformationMatrix(Matrix4f matrix)
{ super.loadMatrix(location_transformationMatrix, matrix); }
public void loadLights(List<Light> lights, Matrix4f viewMatrix)
{
for (int i = 0; i < MAX_LIGHTS; i++)
{
if (i < lights.size())
{
super.loadVector(location_lightPositionEyeSpace[i], getEyeSpacePosition(lights.get(i), viewMatrix));
super.loadVector(location_lightColour[i], lights.get(i).getColour());
super.loadVector(location_attenuation[i], lights.get(i).getAttenuation());
}else{
}
else
{
super.loadVector(location_lightPositionEyeSpace[i], new Vector3f(0, 0, 0));
super.loadVector(location_lightColour[i], new Vector3f(0, 0, 0));
super.loadVector(location_attenuation[i], new Vector3f(1, 0, 0));
}
}
}
public void loadViewMatrix(Matrix4f viewMatrix){
super.loadMatrix(location_viewMatrix, viewMatrix);
}
public void loadProjectionMatrix(Matrix4f projection){
super.loadMatrix(location_projectionMatrix, projection);
}
public Vector3f getEyeSpacePosition(Light light, Matrix4f viewMatrix){
public void loadViewMatrix(Matrix4f viewMatrix)
{ super.loadMatrix(location_viewMatrix, viewMatrix); }
public void loadProjectionMatrix(Matrix4f projection)
{ super.loadMatrix(location_projectionMatrix, projection); }
public Vector3f getEyeSpacePosition(Light light, Matrix4f viewMatrix)
{
Vector3f position = light.getPosition();
Vector4f eyeSpacePos = new Vector4f(position.x,position.y, position.z, 1f);
Vector4f eyeSpacePos = new Vector4f(position.x, position.y, position.z, 1f);
Matrix4f.transform(viewMatrix, eyeSpacePos, eyeSpacePos);
return new Vector3f(eyeSpacePos);
}
public void loadSkyColour(Vector3f colour) {
super.loadVector(location_skyColour, colour);
}
public void loadSkyColour(Vector3f colour)
{ super.loadVector(location_skyColour, colour); }
}

View File

@ -2,41 +2,35 @@ package io.github.hydos.ginger.engine.renderEngine.shaders;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
public class ParticleShader extends ShaderProgram {
public class ParticleShader extends ShaderProgram
{
private static final String VERTEX_FILE = "particleVertexShader.glsl";
private static final String FRAGMENT_FILE = "particleFragmentShader.glsl";
private int location_numberOfRows;
private int location_projectionMatrix;
public ParticleShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public ParticleShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
@Override
protected void getAllUniformLocations() {
protected void getAllUniformLocations()
{
location_numberOfRows = super.getUniformLocation("numberOfRows");
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
}
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "position");
super.bindAttribute(1, "modelViewMatrix");
super.bindAttribute(5, "texOffsets");
super.bindAttribute(6, "blendFactor");
}
public void loadNumberOfRows(float numberOfRows) {
super.loadFloat(location_numberOfRows, numberOfRows);
}
public void loadProjectionMatrix(Matrix4f projectionMatrix) {
super.loadMatrix(location_projectionMatrix, projectionMatrix);
}
public void loadNumberOfRows(float numberOfRows)
{ super.loadFloat(location_numberOfRows, numberOfRows); }
public void loadProjectionMatrix(Matrix4f projectionMatrix)
{ super.loadMatrix(location_projectionMatrix, projectionMatrix); }
}

View File

@ -14,17 +14,17 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
public abstract class ShaderProgram {
public abstract class ShaderProgram
{
private int programID;
private int vertexShaderID;
private int fragmentShaderID;
private static FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
public ShaderProgram(String vertexFile,String fragmentFile){
vertexShaderID = loadShader(vertexFile,GL20.GL_VERTEX_SHADER);
fragmentShaderID = loadShader(fragmentFile,GL20.GL_FRAGMENT_SHADER);
public ShaderProgram(String vertexFile, String fragmentFile)
{
vertexShaderID = loadShader(vertexFile, GL20.GL_VERTEX_SHADER);
fragmentShaderID = loadShader(fragmentFile, GL20.GL_FRAGMENT_SHADER);
programID = GL20.glCreateProgram();
GL20.glAttachShader(programID, vertexShaderID);
GL20.glAttachShader(programID, fragmentShaderID);
@ -33,22 +33,20 @@ public abstract class ShaderProgram {
GL20.glValidateProgram(programID);
getAllUniformLocations();
}
protected abstract void getAllUniformLocations();
protected int getUniformLocation(String uniformName){
return GL20.glGetUniformLocation(programID,uniformName);
}
public void start(){
GL20.glUseProgram(programID);
}
public void stop(){
GL20.glUseProgram(0);
}
public void cleanUp(){
protected int getUniformLocation(String uniformName)
{ return GL20.glGetUniformLocation(programID, uniformName); }
public void start()
{ GL20.glUseProgram(programID); }
public void stop()
{ GL20.glUseProgram(0); }
public void cleanUp()
{
stop();
GL20.glDetachShader(programID, vertexShaderID);
GL20.glDetachShader(programID, fragmentShaderID);
@ -56,69 +54,67 @@ public abstract class ShaderProgram {
GL20.glDeleteShader(fragmentShaderID);
GL20.glDeleteProgram(programID);
}
protected abstract void bindAttributes();
protected void bindAttribute(int attribute, String variableName){
GL20.glBindAttribLocation(programID, attribute, variableName);
}
protected void loadFloat(int location, float value){
GL20.glUniform1f(location, value);
}
protected void loadInt(int location, int value){
GL20.glUniform1i(location, value);
}
protected void loadVector(int location, Vector3f vector){
GL20.glUniform3f(location,vector.x,vector.y,vector.z);
}
protected void loadVector(int location, Vector4f vector){
GL20.glUniform4f(location,vector.x,vector.y,vector.z, vector.w);
}
protected void load2DVector(int location, Vector2f vector){
GL20.glUniform2f(location,vector.x,vector.y);
}
protected void loadBoolean(int location, boolean value){
protected void bindAttribute(int attribute, String variableName)
{ GL20.glBindAttribLocation(programID, attribute, variableName); }
protected void loadFloat(int location, float value)
{ GL20.glUniform1f(location, value); }
protected void loadInt(int location, int value)
{ GL20.glUniform1i(location, value); }
protected void loadVector(int location, Vector3f vector)
{ GL20.glUniform3f(location, vector.x, vector.y, vector.z); }
protected void loadVector(int location, Vector4f vector)
{ GL20.glUniform4f(location, vector.x, vector.y, vector.z, vector.w); }
protected void load2DVector(int location, Vector2f vector)
{ GL20.glUniform2f(location, vector.x, vector.y); }
protected void loadBoolean(int location, boolean value)
{
float toLoad = 0;
if(value){
toLoad = 1;
}
if (value)
{ toLoad = 1; }
GL20.glUniform1f(location, toLoad);
}
protected void loadMatrix(int location, Matrix4f matrix){
protected void loadMatrix(int location, Matrix4f matrix)
{
matrix.store(matrixBuffer);
matrixBuffer.flip();
GL20.glUniformMatrix4fv(location, false, matrixBuffer);
}
private static int loadShader(String file, int type){
StringBuilder shaderSource = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(ShaderProgram.class.getResourceAsStream("/shaders/" + file)));
String line;
while((line = reader.readLine())!=null){
shaderSource.append(line).append("\n");
}
reader.close();
}catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID);
if(GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS )== GL11.GL_FALSE){
System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
System.err.println("Could not compile shader: " + file);
System.exit(-1);
}
return shaderID;
}
private static int loadShader(String file, int type)
{
StringBuilder shaderSource = new StringBuilder();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ShaderProgram.class.getResourceAsStream("/shaders/" + file)));
String line;
while ((line = reader.readLine()) != null)
{ shaderSource.append(line).append("\n"); }
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID);
if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE)
{
System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
System.err.println("Could not compile shader: " + file);
System.exit(-1);
}
return shaderID;
}
}

View File

@ -4,36 +4,34 @@ import io.github.hydos.ginger.engine.cameras.ThirdPersonCamera;
import io.github.hydos.ginger.engine.mathEngine.Maths;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
public class SkyboxShader extends ShaderProgram{
private int location_projectionMatrix;
private int location_viewMatrix;
public SkyboxShader() {
super("skyboxVertexShader.glsl", "skyboxFragmentShader.glsl");
}
public void loadProjectionMatrix(Matrix4f matrix){
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(ThirdPersonCamera camera){
Matrix4f matrix = Maths.createViewMatrix(camera);
matrix.m30 = 0;
matrix.m31 = 0;
matrix.m32 = 0;
super.loadMatrix(location_viewMatrix, matrix);
}
@Override
protected void getAllUniformLocations() {
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
public class SkyboxShader extends ShaderProgram
{
private int location_projectionMatrix;
private int location_viewMatrix;
public SkyboxShader()
{ super("skyboxVertexShader.glsl", "skyboxFragmentShader.glsl"); }
public void loadProjectionMatrix(Matrix4f matrix)
{ super.loadMatrix(location_projectionMatrix, matrix); }
public void loadViewMatrix(ThirdPersonCamera camera)
{
Matrix4f matrix = Maths.createViewMatrix(camera);
matrix.m30 = 0;
matrix.m31 = 0;
matrix.m32 = 0;
super.loadMatrix(location_viewMatrix, matrix);
}
@Override
protected void getAllUniformLocations()
{
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
}
@Override
protected void bindAttributes()
{ super.bindAttribute(0, "position"); }
}

View File

@ -8,10 +8,9 @@ import io.github.hydos.ginger.engine.mathEngine.Maths;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class StaticShader extends ShaderProgram{
public class StaticShader extends ShaderProgram
{
private static final int MAX_LIGHTS = 5;
private int location_transformationMatrix;
private int location_projectionMatrix;
private int location_viewMatrix;
@ -22,15 +21,13 @@ public class StaticShader extends ShaderProgram{
private int location_reflectivity;
private int location_useFakeLighting;
private int location_skyColour;
public StaticShader() {
super("entityVertexShader.glsl", "entityFragmentShader.glsl");
}
public StaticShader()
{ super("entityVertexShader.glsl", "entityFragmentShader.glsl"); }
@Override
protected void getAllUniformLocations() {
protected void getAllUniformLocations()
{
location_transformationMatrix = super.getUniformLocation("transformationMatrix");
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
@ -38,63 +35,65 @@ public class StaticShader extends ShaderProgram{
location_reflectivity = super.getUniformLocation("reflectivity");
location_useFakeLighting = super.getUniformLocation("useFakeLighting");
location_skyColour = super.getUniformLocation("skyColour");
location_lightPosition = new int[MAX_LIGHTS];
location_lightColour = new int[MAX_LIGHTS];
location_attenuation = new int[MAX_LIGHTS];
for(int i=0; i<MAX_LIGHTS;i++) {
for (int i = 0; i < MAX_LIGHTS; i++)
{
location_lightPosition[i] = super.getUniformLocation("lightPosition[" + i + "]");
location_lightColour[i] = super.getUniformLocation("lightColour[" + i + "]");
location_attenuation[i] = super.getUniformLocation("attenuation[" + i + "]");
}
}
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoords");
super.bindAttribute(2, "normal");
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(location_transformationMatrix, matrix);
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(ThirdPersonCamera camera) {
public void loadTransformationMatrix(Matrix4f matrix)
{ super.loadMatrix(location_transformationMatrix, matrix); }
public void loadProjectionMatrix(Matrix4f matrix)
{ super.loadMatrix(location_projectionMatrix, matrix); }
public void loadViewMatrix(ThirdPersonCamera camera)
{
Matrix4f matrix = Maths.createViewMatrix(camera);
super.loadMatrix(location_viewMatrix, matrix);
}
public void loadLights(List<Light> lights) {
for(int i=0; i<MAX_LIGHTS;i++) {
if(i<lights.size()) {
public void loadLights(List<Light> lights)
{
for (int i = 0; i < MAX_LIGHTS; i++)
{
if (i < lights.size())
{
super.loadVector(location_lightPosition[i], lights.get(i).getPosition());
super.loadVector(location_lightColour[i], lights.get(i).getColour());
super.loadVector(location_attenuation[i], lights.get(i).getAttenuation());
}else {
}
else
{
super.loadVector(location_lightPosition[i], new Vector3f(0, 0, 0));
super.loadVector(location_lightColour[i], new Vector3f(0, 0, 0));
super.loadVector(location_attenuation[i], new Vector3f(1, 0, 0));
}
}
}
public void loadShine(float damper, float reflectivity) {
public void loadShine(float damper, float reflectivity)
{
super.loadFloat(location_shineDamper, damper);
super.loadFloat(location_reflectivity, reflectivity);
}
public void loadFakeLightingVariable(boolean useFake) {
super.loadBoolean(location_useFakeLighting, useFake);
}
public void loadSkyColour(Vector3f colour) {
super.loadVector(location_skyColour, colour);
}
public void loadFakeLightingVariable(boolean useFake)
{ super.loadBoolean(location_useFakeLighting, useFake); }
public void loadSkyColour(Vector3f colour)
{ super.loadVector(location_skyColour, colour); }
}

View File

@ -8,50 +8,40 @@ import io.github.hydos.ginger.engine.mathEngine.Maths;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
public class TerrainShader extends ShaderProgram{
public class TerrainShader extends ShaderProgram
{
private static final int MAX_LIGHTS = 5;
private int location_transformationMatrix;
private int location_projectionMatrix;
private int location_viewMatrix;
private int location_lightColour[];
private int location_lightPosition[];
private int location_attenuation[];
private int location_shineDamper;
private int location_reflectivity;
private int location_skyColour;
private int location_backgroundTexture;
private int location_rTexture;
private int location_gTexture;
private int location_bTexture;
private int location_blendMap;
private int location_toShadowMapSpace;
private int location_shadowMap;
public TerrainShader() {
super("terrainVertexShader.glsl", "terrainFragmentShader.glsl");
}
public TerrainShader()
{ super("terrainVertexShader.glsl", "terrainFragmentShader.glsl"); }
@Override
protected void getAllUniformLocations() {
protected void getAllUniformLocations()
{
location_transformationMatrix = super.getUniformLocation("transformationMatrix");
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
location_lightPosition = new int[MAX_LIGHTS];
location_lightColour = new int[MAX_LIGHTS];
location_attenuation = new int[MAX_LIGHTS];
for(int i=0; i<MAX_LIGHTS;i++) {
for (int i = 0; i < MAX_LIGHTS; i++)
{
location_lightPosition[i] = super.getUniformLocation("lightPosition[" + i + "]");
location_lightColour[i] = super.getUniformLocation("lightColour[" + i + "]");
location_attenuation[i] = super.getUniformLocation("attenuation[" + i + "]");
@ -69,53 +59,58 @@ public class TerrainShader extends ShaderProgram{
}
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoords");
super.bindAttribute(2, "normal");
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(location_transformationMatrix, matrix);
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(ThirdPersonCamera camera) {
public void loadTransformationMatrix(Matrix4f matrix)
{ super.loadMatrix(location_transformationMatrix, matrix); }
public void loadProjectionMatrix(Matrix4f matrix)
{ super.loadMatrix(location_projectionMatrix, matrix); }
public void loadViewMatrix(ThirdPersonCamera camera)
{
Matrix4f matrix = Maths.createViewMatrix(camera);
super.loadMatrix(location_viewMatrix, matrix);
}
public void loadLights(List<Light> lights) {
for(int i=0; i<MAX_LIGHTS;i++) {
if(i<lights.size()) {
public void loadLights(List<Light> lights)
{
for (int i = 0; i < MAX_LIGHTS; i++)
{
if (i < lights.size())
{
super.loadVector(location_lightPosition[i], lights.get(i).getPosition());
super.loadVector(location_lightColour[i], lights.get(i).getColour());
super.loadVector(location_attenuation[i], lights.get(i).getAttenuation());
}else {
}
else
{
super.loadVector(location_lightPosition[i], new Vector3f(0, 0, 0));
super.loadVector(location_lightColour[i], new Vector3f(0, 0, 0));
super.loadVector(location_attenuation[i], new Vector3f(1, 0, 0));
}
}
}
public void loadShine(float damper, float reflectivity) {
public void loadShine(float damper, float reflectivity)
{
super.loadFloat(location_shineDamper, damper);
super.loadFloat(location_reflectivity, reflectivity);
}
public void loadSkyColour(Vector3f colour) {
super.loadVector(location_skyColour, colour);
}
public void loadToShadowMapSpace(Matrix4f matrix) {
super.loadMatrix(location_toShadowMapSpace, matrix);
}
public void connectTextureUnits() {
public void loadSkyColour(Vector3f colour)
{ super.loadVector(location_skyColour, colour); }
public void loadToShadowMapSpace(Matrix4f matrix)
{ super.loadMatrix(location_toShadowMapSpace, matrix); }
public void connectTextureUnits()
{
super.loadInt(location_backgroundTexture, 0);
super.loadInt(location_rTexture, 1);
super.loadInt(location_gTexture, 2);
@ -123,5 +118,4 @@ public class TerrainShader extends ShaderProgram{
super.loadInt(location_blendMap, 4);
super.loadInt(location_shadowMap, 5);
}
}

View File

@ -13,94 +13,87 @@ import org.lwjgl.system.MemoryStack;
import io.github.hydos.ginger.engine.renderEngine.tools.IOUtil;
public class Image {
public Image(String imagePath) {
public class Image
{
public Image(String imagePath)
{
ByteBuffer img;
ByteBuffer imageBuffer;
try {
imageBuffer = IOUtil.ioResourceToByteBuffer(imagePath, 8 * 1024);
} catch (IOException e) {
throw new RuntimeException(e);
}
ByteBuffer imageBuffer;
try
{
imageBuffer = IOUtil.ioResourceToByteBuffer(imagePath, 8 * 1024);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
try (MemoryStack stack = stackPush())
{
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer comp = stack.mallocInt(1);
// Use info to read image metadata without decoding the entire image.
// We don't need this for this demo, just testing the API.
if (!stbi_info_from_memory(imageBuffer, w, h, comp))
{ throw new RuntimeException("Failed to read image information: " + stbi_failure_reason()); }
// System.out.println("Image width: " + w.get(0));
// System.out.println("Image height: " + h.get(0));
// System.out.println("Image components: " + comp.get(0));
// System.out.println("Image HDR: " + stbi_is_hdr_from_memory(imageBuffer));
// Decode the image
img = stbi_load_from_memory(imageBuffer, w, h, comp, 0);
if (img == null)
{ throw new RuntimeException("Failed to load image: " + stbi_failure_reason()); }
this.image = img;
this.width = w.get(0);
this.height = h.get(0);
}
}
try (MemoryStack stack = stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer comp = stack.mallocInt(1);
// Use info to read image metadata without decoding the entire image.
// We don't need this for this demo, just testing the API.
if (!stbi_info_from_memory(imageBuffer, w, h, comp)) {
throw new RuntimeException("Failed to read image information: " + stbi_failure_reason());
}
// System.out.println("Image width: " + w.get(0));
// System.out.println("Image height: " + h.get(0));
// System.out.println("Image components: " + comp.get(0));
// System.out.println("Image HDR: " + stbi_is_hdr_from_memory(imageBuffer));
// Decode the image
img = stbi_load_from_memory(imageBuffer, w, h, comp, 0);
if (img == null) {
throw new RuntimeException("Failed to load image: " + stbi_failure_reason());
}
this.image = img;
this.width = w.get(0);
this.height = h.get(0);
}
}
public static Image createImage(String imagePath) {
public static Image createImage(String imagePath)
{
ByteBuffer img;
ByteBuffer imageBuffer;
try {
imageBuffer = IOUtil.ioResourceToByteBuffer(imagePath, 8 * 1024);
} catch (IOException e) {
throw new RuntimeException(e);
}
ByteBuffer imageBuffer;
try
{
imageBuffer = IOUtil.ioResourceToByteBuffer(imagePath, 8 * 1024);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
try (MemoryStack stack = stackPush())
{
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer comp = stack.mallocInt(1);
// Use info to read image metadata without decoding the entire image.
// We don't need this for this demo, just testing the API.
if (!stbi_info_from_memory(imageBuffer, w, h, comp))
{ throw new RuntimeException("Failed to read image information: " + stbi_failure_reason()); }
img = stbi_load_from_memory(imageBuffer, w, h, comp, 0);
if (img == null)
{ throw new RuntimeException("Failed to load image: " + stbi_failure_reason()); }
return new Image(w.get(0), h.get(0), img);
}
}
try (MemoryStack stack = stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer comp = stack.mallocInt(1);
public ByteBuffer getImage()
{ return image; }
// Use info to read image metadata without decoding the entire image.
// We don't need this for this demo, just testing the API.
if (!stbi_info_from_memory(imageBuffer, w, h, comp)) {
throw new RuntimeException("Failed to read image information: " + stbi_failure_reason());
}
public int getWidth()
{ return width; }
img = stbi_load_from_memory(imageBuffer, w, h, comp, 0);
if (img == null) {
throw new RuntimeException("Failed to load image: " + stbi_failure_reason());
}
return new Image(w.get(0), h.get(0), img);
}
}
public ByteBuffer getImage() {
return image;
}
public int getHeight()
{ return height; }
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
private ByteBuffer image;
private int width, height;
Image(int width, int heigh, ByteBuffer image) {
this.image = image;
this.height = heigh;
this.width = width;
}
private ByteBuffer image;
private int width, height;
Image(int width, int heigh, ByteBuffer image)
{
this.image = image;
this.height = heigh;
this.width = width;
}
}

View File

@ -4,93 +4,75 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
public class ModelTexture {
private int textureID = GL11.glGenTextures();
private boolean transparency = false;
private boolean useFakeLighting = false;
public int numberOfRows = 1;
private int normalMap;
private float shineDamper = 1;
private float reflectivity = 0;
private Image texture;
public ModelTexture(String file) {
texture = Image.createImage("/textures/" + file);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -0.4f);
}
public class ModelTexture
{
private int textureID = GL11.glGenTextures();
private boolean transparency = false;
private boolean useFakeLighting = false;
public int numberOfRows = 1;
private int normalMap;
private float shineDamper = 1;
private float reflectivity = 0;
private Image texture;
public ModelTexture(Image texture) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, 6408, texture.getWidth(), texture.getHeight(), 0, 6408, 5121, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
public ModelTexture(String file)
{
texture = Image.createImage("/textures/" + file);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -0.4f);
}
public void remove() {
GL11.glDeleteTextures(this.textureID);
}
public int getTextureID() {
return this.textureID;
}
public Image getTexture() {
return texture;
}
public int getNormalMap() {
return normalMap;
public ModelTexture(Image texture)
{
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, 6408, texture.getWidth(), texture.getHeight(), 0, 6408, 5121, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
}
public void setNormalMap(int normalMap) {
this.normalMap = normalMap;
}
public void remove()
{ GL11.glDeleteTextures(this.textureID); }
public float getShineDamper() {
return shineDamper;
}
public int getTextureID()
{ return this.textureID; }
public float getReflectivity() {
return reflectivity;
}
public Image getTexture()
{ return texture; }
public void setShineDamper(float shineDamper) {
this.shineDamper = shineDamper;
}
public int getNormalMap()
{ return normalMap; }
public void setReflectivity(float reflectivity) {
this.reflectivity = reflectivity;
}
public void setNormalMap(int normalMap)
{ this.normalMap = normalMap; }
public boolean isTransparent() {
return transparency;
}
public float getShineDamper()
{ return shineDamper; }
public void setTransparency(boolean b) {
this.transparency = b;
}
public float getReflectivity()
{ return reflectivity; }
public boolean isUseFakeLighting() {
return useFakeLighting;
}
public void setShineDamper(float shineDamper)
{ this.shineDamper = shineDamper; }
public void useFakeLighting(boolean useFakeLighting) {
this.useFakeLighting = useFakeLighting;
}
public void setReflectivity(float reflectivity)
{ this.reflectivity = reflectivity; }
public boolean isTransparent()
{ return transparency; }
public void setTransparency(boolean b)
{ this.transparency = b; }
public boolean isUseFakeLighting()
{ return useFakeLighting; }
public void useFakeLighting(boolean useFakeLighting)
{ this.useFakeLighting = useFakeLighting; }
}

View File

@ -10,41 +10,37 @@ import java.nio.channels.ReadableByteChannel;
import org.lwjgl.BufferUtils;
public class IOUtil {
public class IOUtil
{
private IOUtil()
{}
private IOUtil() {
}
private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
buffer.flip();
newBuffer.put(buffer);
return newBuffer;
}
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
ByteBuffer buffer;
try (
InputStream source = IOUtil.class.getResourceAsStream(resource);
ReadableByteChannel rbc = Channels.newChannel(source)
) {
buffer = createByteBuffer(bufferSize);
while (true) {
int bytes = rbc.read(buffer);
if (bytes == -1) {
break;
}
if (buffer.remaining() == 0) {
buffer = resizeBuffer(buffer, buffer.capacity() * 3 / 2);
}
}
}
buffer.flip();
return buffer;
}
private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity)
{
ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
buffer.flip();
newBuffer.put(buffer);
return newBuffer;
}
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException
{
ByteBuffer buffer;
try (
InputStream source = IOUtil.class.getResourceAsStream(resource);
ReadableByteChannel rbc = Channels.newChannel(source))
{
buffer = createByteBuffer(bufferSize);
while (true)
{
int bytes = rbc.read(buffer);
if (bytes == -1)
{ break; }
if (buffer.remaining() == 0)
{ buffer = resizeBuffer(buffer, buffer.capacity() * 3 / 2); }
}
}
buffer.flip();
return buffer;
}
}

View File

@ -9,48 +9,49 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
import io.github.hydos.ginger.engine.terrain.Terrain;
public class MousePicker {
public class MousePicker
{
private static final int RECURSION_COUNT = 200;
private static final float RAY_RANGE = 600;
private Vector3f currentRay = new Vector3f();
private Matrix4f projectionMatrix;
private Matrix4f viewMatrix;
private ThirdPersonCamera camera;
private Terrain terrain;
private Vector3f currentTerrainPoint;
public MousePicker(ThirdPersonCamera cam, Matrix4f projection, Terrain terrain) {
public MousePicker(ThirdPersonCamera cam, Matrix4f projection, Terrain terrain)
{
camera = cam;
projectionMatrix = projection;
viewMatrix = Maths.createViewMatrix(camera);
this.terrain = terrain;
}
public Vector3f getCurrentTerrainPoint() {
return currentTerrainPoint;
}
public Vector3f getCurrentRay() {
return currentRay;
}
public Vector3f getCurrentTerrainPoint()
{ return currentTerrainPoint; }
public void update() {
public Vector3f getCurrentRay()
{ return currentRay; }
public void update()
{
viewMatrix = Maths.createViewMatrix(camera);
currentRay = calculateMouseRay();
if (intersectionInRange(0, RAY_RANGE, currentRay)) {
if (intersectionInRange(0, RAY_RANGE, currentRay))
{
currentTerrainPoint = binarySearch(0, 0, RAY_RANGE, currentRay);
} else {
}
else
{
currentTerrainPoint = null;
}
}
private Vector3f calculateMouseRay() {
private Vector3f calculateMouseRay()
{
float mouseX = (float) Window.getMouseX();
float mouseY = (float) ((float) Window.height - Window.getMouseY());
float mouseY = (float) (Window.height - Window.getMouseY());
Vector2f normalizedCoords = getNormalisedDeviceCoordinates(mouseX, mouseY);
Vector4f clipCoords = new Vector4f(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
Vector4f eyeCoords = toEyeCoords(clipCoords);
@ -58,7 +59,8 @@ public class MousePicker {
return worldRay;
}
private Vector3f toWorldCoords(Vector4f eyeCoords) {
private Vector3f toWorldCoords(Vector4f eyeCoords)
{
Matrix4f invertedView = Matrix4f.invert(viewMatrix, null);
Vector4f rayWorld = Matrix4f.transform(invertedView, eyeCoords, null);
Vector3f mouseRay = new Vector3f(rayWorld.x, rayWorld.y, rayWorld.z);
@ -66,70 +68,85 @@ public class MousePicker {
return mouseRay;
}
private Vector4f toEyeCoords(Vector4f clipCoords) {
private Vector4f toEyeCoords(Vector4f clipCoords)
{
Matrix4f invertedProjection = Matrix4f.invert(projectionMatrix, null);
Vector4f eyeCoords = Matrix4f.transform(invertedProjection, clipCoords, null);
return new Vector4f(eyeCoords.x, eyeCoords.y, -1f, 0f);
}
private Vector2f getNormalisedDeviceCoordinates(float mouseX, float mouseY) {
private Vector2f getNormalisedDeviceCoordinates(float mouseX, float mouseY)
{
float x = (2.0f * mouseX) / Window.width - 1f;
float y = (2.0f * mouseY) / Window.height - 1f;
return new Vector2f(x, y);
}
//**********************************************************
private Vector3f getPointOnRay(Vector3f ray, float distance) {
private Vector3f getPointOnRay(Vector3f ray, float distance)
{
Vector3f camPos = camera.getPosition();
Vector3f start = new Vector3f(camPos.x, camPos.y, camPos.z);
Vector3f scaledRay = new Vector3f(ray.x * distance, ray.y * distance, ray.z * distance);
return Vector3f.add(start, scaledRay, null);
}
private Vector3f binarySearch(int count, float start, float finish, Vector3f ray) {
private Vector3f binarySearch(int count, float start, float finish, Vector3f ray)
{
float half = start + ((finish - start) / 2f);
if (count >= RECURSION_COUNT) {
if (count >= RECURSION_COUNT)
{
Vector3f endPoint = getPointOnRay(ray, half);
Terrain terrain = getTerrain(endPoint.getX(), endPoint.getZ());
if (terrain != null) {
if (terrain != null)
{
return endPoint;
} else {
}
else
{
return null;
}
}
if (intersectionInRange(start, half, ray)) {
if (intersectionInRange(start, half, ray))
{
return binarySearch(count + 1, start, half, ray);
} else {
}
else
{
return binarySearch(count + 1, half, finish, ray);
}
}
private boolean intersectionInRange(float start, float finish, Vector3f ray) {
private boolean intersectionInRange(float start, float finish, Vector3f ray)
{
Vector3f startPoint = getPointOnRay(ray, start);
Vector3f endPoint = getPointOnRay(ray, finish);
if (!isUnderGround(startPoint) && isUnderGround(endPoint)) {
if (!isUnderGround(startPoint) && isUnderGround(endPoint))
{
return true;
} else {
}
else
{
return false;
}
}
private boolean isUnderGround(Vector3f testPoint) {
private boolean isUnderGround(Vector3f testPoint)
{
Terrain terrain = getTerrain(testPoint.getX(), testPoint.getZ());
float height = 0;
if (terrain != null) {
height = terrain.getHeightOfTerrain(testPoint.getX(), testPoint.getZ());
}
if (testPoint.y < height) {
if (terrain != null)
{ height = terrain.getHeightOfTerrain(testPoint.getX(), testPoint.getZ()); }
if (testPoint.y < height)
{
return true;
} else {
}
else
{
return false;
}
}
private Terrain getTerrain(float worldX, float worldZ) {
return terrain;
}
private Terrain getTerrain(float worldX, float worldZ)
{ return terrain; }
}

View File

@ -7,75 +7,66 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector4f;
import io.github.hydos.ginger.engine.renderEngine.MasterRenderer;
/**
* Represents the 3D cuboidal area of the world in which objects will cast
/** Represents the 3D cuboidal area of the world in which objects will cast
* shadows (basically represents the orthographic projection area for the shadow
* render pass). It is updated each frame to optimise the area, making it as
* small as possible (to allow for optimal shadow map resolution) while not
* being too small to avoid objects not having shadows when they should.
* Everything inside the cuboidal area represented by this object will be
* rendered to the shadow map in the shadow render pass. Everything outside the
* area won't be.
*
*
*/
public class ShadowBox {
* area won't be. */
public class ShadowBox
{
private static final float OFFSET = 10;
private static final Vector4f UP = new Vector4f(0, 1, 0, 0);
private static final Vector4f FORWARD = new Vector4f(0, 0, -1, 0);
private static final float SHADOW_DISTANCE = 100;
private float minX, maxX;
private float minY, maxY;
private float minZ, maxZ;
private Matrix4f lightViewMatrix;
private ThirdPersonCamera cam;
private float farHeight, farWidth, nearHeight, nearWidth;
/**
* Creates a new shadow box and calculates some initial values relating to
/** Creates a new shadow box and calculates some initial values relating to
* the camera's view frustum, namely the width and height of the near plane
* and (possibly adjusted) far plane.
*
* @param lightViewMatrix
* - basically the "view matrix" of the light. Can be used to
* transform a point from world space into "light" space (i.e.
* changes a point's coordinates from being in relation to the
* world's axis to being in terms of the light's local axis).
* - basically the "view matrix" of the light. Can be used to
* transform a point from world space into "light" space (i.e.
* changes a point's coordinates from being in relation to the
* world's axis to being in terms of the light's local axis).
* @param camera
* - the in-game camera.
*/
protected ShadowBox(Matrix4f lightViewMatrix, ThirdPersonCamera camera) {
* - the in-game camera. */
protected ShadowBox(Matrix4f lightViewMatrix, ThirdPersonCamera camera)
{
this.lightViewMatrix = lightViewMatrix;
this.cam = camera;
calculateWidthsAndHeights();
}
/**
* Updates the bounds of the shadow box based on the light direction and the
/** Updates the bounds of the shadow box based on the light direction and the
* camera's view frustum, to make sure that the box covers the smallest area
* possible while still ensuring that everything inside the camera's view
* (within a certain range) will cast shadows.
*/
protected void update() {
* (within a certain range) will cast shadows. */
protected void update()
{
Matrix4f rotation = calculateCameraRotationMatrix();
Vector3f forwardVector = new Vector3f(Matrix4f.transform(rotation, FORWARD, null));
Vector3f toFar = new Vector3f(forwardVector);
toFar.scale(SHADOW_DISTANCE);
Vector3f toNear = new Vector3f(forwardVector);
toNear.scale(MasterRenderer.NEAR_PLANE);
Vector3f centerNear = Vector3f.add(toNear, cam.getPosition(), null);
Vector3f centerFar = Vector3f.add(toFar, cam.getPosition(), null);
Vector4f[] points = calculateFrustumVertices(rotation, forwardVector, centerNear,
centerFar);
centerFar);
boolean first = true;
for (Vector4f point : points) {
if (first) {
for (Vector4f point : points)
{
if (first)
{
minX = point.x;
maxX = point.x;
minY = point.y;
@ -85,33 +76,34 @@ public class ShadowBox {
first = false;
continue;
}
if (point.x > maxX) {
if (point.x > maxX)
{
maxX = point.x;
} else if (point.x < minX) {
minX = point.x;
}
if (point.y > maxY) {
else if (point.x < minX)
{ minX = point.x; }
if (point.y > maxY)
{
maxY = point.y;
} else if (point.y < minY) {
minY = point.y;
}
if (point.z > maxZ) {
else if (point.y < minY)
{ minY = point.y; }
if (point.z > maxZ)
{
maxZ = point.z;
} else if (point.z < minZ) {
minZ = point.z;
}
else if (point.z < minZ)
{ minZ = point.z; }
}
maxZ += OFFSET;
}
/**
* Calculates the center of the "view cuboid" in light space first, and then
/** Calculates the center of the "view cuboid" in light space first, and then
* converts this to world space using the inverse light's view matrix.
*
* @return The center of the "view cuboid" in world space.
*/
protected Vector3f getCenter() {
* @return The center of the "view cuboid" in world space. */
protected Vector3f getCenter()
{
float x = (minX + maxX) / 2f;
float y = (minY + maxY) / 2f;
float z = (minZ + maxZ) / 2f;
@ -121,57 +113,47 @@ public class ShadowBox {
return new Vector3f(Matrix4f.transform(invertedLight, cen, null));
}
/**
* @return The width of the "view cuboid" (orthographic projection area).
*/
protected float getWidth() {
return maxX - minX;
}
/** @return The width of the "view cuboid" (orthographic projection area). */
protected float getWidth()
{ return maxX - minX; }
/**
* @return The height of the "view cuboid" (orthographic projection area).
*/
protected float getHeight() {
return maxY - minY;
}
/** @return The height of the "view cuboid" (orthographic projection area). */
protected float getHeight()
{ return maxY - minY; }
/**
* @return The length of the "view cuboid" (orthographic projection area).
*/
protected float getLength() {
return maxZ - minZ;
}
/** @return The length of the "view cuboid" (orthographic projection area). */
protected float getLength()
{ return maxZ - minZ; }
/**
* Calculates the position of the vertex at each corner of the view frustum
/** Calculates the position of the vertex at each corner of the view frustum
* in light space (8 vertices in total, so this returns 8 positions).
*
* @param rotation
* - camera's rotation.
* @param forwardVector
* - the direction that the camera is aiming, and thus the
* direction of the frustum.
* @param centerNear
* - the center point of the frustum's near plane.
* @param centerFar
* - the center point of the frustum's (possibly adjusted) far
* plane.
* @return The positions of the vertices of the frustum in light space.
*/
* @param rotation
* - camera's rotation.
* @param forwardVector
* - the direction that the camera is aiming, and thus the
* direction of the frustum.
* @param centerNear
* - the center point of the frustum's near plane.
* @param centerFar
* - the center point of the frustum's (possibly adjusted) far
* plane.
* @return The positions of the vertices of the frustum in light space. */
private Vector4f[] calculateFrustumVertices(Matrix4f rotation, Vector3f forwardVector,
Vector3f centerNear, Vector3f centerFar) {
Vector3f centerNear, Vector3f centerFar)
{
Vector3f upVector = new Vector3f(Matrix4f.transform(rotation, UP, null));
Vector3f rightVector = Vector3f.cross(forwardVector, upVector, null);
Vector3f downVector = new Vector3f(-upVector.x, -upVector.y, -upVector.z);
Vector3f leftVector = new Vector3f(-rightVector.x, -rightVector.y, -rightVector.z);
Vector3f farTop = Vector3f.add(centerFar, new Vector3f(upVector.x * farHeight,
upVector.y * farHeight, upVector.z * farHeight), null);
upVector.y * farHeight, upVector.z * farHeight), null);
Vector3f farBottom = Vector3f.add(centerFar, new Vector3f(downVector.x * farHeight,
downVector.y * farHeight, downVector.z * farHeight), null);
downVector.y * farHeight, downVector.z * farHeight), null);
Vector3f nearTop = Vector3f.add(centerNear, new Vector3f(upVector.x * nearHeight,
upVector.y * nearHeight, upVector.z * nearHeight), null);
upVector.y * nearHeight, upVector.z * nearHeight), null);
Vector3f nearBottom = Vector3f.add(centerNear, new Vector3f(downVector.x * nearHeight,
downVector.y * nearHeight, downVector.z * nearHeight), null);
downVector.y * nearHeight, downVector.z * nearHeight), null);
Vector4f[] points = new Vector4f[8];
points[0] = calculateLightSpaceFrustumCorner(farTop, rightVector, farWidth);
points[1] = calculateLightSpaceFrustumCorner(farTop, leftVector, farWidth);
@ -184,57 +166,50 @@ public class ShadowBox {
return points;
}
/**
* Calculates one of the corner vertices of the view frustum in world space
/** Calculates one of the corner vertices of the view frustum in world space
* and converts it to light space.
*
* @param startPoint
* - the starting center point on the view frustum.
* @param direction
* - the direction of the corner from the start point.
* @param width
* - the distance of the corner from the start point.
* @return - The relevant corner vertex of the view frustum in light space.
*/
* @param startPoint
* - the starting center point on the view frustum.
* @param direction
* - the direction of the corner from the start point.
* @param width
* - the distance of the corner from the start point.
* @return - The relevant corner vertex of the view frustum in light space. */
private Vector4f calculateLightSpaceFrustumCorner(Vector3f startPoint, Vector3f direction,
float width) {
float width)
{
Vector3f point = Vector3f.add(startPoint,
new Vector3f(direction.x * width, direction.y * width, direction.z * width), null);
new Vector3f(direction.x * width, direction.y * width, direction.z * width), null);
Vector4f point4f = new Vector4f(point.x, point.y, point.z, 1f);
Matrix4f.transform(lightViewMatrix, point4f, point4f);
return point4f;
}
/**
* @return The rotation of the camera represented as a matrix.
*/
private Matrix4f calculateCameraRotationMatrix() {
/** @return The rotation of the camera represented as a matrix. */
private Matrix4f calculateCameraRotationMatrix()
{
Matrix4f rotation = new Matrix4f();
rotation.rotate((float) Math.toRadians(-cam.getYaw()), new Vector3f(0, 1, 0));
rotation.rotate((float) Math.toRadians(-cam.getPitch()), new Vector3f(1, 0, 0));
return rotation;
}
/**
* Calculates the width and height of the near and far planes of the
/** Calculates the width and height of the near and far planes of the
* camera's view frustum. However, this doesn't have to use the "actual" far
* plane of the view frustum. It can use a shortened view frustum if desired
* by bringing the far-plane closer, which would increase shadow resolution
* but means that distant objects wouldn't cast shadows.
*/
private void calculateWidthsAndHeights() {
* but means that distant objects wouldn't cast shadows. */
private void calculateWidthsAndHeights()
{
farWidth = (float) (SHADOW_DISTANCE * Math.tan(Math.toRadians(MasterRenderer.FOV)));
nearWidth = (float) (MasterRenderer.NEAR_PLANE
* Math.tan(Math.toRadians(MasterRenderer.FOV)));
* Math.tan(Math.toRadians(MasterRenderer.FOV)));
farHeight = farWidth / getAspectRatio();
nearHeight = nearWidth / getAspectRatio();
}
/**
* @return The aspect ratio of the display (width:height ratio).
*/
private float getAspectRatio() {
return (float) Window.width / (float) Window.height;
}
/** @return The aspect ratio of the display (width:height ratio). */
private float getAspectRatio()
{ return (float) Window.width / (float) Window.height; }
}

View File

@ -10,98 +10,82 @@ import org.lwjgl.opengl.GL32;
import io.github.hydos.ginger.engine.io.Window;
/**
* The frame buffer for the shadow pass. This class sets up the depth texture
/** The frame buffer for the shadow pass. This class sets up the depth texture
* which can be rendered to during the shadow render pass, producing a shadow
* map.
*
*
*/
public class ShadowFrameBuffer {
* map. */
public class ShadowFrameBuffer
{
private final int WIDTH;
private final int HEIGHT;
private int fbo;
private int shadowMap;
/**
* Initialises the frame buffer and shadow map of a certain size.
/** Initialises the frame buffer and shadow map of a certain size.
*
* @param width
* - the width of the shadow map in pixels.
* - the width of the shadow map in pixels.
* @param height
* - the height of the shadow map in pixels.
*/
protected ShadowFrameBuffer(int width, int height) {
* - the height of the shadow map in pixels. */
protected ShadowFrameBuffer(int width, int height)
{
this.WIDTH = width;
this.HEIGHT = height;
initialiseFrameBuffer();
}
/**
* Deletes the frame buffer and shadow map texture when the game closes.
*/
protected void cleanUp() {
/** Deletes the frame buffer and shadow map texture when the game closes. */
protected void cleanUp()
{
GL30.glDeleteFramebuffers(fbo);
GL11.glDeleteTextures(shadowMap);
}
/**
* Binds the frame buffer, setting it as the current render target.
*/
protected void bindFrameBuffer() {
bindFrameBuffer(fbo, WIDTH, HEIGHT);
}
/** Binds the frame buffer, setting it as the current render target. */
protected void bindFrameBuffer()
{ bindFrameBuffer(fbo, WIDTH, HEIGHT); }
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
* render target.
*/
protected void unbindFrameBuffer() {
/** Unbinds the frame buffer, setting the default frame buffer as the current
* render target. */
protected void unbindFrameBuffer()
{
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
GL11.glViewport(0, 0, Window.width, Window.height);
}
/**
* @return The ID of the shadow map texture.
*/
protected int getShadowMap() {
return shadowMap;
}
/** @return The ID of the shadow map texture. */
protected int getShadowMap()
{ return shadowMap; }
/**
* Creates the frame buffer and adds its depth attachment texture.
*/
private void initialiseFrameBuffer() {
/** Creates the frame buffer and adds its depth attachment texture. */
private void initialiseFrameBuffer()
{
fbo = createFrameBuffer();
shadowMap = createDepthBufferAttachment(WIDTH, HEIGHT);
unbindFrameBuffer();
}
/**
* Binds the frame buffer as the current render target.
/** Binds the frame buffer as the current render target.
*
* @param frameBuffer
* - the frame buffer.
* - the frame buffer.
* @param width
* - the width of the frame buffer.
* - the width of the frame buffer.
* @param height
* - the height of the frame buffer.
*/
private static void bindFrameBuffer(int frameBuffer, int width, int height) {
* - the height of the frame buffer. */
private static void bindFrameBuffer(int frameBuffer, int width, int height)
{
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, frameBuffer);
GL11.glViewport(0, 0, width, height);
}
/**
* Creates a frame buffer and binds it so that attachments can be added to
/** Creates a frame buffer and binds it so that attachments can be added to
* it. The draw buffer is set to none, indicating that there's no colour
* buffer to be rendered to.
*
* @return The newly created frame buffer's ID.
*/
private static int createFrameBuffer() {
* @return The newly created frame buffer's ID. */
private static int createFrameBuffer()
{
int frameBuffer = GL30.glGenFramebuffers();
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, frameBuffer);
GL11.glDrawBuffer(GL11.GL_NONE);
@ -109,20 +93,19 @@ public class ShadowFrameBuffer {
return frameBuffer;
}
/**
* Creates a depth buffer texture attachment.
/** Creates a depth buffer texture attachment.
*
* @param width
* - the width of the texture.
* @param height
* - the height of the texture.
* @return The ID of the depth texture.
*/
private static int createDepthBufferAttachment(int width, int height) {
* @param width
* - the width of the texture.
* @param height
* - the height of the texture.
* @return The ID of the depth texture. */
private static int createDepthBufferAttachment(int width, int height)
{
int texture = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT16, width, height, 0,
GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);

View File

@ -15,82 +15,77 @@ import io.github.hydos.ginger.engine.renderEngine.MasterRenderer;
import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
public class ShadowMapEntityRenderer {
public class ShadowMapEntityRenderer
{
private Matrix4f projectionViewMatrix;
private ShadowShader shader;
/**
* @param shader
* - the simple shader program being used for the shadow render
* pass.
/** @param shader
* - the simple shader program being used for the shadow render
* pass.
* @param projectionViewMatrix
* - the orthographic projection matrix multiplied by the light's
* "view" matrix.
*/
protected ShadowMapEntityRenderer(ShadowShader shader, Matrix4f projectionViewMatrix) {
* - the orthographic projection matrix multiplied by the light's
* "view" matrix. */
protected ShadowMapEntityRenderer(ShadowShader shader, Matrix4f projectionViewMatrix)
{
this.shader = shader;
this.projectionViewMatrix = projectionViewMatrix;
}
/**
* Renders entieis to the shadow map. Each model is first bound and then all
/** Renders entieis to the shadow map. Each model is first bound and then all
* of the entities using that model are rendered to the shadow map.
*
* @param entities
* - the entities to be rendered to the shadow map.
*/
protected void render(Map<TexturedModel, List<Entity>> entities) {
for (TexturedModel model : entities.keySet()) {
* - the entities to be rendered to the shadow map. */
protected void render(Map<TexturedModel, List<Entity>> entities)
{
for (TexturedModel model : entities.keySet())
{
RawModel rawModel = model.getRawModel();
bindModel(rawModel);
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getTexture().getTextureID());
if(model.getTexture().isTransparent()) {
MasterRenderer.disableCulling();
}
for (Entity entity : entities.get(model)) {
if (model.getTexture().isTransparent())
{ MasterRenderer.disableCulling(); }
for (Entity entity : entities.get(model))
{
prepareInstance(entity);
GL11.glDrawElements(GL11.GL_TRIANGLES, rawModel.getVertexCount(),
GL11.GL_UNSIGNED_INT, 0);
}
if(model.getTexture().isTransparent()) {
MasterRenderer.enableCulling();
GL11.GL_UNSIGNED_INT, 0);
}
if (model.getTexture().isTransparent())
{ MasterRenderer.enableCulling(); }
}
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL30.glBindVertexArray(0);
}
/**
* Binds a raw model before rendering. Only the attribute 0 is enabled here
/** Binds a raw model before rendering. Only the attribute 0 is enabled here
* because that is where the positions are stored in the VAO, and only the
* positions are required in the vertex shader.
*
* @param rawModel
* - the model to be bound.
*/
private void bindModel(RawModel rawModel) {
* - the model to be bound. */
private void bindModel(RawModel rawModel)
{
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
}
/**
* Prepares an entity to be rendered. The model matrix is created in the
/** Prepares an entity to be rendered. The model matrix is created in the
* usual way and then multiplied with the projection and view matrix (often
* in the past we've done this in the vertex shader) to create the
* mvp-matrix. This is then loaded to the vertex shader as a uniform.
*
* @param entity
* - the entity to be prepared for rendering.
*/
private void prepareInstance(Entity entity) {
* - the entity to be prepared for rendering. */
private void prepareInstance(Entity entity)
{
Matrix4f modelMatrix = Maths.createTransformationMatrix(entity.getPosition(),
entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale());
entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale());
Matrix4f mvpMatrix = Matrix4f.mul(projectionViewMatrix, modelMatrix, null);
shader.loadMvpMatrix(mvpMatrix);
}
}

View File

@ -13,16 +13,13 @@ import io.github.hydos.ginger.engine.mathEngine.vectors.Vector2f;
import io.github.hydos.ginger.engine.mathEngine.vectors.Vector3f;
import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
/**
* This class is in charge of using all of the classes in the shadows package to
/** This class is in charge of using all of the classes in the shadows package to
* carry out the shadow render pass, i.e. rendering the scene to the shadow map
* texture. This is the only class in the shadows package which needs to be
* referenced from outside the shadows package.
*/
public class ShadowMapMasterRenderer {
* referenced from outside the shadows package. */
public class ShadowMapMasterRenderer
{
private static final int SHADOW_MAP_SIZE = 5120;
private ShadowFrameBuffer shadowFbo;
private ShadowShader shader;
private ShadowBox shadowBox;
@ -30,11 +27,9 @@ public class ShadowMapMasterRenderer {
private Matrix4f lightViewMatrix = new Matrix4f();
private Matrix4f projectionViewMatrix = new Matrix4f();
private Matrix4f offset = createOffset();
private ShadowMapEntityRenderer entityRenderer;
/**
* Creates instances of the important objects needed for rendering the scene
/** Creates instances of the important objects needed for rendering the scene
* to the shadow map. This includes the {@link ShadowBox} which calculates
* the position and size of the "view cuboid", the simple renderer and
* shader program that are used to render objects to the shadow map, and the
@ -42,17 +37,16 @@ public class ShadowMapMasterRenderer {
* shadow map is determined here.
*
* @param camera
* - the camera being used in the scene.
*/
public ShadowMapMasterRenderer(ThirdPersonCamera camera) {
* - the camera being used in the scene. */
public ShadowMapMasterRenderer(ThirdPersonCamera camera)
{
shader = new ShadowShader();
shadowBox = new ShadowBox(lightViewMatrix, camera);
shadowFbo = new ShadowFrameBuffer(SHADOW_MAP_SIZE, SHADOW_MAP_SIZE);
entityRenderer = new ShadowMapEntityRenderer(shader, projectionViewMatrix);
}
/**
* Carries out the shadow render pass. This renders the entities to the
/** Carries out the shadow render pass. This renders the entities to the
* shadow map. First the shadow box is updated to calculate the size and
* position of the "view cuboid". The light direction is assumed to be
* "-lightPosition" which will be fairly accurate assuming that the light is
@ -60,13 +54,13 @@ public class ShadowMapMasterRenderer {
* to the shadow map, and finishes rendering.
*
* @param entities
* - the lists of entities to be rendered. Each list is
* associated with the {@link TexturedModel} that all of the
* entities in that list use.
* - the lists of entities to be rendered. Each list is
* associated with the {@link TexturedModel} that all of the
* entities in that list use.
* @param sun
* - the light acting as the sun in the scene.
*/
public void render(Map<TexturedModel, List<Entity>> entities, Light sun) {
* - the light acting as the sun in the scene. */
public void render(Map<TexturedModel, List<Entity>> entities, Light sun)
{
shadowBox.update();
Vector3f sunPosition = sun.getPosition();
Vector3f lightDirection = new Vector3f(-sunPosition.x, -sunPosition.y, -sunPosition.z);
@ -75,44 +69,33 @@ public class ShadowMapMasterRenderer {
finish();
}
/**
* This biased projection-view matrix is used to convert fragments into
/** This biased projection-view matrix is used to convert fragments into
* "shadow map space" when rendering the main render pass. It converts a
* world space position into a 2D coordinate on the shadow map. This is
* needed for the second part of shadow mapping.
*
* @return The to-shadow-map-space matrix.
*/
public Matrix4f getToShadowMapSpaceMatrix() {
return Matrix4f.mul(offset, projectionViewMatrix, null);
}
* @return The to-shadow-map-space matrix. */
public Matrix4f getToShadowMapSpaceMatrix()
{ return Matrix4f.mul(offset, projectionViewMatrix, null); }
/**
* Clean up the shader and FBO on closing.
*/
public void cleanUp() {
/** Clean up the shader and FBO on closing. */
public void cleanUp()
{
shader.cleanUp();
shadowFbo.cleanUp();
}
/**
* @return The ID of the shadow map texture. The ID will always stay the
/** @return The ID of the shadow map texture. The ID will always stay the
* same, even when the contents of the shadow map texture change
* each frame.
*/
public int getShadowMap() {
return shadowFbo.getShadowMap();
}
* each frame. */
public int getShadowMap()
{ return shadowFbo.getShadowMap(); }
/**
* @return The light's "view" matrix.
*/
protected Matrix4f getLightSpaceTransform() {
return lightViewMatrix;
}
/** @return The light's "view" matrix. */
protected Matrix4f getLightSpaceTransform()
{ return lightViewMatrix; }
/**
* Prepare for the shadow render pass. This first updates the dimensions of
/** Prepare for the shadow render pass. This first updates the dimensions of
* the orthographic "view cuboid" based on the information that was
* calculated in the {@link SHadowBox} class. The light's "view" matrix is
* also calculated based on the light's direction and the center position of
@ -126,12 +109,12 @@ public class ShadowMapMasterRenderer {
* started.
*
* @param lightDirection
* - the direction of the light rays coming from the sun.
* - the direction of the light rays coming from the sun.
* @param box
* - the shadow box, which contains all the info about the
* "view cuboid".
*/
private void prepare(Vector3f lightDirection, ShadowBox box) {
* - the shadow box, which contains all the info about the
* "view cuboid". */
private void prepare(Vector3f lightDirection, ShadowBox box)
{
updateOrthoProjectionMatrix(box.getWidth(), box.getHeight(), box.getLength());
updateLightViewMatrix(lightDirection, box.getCenter());
Matrix4f.mul(projectionMatrix, lightViewMatrix, projectionViewMatrix);
@ -141,18 +124,16 @@ public class ShadowMapMasterRenderer {
shader.start();
}
/**
* Finish the shadow render pass. Stops the shader and unbinds the shadow
/** Finish the shadow render pass. Stops the shader and unbinds the shadow
* FBO, so everything rendered after this point is rendered to the screen,
* rather than to the shadow FBO.
*/
private void finish() {
* rather than to the shadow FBO. */
private void finish()
{
shader.stop();
shadowFbo.unbindFrameBuffer();
}
/**
* Updates the "view" matrix of the light. This creates a view matrix which
/** Updates the "view" matrix of the light. This creates a view matrix which
* will line up the direction of the "view cuboid" with the direction of the
* light. The light itself has no position, so the "view" matrix is centered
* at the center of the "view cuboid". The created view matrix determines
@ -160,12 +141,12 @@ public class ShadowMapMasterRenderer {
* the view cuboid, however, is determined by the projection matrix.
*
* @param direction
* - the light direction, and therefore the direction that the
* "view cuboid" should be pointing.
* - the light direction, and therefore the direction that the
* "view cuboid" should be pointing.
* @param center
* - the center of the "view cuboid" in world space.
*/
private void updateLightViewMatrix(Vector3f direction, Vector3f center) {
* - the center of the "view cuboid" in world space. */
private void updateLightViewMatrix(Vector3f direction, Vector3f center)
{
direction.normalise();
center.negate();
lightViewMatrix.setIdentity();
@ -174,23 +155,22 @@ public class ShadowMapMasterRenderer {
float yaw = (float) Math.toDegrees(((float) Math.atan(direction.x / direction.z)));
yaw = direction.z > 0 ? yaw - 180 : yaw;
Matrix4f.rotate((float) -Math.toRadians(yaw), new Vector3f(0, 1, 0), lightViewMatrix,
lightViewMatrix);
lightViewMatrix);
Matrix4f.translate(center, lightViewMatrix, lightViewMatrix);
}
/**
* Creates the orthographic projection matrix. This projection matrix
/** Creates the orthographic projection matrix. This projection matrix
* basically sets the width, length and height of the "view cuboid", based
* on the values that were calculated in the {@link ShadowBox} class.
*
* @param width
* - shadow box width.
* - shadow box width.
* @param height
* - shadow box height.
* - shadow box height.
* @param length
* - shadow box length.
*/
private void updateOrthoProjectionMatrix(float width, float height, float length) {
* - shadow box length. */
private void updateOrthoProjectionMatrix(float width, float height, float length)
{
projectionMatrix.setIdentity();
projectionMatrix.m00 = 2f / width;
projectionMatrix.m11 = 2f / height;
@ -198,14 +178,13 @@ public class ShadowMapMasterRenderer {
projectionMatrix.m33 = 1;
}
/**
* Create the offset for part of the conversion to shadow map space. This
/** Create the offset for part of the conversion to shadow map space. This
* conversion is necessary to convert from one coordinate system to the
* coordinate system that we can use to sample to shadow map.
*
* @return The offset as a matrix (so that it's easy to apply to other matrices).
*/
private static Matrix4f createOffset() {
* @return The offset as a matrix (so that it's easy to apply to other matrices). */
private static Matrix4f createOffset()
{
Matrix4f offset = new Matrix4f();
offset.translate(new Vector3f(0.5f, 0.5f, 0.5f));
offset.scale(new Vector3f(0.5f, 0.5f, 0.5f));

View File

@ -3,31 +3,26 @@ package io.github.hydos.ginger.engine.shadow;
import io.github.hydos.ginger.engine.mathEngine.matrixes.Matrix4f;
import io.github.hydos.ginger.engine.renderEngine.shaders.ShaderProgram;
public class ShadowShader extends ShaderProgram {
public class ShadowShader extends ShaderProgram
{
private static final String VERTEX_FILE = "shadowVertexShader.glsl";
private static final String FRAGMENT_FILE = "shadowFragmentShader.glsl";
private int location_mvpMatrix;
protected ShadowShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
protected ShadowShader()
{ super(VERTEX_FILE, FRAGMENT_FILE); }
@Override
protected void getAllUniformLocations() {
location_mvpMatrix = super.getUniformLocation("mvpMatrix");
}
protected void loadMvpMatrix(Matrix4f mvpMatrix){
super.loadMatrix(location_mvpMatrix, mvpMatrix);
}
protected void getAllUniformLocations()
{ location_mvpMatrix = super.getUniformLocation("mvpMatrix"); }
protected void loadMvpMatrix(Matrix4f mvpMatrix)
{ super.loadMatrix(location_mvpMatrix, mvpMatrix); }
@Override
protected void bindAttributes() {
protected void bindAttributes()
{
super.bindAttribute(0, "in_position");
super.bindAttribute(1, "in_textureCoords");
}
}

View File

@ -12,113 +12,117 @@ import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.utils.Loader;
import io.github.hydos.ginger.main.settings.Constants;
public class Terrain {
public class Terrain
{
private static final float MAX_PIXEL_COLOUR = 256 * 256 * 256;
private float[][] heights;
private float x, z;
private RawModel model;
private TerrainTexturePack texturePack;
private TerrainTexture blendMap;
public Terrain(float gridX, float gridZ, TerrainTexturePack texturePack, TerrainTexture blendMap, String heightMapLocation) {
public Terrain(float gridX, float gridZ, TerrainTexturePack texturePack, TerrainTexture blendMap, String heightMapLocation)
{
this.texturePack = texturePack;
this.blendMap = blendMap;
this.x = gridX * Constants.terrainSize;
this.z = gridZ * Constants.terrainSize;
this.model = generateTerrain(heightMapLocation);
}
public float getHeightOfTerrain(float worldX, float worldZ) {
public float getHeightOfTerrain(float worldX, float worldZ)
{
float terrainX = worldX - this.x;
float terrainZ = worldZ - this.z;
float gridSquareSize = Constants.terrainSize / ((float) heights.length - 1);
int gridX = (int) Math.floor(terrainX / gridSquareSize);
int gridZ = (int) Math.floor(terrainZ / gridSquareSize);
if(gridX >= heights.length - 1 || gridZ >= heights.length - 1 || gridX <0 || gridZ < 0) {
return 0;
}
if (gridX >= heights.length - 1 || gridZ >= heights.length - 1 || gridX < 0 || gridZ < 0)
{ return 0; }
float xCoord = (terrainX % gridSquareSize) / gridSquareSize;
float zCoord = (terrainZ % gridSquareSize) / gridSquareSize;
float answer;
if (xCoord <= (1-zCoord)) {
if (xCoord <= (1 - zCoord))
{
answer = Maths
.barryCentric(new Vector3f(0, heights[gridX][gridZ], 0), new Vector3f(1,
heights[gridX + 1][gridZ], 0), new Vector3f(0,
heights[gridX][gridZ + 1], 1), new Vector2f(xCoord, zCoord));
} else {
.barryCentric(new Vector3f(0, heights[gridX][gridZ], 0), new Vector3f(1,
heights[gridX + 1][gridZ], 0),
new Vector3f(0,
heights[gridX][gridZ + 1], 1),
new Vector2f(xCoord, zCoord));
}
else
{
answer = Maths
.barryCentric(new Vector3f(1, heights[gridX + 1][gridZ], 0), new Vector3f(1,
heights[gridX + 1][gridZ + 1], 1), new Vector3f(0,
heights[gridX][gridZ + 1], 1), new Vector2f(xCoord, zCoord));
.barryCentric(new Vector3f(1, heights[gridX + 1][gridZ], 0), new Vector3f(1,
heights[gridX + 1][gridZ + 1], 1),
new Vector3f(0,
heights[gridX][gridZ + 1], 1),
new Vector2f(xCoord, zCoord));
}
return answer;
}
public float getX() {
return x;
}
public float getZ() {
return z;
}
public float getX()
{ return x; }
public RawModel getModel() {
return model;
}
public float getZ()
{ return z; }
public TerrainTexturePack getTexturePack() {
return texturePack;
}
public RawModel getModel()
{ return model; }
public TerrainTexture getBlendMap() {
return blendMap;
}
public TerrainTexturePack getTexturePack()
{ return texturePack; }
private RawModel generateTerrain(String heightMap){
public TerrainTexture getBlendMap()
{ return blendMap; }
private RawModel generateTerrain(String heightMap)
{
BufferedImage image = null;
try {
try
{
image = ImageIO.read(Class.class.getResourceAsStream("/textures/terrain/" + heightMap));
} catch (IOException e) {
}
catch (IOException e)
{
e.printStackTrace();
}
int VERTEX_COUNT = image.getHeight();
heights = new float[VERTEX_COUNT][VERTEX_COUNT];
int count = VERTEX_COUNT * VERTEX_COUNT;
float[] vertices = new float[count * 3];
float[] normals = new float[count * 3];
float[] textureCoords = new float[count*2];
int[] indices = new int[6*(VERTEX_COUNT-1)*(VERTEX_COUNT-1)];
float[] textureCoords = new float[count * 2];
int[] indices = new int[6 * (VERTEX_COUNT - 1) * (VERTEX_COUNT - 1)];
int vertexPointer = 0;
for(int i=0;i<VERTEX_COUNT;i++){
for(int j=0;j<VERTEX_COUNT;j++){
vertices[vertexPointer*3] = j/((float)VERTEX_COUNT - 1) * Constants.terrainSize;
for (int i = 0; i < VERTEX_COUNT; i++)
{
for (int j = 0; j < VERTEX_COUNT; j++)
{
vertices[vertexPointer * 3] = j / ((float) VERTEX_COUNT - 1) * Constants.terrainSize;
float height = getHeight(j, i, image);
heights[j][i] = height;
vertices[vertexPointer*3+1] = height;
vertices[vertexPointer*3+2] = i/((float)VERTEX_COUNT - 1) * Constants.terrainSize;
vertices[vertexPointer * 3 + 1] = height;
vertices[vertexPointer * 3 + 2] = i / ((float) VERTEX_COUNT - 1) * Constants.terrainSize;
Vector3f normal = calculateNormal(j, i, image);
normals[vertexPointer*3] = normal.x;
normals[vertexPointer*3+1] = normal.y;
normals[vertexPointer*3+2] = normal.z;
textureCoords[vertexPointer*2] = j/((float)VERTEX_COUNT - 1);
textureCoords[vertexPointer*2+1] = i/((float)VERTEX_COUNT - 1);
normals[vertexPointer * 3] = normal.x;
normals[vertexPointer * 3 + 1] = normal.y;
normals[vertexPointer * 3 + 2] = normal.z;
textureCoords[vertexPointer * 2] = j / ((float) VERTEX_COUNT - 1);
textureCoords[vertexPointer * 2 + 1] = i / ((float) VERTEX_COUNT - 1);
vertexPointer++;
}
}
int pointer = 0;
for(int gz=0;gz<VERTEX_COUNT-1;gz++){
for(int gx=0;gx<VERTEX_COUNT-1;gx++){
int topLeft = (gz*VERTEX_COUNT)+gx;
for (int gz = 0; gz < VERTEX_COUNT - 1; gz++)
{
for (int gx = 0; gx < VERTEX_COUNT - 1; gx++)
{
int topLeft = (gz * VERTEX_COUNT) + gx;
int topRight = topLeft + 1;
int bottomLeft = ((gz+1)*VERTEX_COUNT)+gx;
int bottomLeft = ((gz + 1) * VERTEX_COUNT) + gx;
int bottomRight = bottomLeft + 1;
indices[pointer++] = topLeft;
indices[pointer++] = bottomLeft;
@ -130,27 +134,26 @@ public class Terrain {
}
return Loader.loadToVAO(vertices, indices, normals, textureCoords);
}
private float getHeight(int x, int z, BufferedImage image) {
if(x<0 || x>=image.getHeight() || z<0 || z>=image.getHeight()) {
return 0;
}
private float getHeight(int x, int z, BufferedImage image)
{
if (x < 0 || x >= image.getHeight() || z < 0 || z >= image.getHeight())
{ return 0; }
float height = image.getRGB(x, z);
height += MAX_PIXEL_COLOUR / 2f;
height /= MAX_PIXEL_COLOUR / 2f;
height *= Constants.terrainMaxHeight;
return height;
}
private Vector3f calculateNormal(int x, int z, BufferedImage image) {
float heightL = getHeight(x-1, z, image);
float heightR = getHeight(x+1, z, image);
float heightD = getHeight(x, z-1, image);
float heightU = getHeight(x, z+1, image);
Vector3f normal = new Vector3f(heightL-heightR, 2f, heightD - heightU);
private Vector3f calculateNormal(int x, int z, BufferedImage image)
{
float heightL = getHeight(x - 1, z, image);
float heightR = getHeight(x + 1, z, image);
float heightD = getHeight(x, z - 1, image);
float heightU = getHeight(x, z + 1, image);
Vector3f normal = new Vector3f(heightL - heightR, 2f, heightD - heightU);
normal.normalise();
return normal;
}
}

View File

@ -1,18 +1,15 @@
package io.github.hydos.ginger.engine.terrain;
public class TerrainTexture {
public class TerrainTexture
{
private int textureID;
public int getTextureID() {
return textureID;
}
public TerrainTexture(int textureID) {
public int getTextureID()
{ return textureID; }
public TerrainTexture(int textureID)
{
super();
this.textureID = textureID;
}
}

View File

@ -1,33 +1,30 @@
package io.github.hydos.ginger.engine.terrain;
public class TerrainTexturePack {
public class TerrainTexturePack
{
private TerrainTexture backgroundTexture;
private TerrainTexture rTexture;
private TerrainTexture gTexture;
private TerrainTexture bTexture;
public TerrainTexturePack(TerrainTexture backgroundTexture, TerrainTexture rTexture, TerrainTexture gTexture,
TerrainTexture bTexture) {
TerrainTexture bTexture)
{
this.backgroundTexture = backgroundTexture;
this.rTexture = rTexture;
this.gTexture = gTexture;
this.bTexture = bTexture;
}
public TerrainTexture getBackgroundTexture() {
return backgroundTexture;
}
public TerrainTexture getrTexture() {
return rTexture;
}
public TerrainTexture getgTexture() {
return gTexture;
}
public TerrainTexture getbTexture() {
return bTexture;
}
public TerrainTexture getBackgroundTexture()
{ return backgroundTexture; }
public TerrainTexture getrTexture()
{ return rTexture; }
public TerrainTexture getgTexture()
{ return gTexture; }
public TerrainTexture getbTexture()
{ return bTexture; }
}

View File

@ -21,67 +21,73 @@ import io.github.hydos.ginger.engine.renderEngine.texture.Image;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
import io.github.hydos.ginger.engine.terrain.TerrainTexture;
public class Loader {
public class Loader
{
private static List<Integer> vaos = new ArrayList<Integer>();
private static List<Integer> vbos = new ArrayList<Integer>();
public static int loadCubeMap(String[] textureFiles) {
public static int loadCubeMap(String[] textureFiles)
{
int texID = GL11.glGenTextures();
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL13.GL_TEXTURE_CUBE_MAP, texID);
for(int i=0;i<textureFiles.length;i++) {
// System.out.println("/textures/skybox/" + textureFiles[i]);
for (int i = 0; i < textureFiles.length; i++)
{
// System.out.println("/textures/skybox/" + textureFiles[i]);
Image data = Image.createImage("/textures/skybox/" + textureFiles[i]);
GL11.glTexImage2D(GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL11.GL_RGBA, data.getWidth(), data.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data.getImage());
}
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL13.GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
vaos.add(texID);
return texID;
}
private static void bindIndicesBuffer(int[] indices) {
private static void bindIndicesBuffer(int[] indices)
{
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
IntBuffer buffer = storeDataInIntBuffer(indices);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
}
public static RawModel loadToVAO(float[] positions, int dimensions) {
public static RawModel loadToVAO(float[] positions, int dimensions)
{
int vaoID = createVAO();
storeDataInAttributeList(0, dimensions, positions);
unbindVAO();
return new RawModel(vaoID, positions.length / dimensions);
}
private static IntBuffer storeDataInIntBuffer(int[] data) {
private static IntBuffer storeDataInIntBuffer(int[] data)
{
IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
private static int createVAO() {
private static int createVAO()
{
int vaoID = GL30.glGenVertexArrays();
vaos.add(vaoID);
GL30.glBindVertexArray(vaoID);
return vaoID;
}
public static int createEmptyVbo(int floatCount) {
public static int createEmptyVbo(int floatCount)
{
int vbo = GL15.glGenBuffers();
vbos.add(vbo);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, floatCount * 4, GL15.GL_STREAM_DRAW);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
return vbo;
}
public static void updateVbo(int vbo, float[] data, FloatBuffer buffer) {
public static void updateVbo(int vbo, float[] data, FloatBuffer buffer)
{
buffer.clear();
buffer.put(data);
buffer.flip();
@ -90,8 +96,9 @@ public class Loader {
GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, buffer);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
public static void addInstancedAttribute(int vao, int vbo, int att, int dataSize, int instancedDataLength, int offset) {
public static void addInstancedAttribute(int vao, int vbo, int att, int dataSize, int instancedDataLength, int offset)
{
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL30.glBindVertexArray(vao);
GL20.glVertexAttribPointer(att, dataSize, GL11.GL_FLOAT, false, instancedDataLength * 4, offset * 4);
@ -99,8 +106,9 @@ public class Loader {
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
}
private static void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {
private static void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data)
{
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
@ -109,36 +117,37 @@ public class Loader {
GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
private static void unbindVAO() {
GL30.glBindVertexArray(0);
}
private static FloatBuffer storeDataInFloatBuffer(float[] data) {
private static void unbindVAO()
{ GL30.glBindVertexArray(0); }
private static FloatBuffer storeDataInFloatBuffer(float[] data)
{
FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
public static void cleanUp() {
for(int vao:vaos) {
GL30.glDeleteVertexArrays(vao);
}
for(int vbo:vbos) {
GL15.glDeleteBuffers(vbo);
}
public static void cleanUp()
{
for (int vao : vaos)
{ GL30.glDeleteVertexArrays(vao); }
for (int vbo : vbos)
{ GL15.glDeleteBuffers(vbo); }
}
public static int loadToVAO(float[] positions, float[] textureCoords) {
public static int loadToVAO(float[] positions, float[] textureCoords)
{
int vaoID = createVAO();
storeDataInAttributeList(0, 2, positions);
storeDataInAttributeList(1, 2, textureCoords);
unbindVAO();
return vaoID;
}
public static RawModel loadToVAO(float[] positions, int[] indices, float[] normals, float[] textureCoords) {
public static RawModel loadToVAO(float[] positions, int[] indices, float[] normals, float[] textureCoords)
{
int vaoID = createVAO();
bindIndicesBuffer(indices);
storeDataInAttributeList(0, 3, positions);
@ -147,8 +156,9 @@ public class Loader {
unbindVAO();
return new RawModel(vaoID, indices.length);
}
public static RawModel loadToVAO(float[] positions, int[] indices, float[] normals, float[] tangents, float[] textureCoords) {
public static RawModel loadToVAO(float[] positions, int[] indices, float[] normals, float[] tangents, float[] textureCoords)
{
int vaoID = createVAO();
bindIndicesBuffer(indices);
storeDataInAttributeList(0, 3, positions);
@ -159,61 +169,65 @@ public class Loader {
return new RawModel(vaoID, indices.length);
}
public static TerrainTexture loadTerrainTexture(String string) {
return new TerrainTexture(new ModelTexture("terrain/" + string).getTextureID());
public static TerrainTexture loadTerrainTexture(String string)
{ return new TerrainTexture(new ModelTexture("terrain/" + string).getTextureID()); }
public static int loadTexture(String path)
{
int textureID = GL11.glGenTextures();
Image texture = Image.createImage("/textures/" + path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -1f);
if (Window.glContext.GL_EXT_texture_filter_anisotropic)
{//TODO: add option to use or disable
float amount = Math.min(4f, GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, amount);
}
else
System.out.println("anisotropic not supported!");
return textureID;
}
public static int loadTexture(String path) {
public static int loadTextureDirectly(String path)
{
int textureID = GL11.glGenTextures();
Image texture = Image.createImage("/textures/" + path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -1f);
if(Window.glContext.GL_EXT_texture_filter_anisotropic) {//TODO: add option to use or disable
float amount = Math.min(4f, GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, amount);
}else
System.out.println("anisotropic not supported!");
return textureID;
Image texture = Image.createImage(path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -1f);
if (Window.glContext.GL_EXT_texture_filter_anisotropic)
{//TODO: add option to use or disable
float amount = Math.min(4f, GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, amount);
}
else
System.out.println("anisotropic not supported!");
return textureID;
}
public static int loadTextureDirectly(String path) {
public static int loadFontAtlas(String path)
{
int textureID = GL11.glGenTextures();
Image texture = Image.createImage(path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -1f);
if(Window.glContext.GL_EXT_texture_filter_anisotropic) {//TODO: add option to use or disable
float amount = Math.min(4f, GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, amount);
}else
System.out.println("anisotropic not supported!");
return textureID;
Image texture = Image.createImage("/fonts/" + path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -0f);
return textureID;
}
public static int loadFontAtlas(String path) {
int textureID = GL11.glGenTextures();
Image texture = Image.createImage("/fonts/" + path);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10241, 9729.0f);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, 10240, 9729.0f);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texture.getImage());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, -0f);
return textureID;
}
}

View File

@ -10,31 +10,32 @@ import io.github.hydos.ginger.engine.renderEngine.models.RawModel;
import io.github.hydos.ginger.engine.renderEngine.models.TexturedModel;
import io.github.hydos.ginger.engine.renderEngine.texture.ModelTexture;
public class GingerMain {
public class GingerMain
{
public static UIManager manager;
public static void init() {
TextMaster.init();
manager = new UIManager(UIColourType.dark);
public static void init()
{
TextMaster.init();
manager = new UIManager(UIColourType.dark);
}
public static TexturedModel createTexturedModel(String texturePath, String modelPath) {
public static TexturedModel createTexturedModel(String texturePath, String modelPath)
{
TexturedModel model = ModelLoader.loadModel(modelPath, texturePath);
return model;
}
public static TexturedModel createTexturedModel(String texturePath, String modelPath, String normalMapPath) {
public static TexturedModel createTexturedModel(String texturePath, String modelPath, String normalMapPath)
{
RawModel model = NormalMappedObjLoader.loadOBJ(modelPath);
TexturedModel texturedModel = new TexturedModel(model, new ModelTexture(texturePath));
return texturedModel;
}
public static void update() {
manager.update();
}
public static void preRenderScene(MasterRenderer renderer) {
renderer.renderGui(manager.getBackgroundTexture());
}
public static void update()
{ manager.update(); }
public static void preRenderScene(MasterRenderer renderer)
{ renderer.renderGui(manager.getBackgroundTexture()); }
}

View File

@ -1,20 +1,15 @@
package io.github.hydos.ginger.main.settings;
public class Constants {
public class Constants
{
//player variables
public static float gravity = 0;
public static float jumpPower = 0;
public static float turnSpeed = 0;
public static float movementSpeed = 0;
public static float movementSpeed = 0;
//terrain variables
public static float terrainSize = 100;
public static float terrainMaxHeight = 10;
//FPS/UPS
public static final double NS = 1000000000/60.0;
public static final double NS = 1000000000 / 60.0;
}

View File

@ -1,10 +1,6 @@
package io.github.hydos.ginger.main.tools;
public class GSceneBuilder {
/**
*
* The class for turning GScene files into the engine parts in java
*/
public class GSceneBuilder
{
/** The class for turning GScene files into the engine parts in java */
}

Some files were not shown because too many files have changed in this diff Show More