diff --git a/pom.xml b/pom.xml index 446590e8..8d1df178 100644 --- a/pom.xml +++ b/pom.xml @@ -108,6 +108,13 @@ TerrainGen 0.1 + + + electrosphere + RendererNetworkParser + 0.1 + + @@ -160,13 +167,23 @@ - main.Main + true + electrosphere.main.Main jar-with-dependencies + + + assemble-all + package + + single + + + diff --git a/src/main/java/electrosphere/cfg/MainConfig.java b/src/main/java/electrosphere/cfg/MainConfig.java index 71d985e6..a11f2d82 100644 --- a/src/main/java/electrosphere/cfg/MainConfig.java +++ b/src/main/java/electrosphere/cfg/MainConfig.java @@ -19,7 +19,7 @@ import java.util.logging.Logger; public class MainConfig { //localconfig.json version - public static final int CONFIG_FILE_VERSION = 2; + public static final int CONFIG_FILE_VERSION = 4; //physical file version public int version; @@ -32,7 +32,8 @@ public class MainConfig { // //should we run a server at all? public boolean runServer; - + public boolean runClient; + public String serverAddress; // //Rendering related @@ -82,6 +83,12 @@ public class MainConfig { } else { Globals.mainConfig.runServer = false; } + System.out.println("Would you like to run the client?(1-y/0-n)"); + if(scan.nextInt() == 1){ + Globals.mainConfig.runClient = true; + } else { + Globals.mainConfig.runClient = false; + } System.out.println("Would you like to run the renderer?(1-y/0-n)"); if(scan.nextInt() == 1){ Globals.mainConfig.runRenderer = true; diff --git a/src/main/java/electrosphere/controls/ControlHandler.java b/src/main/java/electrosphere/controls/ControlHandler.java index 5a00faaa..c88a3682 100644 --- a/src/main/java/electrosphere/controls/ControlHandler.java +++ b/src/main/java/electrosphere/controls/ControlHandler.java @@ -1,11 +1,13 @@ package electrosphere.controls; +import electrosphere.entity.CameraEntityUtils; import electrosphere.entity.CreatureUtils; -import electrosphere.entity.EntityUtil; +import electrosphere.entity.EntityUtils; import electrosphere.entity.state.MovementTree; import electrosphere.entity.state.MovementTree.MovementTreeState; import electrosphere.main.Globals; -import static electrosphere.main.Main.camera_Current; +import electrosphere.net.client.ClientNetworkMessage; +import electrosphere.net.message.EntityMessage; import electrosphere.util.Utilities; import java.util.HashMap; import java.util.List; @@ -68,86 +70,97 @@ public class ControlHandler { public void pollControls(){ - MovementTree movementTree = CreatureUtils.getEntityMovementTree(Globals.playerCharacter); - /* - Move forward - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD)){ - if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD)) == GLFW_PRESS){ - CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-camera_Current.pos_Center.x,0,-camera_Current.pos_Center.z).normalize()); - if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ - movementTree.start(); + if(Globals.playerCharacter != null){ + MovementTree movementTree = CreatureUtils.getEntityMovementTree(Globals.playerCharacter); + Vector3f cameraEyeVector = CameraEntityUtils.getCameraEye(Globals.playerCamera); + /* + Move forward + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD)){ + if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD)) == GLFW_PRESS){ + CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-cameraEyeVector.x,0,-cameraEyeVector.z).normalize()); + if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ + movementTree.start(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD, true); + Vector3f position = EntityUtils.getEntityPosition(Globals.playerCharacter); + EntityMessage outgoingMessage = EntityMessage.constructMoveMessage( + Globals.playerCharacter.getId(), + position.x, + position.y, + position.z + ); + Globals.clientConnection.queueOutgoingMessage(outgoingMessage); + } else { + if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD) == true){ + movementTree.slowdown(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD, false); } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD, true); - } else { - if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD) == true){ - movementTree.slowdown(); - } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_FORWARD, false); } - } - /* - Move backward - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD)){ - if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD)) == GLFW_PRESS){ - CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(camera_Current.pos_Center.x,0,camera_Current.pos_Center.z).normalize()); - if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ - movementTree.start(); + /* + Move backward + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD)){ + if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD)) == GLFW_PRESS){ + CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(cameraEyeVector.x,0,cameraEyeVector.z).normalize()); + if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ + movementTree.start(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD, true); + } else { + if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD) == true){ + movementTree.slowdown(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD, false); } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD, true); - } else { - if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD) == true){ - movementTree.slowdown(); - } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_BACKWARD, false); } - } - /* - Move left - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT)){ - if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT)) == GLFW_PRESS){ - CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-camera_Current.pos_Center.x,0,-camera_Current.pos_Center.z).rotateY((float)(90 * Math.PI / 180)).normalize()); - if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ - movementTree.start(); + /* + Move left + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT)){ + if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT)) == GLFW_PRESS){ + CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-cameraEyeVector.x,0,-cameraEyeVector.z).rotateY((float)(90 * Math.PI / 180)).normalize()); + if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ + movementTree.start(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT, true); + } else { + if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT) == true){ + movementTree.slowdown(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT, false); } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT, true); - } else { - if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT) == true){ - movementTree.slowdown(); - } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_LEFT, false); } - } - /* - Move right - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT)){ - if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT)) == GLFW_PRESS){ - CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-camera_Current.pos_Center.x,0,-camera_Current.pos_Center.z).rotateY((float)(-90 * Math.PI / 180)).normalize()); - if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ - movementTree.start(); + /* + Move right + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT)){ + if(glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT)) == GLFW_PRESS){ + CreatureUtils.setMovementVector(Globals.playerCharacter, new Vector3f(-cameraEyeVector.x,0,-cameraEyeVector.z).rotateY((float)(-90 * Math.PI / 180)).normalize()); + if(movementTree.getState()==MovementTreeState.IDLE || movementTree.getState()==MovementTreeState.SLOWDOWN){ + movementTree.start(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT, true); + } else { + if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT) == true){ + movementTree.slowdown(); + } + controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT, false); } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT, true); - } else { - if(controlsState.get(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT) == true){ - movementTree.slowdown(); - } - controlsState.put(DATA_STRING_INPUT_CODE_MOVEMENT_RIGHT, false); } - } - /* - Move up - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_JUMP) && glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_JUMP)) == GLFW_PRESS){ - EntityUtil.getEntityPosition(Globals.playerCharacter).add(new Vector3f(0,0.6f,0).mul(1f)); - } - /* - Move down - */ - if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_FALL) && glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_FALL)) == GLFW_PRESS){ - EntityUtil.getEntityPosition(Globals.playerCharacter).add(new Vector3f(0,-0.6f,0).mul(1f)); + /* + Move up + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_JUMP) && glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_JUMP)) == GLFW_PRESS){ + EntityUtils.getEntityPosition(Globals.playerCharacter).add(new Vector3f(0,0.6f,0).mul(1f)); + } + /* + Move down + */ + if(controlsMap.containsKey(DATA_STRING_INPUT_CODE_MOVEMENT_FALL) && glfwGetKey(Globals.window, controlsMap.get(DATA_STRING_INPUT_CODE_MOVEMENT_FALL)) == GLFW_PRESS){ + EntityUtils.getEntityPosition(Globals.playerCharacter).add(new Vector3f(0,-0.6f,0).mul(1f)); + } } } diff --git a/src/main/java/electrosphere/entity/CameraEntityUtils.java b/src/main/java/electrosphere/entity/CameraEntityUtils.java index 946c06b1..a809c231 100644 --- a/src/main/java/electrosphere/entity/CameraEntityUtils.java +++ b/src/main/java/electrosphere/entity/CameraEntityUtils.java @@ -1,6 +1,7 @@ package electrosphere.entity; import electrosphere.main.Globals; +import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -11,19 +12,21 @@ import org.joml.Vector3f; public class CameraEntityUtils { - public static Entity spawnBasicCameraEntity(Vector3f position){ + public static Entity spawnBasicCameraEntity(Vector3f center, Vector3f eye){ Entity rVal = new Entity(); Globals.entityManager.registerEntity(rVal); + rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_TYPE, EntityDataStrings.DATA_STRING_CAMERA_TYPE_BASIC); + rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_CENTER, center); + rVal.putData(EntityDataStrings .DATA_STRING_CAMERA_EYE, eye); return rVal; } - public static Entity spawnOrbitalCameraEntity(Entity target, float distance){ + public static Entity spawnPointTrackingCameraEntity(Vector3f center, Vector3f eye){ Entity rVal = new Entity(); - rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_TYPE, EntityDataStrings.DATA_STRING_CAMERA_TYPE_ORBIT); - rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_ORBIT_TARGET, target); - rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_POSITION, new Vector3f(0,0,0)); - rVal.putData(EntityDataStrings .DATA_STRING_CAMERA_ROTATION, new Quaternionf()); Globals.entityManager.registerEntity(rVal); + rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_TYPE, EntityDataStrings.DATA_STRING_CAMERA_TYPE_ORBIT); + rVal.putData(EntityDataStrings.DATA_STRING_CAMERA_CENTER, center); + rVal.putData(EntityDataStrings .DATA_STRING_CAMERA_EYE, eye); return rVal; } @@ -35,20 +38,20 @@ public class CameraEntityUtils { return (float)camera.getData(EntityDataStrings.DATA_STRING_CAMERA_ORBIT_DISTANCE); } - public static void setCameraPosition(Entity camera, Vector3f position){ - camera.putData(EntityDataStrings.DATA_STRING_CAMERA_POSITION, position); + public static void setCameraCenter(Entity camera, Vector3f center){ + camera.putData(EntityDataStrings.DATA_STRING_CAMERA_CENTER, center); } - public static Vector3f getCameraPosition(Entity camera){ - return (Vector3f)camera.getData(EntityDataStrings.DATA_STRING_CAMERA_POSITION); + public static Vector3f getCameraCenter(Entity camera){ + return (Vector3f)camera.getData(EntityDataStrings.DATA_STRING_CAMERA_CENTER); } - public static void setCameraRotation(Entity camera, Quaternionf rotation){ - camera.putData(EntityDataStrings.DATA_STRING_CAMERA_ROTATION, rotation); + public static void setCameraEye(Entity camera, Vector3f eye){ + camera.putData(EntityDataStrings.DATA_STRING_CAMERA_EYE, eye); } - public static Quaternionf getCameraRotation(Entity camera){ - return (Quaternionf)camera.getData(EntityDataStrings.DATA_STRING_CAMERA_ROTATION); + public static Vector3f getCameraEye(Entity camera){ + return (Vector3f)camera.getData(EntityDataStrings.DATA_STRING_CAMERA_EYE); } public static void destroyCameraEntity(Entity e){ @@ -57,4 +60,13 @@ public class CameraEntityUtils { } } + public static Matrix4f getCameraViewMatrix(Vector3f cameraEye){ + Matrix4f rVal = new Matrix4f().setLookAt( + cameraEye, //eye + new Vector3f(0,0,0), //center + new Vector3f(cameraEye).add(new Vector3f(0,1.0f,0)) // up + ).scale(1.0f, 1.5f, 1.0f); + return rVal; + } + } diff --git a/src/main/java/electrosphere/entity/CreatureUtils.java b/src/main/java/electrosphere/entity/CreatureUtils.java index 554ef43a..395bc7d5 100644 --- a/src/main/java/electrosphere/entity/CreatureUtils.java +++ b/src/main/java/electrosphere/entity/CreatureUtils.java @@ -2,7 +2,10 @@ package electrosphere.entity; import electrosphere.entity.state.MovementTree; import electrosphere.main.Globals; +import electrosphere.main.Main; +import electrosphere.net.message.EntityMessage; import electrosphere.renderer.Model; +import electrosphere.util.ModelLoader; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -11,9 +14,12 @@ import org.joml.Vector3f; * @author amaterasu */ public class CreatureUtils { - public static Entity spawnBasicControllableEntity(Model m, float acceleration, float maxVelocity){ + public static Entity spawnBasicCreature(int creatureId, float acceleration, float maxVelocity){ Entity rVal = new Entity(); - rVal.putData(EntityDataStrings.DATA_STRING_MODEL, m); + rVal.putData(EntityDataStrings.DATA_STRING_CREATURE_IS_CREATURE, true); + rVal.putData(EntityDataStrings.DATA_STRING_MODEL_PATH, Globals.entityTypeMap.get(creatureId).getModelPath()); + Globals.assetManager.addModelPathToQueue(Globals.entityTypeMap.get(creatureId).getModelPath()); + rVal.putData(EntityDataStrings.DATA_STRING_CREATURE_TYPE, creatureId); rVal.putData(EntityDataStrings.DATA_STRING_POSITION, new Vector3f(0,0,0)); rVal.putData(EntityDataStrings.DATA_STRING_ROTATION, new Quaternionf().rotateAxis((float)0, new Vector3f(1,0,0))); rVal.putData(EntityDataStrings.DATA_STRING_SCALE, new Vector3f(1,1,1)); @@ -63,4 +69,28 @@ public class CreatureUtils { public static MovementTree getEntityMovementTree(Entity e){ return (MovementTree)e.getData(EntityDataStrings.DATA_STRING_MOVEMENT_BT); } + + public static void attachEntityMessageToMovementTree(Entity e, EntityMessage em){ + getEntityMovementTree(e).addNetworkMessage(em); + } + + public static int getCreatureType(Entity e){ + return (int)e.getData(EntityDataStrings.DATA_STRING_CREATURE_TYPE); + } + + public static int getControllerPlayerId(Entity e){ + return (int)e.getData(EntityDataStrings.DATA_STRING_CREATURE_CONTROLLER_PLAYER_ID); + } + + public static void setControllerPlayerId(Entity e, int id){ + e.putData(EntityDataStrings.DATA_STRING_CREATURE_CONTROLLER_PLAYER_ID, id); + } + + public static boolean hasControllerPlayerId(Entity e){ + return e.getDataKeys().contains(EntityDataStrings.DATA_STRING_CREATURE_CONTROLLER_PLAYER_ID); + } + + public static boolean isCreature(Entity e){ + return e.getDataKeys().contains(EntityDataStrings.DATA_STRING_CREATURE_IS_CREATURE); + } } diff --git a/src/main/java/electrosphere/entity/Entity.java b/src/main/java/electrosphere/entity/Entity.java index ff1d60a5..6b3c6217 100644 --- a/src/main/java/electrosphere/entity/Entity.java +++ b/src/main/java/electrosphere/entity/Entity.java @@ -26,6 +26,10 @@ public class Entity { public int getId() { return id; } + + public void setId(int id){ + this.id = id; + } // HashMap getData() { // return data; diff --git a/src/main/java/electrosphere/entity/EntityDataStrings.java b/src/main/java/electrosphere/entity/EntityDataStrings.java index 33fbaaac..a369eb9a 100644 --- a/src/main/java/electrosphere/entity/EntityDataStrings.java +++ b/src/main/java/electrosphere/entity/EntityDataStrings.java @@ -12,12 +12,15 @@ public class EntityDataStrings { public static final String DATA_STRING_POSITION = "position"; public static final String DATA_STRING_ROTATION = "rotation"; public static final String DATA_STRING_SCALE = "scale"; - public static final String DATA_STRING_MODEL = "model"; + public static final String DATA_STRING_MODEL_PATH = "modelPath"; /* - Moveable Entity + Creature Entity */ + public static final String DATA_STRING_CREATURE_IS_CREATURE = "isCreature"; + public static final String DATA_STRING_CREATURE_TYPE = "creatureType"; + public static final String DATA_STRING_CREATURE_CONTROLLER_PLAYER_ID = "creaturePlayerId"; public static final String DATA_STRING_MOVEMENT_BT = "movementBT"; public static final String DATA_STRING_MOVEMENT_VECTOR = "movementVector"; public static final String DATA_STRING_VELOCITY = "velocity"; @@ -29,9 +32,10 @@ public class EntityDataStrings { */ public static final String DATA_STRING_CAMERA_TYPE = "cameraType"; + public static final String DATA_STRING_CAMERA_TYPE_BASIC = "cameraTypeBasic"; public static final String DATA_STRING_CAMERA_TYPE_ORBIT = "cameraTypeOrbit"; - public static final String DATA_STRING_CAMERA_POSITION = "cameraPosition"; - public static final String DATA_STRING_CAMERA_ROTATION = "cameraRotation"; + public static final String DATA_STRING_CAMERA_EYE = "cameraEye"; + public static final String DATA_STRING_CAMERA_CENTER = "cameraCenter"; /* diff --git a/src/main/java/electrosphere/entity/EntityManager.java b/src/main/java/electrosphere/entity/EntityManager.java index 15775faf..39b57ef5 100644 --- a/src/main/java/electrosphere/entity/EntityManager.java +++ b/src/main/java/electrosphere/entity/EntityManager.java @@ -1,6 +1,7 @@ package electrosphere.entity; import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** @@ -9,17 +10,18 @@ import java.util.concurrent.CopyOnWriteArrayList; */ public class EntityManager { - static CopyOnWriteArrayList entityList; - static CopyOnWriteArrayList drawableList; - static CopyOnWriteArrayList moveableList; + + static ConcurrentHashMap entityIdMap = new ConcurrentHashMap(); + static CopyOnWriteArrayList entityList = new CopyOnWriteArrayList(); + static CopyOnWriteArrayList drawableList = new CopyOnWriteArrayList(); + static CopyOnWriteArrayList moveableList = new CopyOnWriteArrayList(); public EntityManager(){ - entityList = new CopyOnWriteArrayList(); - drawableList = new CopyOnWriteArrayList(); - moveableList = new CopyOnWriteArrayList(); + } public void registerEntity(Entity e){ + entityIdMap.put(e.getId(), e); entityList.add(e); } @@ -27,26 +29,38 @@ public class EntityManager { drawableList.add(e); } - public Iterator getDrawableIterator(){ - return drawableList.iterator(); + public CopyOnWriteArrayList getDrawable(){ + return drawableList; } public void registerMoveableEntity(Entity e){ moveableList.add(e); } - public Iterator getMoveableIterator(){ - return moveableList.iterator(); + public CopyOnWriteArrayList getMoveable(){ + return moveableList; } public void deregisterEntity(Entity e){ if(drawableList.contains(e)){ drawableList.remove(e); - EntityUtil.cleanUpDrawableEntity(e); + EntityUtils.cleanUpDrawableEntity(e); } if(entityList.contains(e)){ entityList.remove(e); } } + public void overrideEntityId(Entity e, int id){ + if(entityIdMap.contains(e.getId())){ + entityIdMap.remove(e.getId()); + } + e.setId(id); + entityIdMap.put(e.getId(), e); + } + + public Entity getEntityFromId(int id){ + return (Entity)entityIdMap.get(id); + } + } diff --git a/src/main/java/electrosphere/entity/EntityUtil.java b/src/main/java/electrosphere/entity/EntityUtils.java similarity index 75% rename from src/main/java/electrosphere/entity/EntityUtil.java rename to src/main/java/electrosphere/entity/EntityUtils.java index f1a41fcc..6fa753e5 100644 --- a/src/main/java/electrosphere/entity/EntityUtil.java +++ b/src/main/java/electrosphere/entity/EntityUtils.java @@ -15,7 +15,7 @@ import org.joml.Vector3f; * * @author amaterasu */ -public class EntityUtil { +public class EntityUtils { public static Vector3f getEntityPosition(Entity e){ return (Vector3f)e.getData(EntityDataStrings.DATA_STRING_POSITION); @@ -29,13 +29,13 @@ public class EntityUtil { return (Vector3f)e.getData(EntityDataStrings.DATA_STRING_SCALE); } - public static Model getEntityModel(Entity e){ - return (Model)e.getData(EntityDataStrings.DATA_STRING_MODEL); + public static String getEntityModelPath(Entity e){ + return (String)e.getData(EntityDataStrings.DATA_STRING_MODEL_PATH); } - public static Entity spawnDrawableEntity(Model m){ + public static Entity spawnDrawableEntity(String modelPath){ Entity rVal = new Entity(); - rVal.putData(EntityDataStrings.DATA_STRING_MODEL, m); + rVal.putData(EntityDataStrings.DATA_STRING_MODEL_PATH, modelPath); rVal.putData(EntityDataStrings.DATA_STRING_POSITION, new Vector3f(0,0,0)); rVal.putData(EntityDataStrings.DATA_STRING_ROTATION, new Quaternionf().rotateAxis((float)0, new Vector3f(1,0,0))); rVal.putData(EntityDataStrings.DATA_STRING_SCALE, new Vector3f(1,1,1)); @@ -47,7 +47,13 @@ public class EntityUtil { public static void cleanUpDrawableEntity(Entity e){ if(e != null){ Globals.entityManager.deregisterEntity(e); - getEntityModel(e).free(); +// getEntityModelPath(e).free(); } } + + public static void setEntityID(Entity e, int id){ + Globals.entityManager.overrideEntityId(e, id); + } + + } diff --git a/src/main/java/electrosphere/entity/state/MovementTree.java b/src/main/java/electrosphere/entity/state/MovementTree.java index efa27acb..f319bd91 100644 --- a/src/main/java/electrosphere/entity/state/MovementTree.java +++ b/src/main/java/electrosphere/entity/state/MovementTree.java @@ -2,10 +2,14 @@ package electrosphere.entity.state; import electrosphere.entity.CreatureUtils; import electrosphere.entity.Entity; -import electrosphere.entity.EntityUtil; +import electrosphere.entity.EntityUtils; import electrosphere.main.Globals; +import electrosphere.net.NetUtils; +import electrosphere.net.message.EntityMessage; import electrosphere.renderer.Animation; import electrosphere.renderer.Model; +import java.util.LinkedList; +import java.util.concurrent.CopyOnWriteArrayList; import org.joml.Vector3f; /** @@ -28,6 +32,8 @@ public class MovementTree { Entity parent; + CopyOnWriteArrayList networkMessageQueue = new CopyOnWriteArrayList(); + public MovementTree(Entity e){ state = MovementTreeState.IDLE; parent = e; @@ -69,18 +75,35 @@ public class MovementTree { float velocity = CreatureUtils.getVelocity(parent); float acceleration = CreatureUtils.getAcceleration(parent); float maxNaturalVelocity = CreatureUtils.getMaxNaturalVelocity(parent); - Model entityModel = EntityUtil.getEntityModel(parent); - Vector3f position = EntityUtil.getEntityPosition(parent); + Model entityModel = Globals.assetManager.fetchModel(EntityUtils.getEntityModelPath(parent)); + Vector3f position = EntityUtils.getEntityPosition(parent); Vector3f movementVector = CreatureUtils.getMovementVector(parent); - System.out.println(movementVector); + + //parse attached network messages + for(EntityMessage message : networkMessageQueue){ + networkMessageQueue.remove(message); +// System.out.println("MOVE to " + message.getX() + " " + message.getY() + " " + message.getZ()); + switch(message.getEntityMessageType()){ + case MOVE: + position.set(message.getX(), message.getY(), message.getZ()); + if(Globals.mainConfig.runServer){ + Globals.server.broadcastMessage(EntityMessage.constructMoveMessage(parent.getId(), message.getX(), message.getY(), message.getZ())); + } + break; + } + } + + //state machine switch(state){ case STARTUP: //run startup code velocity = velocity + acceleration; CreatureUtils.setVelocity(parent, velocity); - if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_STARTUP)){ - entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_STARTUP); - entityModel.currentAnimation.incrementTime(0.01); + if(entityModel != null){ + if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_STARTUP)){ + entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_STARTUP); + entityModel.currentAnimation.incrementTime(0.01); + } } //check if can transition state if(velocity >= maxNaturalVelocity){ @@ -89,29 +112,33 @@ public class MovementTree { } //move the entity position.add(new Vector3f(movementVector).mul(velocity)); - position.y = Globals.cellManager.getElevationAtRealPoint(position.x, position.z); - EntityUtil.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); + position.y = Globals.drawCellManager.getElevationAtRealPoint(position.x, position.z); + EntityUtils.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); break; case MOVE: //check if can restart animation //if yes, restart animation - if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_MOVE)){ - entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_MOVE); - entityModel.currentAnimation.incrementTime(0.01); + if(entityModel != null){ + if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_MOVE)){ + entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_MOVE); + entityModel.currentAnimation.incrementTime(0.01); + } } //check if can move forward (collision engine) //if can, move forward by entity movement stats position.add(new Vector3f(movementVector).mul(velocity)); - position.y = Globals.cellManager.getElevationAtRealPoint(position.x, position.z); - EntityUtil.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); + position.y = Globals.drawCellManager.getElevationAtRealPoint(position.x, position.z); + EntityUtils.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); break; case SLOWDOWN: //run slowdown code velocity = velocity - acceleration; CreatureUtils.setVelocity(parent, velocity); - if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_STARTUP)){ - entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_STARTUP); - entityModel.currentAnimation.incrementTime(0.01); + if(entityModel != null){ + if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_MOVEMENT_STARTUP)){ + entityModel.playAnimation(Animation.ANIMATION_MOVEMENT_STARTUP); + entityModel.currentAnimation.incrementTime(0.01); + } } //check if can transition state if(velocity <= 0){ @@ -120,17 +147,25 @@ public class MovementTree { } //move the entity position.add(new Vector3f(movementVector).mul(velocity)); - position.y = Globals.cellManager.getElevationAtRealPoint(position.x, position.z); - EntityUtil.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); + position.y = Globals.drawCellManager.getElevationAtRealPoint(position.x, position.z); + EntityUtils.getEntityRotation(parent).rotationTo(new Vector3f(0,0,1), movementVector); break; case IDLE: - if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_IDLE_1)){ - entityModel.playAnimation(Animation.ANIMATION_IDLE_1); - entityModel.currentAnimation.incrementTime(0.01); + if(entityModel != null){ + if(entityModel.currentAnimation == null || !entityModel.currentAnimation.name.equals(Animation.ANIMATION_IDLE_1)){ + entityModel.playAnimation(Animation.ANIMATION_IDLE_1); + entityModel.currentAnimation.incrementTime(0.01); + } } break; } } + + public void addNetworkMessage(EntityMessage networkMessage) { + networkMessageQueue.add(networkMessage); + } + + } diff --git a/src/main/java/electrosphere/entity/types/creature/CreatureType.java b/src/main/java/electrosphere/entity/types/creature/CreatureType.java new file mode 100644 index 00000000..c0c79373 --- /dev/null +++ b/src/main/java/electrosphere/entity/types/creature/CreatureType.java @@ -0,0 +1,27 @@ +package electrosphere.entity.types.creature; + +/** + * + * @author amaterasu + */ +public class CreatureType { + int id; + String modelPath; + + public int getId() { + return id; + } + + public String getModelPath() { + return modelPath; + } + + public void setId(int id) { + this.id = id; + } + + public void setModelPath(String modelPath) { + this.modelPath = modelPath; + } + +} diff --git a/src/main/java/electrosphere/entity/types/creature/CreatureTypeList.java b/src/main/java/electrosphere/entity/types/creature/CreatureTypeList.java new file mode 100644 index 00000000..02702989 --- /dev/null +++ b/src/main/java/electrosphere/entity/types/creature/CreatureTypeList.java @@ -0,0 +1,16 @@ +package electrosphere.entity.types.creature; + +import java.util.List; + +/** + * + * @author amaterasu + */ +public class CreatureTypeList { + List types; + + public List getTypes() { + return types; + } + +} diff --git a/src/main/java/electrosphere/game/cell/DrawCell.java b/src/main/java/electrosphere/game/cell/DrawCell.java index 4d2a1d5a..960ce615 100644 --- a/src/main/java/electrosphere/game/cell/DrawCell.java +++ b/src/main/java/electrosphere/game/cell/DrawCell.java @@ -1,7 +1,7 @@ package electrosphere.game.cell; import electrosphere.entity.Entity; -import electrosphere.entity.EntityUtil; +import electrosphere.entity.EntityUtils; import electrosphere.main.Globals; import electrosphere.renderer.Model; import electrosphere.renderer.ModelUtils; @@ -44,13 +44,14 @@ public class DrawCell { Globals.entityManager.deregisterEntity(modelEntity); } Model terrainModel = ModelUtils.createTerrainModelPrecomputedShader(drawArray, program, stride); - modelEntity = EntityUtil.spawnDrawableEntity(terrainModel); + String terrainModelPath = Globals.assetManager.registerModel(terrainModel); + modelEntity = EntityUtils.spawnDrawableEntity(terrainModelPath); // System.out.println("New cell @ " + cellX * cellWidth + "," + cellY * cellWidth); - EntityUtil.getEntityPosition(modelEntity).set(new Vector3f(cellX * cellWidth, 0.01f, cellY * cellWidth)); + EntityUtils.getEntityPosition(modelEntity).set(new Vector3f(cellX * cellWidth, 0.01f, cellY * cellWidth)); } public void retireCell(){ - EntityUtil.cleanUpDrawableEntity(modelEntity); + EntityUtils.cleanUpDrawableEntity(modelEntity); } } diff --git a/src/main/java/electrosphere/game/cell/CellManager.java b/src/main/java/electrosphere/game/cell/DrawCellManager.java similarity index 98% rename from src/main/java/electrosphere/game/cell/CellManager.java rename to src/main/java/electrosphere/game/cell/DrawCellManager.java index 997f8964..e4f242e7 100644 --- a/src/main/java/electrosphere/game/cell/CellManager.java +++ b/src/main/java/electrosphere/game/cell/DrawCellManager.java @@ -9,7 +9,7 @@ import org.joml.Vector3f; * * @author satellite */ -public class CellManager { +public class DrawCellManager { //the terrain manager this cell manager constructs off of TerrainManager terrainManager; @@ -36,7 +36,7 @@ public class CellManager { int drawStepdownInterval = 3; int drawStepdownValue = 5; - public CellManager(TerrainManager terrainManager, float realX, float realY){ + public DrawCellManager(TerrainManager terrainManager, float realX, float realY){ this.terrainManager = terrainManager; this.miniCellWidth = miniCellWidth; cells = new DrawCell[drawRadius * 2 + 1][drawRadius * 2 + 1]; diff --git a/src/main/java/electrosphere/game/simcell/entity/EntityCell.java b/src/main/java/electrosphere/game/simcell/entity/EntityCell.java new file mode 100644 index 00000000..a1cd1883 --- /dev/null +++ b/src/main/java/electrosphere/game/simcell/entity/EntityCell.java @@ -0,0 +1,40 @@ +package electrosphere.game.simcell.entity; + +import electrosphere.entity.Entity; +import electrosphere.entity.EntityUtils; +import java.util.concurrent.CopyOnWriteArrayList; +import org.joml.Vector3f; + +/** + * + * @author satellite + */ +public class EntityCell { + int realWorldXStart; + int realWorldYStart; + int width; + + CopyOnWriteArrayList residentEntities = new CopyOnWriteArrayList(); + + public boolean containsPoint(Vector3f position){ + float x = position.x; + float z = position.z; + return x >=realWorldXStart && + x < realWorldXStart + width && + z >=realWorldYStart && + z < realWorldYStart + width; + } + + public CopyOnWriteArrayList getResidentEntities(){ + return residentEntities; + } + + public void simulate(){ + for(Entity entity : residentEntities){ + if(!containsPoint(EntityUtils.getEntityPosition(entity))){ + residentEntities.remove(entity); + } + } + } + +} diff --git a/src/main/java/electrosphere/game/simcell/physical/PhysicalCell.java b/src/main/java/electrosphere/game/simcell/physical/PhysicalCell.java deleted file mode 100644 index 5630b7d6..00000000 --- a/src/main/java/electrosphere/game/simcell/physical/PhysicalCell.java +++ /dev/null @@ -1,9 +0,0 @@ -package electrosphere.game.simcell.physical; - -/** - * - * @author satellite - */ -public class PhysicalCell { - -} diff --git a/src/main/java/electrosphere/game/simcell/virtual/VirtualCell.java b/src/main/java/electrosphere/game/simcell/virtual/VirtualCell.java deleted file mode 100644 index 94a78154..00000000 --- a/src/main/java/electrosphere/game/simcell/virtual/VirtualCell.java +++ /dev/null @@ -1,9 +0,0 @@ -package electrosphere.game.simcell.virtual; - -/** - * - * @author satellite - */ -public class VirtualCell { - -} diff --git a/src/main/java/electrosphere/main/Globals.java b/src/main/java/electrosphere/main/Globals.java index a8b07166..d9ee0221 100644 --- a/src/main/java/electrosphere/main/Globals.java +++ b/src/main/java/electrosphere/main/Globals.java @@ -13,8 +13,13 @@ import electrosphere.cfg.MainConfig; import electrosphere.controls.ControlHandler; import electrosphere.entity.Entity; import electrosphere.entity.EntityManager; -import electrosphere.game.cell.CellManager; -import electrosphere.net.client.Connection; +import electrosphere.entity.types.creature.CreatureType; +import electrosphere.entity.types.creature.CreatureTypeList; +import electrosphere.game.cell.DrawCellManager; +import electrosphere.game.terrain.TerrainManager; +import electrosphere.net.client.ClientNetworking; +import electrosphere.net.server.Server; +import electrosphere.renderer.assetmanager.AssetManager; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -24,6 +29,8 @@ import java.util.logging.Logger; import org.joml.Matrix4f; import org.joml.Vector3f; import electrosphere.util.ModelLoader; +import electrosphere.util.Utilities; +import java.util.HashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.lwjgl.glfw.GLFWErrorCallback; @@ -43,7 +50,12 @@ public class Globals { // //Client connection to server // - public static Connection connection; + public static ClientNetworking clientConnection; + + // + //Server manager thing + // + public static Server server; // @@ -52,6 +64,12 @@ public class Globals { public static ControlHandler controlHandler; + // + //Entity Types Map + // + public static HashMap entityTypeMap = new HashMap(); + + // //Generic OpenGL Statements @@ -83,7 +101,10 @@ public class Globals { public static EntityManager entityManager; - public static Camera cameraVisible; + public static TerrainManager terrainManager; + + + public static AssetManager assetManager; // //Game specific models @@ -92,7 +113,7 @@ public class Globals { //chunk stuff //constant for how far in game units you have to move to load chunks - public static CellManager cellManager; + public static DrawCellManager drawCellManager; //famous fuckin last words, but temporary solution @@ -100,8 +121,6 @@ public class Globals { public static ArrayList skyboxColors; - //player's entity - //the player camera entity public static Entity playerCamera; @@ -112,6 +131,27 @@ public class Globals { public static void initGlobals(){ + + //load in default texture map + Gson gson = new Gson(); + try { + //deserializes the texture map from its default path using gson + //also done in one line + textureMapDefault = gson.fromJson(Files.newBufferedReader(new File(Thread.currentThread().getContextClassLoader().getResource("Textures/default_texture_map.json").getFile()).toPath()), TextureMap.class); //only the best of coding practices :) + } catch (IOException ex) { ex.printStackTrace(); } //TODO: handle better :tm: + //entity type map + initEntityTypeMap(); + //create entity manager + entityManager = new EntityManager(); + //init game specific variables + initGameSpecifics(); + //temporary hold for skybox colors + skyboxColors = new ArrayList(); + //load asset manager + assetManager = new AssetManager(); + } + + public static void initDefaultResources(){ //create default textures textureDiffuseDefault = new Texture("Textures/default_diffuse.png"); textureSpecularDefault = new Texture("Textures/default_specular.png"); @@ -121,23 +161,15 @@ public class Globals { materialDefault.set_specular(textureSpecularDefault); //create default lights lightDirectionalDefault = new DirectionalLight(new Vector3f(0,-1f,0)); - //load in default texture map - Gson gson = new Gson(); - try { - //deserializes the texture map from its default path using gson - //also done in one line - textureMapDefault = gson.fromJson(Files.newBufferedReader(new File(Thread.currentThread().getContextClassLoader().getResource("Textures/default_texture_map.json").getFile()).toPath()), TextureMap.class); //only the best of coding practices :) - } catch (IOException ex) { ex.printStackTrace(); } //TODO: handle better :tm: - //create entity manager - entityManager = new EntityManager(); - //create the camera object that generates view matrix - cameraVisible = new Camera(); - //init game specific variables - initGameSpecifics(); - //temporary hold for skybox colors - skyboxColors = new ArrayList(); } public static void initGameSpecifics(){ } + + static void initEntityTypeMap(){ + CreatureTypeList typeList = Utilities.loadObjectFromJsonFile("/Data/entity_map.json", CreatureTypeList.class); + for(CreatureType type : typeList.getTypes()){ + entityTypeMap.put(type.getId(), type); + } + } } diff --git a/src/main/java/electrosphere/main/Main.java b/src/main/java/electrosphere/main/Main.java index cce765f7..478dd744 100644 --- a/src/main/java/electrosphere/main/Main.java +++ b/src/main/java/electrosphere/main/Main.java @@ -12,11 +12,12 @@ import electrosphere.renderer.RenderUtils; import electrosphere.renderer.ShaderProgram; import electrosphere.renderer.texture.Texture; import electrosphere.entity.Entity; -import electrosphere.entity.EntityUtil; +import electrosphere.entity.EntityUtils; import electrosphere.entity.state.MovementTree; -import electrosphere.game.cell.CellManager; +import electrosphere.game.cell.DrawCellManager; import electrosphere.game.terrain.TerrainManager; -import electrosphere.net.client.Connection; +import electrosphere.net.client.ClientNetworkMessage; +import electrosphere.net.client.ClientNetworking; import electrosphere.net.server.Server; import electrosphere.renderer.ModelUtils; import electrosphere.terraingen.TerrainGen; @@ -45,6 +46,7 @@ import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardOpenOption; +import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; @@ -69,7 +71,6 @@ public class Main { public static float lastFrame = 0.0f; //View Controls public static float view_Range = 200000.0f; - public static Camera camera_Current = new Camera(); /* Mouse Controls */ @@ -86,14 +87,6 @@ public class Main { - // - //Player Object Variables - // - public static boolean CAMERA_UNDER_USER_CONTROL = false; - public static boolean CAMERA_UNDER_FREE_CONTROL = false; - public static boolean PLAYER_UNDER_USER_CONTROL = true; - public static boolean CAMERA_IS_ORBIT = true; - public static float camera_Orbit_Length = 1.0f; static int playerStartRealX = 0; static int playerStartRealY = 0; @@ -105,8 +98,10 @@ public class Main { public static Model model; + public static int playerId = -1; - static TerrainManager terrainManager; + + static boolean running = true; @@ -120,13 +115,23 @@ public class Main { // // + //temporary prompt user for stuff + Scanner scan = new Scanner(System.in); + System.out.println("Run server?"); + if(scan.nextInt() == 1){ + Globals.mainConfig.runServer = true; + } else { + Globals.mainConfig.runServer = false; + System.out.println("Address?"); + Globals.mainConfig.serverAddress = scan.next(); + } + //controls initControlHandler(); - //run initialization stuff - - initWorld(); - + //init global variables + Globals.initGlobals(); + //run initialization stuff initTerrainManager(); @@ -135,13 +140,24 @@ public class Main { RenderUtils.createOpenglContext(); } - //init global variables - Globals.initGlobals(); - - if(Globals.mainConfig.runRenderer){ - forkConnection(); + //start server networking + Thread serverThread = null; + if(Globals.mainConfig.runServer){ + Globals.server = new Server(42536); + serverThread = new Thread(Globals.server); + serverThread.start(); } + //start client networking + Thread clientThread = null; + if(Globals.mainConfig.runClient){ + Globals.clientConnection = new ClientNetworking(Globals.mainConfig.serverAddress,42536); + clientThread = new Thread(Globals.clientConnection); + clientThread.start(); + } + + //init default resources + Globals.initDefaultResources(); if(Globals.mainConfig.runRenderer){ initCellManager(); @@ -151,21 +167,21 @@ public class Main { initPlayer(); + createPlayerCamera(); - - - Entity unitCube = EntityUtil.spawnDrawableEntity(ModelUtils.createUnitCube()); - EntityUtil.getEntityPosition(unitCube).set(playerStartRealX - 0.5f,10,playerStartRealY - 0.5f); +// String unitCubeModelPath = Globals.assetManager.registerModel(ModelUtils.createUnitCube()); +// Entity unitCube = EntityUtils.spawnDrawableEntity(unitCubeModelPath); +// EntityUtils.getEntityPosition(unitCube).set(playerStartRealX - 0.5f,10,playerStartRealY - 0.5f); RenderUtils.recaptureScreen(); /// /// C A M E R A C R E A T I O N /// - Camera camera_player_chase = new Camera(); Camera cam_Player_Orbit = new Camera(); + Vector3f cameraRotationVector = new Vector3f(); + - boolean running = true; //main loop while (running) { @@ -178,29 +194,24 @@ public class Main { lastFrame = currentFrame; - - //poll mouse variables and update camera variables - updateMouseVariables(); - - - float cam_Player_Orbit_Magnitude = 1f; - float cam_Player_Orbit_Offset_Height = 0f; - cam_Player_Orbit.pos_Center = new Vector3f(0, 0, 0); - cam_Player_Orbit.pos_Center.x = 0 + (float) Math.cos(yaw / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; - cam_Player_Orbit.pos_Center.y = 0 + (float) Math.sin(pitch / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; - cam_Player_Orbit.pos_Center.z = 0 + (float) Math.sin(yaw / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; - cam_Player_Orbit.pos_Center.normalize(); -// System.out.println(cam_Player_Orbit.pos_Center); + /// + /// A S S E T M A N A G E R S T U F F + /// + Globals.assetManager.loadAssetsInQueue(); - if(CAMERA_IS_ORBIT){ - camera_Current = cam_Player_Orbit; + + /// + /// C L I E N T N E T W O R K I N G S T U F F + /// + //Why is this its own function? Just to get the networking code out of main() + if(Globals.mainConfig.runClient){ + Globals.clientConnection.parseMessages(); } - /// /// I N P U T C O N T R O L S /// @@ -210,43 +221,59 @@ public class Main { } //Poll controls - Vector3f oldPlayerCharacterPosition = new Vector3f(EntityUtil.getEntityPosition(Globals.playerCharacter)); + Vector3f oldPlayerCharacterPosition = new Vector3f(); + if(Globals.playerCharacter != null){ + oldPlayerCharacterPosition = new Vector3f(EntityUtils.getEntityPosition(Globals.playerCharacter)); + } + Vector3f newPlayerCharacterPosition = oldPlayerCharacterPosition; Globals.controlHandler.pollControls(); + /// - /// C R E A T U R E S I M U L A T I O N T R E E S + /// C L I E N T S I M U L A T I O N S T U F F /// - Iterator moveablesIterator = Globals.entityManager.getMoveableIterator(); - while(moveablesIterator.hasNext()){ - Entity currentMoveable = moveablesIterator.next(); - MovementTree behaviorTree = CreatureUtils.getEntityMovementTree(currentMoveable); - behaviorTree.simulate(); + if(Globals.mainConfig.runClient){ + //simulate creature behavior trees + for(Entity currentMoveable : Globals.entityManager.getMoveable()){ + MovementTree behaviorTree = CreatureUtils.getEntityMovementTree(currentMoveable); + behaviorTree.simulate(); + } } - Vector3f newPlayerCharacterPosition = EntityUtil.getEntityPosition(Globals.playerCharacter); + /// - /// C E L L M A N A G E R + /// C L I E N T C E L L M A N A G E R /// - //Cell manager do your things - Globals.cellManager.calculateDeltas(oldPlayerCharacterPosition, newPlayerCharacterPosition); - Globals.cellManager.update(); + if(Globals.mainConfig.runRenderer){ + if(Globals.playerCharacter != null){ + newPlayerCharacterPosition = EntityUtils.getEntityPosition(Globals.playerCharacter); + } + //Cell manager do your things + Globals.drawCellManager.calculateDeltas(oldPlayerCharacterPosition, newPlayerCharacterPosition); + Globals.drawCellManager.update(); + } -// camera_player_chase.pos_Center = new Vector3f(EntityUtil.getEntityPosition(player)).sub(EntityUtil.getEntityRotation(player).transform(new Vector3f(-1,1,0))); /// /// C A M E R A S T U F F /// - Globals.cameraVisible.apply_camera(camera_player_chase); - - Globals.viewMatrix = Globals.cameraVisible.get_view_matrix(); - Globals.viewMatrix = new Matrix4f().setLookAt( - camera_Current.pos_Center, //eye - new Vector3f(0,0,0), //center - new Vector3f(camera_Current.pos_Center).add(new Vector3f(0,1.0f,0)) // up - ).scale(1.0f, 1.5f, 1.0f); + //poll mouse variables and update camera variables + updateMouseVariables(); + if(Globals.playerCharacter != null){ + CameraEntityUtils.setCameraCenter(Globals.playerCamera, EntityUtils.getEntityPosition(Globals.playerCharacter)); + } + float cam_Player_Orbit_Magnitude = 1f; +// cam_Player_Orbit.pos_Center = new Vector3f(0, 0, 0); + cameraRotationVector.x = 0 + (float) Math.cos(yaw / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; + cameraRotationVector.y = 0 + (float) Math.sin(pitch / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; + cameraRotationVector.z = 0 + (float) Math.sin(yaw / 180.0f * Math.PI) * cam_Player_Orbit_Magnitude; + cameraRotationVector.normalize(); + CameraEntityUtils.setCameraEye(Globals.playerCamera, cameraRotationVector); +// System.out.println(cam_Player_Orbit.pos_Center); + Globals.viewMatrix = CameraEntityUtils.getCameraViewMatrix(CameraEntityUtils.getCameraEye(Globals.playerCamera)); @@ -259,20 +286,20 @@ public class Main { // - // Draw all entities + // D R A W A L L E N T I T I E S // - Iterator entity_iterator = Globals.entityManager.getDrawableIterator(); - while(entity_iterator.hasNext()){ - Entity currentEntity = entity_iterator.next(); - Model currentModel = EntityUtil.getEntityModel(currentEntity); - if(currentModel.currentAnimation != null){ - currentModel.incrementTime(deltaTime * 500); + for(Entity currentEntity : Globals.entityManager.getDrawable()){ + Model currentModel = Globals.assetManager.fetchModel(EntityUtils.getEntityModelPath(currentEntity)); + if(currentModel != null){ + if(currentModel.currentAnimation != null){ + currentModel.incrementTime(deltaTime * 500); + } + currentModel.modelMatrix = new Matrix4f(); + currentModel.modelMatrix.translate(new Vector3f(EntityUtils.getEntityPosition(currentEntity)).sub(CameraEntityUtils.getCameraCenter(Globals.playerCamera)).sub(new Vector3f(0,1,0))); + currentModel.modelMatrix.rotate(EntityUtils.getEntityRotation(currentEntity)); + currentModel.modelMatrix.scale(EntityUtils.getEntityScale(currentEntity)); + currentModel.draw(); } - currentModel.modelMatrix = new Matrix4f(); - currentModel.modelMatrix.translate(new Vector3f(EntityUtil.getEntityPosition(currentEntity)).sub(EntityUtil.getEntityPosition(Globals.playerCharacter)).sub(new Vector3f(0,1,0))); - currentModel.modelMatrix.rotate(EntityUtil.getEntityRotation(currentEntity)); - currentModel.modelMatrix.scale(EntityUtil.getEntityScale(currentEntity)); - currentModel.draw(); } @@ -287,6 +314,9 @@ public class Main { } //Terminate the program. glfwTerminate(); + //used to signal threads to stop + running = false; + Globals.server.close(); } static void sleep(int i) { @@ -298,7 +328,9 @@ public class Main { } - + public static boolean isRunning(){ + return running; + } @@ -333,8 +365,9 @@ public class Main { static void initSkybox(){ Model skyboxModel = RenderUtils.createSkyboxModel(null); - Entity skyboxEntity = EntityUtil.spawnDrawableEntity(skyboxModel); - EntityUtil.getEntityScale(skyboxEntity).mul(100); + String skyboxModelPath = Globals.assetManager.registerModel(skyboxModel); + Entity skyboxEntity = EntityUtils.spawnDrawableEntity(skyboxModelPath); + EntityUtils.getEntityScale(skyboxEntity).mul(100); Globals.skyboxColors.add(new Vector3f(100,150,200)); @@ -352,12 +385,14 @@ public class Main { static void initTerrainManager(){ float[][] elevation; - terrainManager = new TerrainManager(2000,200,100,0.25f); - if(Globals.mainConfig.loadTerrain){ - terrainManager.load(); - } else { - terrainManager.generate(); - terrainManager.save(); + Globals.terrainManager = new TerrainManager(2000,200,100,0.25f); + if(Globals.mainConfig.runServer){ + if(Globals.mainConfig.loadTerrain){ + Globals.terrainManager.load(); + } else { + Globals.terrainManager.generate(); + Globals.terrainManager.save(); + } } @@ -368,27 +403,27 @@ public class Main { } static void initCellManager(){ - Globals.cellManager = new CellManager(terrainManager, playerStartRealX, playerStartRealY); + Globals.drawCellManager = new DrawCellManager(Globals.terrainManager, playerStartRealX, playerStartRealY); - while(Globals.cellManager.containsInvalidCell()){ - Globals.cellManager.updateInvalidCell(); + while(Globals.drawCellManager.containsInvalidCell()){ + Globals.drawCellManager.updateInvalidCell(); } - while(Globals.cellManager.containsUndrawableCell()){ - Globals.cellManager.makeCellDrawable(); + while(Globals.drawCellManager.containsUndrawableCell()){ + Globals.drawCellManager.makeCellDrawable(); } } static void initPlayer(){ int playerStartX = 0; int playerStartY = 0; - int discreteSize = terrainManager.getWorldDiscreteSize(); - int chunkSize = terrainManager.getChunkWidth(); + int discreteSize = Globals.terrainManager.getWorldDiscreteSize(); + int chunkSize = Globals.terrainManager.getChunkWidth(); boolean found = false; for(int x = 0; x < discreteSize; x++){ for(int y = 0; y < discreteSize; y++){ - if(terrainManager.getDiscreteValue(x, y)>0){ + if(Globals.terrainManager.getDiscreteValue(x, y)>0){ playerStartX = x; playerStartY = y; found = true; @@ -404,42 +439,25 @@ public class Main { playerStartRealX = playerStartX * chunkSize; playerStartRealY = playerStartY * chunkSize; -// Globals.player = CameraEntityUtils.spawnOrbitalCameraEntity(target, 3f); -// Globals.player.putData("position", new Vector3f(playerStartRealX,terrainManager.getHeightAtPosition(playerStartRealX, playerStartRealY),playerStartRealY)); - - /* - Entity playerCharacter = EntityUtil.spawnDrawableEntity(ModelLoader.load_Model_From_File("Models/person1walkanim.fbx")); - EntityUtil.getEntityPosition(playerCharacter).set(playerStartRealX - 0.5f,terrainManager.getHeightAtPosition(playerStartRealX, playerStartRealY),playerStartRealY - 0.5f); - Model playerCharacterModel = EntityUtil.getEntityModel(playerCharacter); - EntityUtil.getEntityScale(playerCharacter).set(0.005f); -// playerCharacterModel.describeAllAnimations(); - playerCharacterModel.playAnimation("Armature|Walk"); - playerCharacterModel.incrementTime(0.1); -// EntityUtil.getEntityModel(playerCharacter).playAnimation("Armature|Idle1"); - */ - Model homieModel = ModelLoader.load_Model_From_File("Models/person1walkanim.fbx"); - homieModel.describeAllAnimations(); - Globals.playerCharacter = CreatureUtils.spawnBasicControllableEntity(homieModel, 0.005f, 0.025f); - EntityUtil.getEntityScale(Globals.playerCharacter).set(0.005f); - EntityUtil.getEntityPosition(Globals.playerCharacter).set(playerStartRealX - 0.5f,terrainManager.getHeightAtPosition(playerStartRealX, playerStartRealY),playerStartRealY - 0.5f); +// Model homieModel = ModelLoader.load_Model_From_File("Models/person1walkanim.fbx"); +// homieModel.describeAllAnimations(); +// Globals.playerCharacter = CreatureUtils.spawnBasicControllableEntity(0, 0.005f, 0.025f); +// EntityUtils.getEntityScale(Globals.playerCharacter).set(0.005f); +// EntityUtils.getEntityPosition(Globals.playerCharacter).set(playerStartRealX - 0.5f,Globals.terrainManager.getHeightAtPosition(playerStartRealX, playerStartRealY),playerStartRealY - 0.5f); +// System.out.println("Player position: " + playerStartRealX + " " + playerStartRealY); - Globals.playerCamera = CameraEntityUtils.spawnOrbitalCameraEntity(Globals.playerCharacter, 3f); +// Globals.playerCamera = CameraEntityUtils.spawnEntityTrackingCameraEntity(Globals.playerCharacter, 3f); - Globals.cellManager.setCellX(Globals.cellManager.transformRealSpaceToCellSpace(playerStartRealX)); - Globals.cellManager.setCellY(Globals.cellManager.transformRealSpaceToCellSpace(playerStartRealY)); + Globals.drawCellManager.setCellX(Globals.drawCellManager.transformRealSpaceToCellSpace(playerStartRealX)); + Globals.drawCellManager.setCellY(Globals.drawCellManager.transformRealSpaceToCellSpace(playerStartRealY)); - Globals.cellManager.invalidateAllCells(); + Globals.drawCellManager.invalidateAllCells(); } - - public static void forkServer(){ - Server.startServerThread(); - } - - public static void forkConnection(){ - Connection.startConnection(); + static void createPlayerCamera(){ + Globals.playerCamera = CameraEntityUtils.spawnBasicCameraEntity(new Vector3f(1,0,1), new Vector3f(0,0,0)); } } diff --git a/src/main/java/electrosphere/net/NetUtils.java b/src/main/java/electrosphere/net/NetUtils.java new file mode 100644 index 00000000..4a6dbb57 --- /dev/null +++ b/src/main/java/electrosphere/net/NetUtils.java @@ -0,0 +1,23 @@ +package electrosphere.net; + +import electrosphere.entity.CreatureUtils; +import electrosphere.entity.Entity; +import electrosphere.net.message.EntityMessage; + +/** + * + * @author amaterasu + */ +public class NetUtils { + + public static EntityMessage createSpawnEntityMessage(Entity e){ + EntityMessage rVal = EntityMessage.constructCreateMessage(e.getId(), CreatureUtils.getCreatureType(e)); + return rVal; + } + + public static EntityMessage createSetCreatureControllerIdEntityMessage(Entity e){ + System.out.println("Controller id: " + CreatureUtils.getControllerPlayerId(e)); + EntityMessage rVal = EntityMessage.constructSetPropertyMessage(e.getId(), 0, CreatureUtils.getControllerPlayerId(e)); + return rVal; + } +} diff --git a/src/main/java/electrosphere/net/Packet.java b/src/main/java/electrosphere/net/Packet.java deleted file mode 100644 index 5b1d0e82..00000000 --- a/src/main/java/electrosphere/net/Packet.java +++ /dev/null @@ -1,9 +0,0 @@ -package electrosphere.net; - -/** - * - * @author satellite - */ -public class Packet { - byte[] rawBytes; -} diff --git a/src/main/java/electrosphere/net/client/ClientNetworkMessage.java b/src/main/java/electrosphere/net/client/ClientNetworkMessage.java new file mode 100644 index 00000000..411b934a --- /dev/null +++ b/src/main/java/electrosphere/net/client/ClientNetworkMessage.java @@ -0,0 +1,70 @@ +package electrosphere.net.client; + +import electrosphere.util.BufferUtils; +import java.nio.ByteBuffer; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * + * @author amaterasu + */ +public class ClientNetworkMessage { + + byte[] bytesRaw; + + public ClientNetworkMessage(byte[] bytes){ + bytesRaw = bytes; + } + + + public byte[] getRawBytes(){ + return bytesRaw; + } + + public static ClientNetworkMessage getMoveForwardMessage(){ + return new ClientNetworkMessage("test".getBytes()); + } + + static final byte CATEGORY_ENTITY = 2; + + static final byte ENTITY_CREATE = 0; + static final byte ENTITY_DELETE = 1; + static final byte ENTITY_MOVE = 2; + static final byte ENTITY_SET_BEHAVIOR_TREE_STATE = 3; + + static ByteBuffer integerCompactor; + + static { + integerCompactor = ByteBuffer.allocate(4); + } + + public static ClientNetworkMessage parseClientNetworkMessageFromByteQueue(CopyOnWriteArrayList byteQueue){ + ClientNetworkMessage rVal = null; + if(byteQueue.size() > 0){ + byte firstByte = byteQueue.get(0); + switch(firstByte){ + case CATEGORY_ENTITY: + if(byteQueue.size() >= 18){ + byte secondByte = byteQueue.get(1); + switch(secondByte){ + case ENTITY_CREATE: + byteQueue.remove(0); + byteQueue.remove(0); + int id = BufferUtils.popIntFromByteQueue(byteQueue); + int type = BufferUtils.popIntFromByteQueue(byteQueue); + System.out.println("Create entity id:" + id + " type:" + type); + break; + case ENTITY_DELETE: + break; + case ENTITY_MOVE: + break; + case ENTITY_SET_BEHAVIOR_TREE_STATE: + break; + } + } + break; + } + } + return rVal; + } +} diff --git a/src/main/java/electrosphere/net/client/ClientNetworking.java b/src/main/java/electrosphere/net/client/ClientNetworking.java new file mode 100644 index 00000000..0fb731cc --- /dev/null +++ b/src/main/java/electrosphere/net/client/ClientNetworking.java @@ -0,0 +1,161 @@ +package electrosphere.net.client; + +import electrosphere.entity.CreatureUtils; +import electrosphere.entity.Entity; +import electrosphere.entity.EntityUtils; +import electrosphere.main.Globals; +import electrosphere.main.Main; +import electrosphere.net.message.EntityMessage; +import electrosphere.net.message.NetworkMessage; +import electrosphere.net.message.PlayerMessage; +import electrosphere.net.raw.NetworkParser; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.Socket; +import java.net.SocketException; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.Properties; +import java.util.Random; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Semaphore; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.crypto.stream.CryptoInputStream; +import org.apache.commons.crypto.stream.CryptoOutputStream; + +/** + * + * @author amaterasu + */ +public class ClientNetworking implements Runnable{ + + + static int port = 42536; + Socket socket; +// CryptoInputStream inputStream; +// CryptoOutputStream outputStream; + InputStream inputStream; + OutputStream outputStream; + boolean initialized; + NetworkParser parser; + + public ClientNetworking(String address, int port){ + try { + this.socket = new Socket(address,port); + } catch (IOException ex) { + System.err.println("Failed to connect!"); + ex.printStackTrace(); + System.exit(1); + } + } + + + + @Override + public void run(){ + initialized = false; + // final SecretKeySpec key = new SecretKeySpec(("1234567890123456").getBytes(),"AES"); +// final Properties properties = new Properties(); +// final RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(4096, BigInteger.probablePrime(4000, new Random())); +// try { +// inputStream = new CryptoInputStream("AES/ECB/PKCS5Padding",properties,socket.getInputStream(),key,spec); +// } catch (IOException ex) { +// ex.printStackTrace(); +// System.exit(1); +// } +// try { +// outputStream = new CryptoOutputStream("AES/ECB/PKCS5Padding",properties,socket.getOutputStream(),key,spec); +// } catch (IOException ex) { +// ex.printStackTrace(); +// System.exit(1); +// } + try { + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + parser = new NetworkParser(inputStream,outputStream); + } catch (IOException ex) { + Logger.getLogger(ClientNetworking.class.getName()).log(Level.SEVERE, null, ex); + } + initialized = true; + while(Main.isRunning()){ + //attempt poll incoming messages + parser.readMessagesIn(); + //outgoing messages + parser.pushMessagesOut(); + } + } + + + public void parseMessages(){ + while(parser.hasIncomingMessaage()){ + NetworkMessage message = parser.popIncomingMessage(); + System.out.println("New message " + message.getType()); + //do something + handleMessage(message); + } + } + + void handleMessage(NetworkMessage message){ + switch(message.getType()){ + case ENTITY_MESSAGE: + handleEntityMessage((EntityMessage)message); + break; + case PLAYER_MESSAGE: + handlePlayerMessage((PlayerMessage)message); + break; + } + } + + void handleEntityMessage(EntityMessage message){ + System.out.println(message.getEntityMessageType()); + switch(message.getEntityMessageType()){ + case CREATE: + System.out.println("Spawn ID " + message.getEntityType()); + Entity newlySpawnedEntity = CreatureUtils.spawnBasicCreature(message.getEntityType(), 0.005f, 0.025f); + EntityUtils.getEntityScale(newlySpawnedEntity).set(0.005f); + EntityUtils.getEntityPosition(newlySpawnedEntity).set(10 - 0.5f,Globals.terrainManager.getHeightAtPosition(10, 10),10 - 0.5f); + EntityUtils.setEntityID(newlySpawnedEntity, message.getId()); + break; + case DESTROY: + break; + case MOVE: + //literally just adding this to scope so I can use `` Entity target; `` again + if(message.getId() != -1){ + Entity target = Globals.entityManager.getEntityFromId(message.getId()); + EntityUtils.getEntityPosition(target).set(message.getX(),message.getY(),message.getZ()); + } +// CreatureUtils.attachEntityMessageToMovementTree(Globals.entityManager.getEntityFromId(message.getId()),message); + break; + case SET_BEHAVIOR_TREE: + break; + case SET_PROPERTY: + if(message.getPropertyType() == 0){ + Entity target = Globals.entityManager.getEntityFromId(message.getId()); + if(target != null){ + CreatureUtils.setControllerPlayerId(target, message.getPropertyValue()); + if(message.getPropertyValue() == Main.playerId){ + Globals.playerCharacter = target; + } + } + } + break; + } + } + + void handlePlayerMessage(PlayerMessage message){ + switch(message.getPlayerMessageType()){ + case SET_PLAYER_ID: + Main.playerId = message.getId(); + System.out.println("Player ID is " + Main.playerId); + break; + } + } + + public void queueOutgoingMessage(NetworkMessage message){ + parser.addOutgoingMessage(message); + } + +} diff --git a/src/main/java/electrosphere/net/client/Connection.java b/src/main/java/electrosphere/net/client/Connection.java deleted file mode 100644 index 6a7a6fbc..00000000 --- a/src/main/java/electrosphere/net/client/Connection.java +++ /dev/null @@ -1,71 +0,0 @@ -package electrosphere.net.client; - -import electrosphere.main.Globals; -import java.io.IOException; -import java.net.Socket; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.commons.crypto.stream.CryptoInputStream; -import org.apache.commons.crypto.stream.CryptoOutputStream; - -/** - * - * @author amaterasu - */ -public class Connection { - - enum ConnectionState { - HANDSHAKE_START, - HANDSHAKE_SUCCESS, - HANDSHAKE_FAILURE, - } - - ConnectionState state; - - static int port = 42536; - - Socket socket; - - CryptoInputStream inputStream; - - CryptoOutputStream outputStream; - - public Connection(String address, int port){ - try { - this.socket = new Socket(address,port); - } catch (IOException ex) { - System.err.println("Failed to connect!"); - ex.printStackTrace(); - System.exit(1); - } - } - - public void processAllPackets(){ - - } - - - public static void startConnection(){ - Globals.connection = new Connection("localhost",port); - - - } - - class ConnectionProtocol implements Runnable { - Connection connection; - - public ConnectionProtocol(Connection conn){ - connection = conn; - } - - @Override - public void run() { - boolean running = true; -// while(running){ -// if(connection.inputStream.read) -// } - } - - } - -} diff --git a/src/main/java/electrosphere/net/server/Client.java b/src/main/java/electrosphere/net/server/Client.java deleted file mode 100644 index d8310825..00000000 --- a/src/main/java/electrosphere/net/server/Client.java +++ /dev/null @@ -1,30 +0,0 @@ -package electrosphere.net.server; - -import java.net.Socket; -import org.apache.commons.crypto.stream.CryptoInputStream; -import org.apache.commons.crypto.stream.CryptoOutputStream; - -/** - * - * @author satellite - */ -public class Client implements Runnable { - - - Socket socket; - - CryptoInputStream inputStream; - - CryptoOutputStream outputStream; - - - public Client(Socket socket) { - this.socket = socket; - } - - @Override - public void run() { - System.out.println("aaaaaaaaaaaeoiu"); - } - -} diff --git a/src/main/java/electrosphere/net/server/Server.java b/src/main/java/electrosphere/net/server/Server.java index 5e53e248..f34b68d8 100644 --- a/src/main/java/electrosphere/net/server/Server.java +++ b/src/main/java/electrosphere/net/server/Server.java @@ -1,9 +1,12 @@ package electrosphere.net.server; +import electrosphere.main.Main; +import electrosphere.net.message.NetworkMessage; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; +import java.net.SocketException; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; @@ -12,13 +15,13 @@ import java.util.logging.Logger; * * @author amaterasu */ -public class Server { +public class Server implements Runnable{ static int port = 42536; ServerSocket serverSocket; - HashMap clientMap; + HashMap clientMap; @@ -28,38 +31,46 @@ public class Server { } - Server(int port){ + public Server(int port){ + this.port = port; + } + + @Override + public void run() { initServer(); try { - serverSocket = new ServerSocket(); + serverSocket = new ServerSocket(port); } catch (IOException ex) { System.err.println("Failed to start server socket!"); ex.printStackTrace(); System.exit(1); } - boolean running = true; - while(running){ + while(Main.isRunning()){ Socket newSocket; try { newSocket = serverSocket.accept(); - Client newClient = new Client(newSocket); + ServerConnectionHandler newClient = new ServerConnectionHandler(newSocket); clientMap.put(newSocket.getInetAddress().getHostAddress(), newClient); new Thread(newClient).start(); } catch (IOException ex) { System.err.println("Socket error on client socket!"); - ex.printStackTrace(); } } } + public void close(){ + try { + serverSocket.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } - public static void startServerThread(){ - Thread t = new Thread(){ - @Override - public void run(){ - Server s = new Server(port); + public void broadcastMessage(NetworkMessage message){ + for(ServerConnectionHandler client : clientMap.values()){ + if(client.playerID != Main.playerId){ + client.addMessagetoOutgoingQueue(message); } - }; - t.start(); + } } } diff --git a/src/main/java/electrosphere/net/server/ServerConnectionHandler.java b/src/main/java/electrosphere/net/server/ServerConnectionHandler.java new file mode 100644 index 00000000..d06742e6 --- /dev/null +++ b/src/main/java/electrosphere/net/server/ServerConnectionHandler.java @@ -0,0 +1,162 @@ +package electrosphere.net.server; + +import electrosphere.entity.CreatureUtils; +import electrosphere.entity.Entity; +import electrosphere.entity.EntityUtils; +import electrosphere.main.Globals; +import electrosphere.main.Main; +import electrosphere.net.NetUtils; +import electrosphere.net.message.EntityMessage; +import electrosphere.net.message.NetworkMessage; +import electrosphere.net.message.NetworkMessage.MessageType; +import electrosphere.net.message.PlayerMessage; +import electrosphere.net.raw.NetworkParser; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.Socket; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.Properties; +import java.util.Random; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.crypto.stream.CryptoInputStream; +import org.apache.commons.crypto.stream.CryptoOutputStream; + +/** + * + * @author satellite + */ +public class ServerConnectionHandler implements Runnable { + + static int playerIdIncrementer = 0; + + Socket socket; +// CryptoInputStream inputStream; +// CryptoOutputStream outputStream; + InputStream inputStream; + OutputStream outputStream; + boolean initialized; + NetworkParser networkParser; + int playerID; + + public ServerConnectionHandler(Socket socket) { + this.socket = socket; + playerID = getPlayerID(); + System.out.println("Player ID: " + playerID); + } + + @Override + public void run() { + System.out.println("aaaaaaaaaaaeoiu"); + initialized = false; + try { + socket.setSoTimeout(100); + } catch (SocketException ex) { + ex.printStackTrace(); + } + // final SecretKeySpec key = new SecretKeySpec(("1234567890123456").getBytes(),"AES"); +// final Properties properties = new Properties(); +// final RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(4096, BigInteger.probablePrime(4000, new Random())); +// try { +// inputStream = new CryptoInputStream("AES/ECB/PKCS5Padding",properties,socket.getInputStream(),key,spec); +// } catch (IOException ex) { +// ex.printStackTrace(); +// System.exit(1); +// } +// try { +// outputStream = new CryptoOutputStream("AES/ECB/PKCS5Padding",properties,socket.getOutputStream(),key,spec); +// } catch (IOException ex) { +// ex.printStackTrace(); +// System.exit(1); +// } + try { + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + networkParser = new NetworkParser(inputStream,outputStream); + } catch (IOException ex) { + ex.printStackTrace(); + System.exit(1); + } + //spawn player in world + Entity newPlayerCharacter = CreatureUtils.spawnBasicCreature(0, 0.001f, 0.025f); + EntityUtils.getEntityScale(newPlayerCharacter).set(0.005f); + EntityUtils.getEntityPosition(newPlayerCharacter).set(10 - 0.5f,Globals.terrainManager.getHeightAtPosition(10, 10),10 - 0.5f); + CreatureUtils.setControllerPlayerId(newPlayerCharacter, playerID); + if(Globals.mainConfig.runServer && Main.playerId == -1){ + Globals.playerCharacter = newPlayerCharacter; + } + //tell them what player stats they are + networkParser.addOutgoingMessage(PlayerMessage.constructSetPlayerIDMessage(playerID)); + //figure out what chunk they're in + + //queue messages for that chunk + if(Globals.mainConfig.runServer){ + + } else { + for(Entity currentEntity : Globals.entityManager.getMoveable()){ + networkParser.addOutgoingMessage(NetUtils.createSpawnEntityMessage(currentEntity)); + if(CreatureUtils.isCreature(currentEntity)){ + if(CreatureUtils.hasControllerPlayerId(currentEntity)){ + System.out.println("Sending controller packets"); + networkParser.addOutgoingMessage(NetUtils.createSetCreatureControllerIdEntityMessage(currentEntity)); + } + } + } + } + + initialized = true; + while(Main.isRunning()){ + //attempt poll incoming messages + networkParser.readMessagesIn(); + //ponder incoming messages + while(networkParser.hasIncomingMessaage()){ + NetworkMessage message = networkParser.popIncomingMessage(); + handleMessage(message); + } + //push outgoing message + networkParser.pushMessagesOut(); + } + } + + + void handleMessage(NetworkMessage message){ + switch(message.getType()){ + case ENTITY_MESSAGE: + handleEntityMessage((EntityMessage)message); + break; + } + } + + void handleEntityMessage(EntityMessage message){ + switch(message.getEntityMessageType()){ + case CREATE: + break; + case DESTROY: + break; + case MOVE: + Entity targetEntity = Globals.entityManager.getEntityFromId(message.getId()); + if(targetEntity != null){ + CreatureUtils.attachEntityMessageToMovementTree(targetEntity,message); + } + break; + case SET_BEHAVIOR_TREE: + break; + } + } + + + static int getPlayerID(){ + playerIdIncrementer++; + return playerIdIncrementer; + } + + public void addMessagetoOutgoingQueue(NetworkMessage message){ + networkParser.addOutgoingMessage(message); + } +} diff --git a/src/main/java/electrosphere/net/server/ServerNetworkMessage.java b/src/main/java/electrosphere/net/server/ServerNetworkMessage.java new file mode 100644 index 00000000..3f4a9e08 --- /dev/null +++ b/src/main/java/electrosphere/net/server/ServerNetworkMessage.java @@ -0,0 +1,33 @@ +package electrosphere.net.server; + +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * + * @author amaterasu + */ +public class ServerNetworkMessage { + + byte[] rawBytes; + + + public byte[] getRawBytes(){ + return rawBytes; + } + + public static ServerNetworkMessage parseServerNetworkMessage(CopyOnWriteArrayList byteQueue){ + ServerNetworkMessage rVal = null; + if(byteQueue.size() > 0){ + byte firstByte = byteQueue.get(0); + switch(firstByte){ + case 0: + break; + case 1: + break; + case 2: + break; + } + } + return rVal; + } +} diff --git a/src/main/java/electrosphere/renderer/Camera.java b/src/main/java/electrosphere/renderer/Camera.java index dfe6f5a9..e0d4dffe 100644 --- a/src/main/java/electrosphere/renderer/Camera.java +++ b/src/main/java/electrosphere/renderer/Camera.java @@ -8,6 +8,7 @@ import org.joml.Vector3f; * * @author satellite */ +@Deprecated public class Camera { public Vector3f pos_Center = new Vector3f(0,0,0); // public Vector3f pos_Front = new Vector3f(0,0,0); diff --git a/src/main/java/electrosphere/renderer/Mesh.java b/src/main/java/electrosphere/renderer/Mesh.java index 112cb8b2..b6092c4d 100644 --- a/src/main/java/electrosphere/renderer/Mesh.java +++ b/src/main/java/electrosphere/renderer/Mesh.java @@ -1,5 +1,6 @@ package electrosphere.renderer; +import electrosphere.entity.CameraEntityUtils; import electrosphere.main.Globals; import electrosphere.main.Main; import electrosphere.renderer.light.LightBuffer; @@ -441,7 +442,7 @@ public class Mesh { GL20.glUniformMatrix4fv(glGetUniformLocation(shader.shaderProgram, "model"), false, parent.modelMatrix.get(new float[16])); - Vector3f cam_Loc = Globals.cameraVisible.pos_Center; + Vector3f cam_Loc = CameraEntityUtils.getCameraEye(Globals.playerCamera);//Globals.cameraVisible.pos_Center; temp[0] = cam_Loc.x; temp[1] = cam_Loc.y; temp[2] = cam_Loc.z; @@ -495,7 +496,7 @@ public class Mesh { glUniformMatrix4fv(shader.shaderVertexModelLoc, false, parent.modelMatrix.get(new float[16])); glUniformMatrix4fv(shader.shaderVertexViewLoc, false, Globals.viewMatrix.get(new float[16])); glUniformMatrix4fv(shader.shaderVertexProjectionLoc, false, Globals.projectionMatrix.get(new float[16])); - glUniform3fv(shader.shaderVertexViewPosLoc, Globals.cameraVisible.pos_Center.get(BufferUtils.createFloatBuffer(3))); + glUniform3fv(shader.shaderVertexViewPosLoc, CameraEntityUtils.getCameraEye(Globals.playerCamera).get(BufferUtils.createFloatBuffer(3))); // // @@ -520,7 +521,7 @@ public class Mesh { test_Light_Data[2] = 0.5f; glUniform3fv(glGetUniformLocation(shader.shaderProgram, "dirLight.diffuse"), test_Light_Data); - Vector3f cam_Loc = Globals.cameraVisible.pos_Center; + Vector3f cam_Loc = CameraEntityUtils.getCameraEye(Globals.playerCamera); test_Light_Data = new float[3]; test_Light_Data[0] = cam_Loc.x; test_Light_Data[1] = cam_Loc.y; diff --git a/src/main/java/electrosphere/renderer/RenderUtils.java b/src/main/java/electrosphere/renderer/RenderUtils.java index 3ebe45a2..0d1f5cf3 100644 --- a/src/main/java/electrosphere/renderer/RenderUtils.java +++ b/src/main/java/electrosphere/renderer/RenderUtils.java @@ -5,6 +5,7 @@ */ package electrosphere.renderer; +import electrosphere.entity.CameraEntityUtils; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; @@ -184,7 +185,7 @@ public class RenderUtils { glUniformMatrix4fv(shader.shaderVertexModelLoc, false, parent.modelMatrix.get(new float[16])); glUniformMatrix4fv(shader.shaderVertexViewLoc, false, new Matrix4f(Globals.viewMatrix).scale(100).get(new float[16])); glUniformMatrix4fv(shader.shaderVertexProjectionLoc, false, Globals.projectionMatrix.get(new float[16])); - glUniform3fv(shader.shaderVertexViewPosLoc, Globals.cameraVisible.pos_Center.get(BufferUtils.createFloatBuffer(3))); + glUniform3fv(shader.shaderVertexViewPosLoc, CameraEntityUtils.getCameraEye(Globals.playerCamera).get(BufferUtils.createFloatBuffer(3))); GL11.glDrawElements(GL_TRIANGLES, elementCount, GL_UNSIGNED_INT, 0); diff --git a/src/main/java/electrosphere/renderer/assetmanager/AssetManager.java b/src/main/java/electrosphere/renderer/assetmanager/AssetManager.java new file mode 100644 index 00000000..29d359c5 --- /dev/null +++ b/src/main/java/electrosphere/renderer/assetmanager/AssetManager.java @@ -0,0 +1,54 @@ +package electrosphere.renderer.assetmanager; + +import electrosphere.renderer.Model; +import electrosphere.util.ModelLoader; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * + * @author amaterasu + */ +public class AssetManager { + + ConcurrentHashMap modelsLoadedIntoMemory = new ConcurrentHashMap(); + + CopyOnWriteArrayList modelsInQueue = new CopyOnWriteArrayList(); + + public void loadAssetsInQueue(){ + for(String currentPath : modelsInQueue){ + modelsInQueue.remove(currentPath); + modelsLoadedIntoMemory.put(currentPath, ModelLoader.load_Model_From_File(currentPath)); + } + } + + public void addModelPathToQueue(String path){ + if(!modelsInQueue.contains(path) && !modelsLoadedIntoMemory.containsKey(path)){ + modelsInQueue.add(path); + } + } + + public Model fetchModel(String path){ + Model rVal = null; + if(modelsLoadedIntoMemory.containsKey(path)){ + rVal = modelsLoadedIntoMemory.get(path); + } + return rVal; + } + + /** + Registers a (presumably generated in code) model with the asset manager + @returns a random string that represents the model in the asset manager + */ + public String registerModel(Model m){ + String rVal; + UUID newUUID = UUID.randomUUID(); + rVal = newUUID.toString(); + modelsLoadedIntoMemory.put(rVal,m); + return rVal; + } +} diff --git a/src/main/java/electrosphere/util/BufferUtils.java b/src/main/java/electrosphere/util/BufferUtils.java new file mode 100644 index 00000000..30393c66 --- /dev/null +++ b/src/main/java/electrosphere/util/BufferUtils.java @@ -0,0 +1,30 @@ +package electrosphere.util; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * + * @author amaterasu + */ +public class BufferUtils { + + static ByteBuffer integerCompactor; + + static { + integerCompactor = ByteBuffer.allocate(4); + } + + public static int popIntFromByteQueue(CopyOnWriteArrayList queue){ + int rVal = -1; + integerCompactor.clear(); + integerCompactor.put(queue.remove(0)); + integerCompactor.put(queue.remove(0)); + integerCompactor.put(queue.remove(0)); + integerCompactor.put(queue.remove(0)); + integerCompactor.flip(); + rVal = integerCompactor.getInt(); + return rVal; + } +} diff --git a/src/main/resources/Data/entity_map.json b/src/main/resources/Data/entity_map.json new file mode 100644 index 00000000..c565183a --- /dev/null +++ b/src/main/resources/Data/entity_map.json @@ -0,0 +1,12 @@ +{ + "types": [ + { + "id" : 0, + "modelPath" : "Models/person1walkanim.fbx" + }, + { + "id" : 1, + "modelPath" : "" + } + ] +}