[DEV] continue integartion of ephysics

This commit is contained in:
Edouard DUPIN 2021-02-08 00:20:47 +01:00
parent c6a1a0b615
commit d8983205f0
18 changed files with 1449 additions and 1636 deletions

View File

@ -14,5 +14,5 @@ open module org.atriasoft.gameengine {
requires transitive org.atriasoft.gale; requires transitive org.atriasoft.gale;
requires transitive org.atriasoft.etk; requires transitive org.atriasoft.etk;
requires transitive net.jreactphysics3d; requires transitive org.atriasoft.ephysics;
} }

View File

@ -1,5 +1,6 @@
package org.atriasoft.gameengine; package org.atriasoft.gameengine;
import org.atriasoft.etk.math.Transform3D;
import org.atriasoft.etk.math.Vector2f; import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.Gale; import org.atriasoft.gale.Gale;
@ -9,34 +10,37 @@ import org.atriasoft.gale.event.EventTime;
import org.atriasoft.gale.key.KeyKeyboard; import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gameengine.camera.Camera; import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.internal.Log; import org.atriasoft.gameengine.components.ComponentPhysics;
import org.atriasoft.gameengine.components.ComponentPlayer; import org.atriasoft.gameengine.components.ComponentPlayer;
import org.atriasoft.gameengine.components.ComponentPosition;
import org.atriasoft.gameengine.components.ComponentPositionPlayer; import org.atriasoft.gameengine.components.ComponentPositionPlayer;
import org.atriasoft.gameengine.internal.Log;
import renderEngine.DisplayManager;
public class ControlCameraPlayer implements ControlInterface { public class ControlCameraPlayer implements ControlInterface {
private Camera camera; private final Camera camera;
private float distanceFromCenter = 2.5f; private float distanceFromCenter = 2.5f;
private boolean fpsMode = false; private boolean fpsMode = false;
private Entity playerEntity; private final Entity playerEntity;
private ComponentPositionPlayer playerPosition; private ComponentPositionPlayer playerPosition;
private ComponentPlayer player; private ComponentPhysics playerPhysics;
private final ComponentPlayer player;
private boolean moveUp = false; private boolean moveUp = false;
private boolean moveDown = false; private boolean moveDown = false;
private boolean moveLeft = false; private boolean moveLeft = false;
private boolean moveRight = false; private boolean moveRight = false;
private boolean walk = false; private boolean walk = false;
public ControlCameraPlayer(Camera camera, Entity playerEntity) { public ControlCameraPlayer(final Camera camera, final Entity playerEntity) {
this.camera = camera; this.camera = camera;
this.playerEntity = playerEntity; this.playerEntity = playerEntity;
this.playerPosition = (ComponentPositionPlayer)this.playerEntity.getComponent("position"); if (this.playerEntity.exist("position")) {
this.player = (ComponentPlayer)this.playerEntity.getComponent("player"); this.playerPosition = (ComponentPositionPlayer) this.playerEntity.getComponent("position");
} else if (this.playerEntity.exist("physics")) {
this.playerPhysics = (ComponentPhysics) this.playerEntity.getComponent("physics");
}
this.player = (ComponentPlayer) this.playerEntity.getComponent("player");
} }
private boolean getState(KeyStatus state, boolean previousState) {
private boolean getState(final KeyStatus state, final boolean previousState) {
if (state == KeyStatus.down) { if (state == KeyStatus.down) {
return true; return true;
} }
@ -45,35 +49,32 @@ public class ControlCameraPlayer implements ControlInterface {
} }
return previousState; return previousState;
} }
@Override @Override
public boolean onEventEntry(EventEntry event) { public boolean onEventEntry(final EventEntry event) {
if(event.getType() == KeyKeyboard.up if (event.getType() == KeyKeyboard.up || (event.getType() == KeyKeyboard.character && (event.getChar() == 'z' || event.getChar() == 'Z'))) {
|| (event.getType() == KeyKeyboard.character && (event.getChar() == 'z' || event.getChar() == 'Z' ))) { this.moveUp = getState(event.getStatus(), this.moveUp);
moveUp = getState(event.getStatus(), moveUp);
} }
if(event.getType() == KeyKeyboard.left if (event.getType() == KeyKeyboard.left || (event.getType() == KeyKeyboard.character && (event.getChar() == 'q' || event.getChar() == 'Q'))) {
|| (event.getType() == KeyKeyboard.character && (event.getChar() == 'q' || event.getChar() == 'Q' ))) { this.moveLeft = getState(event.getStatus(), this.moveLeft);
moveLeft = getState(event.getStatus(), moveLeft);
} }
if(event.getType() == KeyKeyboard.right if (event.getType() == KeyKeyboard.right || (event.getType() == KeyKeyboard.character && (event.getChar() == 'd' || event.getChar() == 'D'))) {
|| (event.getType() == KeyKeyboard.character && (event.getChar() == 'd' || event.getChar() == 'D' ))) { this.moveRight = getState(event.getStatus(), this.moveRight);
moveRight = getState(event.getStatus(), moveRight);
} }
if(event.getType() == KeyKeyboard.down if (event.getType() == KeyKeyboard.down || (event.getType() == KeyKeyboard.character && (event.getChar() == 's' || event.getChar() == 'S'))) {
|| (event.getType() == KeyKeyboard.character && (event.getChar() == 's' || event.getChar() == 'S' ))) { this.moveDown = getState(event.getStatus(), this.moveDown);
moveDown = getState(event.getStatus(), moveDown);
} }
if(event.getType() == KeyKeyboard.shiftLeft || event.getType() == KeyKeyboard.shiftRight) { if (event.getType() == KeyKeyboard.shiftLeft || event.getType() == KeyKeyboard.shiftRight) {
walk = event.getSpecialKey().getShift(); this.walk = event.getSpecialKey().getShift();
} }
if(event.getType() == KeyKeyboard.f10) { if (event.getType() == KeyKeyboard.f10) {
if (event.getStatus() == KeyStatus.up) { if (event.getStatus() == KeyStatus.up) {
if (fpsMode == false) { if (this.fpsMode == false) {
fpsMode = true; this.fpsMode = true;
distanceFromCenter = 0; this.distanceFromCenter = 0;
} else { } else {
fpsMode = false; this.fpsMode = false;
distanceFromCenter = 2.5f; this.distanceFromCenter = 2.5f;
} }
} }
} }
@ -81,29 +82,29 @@ public class ControlCameraPlayer implements ControlInterface {
} }
@Override @Override
public boolean onEventInput(EventInput event, Vector2f relativePosition) { public boolean onEventInput(final EventInput event, final Vector2f relativePosition) {
// Log.info("" + event); // Log.info("" + event);
// TODO Auto-generated method stub // TODO Auto-generated method stub
if (fpsMode == false) { if (this.fpsMode == false) {
if (event.getInputId() == 4) { if (event.getInputId() == 4) {
if (event.getStatus() == KeyStatus.down) { if (event.getStatus() == KeyStatus.down) {
distanceFromCenter -= 0.2; this.distanceFromCenter -= 0.2;
} }
if (distanceFromCenter < 0.0) { if (this.distanceFromCenter < 0.0) {
distanceFromCenter = 0.0f; this.distanceFromCenter = 0.0f;
} }
return true; return true;
} else if (event.getInputId() == 5) { } else if (event.getInputId() == 5) {
if (event.getStatus() == KeyStatus.down) { if (event.getStatus() == KeyStatus.down) {
distanceFromCenter += 0.2; this.distanceFromCenter += 0.2;
} }
if (distanceFromCenter < 0.3) { if (this.distanceFromCenter < 0.3) {
distanceFromCenter = 0.3f; this.distanceFromCenter = 0.3f;
} }
return true; return true;
} }
} else { } else {
distanceFromCenter = 0; this.distanceFromCenter = 0;
} }
// TODO check if grabbing is enable ... // TODO check if grabbing is enable ...
// in grabbing mouse only: // in grabbing mouse only:
@ -111,15 +112,15 @@ public class ControlCameraPlayer implements ControlInterface {
return false; return false;
} }
if (event.getStatus() == KeyStatus.move) { if (event.getStatus() == KeyStatus.move) {
Vector2f delta = event.getPosition().clone(); final Vector2f delta = event.getPosition().clone();
//angleZ += delta.x; //angleZ += delta.x;
//this.camera.setYaw(this.camera.getYaw() + (float)Math.toRadians(delta.x)); //this.camera.setYaw(this.camera.getYaw() + (float)Math.toRadians(delta.x));
this.camera.setPitch(this.camera.getPitch() + (float)Math.toRadians(delta.y * this.player.getTurnSpeed())); this.camera.setPitch(this.camera.getPitch() + (float) Math.toRadians(delta.y * this.player.getTurnSpeed()));
if (this.camera.getPitch()>0) { if (this.camera.getPitch() > 0) {
this.camera.setPitch(0); this.camera.setPitch(0);
} }
if (this.camera.getPitch()<-Math.PI) { if (this.camera.getPitch() < -Math.PI) {
this.camera.setPitch((float)-Math.PI); this.camera.setPitch((float) -Math.PI);
} }
/* /*
this.camera.setRoll(this.camera.getRoll() - (float)Math.toRadians(delta.x * this.player.getTurnSpeed())); this.camera.setRoll(this.camera.getRoll() - (float)Math.toRadians(delta.x * this.player.getTurnSpeed()));
@ -132,66 +133,83 @@ public class ControlCameraPlayer implements ControlInterface {
} }
this.playerPosition.setAngles(new Vector3f(0,0,-this.camera.getRoll())); this.playerPosition.setAngles(new Vector3f(0,0,-this.camera.getRoll()));
*/ */
float tmpAngle = this.playerPosition.getAngles().z + (float)Math.toRadians(delta.x * this.player.getTurnSpeed()); if (this.playerPosition != null) {
final float playerZAngle = this.playerPosition.getAngles().z;
float tmpAngle = playerZAngle + (float) Math.toRadians(delta.x * this.player.getTurnSpeed());
if (tmpAngle > Math.PI) { if (tmpAngle > Math.PI) {
tmpAngle -= (float)Math.PI*2.0f; tmpAngle -= (float) Math.PI * 2.0f;
}
if (tmpAngle < -Math.PI) {
tmpAngle += (float) Math.PI * 2.0f;
}
this.playerPosition.setAngles(new Vector3f(0, 0, tmpAngle));
this.camera.setRoll(-playerZAngle);
Log.info("Change camera: " + this.camera.getYaw() + " " + this.camera.getPitch());
} else if (this.playerPhysics != null) {
//this.playerPhysics.applyTorque(new Vector3f(0, 0, (float) Math.toRadians(delta.x * this.player.getTurnSpeed())));
} }
if (tmpAngle < -Math.PI) {
tmpAngle += (float)Math.PI*2.0f;
}
this.playerPosition.setAngles(new Vector3f(0,0,tmpAngle));
this.camera.setRoll(-this.playerPosition.getAngles().z);
Log.info("Change camera: " + this.camera.getYaw() + " " + this.camera.getPitch());
} }
return false; return false;
} }
@Override @Override
public void periodicCall(EventTime event) { public void periodicCall(final EventTime event) {
if (this.playerPhysics != null) {
//this.camera.setRoll(-this.playerPhysics.getAngles().z);
}
float speed = 0; float speed = 0;
float walkFactor = 1; float walkFactor = 1;
if (this.walk == true) { if (this.walk == true) {
walkFactor = this.player.getWalkFactor(); walkFactor = this.player.getWalkFactor();
} }
//distanceFromCenter = 6; //distanceFromCenter = 6;
if (moveUp != moveDown) { if (this.moveUp != this.moveDown) {
if (moveUp) { if (this.moveUp) {
speed = this.player.getRunSpeed(); speed = this.player.getRunSpeed();
} else { } else {
speed = -this.player.getRunSpeed(); speed = -this.player.getRunSpeed();
} }
} }
float distance = speed * walkFactor * event.getTimeDeltaCallSecond(); float distance = speed * walkFactor * event.getTimeDeltaCallSecond();
float dx = -(float) (distance * Math.sin(this.playerPosition.getAngles().z)); float playerZAngle = 0;
float dy = (float) (distance * Math.cos(this.playerPosition.getAngles().z)); Transform3D playerTransform = null;
if (this.playerPosition != null) {
playerZAngle = this.playerPosition.getAngles().z;
playerTransform = this.playerPosition.getTransform();
} else if (this.playerPhysics != null) {
playerZAngle = 0; // TODO ...
playerTransform = this.playerPhysics.getTransform();
}
final float dx = -(float) (distance * Math.sin(playerZAngle));
final float dy = (float) (distance * Math.cos(playerZAngle));
speed = 0; speed = 0;
if (moveRight != moveLeft) { if (this.moveRight != this.moveLeft) {
if (moveRight) { if (this.moveRight) {
speed = this.player.getStrafSpeed(); speed = this.player.getStrafSpeed();
} else { } else {
speed = -this.player.getStrafSpeed(); speed = -this.player.getStrafSpeed();
} }
} }
distance = speed * walkFactor * event.getTimeDeltaCallSecond(); distance = speed * walkFactor * event.getTimeDeltaCallSecond();
float dxStraf = (float) (distance * Math.sin((float)Math.PI*0.5f + this.playerPosition.getAngles().z)); final float dxStraf = (float) (distance * Math.sin((float) Math.PI * 0.5f + playerZAngle));
float dyStraf = -(float) (distance * Math.cos((float)Math.PI*0.5f + this.playerPosition.getAngles().z)); final float dyStraf = -(float) (distance * Math.cos((float) Math.PI * 0.5f + playerZAngle));
//Log.error("update position ..." + dx + " " + dy); //Log.error("update position ..." + dx + " " + dy);
this.playerPosition.getTransform().getPosition().x += dx + dxStraf; playerTransform.getPosition().x += dx + dxStraf;
this.playerPosition.getTransform().getPosition().y += dy + dyStraf; playerTransform.getPosition().y += dy + dyStraf;
// here the camera is behind the player, we need to move the camera ... // here the camera is behind the player, we need to move the camera ...
//Log.info(" pitch: " + Math.toDegrees(this.camera.getPitch()) + " " + Math.toDegrees(this.playerPosition.getAngles().z)); //Log.info(" pitch: " + Math.toDegrees(this.camera.getPitch()) + " " + Math.toDegrees(playerZAngle));
float horinzontalDistance = (float) (distanceFromCenter * Math.sin(this.camera.getPitch())); final float horinzontalDistance = (float) (this.distanceFromCenter * Math.sin(this.camera.getPitch()));
float verticalDistance = (float) (distanceFromCenter * Math.cos(this.camera.getPitch())); final float verticalDistance = (float) (this.distanceFromCenter * Math.cos(this.camera.getPitch()));
//Log.info(" distanceFromCenter " + distanceFromCenter); //Log.info(" distanceFromCenter " + distanceFromCenter);
float tmp = -horinzontalDistance; final float tmp = -horinzontalDistance;
float theta = (float)Math.PI + this.playerPosition.getAngles().z;// - (float)Math.PI*0.5f; final float theta = (float) Math.PI + playerZAngle;// - (float)Math.PI*0.5f;
float offsetX = (float) (tmp * Math.sin(-theta)); final float offsetX = (float) (tmp * Math.sin(-theta));
float offsetY = (float) (tmp * Math.cos(-theta)); final float offsetY = (float) (tmp * Math.cos(-theta));
//Log.info(" res" + offsetX + " " + offsetY); //Log.info(" res" + offsetX + " " + offsetY);
this.camera.getPosition().x = this.playerPosition.getTransform().getPosition().x + offsetX; this.camera.getPosition().x = playerTransform.getPosition().x + offsetX;
this.camera.getPosition().y = this.playerPosition.getTransform().getPosition().y + offsetY; this.camera.getPosition().y = playerTransform.getPosition().y + offsetY;
this.camera.getPosition().z = this.playerPosition.getTransform().getPosition().z + 1.6f + verticalDistance; this.camera.getPosition().z = playerTransform.getPosition().z + 1.6f + verticalDistance;
} }
} }

View File

@ -7,18 +7,27 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gameengine.internal.Log; import org.atriasoft.gameengine.internal.Log;
public class Entity { public class Entity {
private static int uIDGlobal = 0; //!< This is a reference on a basic Entity ID
protected Environement env = null; protected Environement env = null;
protected List<Component> component = new ArrayList<Component>(); protected List<Component> component = new ArrayList<Component>();
private final int uID = uIDGlobal++; //!< This is a reference on a basic Entity ID
protected float life = 100; //!< Current life of the object
protected float lifeMax = 100; //!< Maximum possible life of the Entity
private int group = 0; //!< Every Entity has a generic group
protected float radius = 0; //!< Radius of the Entity (all Entity have a radius, if == 0 ==> then ghost ...
/** /**
* @brief Constructor (when ructer is called just add Entity that did not change. * @brief Constructor (when ructer is called just add Entity that did not change.
* The objest will be stored in a pool of Entity and keep a second time if needed == > reduce memory allocation, * The objest will be stored in a pool of Entity and keep a second time if needed == > reduce memory allocation,
* when needed, the system will call the init and un-init function... * when needed, the system will call the init and un-init function...
*/ */
public Entity(Environement env) { public Entity(final Environement env) {
this.env = env; this.env = env;
} }
public void addComponent(Component ref) { public void addComponent(final Component ref) {
if (ref == null) { if (ref == null) {
Log.error("try to add an empty component"); Log.error("try to add an empty component");
return; return;
@ -26,115 +35,236 @@ public class Entity {
// Remove component with the same name. // Remove component with the same name.
this.removeComponent(ref.getType()); this.removeComponent(ref.getType());
Log.print("Entity: Add New component ... [START]"); Log.print("Entity: Add New component ... [START]");
component.add(ref); this.component.add(ref);
env.engineComponentAdd(ref); this.env.engineComponentAdd(ref);
for (Component it : component) { for (final Component it : this.component) {
ref.addFriendComponent(it); ref.addFriendComponent(it);
it.addFriendComponent(ref); it.addFriendComponent(ref);
} }
Log.print("Entity: Add New component ... [END]"); Log.print("Entity: Add New component ... [END]");
} }
public void removeComponent(Component ref){
if (ref == null) { /**
Log.error("try to remove an empty component"); * @brief remove this Entity from the physique engine
return; */
} public void dynamicDisable() {}
if (component.remove(ref) == false) {
Log.error("try to remove an unexisting component"); /**
return; * @brief set the elment in the physique engine
} */
env.engineComponentRemove(ref); public void dynamicEnable() {}
for (Component it : component) {
it.removeFriendComponent(ref); /**
} * @brief Debug display of the current Entity
} * @param[in,out] draw Basic system to draw the debug shape and informations
public void removeComponent(String type) { * @param camera Current camera for display
boolean findIt = false; */
Component componentRemoved = null; // public void drawDebug(Colored3DObject draw, Camera camera) {
// check if not exist // /*
for (int iii=0; iii<component.size(); ++iii) { // mdebugText.clear();
if (component.get(iii).getType().contentEquals(type)) { // mdebugText.setColor(etk::Color<>(0x00, 0xFF, 0x00, 0xFF));
componentRemoved = component.get(iii); // mdebugText.setPos(Vector3f(-20,32,0));
component.remove(iii); // mdebugText.print(getType());
findIt = true; // mdebugText.setPos(Vector3f(-20,20,0));
break; // mdebugText.print("life=("+etk::toString(getLifeRatio()));
} // */
} // //mdebugText.print(String("Axe=(")+String(mtmpAxe.x())+String(",")+etk::UString(mtmpAxe.y())+etk::UString(",")+etk::UString(m_tmpAxe.z())+etk::UString(")"));
if (findIt == false) { // /*
//Log.error("try to remove an unexisting component type : '" + type + "'"); // // TODO Keep this it can be usefull to print something in direction of the camera ...
return; // mdebugText.draw( etk::matTranslate(getPosition())
} // * etk::matRotate(Vector3f(0,0,1),camera.getAngleZ())
env.engineComponentRemove(componentRemoved); // * etk::matRotate(Vector3f(1,0,0),(MPI/2.0f-camera.getAngleTeta()))
for (Component it : component) { // * etk::matScale(Vector3f(0.05,0.05,0.05)));
it.removeFriendComponent(componentRemoved); // */
} // }
} /**
public Component getComponent(String type) { * @brief Event arrive when an Entity has been remove from the system == > this permit to keep pointer of ennemy, and not search them every cycle ...
// check if not exist * @param removedEntity Pointer on the Entity removed.
for (int iii=0; iii<component.size(); ++iii) { */
if (component.get(iii) == null) { public void entityIsRemoved(final Entity removedEntity) {};
public boolean exist(final String type) {
for (int iii = 0; iii < this.component.size(); ++iii) {
if (this.component.get(iii) == null) {
continue; continue;
} }
if (component.get(iii).getType().contentEquals(type)) { if (this.component.get(iii).getType().contentEquals(type)) {
return component.get(iii); return true;
}
}
return false;
}
public Component getComponent(final String type) {
// check if not exist
for (int iii = 0; iii < this.component.size(); ++iii) {
if (this.component.get(iii) == null) {
continue;
}
if (this.component.get(iii).getType().contentEquals(type)) {
return this.component.get(iii);
} }
} }
return null; return null;
} }
/**
* @brief get the Group of the Entity.
* @return The group ID
*/
public int getGroup() {
return this.group;
}
/**
* @brief get the curent life ratio [0..1]
* @return The proportionnal life
*/
public float getLifeRatio() {
if (0 >= this.life) {
return 0;
}
return this.life / this.lifeMax;
};
/**
* @brief get the current space needed by the Entity in the workspace
* @return The dimention needed.
*/
public float getRadius() {
return this.radius;
}
/**
* @brief get the curent Entity Unique ID in the all Game.
* @return The requested Unique ID.
*/
public int getUID() {
return this.uID;
}
/** /**
* @brief init the Entity with the defined properties * @brief init the Entity with the defined properties
* @param property Type of the next Entity * @param property Type of the next Entity
* @param value pointer on the value type * @param value pointer on the value type
* @return true, the Entity is corectly initialized. * @return true, the Entity is corectly initialized.
*/ */
public boolean init(){ public boolean init() {
Log.warning("init() not implemented: uId=" + uID); Log.warning("init() not implemented: uId=" + this.uID);
return false; return false;
} };
public boolean init(Object description){
Log.warning("init(Object) not implemented: uId=" + uID); // float lifeBorder = 0.1f;
// float lifeHeight = 0.3f;
// float lifeWidth = 2.0f;
// float lifeYPos = 1.7f;
// void Entity::drawLife(ewol::resource::Colored3DObject> draw, Camera> camera) {
// if (draw == null) {
// return;
// }
// float ratio = getLifeRatio();
// if (ratio == 1.0f) {
// return;
// }
// #if 0
// mat4 transformationMatrix = etk::matTranslate(getPosition())
// * etk::matRotate(Vector3f(0,0,1),camera.getAngleZ())
// * etk::matRotate(Vector3f(1,0,0),(MPI/2.0f-camera.getAngleTeta()));
// List<Vector3f> localVertices;
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos -lifeBorder,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos -lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos -lifeBorder,0));
// etk::Color<float> myColor(0x0000FF99);
// draw.draw(localVertices, myColor, transformationMatrix, false, false);
// localVertices.clear();
// /** Bounding box == > model shape **/
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos,0));
// myColor =0x00FF00FF;
// if (ratio < 0.2f) {
// myColor = 0xFF0000FF;
// } else if (ratio < 0.4f) {
// myColor = 0xDA7B00FF;
// }
// draw.draw(localVertices, myColor, transformationMatrix, false, false);
// #endif
// }
public boolean init(final Object description) {
Log.warning("init(Object) not implemented: uId=" + this.uID);
return false; return false;
} }
public boolean unInit() {
return true;
}
private static int uIDGlobal = 0; //!< This is a reference on a basic Entity ID
private int uID = uIDGlobal++; //!< This is a reference on a basic Entity ID
/**
* @brief get the curent Entity Unique ID in the all Game.
* @return The requested Unique ID.
*/
public int getUID() {
return this.uID;
};
protected float life = 100; //!< Current life of the object
protected float lifeMax = 100; //!< Maximum possible life of the Entity
/**
* @brief get the curent life ratio [0..1]
* @return The proportionnal life
*/
public float getLifeRatio() {
if (0 >= life) {
return 0;
}
return life/lifeMax;
}
/* /*
* @brief Check if the Entity is dead. * @brief Check if the Entity is dead.
* @return true if the Entity does not exist anymore, false otherwise. * @return true if the Entity does not exist anymore, false otherwise.
*/ */
public boolean isDead() { public boolean isDead() {
return (0 >= this.life)?true:false; return (0 >= this.life) ? true : false;
}; };
/** /**
* @brief Request if the Entity might be removed from the system * @brief Request if the Entity might be removed from the system
* @return true == > the object is removed * @return true == > the object is removed
*/ */
public boolean needToRemove() { public boolean needToRemove() {
return isDead(); return isDead();
} };
/**
* @brief, call when the Entity is removed (call only one time)
*/
public void onDestroy() {};
/**
* @brief Call when the Entity life change.
*/
public void onLifeChange() {}
public void removeComponent(final Component ref) {
if (ref == null) {
Log.error("try to remove an empty component");
return;
}
if (this.component.remove(ref) == false) {
Log.error("try to remove an unexisting component");
return;
}
this.env.engineComponentRemove(ref);
for (final Component it : this.component) {
it.removeFriendComponent(ref);
}
};
public void removeComponent(final String type) {
boolean findIt = false;
Component componentRemoved = null;
// check if not exist
for (int iii = 0; iii < this.component.size(); ++iii) {
if (this.component.get(iii).getType().contentEquals(type)) {
componentRemoved = this.component.get(iii);
this.component.remove(iii);
findIt = true;
break;
}
}
if (findIt == false) {
//Log.error("try to remove an unexisting component type : '" + type + "'");
return;
}
this.env.engineComponentRemove(componentRemoved);
for (final Component it : this.component) {
it.removeFriendComponent(componentRemoved);
}
};
/** /**
* @brief apply a fire on the Entity at a current power and a specific power. * @brief apply a fire on the Entity at a current power and a specific power.
* @param groupIdSource Source Id of the group, by default all event arrive at all group, buf some event can not be obviously apply at the ennemy like reparing .... * @param groupIdSource Source Id of the group, by default all event arrive at all group, buf some event can not be obviously apply at the ennemy like reparing ....
@ -142,129 +272,27 @@ public class Entity {
* @param power Power of the event (can be >0 for adding life). * @param power Power of the event (can be >0 for adding life).
* @param center Some fire decrease in function of space distance... * @param center Some fire decrease in function of space distance...
*/ */
public void setFireOn(int groupIdSource, int type, float power, Vector3f center) { public void setFireOn(final int groupIdSource, final int type, final float power, final Vector3f center) {
float previousLife = life; final float previousLife = this.life;
life += power; this.life += power;
life = Math.min(Math.max(0.0f, life), lifeMax); this.life = Math.min(Math.max(0.0f, this.life), this.lifeMax);
if (life <= 0) { if (this.life <= 0) {
Log.debug("[" + getUID() + "] Entity is killed ..."); Log.debug("[" + getUID() + "] Entity is killed ...");
} }
if (life != previousLife) { if (this.life != previousLife) {
onLifeChange(); onLifeChange();
} }
}
/**
* @brief Call when the Entity life change.
*/
public void onLifeChange() { };
// float lifeBorder = 0.1f;
// float lifeHeight = 0.3f;
// float lifeWidth = 2.0f;
// float lifeYPos = 1.7f;
// void Entity::drawLife(ewol::resource::Colored3DObject> draw, Camera> camera) {
// if (draw == null) {
// return;
// }
// float ratio = getLifeRatio();
// if (ratio == 1.0f) {
// return;
// }
// #if 0
// mat4 transformationMatrix = etk::matTranslate(getPosition())
// * etk::matRotate(Vector3f(0,0,1),camera.getAngleZ())
// * etk::matRotate(Vector3f(1,0,0),(MPI/2.0f-camera.getAngleTeta()));
// List<Vector3f> localVertices;
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos -lifeBorder,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0-lifeBorder,lifeYPos -lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos+lifeHeight+lifeBorder,0));
// localVertices.pushBack(Vector3f( lifeWidth/2.0+lifeBorder,lifeYPos -lifeBorder,0));
// etk::Color<float> myColor(0x0000FF99);
// draw.draw(localVertices, myColor, transformationMatrix, false, false);
// localVertices.clear();
// /** Bounding box == > model shape **/
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0 ,lifeYPos,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos + lifeHeight,0));
// localVertices.pushBack(Vector3f(-lifeWidth/2.0+lifeWidth*ratio,lifeYPos,0));
// myColor =0x00FF00FF;
// if (ratio < 0.2f) {
// myColor = 0xFF0000FF;
// } else if (ratio < 0.4f) {
// myColor = 0xDA7B00FF;
// }
// draw.draw(localVertices, myColor, transformationMatrix, false, false);
// #endif
// }
private int group = 0; //!< Every Entity has a generic group
/**
* @brief get the Group of the Entity.
* @return The group ID
*/
public int getGroup() {
return this.group;
}; };
/** /**
* @brief set the group of the curent Entity * @brief set the group of the curent Entity
* @param newGroup The new Group ID of the Entity. * @param newGroup The new Group ID of the Entity.
*/ */
public void setGroup(int newGroup) { public void setGroup(final int newGroup) {
this.group = newGroup; this.group = newGroup;
}
public boolean unInit() {
return true;
}; };
/**
* @brief Debug display of the current Entity
* @param[in,out] draw Basic system to draw the debug shape and informations
* @param camera Current camera for display
*/
// public void drawDebug(Colored3DObject draw, Camera camera) {
// /*
// mdebugText.clear();
// mdebugText.setColor(etk::Color<>(0x00, 0xFF, 0x00, 0xFF));
// mdebugText.setPos(Vector3f(-20,32,0));
// mdebugText.print(getType());
// mdebugText.setPos(Vector3f(-20,20,0));
// mdebugText.print("life=("+etk::toString(getLifeRatio()));
// */
// //mdebugText.print(String("Axe=(")+String(mtmpAxe.x())+String(",")+etk::UString(mtmpAxe.y())+etk::UString(",")+etk::UString(m_tmpAxe.z())+etk::UString(")"));
// /*
// // TODO Keep this it can be usefull to print something in direction of the camera ...
// mdebugText.draw( etk::matTranslate(getPosition())
// * etk::matRotate(Vector3f(0,0,1),camera.getAngleZ())
// * etk::matRotate(Vector3f(1,0,0),(MPI/2.0f-camera.getAngleTeta()))
// * etk::matScale(Vector3f(0.05,0.05,0.05)));
// */
// }
/**
* @brief Event arrive when an Entity has been remove from the system == > this permit to keep pointer of ennemy, and not search them every cycle ...
* @param removedEntity Pointer on the Entity removed.
*/
public void entityIsRemoved(Entity removedEntity) { };
protected float radius = 0; //!< Radius of the Entity (all Entity have a radius, if == 0 ==> then ghost ...
/**
* @brief get the current space needed by the Entity in the workspace
* @return The dimention needed.
*/
public float getRadius() {
return this.radius;
};
/**
* @brief, call when the Entity is removed (call only one time)
*/
public void onDestroy() {};
/**
* @brief set the elment in the physique engine
*/
public void dynamicEnable() {};
/**
* @brief remove this Entity from the physique engine
*/
public void dynamicDisable() {};
} }

View File

@ -15,7 +15,6 @@ import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType; import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gameengine.camera.Camera; import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.engines.EngineRender;
import org.atriasoft.gameengine.engines.EngineAI; import org.atriasoft.gameengine.engines.EngineAI;
import org.atriasoft.gameengine.engines.EngineDynamicMeshs; import org.atriasoft.gameengine.engines.EngineDynamicMeshs;
import org.atriasoft.gameengine.engines.EngineGravity; import org.atriasoft.gameengine.engines.EngineGravity;
@ -23,25 +22,46 @@ import org.atriasoft.gameengine.engines.EngineLight;
import org.atriasoft.gameengine.engines.EngineParticle; import org.atriasoft.gameengine.engines.EngineParticle;
import org.atriasoft.gameengine.engines.EnginePhysics; import org.atriasoft.gameengine.engines.EnginePhysics;
import org.atriasoft.gameengine.engines.EnginePlayer; import org.atriasoft.gameengine.engines.EnginePlayer;
import org.atriasoft.gameengine.engines.EngineRender;
import org.atriasoft.gameengine.internal.Log; import org.atriasoft.gameengine.internal.Log;
//import org.atriasoft.gameengine.resource.Mesh; //import org.atriasoft.gameengine.resource.Mesh;
public class Environement { public class Environement {
private static Map<String, CreatorEntity> creators = new HashMap<String, CreatorEntity>();
/**
* @brief add a creator entity system
* @param type Type of the entity.
* @param creator Function pointer that reference the entity creating.
*/
public static void addCreator(final String type, final CreatorEntity creator) {
if (creator == null) {
Log.error("Try to add an empty CREATOR ...");
return;
}
Log.debug("Add creator: " + type);
creators.put(type, creator);
Log.debug("Add creator: " + type + " (done)");
}
public Signal<Float> signalPlayTimeChange = new Signal<Float>(); public Signal<Float> signalPlayTimeChange = new Signal<Float>();
private GameStatus propertyStatus = GameStatus.gameStop; // !< the display is running (not in pause) private GameStatus propertyStatus = GameStatus.gameStop; // !< the display is running (not in pause)
public float propertyRatio = 1.0f; // !< Speed ratio public float propertyRatio = 1.0f; // !< Speed ratio
protected List<Engine> engines = new ArrayList<Engine>(); // !< EGE sub engine interface (like physique, rendering, protected List<Engine> engines = new ArrayList<Engine>(); // !< EGE sub engine interface (like physique, rendering,
// audio, ...). // audio, ...).
private List<Entity> listEntity = new ArrayList<Entity>(); // !< List of all entity added in the Game private final List<Entity> listEntity = new ArrayList<Entity>(); // !< List of all entity added in the Game
List<ControlInterface> controls = new ArrayList<ControlInterface>(); List<ControlInterface> controls = new ArrayList<ControlInterface>();
long lastCallTime = 0; long lastCallTime = 0;
// ! list of all camera in the world // ! list of all camera in the world
protected Map<String, Camera> listCamera = new HashMap<String, Camera>(); protected Map<String, Camera> listCamera = new HashMap<String, Camera>();
protected long gameTime = 0; // !< time of the game running
private long startTime;
//protected List<Mesh> listMeshToDrawFirst = new ArrayList<Mesh>();
protected long gameTime = 0; // !< time of the game running
private long startTime;
//protected List<Mesh> listMeshToDrawFirst = new ArrayList<Mesh>();
public Environement() { public Environement() {
addEngine(new EngineGravity(this)); addEngine(new EngineGravity(this));
addEngine(new EnginePlayer(this)); addEngine(new EnginePlayer(this));
@ -53,163 +73,57 @@ public class Environement {
addEngine(new EngineLight(this)); addEngine(new EngineLight(this));
} }
public void addControlInterface(ControlInterface ref) { /**
controls.add(ref); * @brief Add a camera in the camera pool.
} * @param name Name of the camera.
public void removeControlInterface(ControlInterface ref) { * @param camera Pointer on the camera to add.
controls.remove(ref); */
public void addCamera(final String name, final Camera camera) {
this.listCamera.put(name, camera);
} }
public void onPointer(KeySpecial special, public void addControlInterface(final ControlInterface ref) {
KeyType type, this.controls.add(ref);
int pointerID,
Vector2f pos,
KeyStatus state) {
EventInput event = new EventInput(type, state, pointerID, pos, special);
for (ControlInterface elem : controls) {
elem.onEventInput(event, pos);
}
}
public void onKeyboard( KeySpecial special,
KeyKeyboard type,
Character value,
KeyStatus state) {
EventEntry event = new EventEntry(special, type, state, value);
for (ControlInterface elem : controls) {
elem.onEventEntry(event);
}
} }
public void addEngine(final Engine ref) {
public void addEngine(Engine ref) {
if (ref == null) { if (ref == null) {
Log.error("try to add an empty Engine"); Log.error("try to add an empty Engine");
return; return;
} }
// check if not exist // check if not exist
for (Engine it : engines) { for (Engine it : this.engines) {
if (it.getType().contains(ref.getType())) { if (it.getType().contains(ref.getType())) {
it = ref; it = ref;
return; return;
} }
} }
// add it at the end ... // add it at the end ...
engines.add(ref); this.engines.add(ref);
} }
public void rmEngine(Engine ref) { /**
engines.remove(ref); * @brief add an entity on the list availlable.
} * @param newEntity Entity to add.
*/
public void rmEngine(String type) { public void addEntity(final Entity newEntity) {
for (Engine it : engines) { // prevent memory allocation and un allocation ...
if (it.getType().contains(type)) { if (newEntity == null) {
engines.remove(it);
return;
}
}
}
public Engine getEngine(String type) {
for (Engine it : engines) {
if (it.getType().contains(type)) {
return it;
}
}
Log.error("try to get an unexisting engine type: '" + type + "'");
return null;
}
public void engineComponentRemove(Component ref) {
for (Engine it: engines) {
if (it.getType().contentEquals(ref.getType())) {
it.componentRemove(ref);
return;
}
}
}
public void engineComponentAdd(Component ref) {
for (Engine it: engines) {
if (it.getType().contentEquals(ref.getType())) {
it.componentAdd(ref);
return;
}
}
}
public void render(long deltaMilli, String cameraName) {
Log.error("Render: " + cameraName + " time:" + deltaMilli);
// get the correct camera:
Camera camera = getCamera(cameraName);
if (camera == null) {
Log.error("Render: Can not get camera named: '" + cameraName + "'");
return; return;
} }
OpenGL.setCameraMatrix(camera.getConvertionMatrix()); this.listEntity.add(newEntity);
for (Engine it: engines) { newEntity.dynamicEnable();
//Log.verbose(" render: " + it.getType());
it.render(deltaMilli, camera);
}
// for (Engine it: engine) {
// if(it == null) {
// continue;
// }
// Log.verbose(" render: " + it.getType());
// it.renderDebug(deltaMilli, camera);
// }
}
/**
* @brief Add a camera in the camera pool.
* @param name Name of the camera.
* @param camera Pointer on the camera to add.
*/
public void addCamera(String name, Camera camera) {
listCamera.put(name, camera);
}
/**
* @brief Get a specific camera.
* @param name Name of the camera.
* @return A pointer on the camera requested.
*/
public Camera getCamera(String name) {
return listCamera.get(name);
}
/**
* @brief Get List of all camera.
* @return All the camera registerred.
*/
public Map<String, Camera> getCameraList() {
return listCamera;
} }
/** /**
* @brief Remove all from the current environement * @brief Remove all from the current environement
*/ */
public void clear() { public void clear() {
listEntity.clear(); this.listEntity.clear();
} }
private static Map<String, CreatorEntity> creators = new HashMap<String, CreatorEntity>(); public Entity createEntity(final String type, final boolean autoAddEntity) {
return this.createEntity(type, null, autoAddEntity);
/**
* @brief add a creator entity system
* @param type Type of the entity.
* @param creator Function pointer that reference the entity creating.
*/
public static void addCreator(String type, CreatorEntity creator) {
if (creator == null) {
Log.error("Try to add an empty CREATOR ...");
return;
}
Log.debug("Add creator: " + type);
creators.put(type, creator);
Log.debug("Add creator: " + type + " (done)");
} }
/** /**
@ -223,17 +137,17 @@ public class Environement {
* already added on the system. * already added on the system.
* @note Pointer is return in case of setting properties on it... * @note Pointer is return in case of setting properties on it...
*/ */
public Entity createEntity(String type, Object value, boolean autoAddEntity) { public Entity createEntity(final String type, final Object value, final boolean autoAddEntity) {
if (creators.containsKey(type) == false) { if (creators.containsKey(type) == false) {
Log.error("Request creating of an type that is not known '" + type + "'"); Log.error("Request creating of an type that is not known '" + type + "'");
return null; return null;
} }
CreatorEntity creatorPointer = creators.get(type); final CreatorEntity creatorPointer = creators.get(type);
if (creatorPointer == null) { if (creatorPointer == null) {
Log.error("null pointer creator == > internal error... '" + type + "'"); Log.error("null pointer creator == > internal error... '" + type + "'");
return null; return null;
} }
Entity tmpEntity = creatorPointer.create(this, value); final Entity tmpEntity = creatorPointer.create(this, value);
if (tmpEntity == null) { if (tmpEntity == null) {
Log.error("allocation error '" + type + "'"); Log.error("allocation error '" + type + "'");
return null; return null;
@ -245,46 +159,21 @@ public class Environement {
} }
public Entity createEntity(String type, boolean autoAddEntity) { public void engineComponentAdd(final Component ref) {
return this.createEntity(type, null, autoAddEntity); for (final Engine it : this.engines) {
if (it.getType().contentEquals(ref.getType())) {
it.componentAdd(ref);
return;
}
}
} }
/** public void engineComponentRemove(final Component ref) {
* @breif get a reference on the curent list of entity games for (final Engine it : this.engines) {
* @return all entity list if (it.getType().contentEquals(ref.getType())) {
*/ it.componentRemove(ref);
public List<Entity> getEntity() { return;
return listEntity; }
};
/**
* @brief add an entity on the list availlable.
* @param newEntity Entity to add.
*/
public void addEntity(Entity newEntity) {
// prevent memory allocation and un allocation ...
if (newEntity == null) {
return;
}
listEntity.add(newEntity);
newEntity.dynamicEnable();
}
/**
* @brief remove an entity on the list availlable.
* @param removeEntity Entity to remove.
*/
public void rmEntity(Entity removeEntity) {
if (removeEntity == null) {
return;
}
for (int iii=0; iii<listEntity.size() ; iii++) {
listEntity.get(iii).entityIsRemoved(removeEntity);
}
if (listEntity.remove(removeEntity) == true) {
removeEntity.onDestroy();
removeEntity.dynamicDisable();
removeEntity.unInit();
} }
} }
@ -293,10 +182,10 @@ public class Environement {
* explosion, or lazer fire ... * explosion, or lazer fire ...
* @param event event that might be apply ... * @param event event that might be apply ...
*/ */
public void generateInteraction(EntityInteraction event) { public void generateInteraction(final EntityInteraction event) {
// inform the entity that an entity has been removed ==> this permit to keep pointer on entitys ... // inform the entity that an entity has been removed ==> this permit to keep pointer on entitys ...
for (int iii=0; iii<listEntity.size() ; iii++) { for (int iii = 0; iii < this.listEntity.size(); iii++) {
event.applyEvent(listEntity.get(iii)); event.applyEvent(this.listEntity.get(iii));
/* /*
Vector3f destPosition = mlistEntity[iii].getPosition(); Vector3f destPosition = mlistEntity[iii].getPosition();
float dist = (sourcePosition - destPosition).length; float dist = (sourcePosition - destPosition).length;
@ -309,115 +198,223 @@ public class Environement {
} }
} }
// private void onCallbackPeriodicCall(ewol::event::Time event) { // private void onCallbackPeriodicCall(ewol::event::Time event) {
// float curentDelta = event.getDeltaCall(); // float curentDelta = event.getDeltaCall();
// EGEVERBOSE("periodic call : " + event); // EGEVERBOSE("periodic call : " + event);
// // small hack to change speed ... // // small hack to change speed ...
// curentDelta *= *propertyRatio; // curentDelta *= *propertyRatio;
// // check if the processing is availlable // // check if the processing is availlable
// if (propertyStatus.get() == gameStop) { // if (propertyStatus.get() == gameStop) {
// return; // return;
// } // }
// // update game time: // // update game time:
// int lastGameTime = mgameTime*0.000001f; // int lastGameTime = mgameTime*0.000001f;
// mgameTime += curentDelta; // mgameTime += curentDelta;
// if (lastGameTime != (int)(mgameTime*0.000001f)) { // if (lastGameTime != (int)(mgameTime*0.000001f)) {
// EGEVERBOSE(" Emit Signal"); // EGEVERBOSE(" Emit Signal");
// signalPlayTimeChange.emit(mgameTime*0.000001f); // signalPlayTimeChange.emit(mgameTime*0.000001f);
// } // }
// //
// //EWOLDEBUG("Time: mlastCallTime=" + mlastCallTime + " deltaTime=" + deltaTime); // //EWOLDEBUG("Time: mlastCallTime=" + mlastCallTime + " deltaTime=" + deltaTime);
// //
// // update camera positions: // // update camera positions:
// for (auto it : mlistCamera) { // for (auto it : mlistCamera) {
// if (it.second != null) { // if (it.second != null) {
// EGEVERBOSE(" update camera : '" + it.first + "'"); // EGEVERBOSE(" update camera : '" + it.first + "'");
// it.second.periodicCall(curentDelta); // it.second.periodicCall(curentDelta);
// } // }
// } // }
// EGEVERBOSE(" step simulation : " + curentDelta); // EGEVERBOSE(" step simulation : " + curentDelta);
// for (auto it: mengine) { // for (auto it: mengine) {
// if(it == null) { // if(it == null) {
// continue; // continue;
// } // }
// EGEVERBOSE(" update: " + it.getType()); // EGEVERBOSE(" update: " + it.getType());
// it.update(echrono::Duration(double(curentDelta))); // it.update(echrono::Duration(double(curentDelta)));
// } // }
// //
// //EGE.debug("stepSimulation (start)"); // //EGE.debug("stepSimulation (start)");
// ///step the simulation // ///step the simulation
// // TODO mphysicEngine.update(curentDelta); // // TODO mphysicEngine.update(curentDelta);
// // TODO //optional but useful: debug drawing // // TODO //optional but useful: debug drawing
// // TODO mphysicEngine.debugDrawWorld(); // // TODO mphysicEngine.debugDrawWorld();
// // TODO EGEINFO(" Update particule engine"); // // TODO EGEINFO(" Update particule engine");
// // TODO mparticuleEngine.update(curentDelta); // // TODO mparticuleEngine.update(curentDelta);
// // remove all entity that requested it ... // // remove all entity that requested it ...
// /** // /**
// { // {
// int numberEnnemyKilled=0; // int numberEnnemyKilled=0;
// int victoryPoint=0; // int victoryPoint=0;
// auto it(mlistEntity.begin()); // auto it(mlistEntity.begin());
// while (it != mlistEntity.end()) { // while (it != mlistEntity.end()) {
// if(*it != null) { // if(*it != null) {
// if ((*it).needToRemove() == true) { // if ((*it).needToRemove() == true) {
// if ((*it).getGroup() > 1) { // if ((*it).getGroup() > 1) {
// numberEnnemyKilled++; // numberEnnemyKilled++;
// victoryPoint++; // victoryPoint++;
// } // }
// EGEINFO("[" + (*it).getUID() + "] entity Removing ... " + (*it).getType()); // EGEINFO("[" + (*it).getUID() + "] entity Removing ... " + (*it).getType());
// rmEntity((*it)); // rmEntity((*it));
// it = mlistEntity.begin(); // it = mlistEntity.begin();
// } else { // } else {
// ++it; // ++it;
// } // }
// } else { // } else {
// ++it; // ++it;
// } // }
// } // }
// if (numberEnnemyKilled != 0) { // if (numberEnnemyKilled != 0) {
// //signalKillEnemy.emit(numberEnnemyKilled); // //signalKillEnemy.emit(numberEnnemyKilled);
// } // }
// } // }
// */ // */
// } // }
// public void addStaticMeshToDraw(Mesh mesh) { /**
// listMeshToDrawFirst.add(mesh); * @brief Get a specific camera.
// } * @param name Name of the camera.
// * @return A pointer on the camera requested.
// public List<Mesh> getStaticMeshToDraw() { */
// return listMeshToDrawFirst; public Camera getCamera(final String name) {
// } return this.listCamera.get(name);
public GameStatus getPropertyStatus() {
return propertyStatus;
} }
public void setPropertyStatus(GameStatus propertyStatus) { /**
* @brief Get List of all camera.
* @return All the camera registerred.
*/
public Map<String, Camera> getCameraList() {
return this.listCamera;
}
public Engine getEngine(final String type) {
for (final Engine it : this.engines) {
if (it.getType().contains(type)) {
return it;
}
}
Log.error("try to get an unexisting engine type: '" + type + "'");
return null;
}
/**
* @breif get a reference on the curent list of entity games
* @return all entity list
*/
public List<Entity> getEntity() {
return this.listEntity;
}
public GameStatus getPropertyStatus() {
return this.propertyStatus;
}
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) {
final EventEntry event = new EventEntry(special, type, state, value);
for (final ControlInterface elem : this.controls) {
elem.onEventEntry(event);
}
}
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) {
final EventInput event = new EventInput(type, state, pointerID, pos, special);
for (final ControlInterface elem : this.controls) {
elem.onEventInput(event, pos);
}
}
public void periodicCall() {
if (this.lastCallTime == 0) {
this.startTime = System.nanoTime() / 1000;
this.lastCallTime = this.startTime;
}
final long lastUpdate = this.lastCallTime;
this.lastCallTime = System.nanoTime() / 1000;
final EventTime event = new EventTime(this.lastCallTime, this.lastCallTime - this.startTime, this.lastCallTime - lastUpdate, this.lastCallTime - lastUpdate);
for (final ControlInterface elem : this.controls) {
elem.periodicCall(event);
}
for (final Engine engine : this.engines) {
engine.update((this.lastCallTime - lastUpdate) / 100);
}
};
public void removeControlInterface(final ControlInterface ref) {
this.controls.remove(ref);
}
public void render(final long deltaMilli, final String cameraName) {
//Log.error("Render: " + cameraName + " time:" + deltaMilli);
// get the correct camera:
final Camera camera = getCamera(cameraName);
if (camera == null) {
Log.error("Render: Can not get camera named: '" + cameraName + "'");
return;
}
OpenGL.setCameraMatrix(camera.getConvertionMatrix());
for (final Engine it : this.engines) {
//Log.verbose(" render: " + it.getType());
it.render(deltaMilli, camera);
}
// for (Engine it: engine) {
// if(it == null) {
// continue;
// }
// Log.verbose(" render: " + it.getType());
// it.renderDebug(deltaMilli, camera);
// }
}
public void rmEngine(final Engine ref) {
this.engines.remove(ref);
}
// public void addStaticMeshToDraw(Mesh mesh) {
// listMeshToDrawFirst.add(mesh);
// }
//
// public List<Mesh> getStaticMeshToDraw() {
// return listMeshToDrawFirst;
// }
public void rmEngine(final String type) {
for (final Engine it : this.engines) {
if (it.getType().contains(type)) {
this.engines.remove(it);
return;
}
}
}
/**
* @brief remove an entity on the list availlable.
* @param removeEntity Entity to remove.
*/
public void rmEntity(final Entity removeEntity) {
if (removeEntity == null) {
return;
}
for (int iii = 0; iii < this.listEntity.size(); iii++) {
this.listEntity.get(iii).entityIsRemoved(removeEntity);
}
if (this.listEntity.remove(removeEntity) == true) {
removeEntity.onDestroy();
removeEntity.dynamicDisable();
removeEntity.unInit();
}
}
public void setPropertyStatus(final GameStatus propertyStatus) {
if (this.propertyStatus == propertyStatus) { if (this.propertyStatus == propertyStatus) {
return; return;
} }
this.propertyStatus = propertyStatus; this.propertyStatus = propertyStatus;
// if (propertyStatus == GameStatus.gameStart) { // if (propertyStatus == GameStatus.gameStart) {
// mperiodicCallConnection = getObjectManager().periodicCall.connect(this, Environement::onCallbackPeriodicCall); // mperiodicCallConnection = getObjectManager().periodicCall.connect(this, Environement::onCallbackPeriodicCall);
// } else { // } else {
// mperiodicCallConnection.disconnect(); // mperiodicCallConnection.disconnect();
// } // }
}
public void periodicCall() {
if (lastCallTime == 0 ) {
startTime = System.nanoTime()/1000;
lastCallTime = startTime;
}
long lastUpdate = lastCallTime;
lastCallTime = System.nanoTime()/1000;
EventTime event = new EventTime(lastCallTime, lastCallTime-startTime, lastCallTime-lastUpdate, lastCallTime-lastUpdate);
for (ControlInterface elem : controls) {
elem.periodicCall(event);
}for (Engine engine : engines) {
engine.update((lastCallTime-lastUpdate)/100);
}
} }
} }

View File

@ -6,36 +6,46 @@ import org.atriasoft.gameengine.Light;
public class ComponentLight extends Component { public class ComponentLight extends Component {
// the material is not a resource, it can change in time... with AI or selection... // the material is not a resource, it can change in time... with AI or selection...
private Light light; private final Light light;
private ComponentPosition position; private ComponentPosition position;
private ComponentPhysics playerPhysics = null;
public ComponentLight(Light light) {
super();
this.light = light;
}
public void addFriendComponent(Component component) {
if (component.getType().contentEquals("position")) {
this.position = (ComponentPosition)component;
}
}
public ComponentLight() { public ComponentLight() {
super(); super();
this.light = new Light(); this.light = new Light();
} }
public ComponentLight(final Light light) {
super();
this.light = light;
}
@Override
public void addFriendComponent(final Component component) {
if (component.getType().contentEquals("position")) {
this.position = (ComponentPosition) component;
}
if (component.getType().contentEquals("physics")) {
this.playerPhysics = (ComponentPhysics) component;
}
}
public Light getLight() {
return this.light;
}
public Vector3f getPosition() {
if (this.position != null) {
return this.position.getTransform().getPosition().clone().add(this.light.getPositionDelta());
} else if (this.playerPhysics != null) {
return this.playerPhysics.getTransform().getPosition().clone().add(this.light.getPositionDelta());
}
return null;
}
@Override @Override
public String getType() { public String getType() {
return "light"; return "light";
} }
public Light getLight() {
return light;
}
public void setLight(Light light) {
this.light = light;
}
public Vector3f getPosition() {
return position.getTransform().getPosition().clone().add(light.getPositionDelta());
}
} }

View File

@ -3,6 +3,20 @@ package org.atriasoft.gameengine.components;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.atriasoft.ephysics.body.BodyType;
import org.atriasoft.ephysics.body.RigidBody;
import org.atriasoft.ephysics.collision.ProxyShape;
import org.atriasoft.ephysics.collision.TriangleMesh;
import org.atriasoft.ephysics.collision.TriangleVertexArray;
import org.atriasoft.ephysics.collision.shapes.AABB;
import org.atriasoft.ephysics.collision.shapes.BoxShape;
import org.atriasoft.ephysics.collision.shapes.CapsuleShape;
import org.atriasoft.ephysics.collision.shapes.CollisionShape;
import org.atriasoft.ephysics.collision.shapes.ConcaveMeshShape;
import org.atriasoft.ephysics.collision.shapes.ConcaveShape;
import org.atriasoft.ephysics.collision.shapes.ConeShape;
import org.atriasoft.ephysics.collision.shapes.CylinderShape;
import org.atriasoft.ephysics.collision.shapes.SphereShape;
import org.atriasoft.etk.Color; import org.atriasoft.etk.Color;
import org.atriasoft.etk.math.Matrix4f; import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Quaternion; import org.atriasoft.etk.math.Quaternion;
@ -11,6 +25,7 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.resource.ResourceColored3DObject; import org.atriasoft.gale.resource.ResourceColored3DObject;
import org.atriasoft.gameengine.Component; import org.atriasoft.gameengine.Component;
import org.atriasoft.gameengine.Environement; import org.atriasoft.gameengine.Environement;
import org.atriasoft.gameengine.Signal;
import org.atriasoft.gameengine.camera.Camera; import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.engines.EnginePhysics; import org.atriasoft.gameengine.engines.EnginePhysics;
import org.atriasoft.gameengine.internal.Log; import org.atriasoft.gameengine.internal.Log;
@ -23,24 +38,8 @@ import org.atriasoft.gameengine.physics.shape.Cylinder;
import org.atriasoft.gameengine.physics.shape.Shape; import org.atriasoft.gameengine.physics.shape.Shape;
import org.atriasoft.gameengine.physics.shape.Sphere; import org.atriasoft.gameengine.physics.shape.Sphere;
import net.jreactphysics3d.body.BodyType;
import net.jreactphysics3d.body.RigidBody;
import net.jreactphysics3d.collision.ProxyShape;
import net.jreactphysics3d.collision.TriangleMesh;
import net.jreactphysics3d.collision.TriangleVertexArray;
import net.jreactphysics3d.collision.shapes.AABB;
import net.jreactphysics3d.collision.shapes.BoxShape;
import net.jreactphysics3d.collision.shapes.CapsuleShape;
import net.jreactphysics3d.collision.shapes.CollisionShape;
import net.jreactphysics3d.collision.shapes.ConcaveMeshShape;
import net.jreactphysics3d.collision.shapes.ConcaveShape;
import net.jreactphysics3d.collision.shapes.ConeShape;
import net.jreactphysics3d.collision.shapes.CylinderShape;
import net.jreactphysics3d.collision.shapes.SphereShape;
public class ComponentPhysics extends Component { public class ComponentPhysics extends Component {
public Signal<Transform3D> signalPosition = new Signal<>();;
//public Signal<Transform3D> signalPosition;
protected Transform3D lastTransformEmit; protected Transform3D lastTransformEmit;
protected EnginePhysics engine; protected EnginePhysics engine;
protected RigidBody rigidBody; protected RigidBody rigidBody;
@ -64,6 +63,8 @@ public class ComponentPhysics extends Component {
this.rigidBody.setUserData(this); this.rigidBody.setUserData(this);
// set collision callback: // set collision callback:
//this.engine.getDynamicWorld().testCollision(this.rigidBody, this); //this.engine.getDynamicWorld().testCollision(this.rigidBody, this);
this.rigidBody.setAngularDamping(0.9f);
this.rigidBody.setLinearDamping(0.9f);
} }
/** /**
@ -90,6 +91,13 @@ public class ComponentPhysics extends Component {
this.rigidBody.setLinearDamping(0.9f); this.rigidBody.setLinearDamping(0.9f);
} }
@Override
public void addFriendComponent(final Component component) {
if (component.getType().contains("position")) {
Log.critical("Can not add a 'physic' component and a 'position' component ... ==> incompatible");
}
}
public void addShape(final Shape _shape) { public void addShape(final Shape _shape) {
this.shape.add(_shape); this.shape.add(_shape);
} }
@ -130,13 +138,13 @@ public class ComponentPhysics extends Component {
} }
/** /**
* @brief Apply an external force to the body at its center of mass. * @brief Apply an external force to the body at its center of mass.
* If the body is sleeping, calling this method will wake it up. * If the body is sleeping, calling this method will wake it up.
* @note The force is apply with a relative axis of the object * @note The force is apply with a relative axis of the object
* @note The force will we added to the sum of the applied forces and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing. * @note The force will we added to the sum of the applied forces and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
* @param[in] _force The external force to apply on the center of mass of the body * @param[in] _force The external force to apply on the center of mass of the body
* @param[in] _static The torque will be apply while the user des not call the same function with 0 value ... * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
*/ */
public void applyRelativeForceToCenterOfMass(final Vector3f _force) { public void applyRelativeForceToCenterOfMass(final Vector3f _force) {
if (this.rigidBody == null) { if (this.rigidBody == null) {
return; return;
@ -155,13 +163,13 @@ public class ComponentPhysics extends Component {
} }
/** /**
* @brief Apply an external torque to the body. * @brief Apply an external torque to the body.
* If the body is sleeping, calling this method will wake it up. * If the body is sleeping, calling this method will wake it up.
* @note The torque is apply with a relative axis of the object * @note The torque is apply with a relative axis of the object
* @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing. * @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
* @param[in] _torque The external torque to apply on the body * @param[in] _torque The external torque to apply on the body
* @param[in] _static The torque will be apply while the user des not call the same function with 0 value ... * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
*/ */
public void applyRelativeTorque(final Vector3f _torque) { public void applyRelativeTorque(final Vector3f _torque) {
if (this.rigidBody == null) { if (this.rigidBody == null) {
return; return;
@ -179,12 +187,12 @@ public class ComponentPhysics extends Component {
} }
/** /**
* @brief Apply an external torque to the body. * @brief Apply an external torque to the body.
* If the body is sleeping, calling this method will wake it up. * If the body is sleeping, calling this method will wake it up.
* @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing. * @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
* @param[in] _torque The external torque to apply on the body * @param[in] _torque The external torque to apply on the body
* @param[in] _static The torque will be apply while the user des not call the same function with 0 value ... * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
*/ */
public void applyTorque(final Vector3f _torque) { public void applyTorque(final Vector3f _torque) {
if (this.rigidBody == null) { if (this.rigidBody == null) {
return; return;
@ -292,7 +300,7 @@ public class ComponentPhysics extends Component {
final Transform3D transform = getTransform(); final Transform3D transform = getTransform();
if (this.lastTransformEmit != transform) { if (this.lastTransformEmit != transform) {
this.lastTransformEmit = transform; this.lastTransformEmit = transform;
//TODO Later ... signalPosition.emit(transform); this.signalPosition.emit(transform);
} }
} }
@ -579,689 +587,3 @@ public class ComponentPhysics extends Component {
} }
} }
} }
//
//
// private List<Shape> shapes = new ArrayList<>();
// //public esignal::Signal<Transform3D> signalPosition;
// protected Transform3D lastTransformEmit;
// protected RigidBody rigidBody;
// List<CollisionShape> listShape = new ArrayList<>();
// List<ProxyShape> listProxyShape = new ArrayList<>();
// protected boolean isStatic = false;
// Vector3f staticForceApplyCenterOfMass = new Vector3f(0, 0, 0);
// Vector3f staticTorqueApply = new Vector3f(0, 0, 0);
//
// /**
// * @brief Create a basic position component (no orientation and position (0,0,0))
// */
// public ComponentPhysics(final boolean isStatic) {
// this.isStatic = isStatic;
// this.lastTransformEmit = new Transform3D(new Vector3f(0, 0, 0), Quaternion.identity());
// }
//
// public ComponentPhysics(final boolean isStatic, final Transform3D _transform) {
// this.isStatic = isStatic;
// this.lastTransformEmit = _transform;
// }
//
// @Override
// public void addFriendComponent(final Component component) {
// if (component.getType().contentEquals("position")) {
// final ComponentPosition position = (ComponentPosition) component;
// }
// }
//
// /**
// * @brief Create a basic position component
// * @param[in] _transform transformation of the position
// */
// /*
// public ComponentPhysics(Environement _env, Transform3D _transform) {
// this.engine = ememory::dynamicPointerCast<ege::physics::Engine>(_env.getEngine(getType()));
// // Create a rigid body in the world
// this.rigidBody = this.engine.getDynamicWorld().createRigidBody(_transform);
// this.rigidBody.setUserData(this);
// this.lastTransformEmit = _transform;
// // set collision callback:
// //this.engine.getDynamicWorld().testCollision(this.rigidBody, this);
// Log.error("Bounciness=" + this.rigidBody.getMaterial().getBounciness());
// Log.error("FrictionCoefficient=" + this.rigidBody.getMaterial().getFrictionCoefficient());
// Log.error("RollingResistance=" + this.rigidBody.getMaterial().getRollingResistance());
// Log.error("LinearDamping=" + this.rigidBody.getLinearDamping());
// Log.error("AngularDamping=" + this.rigidBody.getAngularDamping());
// this.rigidBody.getMaterial().setBounciness(0.4);
// //this.rigidBody.getMaterial().setFrictionCoefficient(0.01);
// //this.rigidBody.getMaterial().setRollingResistance(0.01);
// this.rigidBody.setAngularDamping(0.9);
// this.rigidBody.setLinearDamping(0.9);
// }
// */
//
// //on close:
// /*
// ~Component() {
// if (this.rigidBody == null) {
// return;
// }
// // disable callback
// this.rigidBody.setUserData(null);
// this.engine.getDynamicWorld().testCollision(this.rigidBody, null);
// this.engine.getDynamicWorld().destroyRigidBody(this.rigidBody);
// this.rigidBody = null;
// }
// */
//
// public void addShape(final Shape _shape) {
// this.shapes.add(_shape);
// }
//
// /**
// * @brief Apply an external force to the body at a given point (in world-space coordinates).
// * If the point is not at the center of mass of the body, it will also generate some torque and therefore, change the angular velocity of the body.
// * If the body is sleeping, calling this method will wake it up. Note that the force will we added to the sum of the applied forces and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
// * @param[in] _force The force to apply on the body
// * @param[in] _point The point where the force is applied (in world-space coordinates)
// */
// public void applyForce(final Vector3f _force, final Vector3f _point) {
// if (this.rigidBody == null) {
// return;
// }
// this.rigidBody.applyForce(_force, _point);
// }
//
// /**
// * @brief Apply an external force to the body at its center of mass.
// * If the body is sleeping, calling this method will wake it up.
// * @note The force will we added to the sum of the applied forces and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
// * @param[in] _force The external force to apply on the center of mass of the body
// * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
// */
// public void applyForceToCenterOfMass(final Vector3f _force, final boolean _static) {
// if (this.rigidBody == null) {
// return;
// }
// if (_static == true) {
// this.staticForceApplyCenterOfMass = _force;
// } else {
// //this.rigidBody.applyForceToCenterOfMass(_force);
// Log.todo("applyForceToCenterOfMass");
// }
// }
//
// /**
// * @brief Apply an external force to the body at its center of mass.
// * If the body is sleeping, calling this method will wake it up.
// * @note The force is apply with a relative axis of the object
// * @note The force will we added to the sum of the applied forces and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
// * @param[in] _force The external force to apply on the center of mass of the body
// * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
// */
// public void applyRelativeForceToCenterOfMass(final Vector3f _force, final boolean _static) {
// if (this.rigidBody == null) {
// return;
// }
// final Vector3f force = this.rigidBody.getTransform().getOrientation().multiply(_force);
// if (_static == true) {
// this.staticForceApplyCenterOfMass = force;
// } else {
// //this.rigidBody.applyForceToCenterOfMass(force);
// Log.todo("applyForceToCenterOfMass");
// }
// }
//
// /**
// * @brief Apply an external torque to the body.
// * If the body is sleeping, calling this method will wake it up.
// * @note The torque is apply with a relative axis of the object
// * @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
// * @param[in] _torque The external torque to apply on the body
// * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
// */
// public void applyRelativeTorque(final Vector3f _torque, final boolean _static) {
// if (this.rigidBody == null) {
// return;
// }
// final Vector3f torque = this.rigidBody.getTransform().getOrientation().multiply(_torque);
// if (_static == true) {
// this.staticTorqueApply = torque;
// } else {
// this.rigidBody.applyTorque(torque);
// }
// }
//
// /**
// * @brief Apply an external torque to the body.
// * If the body is sleeping, calling this method will wake it up.
// * @note The force will we added to the sum of the applied torques and that this sum will be reset to zero at the end of each call of the DynamicsWorld::update() method. You can only apply a force to a dynamic body otherwise, this method will do nothing.
// * @param[in] _torque The external torque to apply on the body
// * @param[in] _static The torque will be apply while the user des not call the same function with 0 value ...
// */
// public void applyTorque(final Vector3f _torque, final boolean _static) {
// if (this.rigidBody == null) {
// return;
// }
// if (_static == true) {
// this.staticTorqueApply = _torque;
// } else {
// this.rigidBody.applyTorque(_torque);
// }
// }
//
// /**
// * @brief Called when a new contact point is found between two bodies that were separated before.
// * @param[in] _other The other component that have the impact
// * @param[in] _normal Normal of the impact
// * @param[in] _pos Position of the impact at the current object
// * @param[in] _posOther Position of the impact at the other object
// * @param[in] _penetrationDepth Depth penetration in the object
// */
// private void beginContact(final Component _other, final Vector3f _normal, final Vector3f _pos, final Vector3f _posOther, final float _penetrationDepth) {
// Log.warning(" collision [BEGIN] " + _pos + " depth=" + _penetrationDepth);
// }
//
// public void clearShape() {
// this.shapes.clear();
// }
//
// protected RigidBody createRigidBody(final CollisionShape collisionShape, final Transform3D transform, final float mass, final DynamicsWorld dynamicsWorld) {
//
// //this.collisionShape = collisionShape;
//
// final Matrix3f inertiaTensor = new Matrix3f();
// collisionShape.computeLocalInertiaTensor(inertiaTensor, mass);
//
// return dynamicsWorld.createRigidBody(transform, mass, inertiaTensor, collisionShape);
// }
//
// public void drawAABB(final ResourceColored3DObject debugDrawProperty) {
// if (this.rigidBody == null) {
// return;
// }
// /*
// Matrix4f transformationMatrix;
// Color<float> tmpColor(0.0, 1.0, 0.0, 0.8);
// ephysics::AABB value = this.rigidBody.getAABB();
// _draw.drawCubeLine(value.getMin(), value.getMax(), tmpColor, transformationMatrix);
// */
// }
//
// // call done after all cycle update of the physical engine
// public void emitAll() {
// // emit onbly of new ...
// final Transform3D transform = getTransform();
// if (this.lastTransformEmit != transform) {
// this.lastTransformEmit = transform;
// //signalPosition.emit(transform);
// }
// }
//
// public void generate(final DynamicsWorld dynamicsWorld) {
// if (this.shapes.size() == 0) {
// Log.warning("No Shape Availlable ...");
// return;
// }
// for (final Shape it : this.shapes) {
// if (it == null) {
// continue;
// }
// if (it.isBox()) {
// Log.debug(" Box");
// final Box tmpElement = (Box) it;
// // Half extents of the box in the x, y and z directions
// final Vector3f halfExtents = new Vector3f(tmpElement.getSize().x, tmpElement.getSize().y, tmpElement.getSize().z);
// // Create the box shape
// final BoxShape shape = new BoxShape(halfExtents, 0.0001f);
// //this.listShape.add(shape);
// // The ephysic use Y as UP ==> ege use Z as UP
// //orientation = orientation.multiplyNew(new Quaternion(-0.707107, 0, 0, 0.707107));
// final Transform3D transform = new Transform3D(it.getOrigin(), it.getOrientation());
// final ProxyShape proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// proxyShape.setUserData(this);
// this.listProxyShape.add(proxyShape);
//
// this.rigidBody = createRigidBody(shape, transform, it.getMass(), dynamicsWorld);
// proxyShape.setUserData(this);
// //this.rigidBody.getMaterial().setBounciness(0.4f);
// //this.rigidBody.setAngularDamping(0.9f);
// //this.rigidBody.setLinearDamping(0.9f);
// } else if (it.isCylinder()) {
// Log.debug(" Cylinder");
// final Cylinder tmpElement = (Cylinder) it;
// // Create the Cylinder shape
// final CylinderShape shape = new CylinderShape(tmpElement.getRadius(), tmpElement.getSize(), 0.0001f);
//
// // The ephysic use Y as UP ==> ege use Z as UP
// //orientation = orientation.multiplyNew(new Quaternion(-0.707107, 0, 0, 0.707107));
// final Transform3D transform = new Transform3D(it.getOrigin(), it.getOrientation());
// //ProxyShape proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// this.rigidBody = createRigidBody(shape, transform, it.getMass(), dynamicsWorld);
// //this.colisionShape = shape;
//
// // set it enable in the system:
// //this.rigidBody.setIsMotionEnabled(true);
// // Change the material properties of the rigid body
// final Material material = this.rigidBody.getMaterial();
// material.setBounciness(0.2f);
// } else if (it.isCapsule()) {
// Log.debug(" Capsule");
// /*
// final Capsule tmpElement = (Capsule) it;
//
// // Create the Capsule shape
// final CapsuleShape shape = new CapsuleShape(tmpElement.getRadius(), tmpElement.getSize(), 0.0001f);
//
// // The ephysic use Y as UP ==> ege use Z as UP
// //orientation = orientation.multiplyNew(new Quaternion(-0.707107, 0, 0, 0.707107));
// final Transform3D transform = new Transform3D(it.getOrigin(), it.getOrientation());
// //ProxyShape proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// this.rigidBody = createRigidBody(shape, transform, it.getMass(), dynamicsWorld);
// //this.colisionShape = shape;
//
// // set it enable in the system:
// //this.rigidBody.isMotionEnabled(true);
// // Change the material properties of the rigid body
// final Material material = this.rigidBody.getMaterial();
// material.setBounciness(0.2f);
// */
// } else if (it.isCone()) {
// /*
// Log.debug(" Cone");
// final Cone tmpElement = (Cone) it;
// final ConeShape shape = new ConeShape(tmpElement.getRadius(), tmpElement.getSize(), 0.0001f);
// // The ephysic use Y as UP ==> ege use Z as UP
// //orientation = orientation.multiplyNew(new Quaternion(-0.707107, 0, 0, 0.707107));
// final Transform3D transform = new Transform3D(it.getOrigin(), it.getOrientation());
// final ProxyShape proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// proxyShape.setUserData(this);
// this.listProxyShape.add(proxyShape);
// this.rigidBody = createRigidBody(shape, transform, it.getMass(), dynamicsWorld);
// //this.colisionShape = shape;
//
// // set it enable in the system:
// //this.rigidBody.setIsMotionEnabled(true);
// // Change the material properties of the rigid body
// final Material material = this.rigidBody.getMaterial();
// material.setBounciness(0.2f);
// */
// } else if (it.isSphere()) {
// /*
// Log.debug(" Sphere");
// final Sphere tmpElement = (Sphere) it;
// final SphereShape shape = new SphereShape(tmpElement.getRadius(), 0.0001f);
// // The ephysic use Y as UP ==> ege use Z as UP
// //orientation = orientation.multiplyNew(new Quaternion(-0.707107, 0, 0, 0.707107));
// final Transform3D transform = new Transform3D(it.getOrigin(), it.getOrientation());
// //ProxyShape proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// this.rigidBody = createRigidBody(shape, transform, it.getMass(), dynamicsWorld);
// this.colisionShape = shape;
//
// // set it enable in the system:
// this.rigidBody.setIsMotionEnabled(true);
// // Change the material properties of the rigid body
// final Material material = this.rigidBody.getMaterial();
// material.setBounciness(0.2f);
// */
// } else if (it.isConcave()) {
// Log.debug(" Concave");
// final Concave tmpElement = (Concave) it;
// /*
// static Vector<Vector3f> vertices = {Vector3f(-100.0f,-100.0f,-50.0f),Vector3f(100.0f,-100.0f,-50.0f),Vector3f(100.0f,100.0f,-50.0f)};
// static Vector<uint32_t> indices = {0,1,2};
//
// ephysics::TriangleVertexArray* triangleArray = ETK_NEW(ephysics::TriangleVertexArray, vertices, indices);
// #else
// ephysics::TriangleVertexArray* triangleArray = ETK_NEW(ephysics::TriangleVertexArray, tmpElement.getVertex(), tmpElement.getIndices());
// #endif
// // Now that we have a TriangleVertexArray, we need to create a TriangleMesh and add the TriangleVertexArray into it as a subpart.
// // Once this is done, we can create the actual ConcaveMeshShape and add it to the body we want to simulate as in the following example:
// ephysics::TriangleMesh* triangleMesh = ETK_NEW(ephysics::TriangleMesh);
// // Add the triangle vertex array to the triangle mesh
// triangleMesh.addSubpart(triangleArray);
// // Create the concave mesh shape
// ephysics::ConcaveShape* shape = ETK_NEW(ephysics::ConcaveMeshShape, triangleMesh);
// // The ephysic use Y as UP ==> ege use Z as UP
// Quaternion orientation = it.getOrientation() * Quaternion(-0.707107, 0, 0, 0.707107);
// Transform3D transform(it.getOrigin(), it.getOrientation());
// ephysics::ProxyShape* proxyShape = this.rigidBody.addCollisionShape(shape, transform, it.getMass());
// proxyShape.setUserData(this);
// this.listProxyShape.pushBack(proxyShape);
// break;
// */
// } else {
// Log.debug(" ???");
// }
// }
// }
//
// /**
// * @brief Get the angular velocity (whole world).
// * @return The angular velocity vector of the body
// */
// public Vector3f getAngularVelocity() {
// if (this.rigidBody == null) {
// return new Vector3f(0, 0, 0);
// }
// return this.rigidBody.getAngularVelocity();
// }
//
// /**
// * @brief Get the linear velocity (whole world).
// * @return The linear velocity vector of the body
// */
// public Vector3f getLinearVelocity() {
// if (this.rigidBody == null) {
// return new Vector3f(0, 0, 0);
// }
// return this.rigidBody.getLinearVelocity();
// }
//
// /**
// * @brief Get the angular velocity (local Body).
// * @return The angular velocity vector of the body
// */
// public Vector3f getRelativeAngularVelocity() {
// if (this.rigidBody == null) {
// return new Vector3f(0, 0, 0);
// }
// final Vector3f value = this.rigidBody.getAngularVelocity();
// return this.rigidBody.getTransform().getOrientation().inverseNew().multiply(value);
// }
//
// /**
// * @brief Get the linear velocity (local Body).
// * @return The linear velocity vector of the body
// */
// public Vector3f getRelativeLinearVelocity() {
// if (this.rigidBody == null) {
// return new Vector3f(0, 0, 0);
// }
// final Vector3f value = this.rigidBody.getLinearVelocity();
// return this.rigidBody.getTransform().getOrientation().inverseNew().multiply(value);
// }
//
// public List<Shape> getShape() {
// return this.shapes;
// }
//
// /**
// * @brief set a new transformation
// * @return Transformation of the position
// */
// public Transform3D getTransform() {
// if (this.rigidBody == null) {
// return Transform3D.identity();
// }
// return this.rigidBody.getTransform();
// }
//
// @Override
// public String getType() {
// return "physics";
// }
//
// /**
// * @brief Called when a new contact point is found between two bodies.
// * @param[in] _other The other component that have the impact
// * @param[in] _normal Normal of the impact
// * @param[in] _pos Position of the impact at the current object
// * @param[in] _posOther Position of the impact at the other object
// * @param[in] _penetrationDepth Depth penetration in the object
// */
// private void newContact(final Component _other, final Vector3f _normal, final Vector3f _pos, final Vector3f _posOther, final float _penetrationDepth) {
// Log.warning(" collision [ NEW ] " + _pos + " depth=" + _penetrationDepth);
// }
//
// @Override
// public void removeFriendComponent(final Component component) {
// // nothing to do.
// }
//
// public void renderDebug(final ResourceColored3DObject debugDrawProperty) {
// final Color displayColor;
// /*
// if (this.aabbIntersection.size() == 0) {
// displayColor = new Color(1,1,1,1);
// } else {
// if (this.narrowIntersection.size() == 0) {
// displayColor = new Color(1,1,0,1);
// } else {
// displayColor = new Color(1,0,0,1);
// }
// }
// if (aabb != null) {
// debugDrawProperty.drawCubeLine(aabb.getMin(), aabb.getMax(), displayColor, Matrix4f.identity(), true, true);
// //debugDrawProperty.drawCubeLine(new Vector3f(0,0,0), new Vector3f(32,32,32), new Color(1,0,1,1), Matrix4f.identity(), true, true);
// } else {
// Log.error("no AABB");
// }
// */
// for (final Shape shape : this.shapes) {
// //shape.renderDebug(position.getTransform(), debugDrawProperty);
// }
// //}
// //public void drawShape(ewol::resource::Colored3DObject _draw, ege::Camera _camera) {
// /*
// Transform3D transform = getTransform();
// float mmm[16];
// // Get the OpenGL matrix array of the transform
// transform.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrix(mmm);
// transformationMatrix.transpose();
// Color<float> tmpColor(1.0, 0.0, 0.0, 0.3);
// for (auto &it: this.shape) {
// if (it == null) {
// continue;
// }
// switch (it.getType()) {
// case ege::physics::Shape::type::box: {
// Log.debug(" Box");
// ege::physics::shape::Box* tmpElement = it.toBox();
// if (tmpElement == null) {
// Log.error(" Box ==> can not cast in BOX");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
// _draw.drawSquare(tmpElement.getSize(), transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::cylinder: {
// Log.debug(" Cylinder");
// ege::physics::shape::Cylinder* tmpElement = it.toCylinder();
// if (tmpElement == null) {
// Log.error(" Cylinder ==> can not cast in Cylinder");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
// _draw.drawCylinder(tmpElement.getRadius(), tmpElement.getSize(), 10, 10, transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::capsule: {
// Log.debug(" Capsule");
// ege::physics::shape::Capsule* tmpElement = it.toCapsule();
// if (tmpElement == null) {
// Log.error(" Capsule ==> can not cast in Capsule");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
// _draw.drawCapsule(tmpElement.getRadius(), tmpElement.getSize(), 10, 10, transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::cone: {
// Log.debug(" Cone");
// ege::physics::shape::Cone* tmpElement = it.toCone();
// if (tmpElement == null) {
// Log.error(" Cone ==> can not cast in Cone");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
// _draw.drawCone(tmpElement.getRadius(), tmpElement.getSize(), 10, 10, transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::sphere: {
// Log.debug(" Sphere");
// ege::physics::shape::Sphere* tmpElement = it.toSphere();
// if (tmpElement == null) {
// Log.error(" Sphere ==> can not cast in Sphere");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
// _draw.drawSphere(tmpElement.getRadius(), 10, 10, transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::concave: {
// Log.debug(" concave");
// ege::physics::shape::Concave* tmpElement = it.toConcave();
// if (tmpElement == null) {
// Log.error(" concave ==> can not cast in convexHull");
// continue;
// }
// Transform3D transformLocal(it.getOrigin(), it.getOrientation());
// transformLocal.getOpenGLMatrix(mmm);
// Matrix4f transformationMatrixLocal(mmm);
// transformationMatrixLocal.transpose();
// transformationMatrixLocal = transformationMatrix * transformationMatrixLocal;
//
// _draw.drawTriangles(tmpElement.getVertex(), tmpElement.getIndices(), transformationMatrixLocal, tmpColor);
// break;
// }
// case ege::physics::Shape::type::convexHull: {
// Log.debug(" convexHull");
// ege::physics::shape::ConvexHull* tmpElement = it.toConvexHull();
// if (tmpElement == null) {
// Log.error(" convexHull ==> can not cast in convexHull");
// continue;
// }
// break;
// }
// default :
// Log.debug(" ???");
// break;
// }
// }
// */
// }
//
// /**
// * @brief Set the angular velocity (whole world).
// * @param[in] _linearVelocity The angular velocity vector of the body
// */
// public void setAngularVelocity(final Vector3f _angularVelocity) {
// if (this.rigidBody == null) {
// return;
// }
// this.rigidBody.setAngularVelocity(_angularVelocity);
// }
//
// /**
// * @brief Set the linear velocity (whole world).
// * @param[in] _linearVelocity The linear velocity vector of the body
// */
// public void setLinearVelocity(final Vector3f _linearVelocity) {
// if (this.rigidBody == null) {
// return;
// }
// this.rigidBody.setLinearVelocity(_linearVelocity);
// };
//
// /**
// * @brief Set the angular velocity (local Body).
// * @param[in] _linearVelocity The angular velocity vector of the body
// */
// public void setRelativeAngularVelocity(final Vector3f _angularVelocity) {
// if (this.rigidBody == null) {
// return;
// }
// final Vector3f value = this.rigidBody.getTransform().getOrientation().multiply(_angularVelocity);
// this.rigidBody.setAngularVelocity(value);
// }
//
// /**
// * @brief Set the linear velocity (local Body).
// * @param[in] _linearVelocity The linear velocity vector of the body
// */
// public void setRelativeLinearVelocity(final Vector3f _linearVelocity) {
// if (this.rigidBody == null) {
// return;
// }
// final Vector3f value = this.rigidBody.getTransform().getOrientation().multiply(_linearVelocity);
// this.rigidBody.setLinearVelocity(value);
// }
//
// public void setShape(final List<Shape> _prop) {
// this.shapes = _prop;
// }
//
// /*
// public enum type {
// bodyDynamic;
// bodyStatic;
// bodyKinematic;
// }
//
// public void setType(type _type) {
// if (this.rigidBody == null) {
// return;
// }
// switch(_type) {
// case bodyStatic:
// //rigidBody.setType(STATIC);
// break;
// case bodyKinematic:
// //rigidBody.setType(KINEMATIC);
// break;
// case bodyDynamic:
// //rigidBody.setType(DYNAMIC);
// break;
// }
// }
// */
// /**
// * @brief set a new transformation
// * @param[in] _transform transformation of the position
// */
// public void setTransform(final Transform3D _transform) {
// if (this.rigidBody == null) {
// return;
// }
// this.rigidBody.setTransform(_transform);
// }
//
// // call of this function every time the call will be done
// private void update(final float _delta) {
// if (this.rigidBody == null) {
// return;
// }
// /*
// if (this.staticForceApplyCenterOfMass != Vector3f(0,0,0)) {
// Vector3f tmp = this.staticForceApplyCenterOfMass*_delta;
// Log.error("FORCE : " + tmp );
// this.rigidBody.applyForceToCenterOfMass(tmp);
// }
// if (this.staticTorqueApply != Vector3f(0,0,0)) {
// Vector3f tmp = this.staticTorqueApply*_delta;
// Log.error("TORQUE : " + tmp);
// this.rigidBody.applyTorque(tmp);
// }
// */
// }

View File

@ -2,49 +2,57 @@ package org.atriasoft.gameengine.components;
import org.atriasoft.etk.math.Transform3D; import org.atriasoft.etk.math.Transform3D;
import org.atriasoft.gameengine.Component; import org.atriasoft.gameengine.Component;
import org.atriasoft.gameengine.internal.Log;
import org.atriasoft.gameengine.Signal; import org.atriasoft.gameengine.Signal;
import org.atriasoft.gameengine.internal.Log;
public class ComponentPosition extends Component { public class ComponentPosition extends Component {
public Signal<Transform3D> signalPosition; public Signal<Transform3D> signalPosition;
protected Transform3D transform; protected Transform3D transform;
/** /**
* @brief Create a basic position component (no orientation and position (0,0,0)) * @brief Create a basic position component (no orientation and position (0,0,0))
*/ */
public ComponentPosition() { public ComponentPosition() {
transform = Transform3D.identity(); this.transform = Transform3D.identity();
} }
/** /**
* @brief Create a basic position component * @brief Create a basic position component
* @param transform transformation of the position * @param transform transformation of the position
*/ */
public ComponentPosition(Transform3D transform) { public ComponentPosition(final Transform3D transform) {
this.transform = transform; this.transform = transform;
} }
/**
* @brief set a new transformation @Override
* @param transform transformation of the position public void addFriendComponent(final Component component) {
*/ if (component.getType().contains("physics")) {
void setTransform(Transform3D transform) { Log.critical("Can not add a 'physic' component and a 'position' component ... ==> incompatible");
if (this.transform.isEqual(transform)) {
return;
} }
this.transform = transform;
signalPosition.emit(this.transform);
} }
/** /**
* @brief set a new transformation * @brief set a new transformation
* @return Transformation of the position * @return Transformation of the position
*/ */
public Transform3D getTransform() { public Transform3D getTransform() {
return transform; return this.transform;
} }
@Override
public String getType() { public String getType() {
return "position"; return "position";
} }
public void addFriendComponent(Component component) {
if (component.getType().contains("physics")) { /**
Log.error("Can not add a 'physic' component and a 'position' component ... ==> incompatible"); * @brief set a new transformation
* @param transform transformation of the position
*/
void setTransform(final Transform3D transform) {
if (this.transform.isEqual(transform)) {
return;
} }
this.transform = transform;
this.signalPosition.emit(this.transform);
} }
} }

View File

@ -9,12 +9,14 @@ import org.atriasoft.gameengine.Component;
import org.atriasoft.gameengine.Light; import org.atriasoft.gameengine.Light;
import org.atriasoft.gameengine.Material; import org.atriasoft.gameengine.Material;
import org.atriasoft.gameengine.engines.EngineLight; import org.atriasoft.gameengine.engines.EngineLight;
public class ComponentRenderTexturedMaterialsStaticMesh extends ComponentRender { public class ComponentRenderTexturedMaterialsStaticMesh extends ComponentRender {
private static final int numberOfLight = 8; private static final int numberOfLight = 8;
ComponentStaticMesh mesh = null; ComponentStaticMesh mesh = null;
ComponentTexture texture = null; ComponentTexture texture = null;
ComponentMaterial material = null; ComponentMaterial material = null;
ComponentPosition position = null; ComponentPosition position = null;
private ComponentPhysics playerPhysics = null;
ResourceProgram program = null; ResourceProgram program = null;
EngineLight lightEngine; EngineLight lightEngine;
private int GLMatrixTransformation; private int GLMatrixTransformation;
@ -26,70 +28,83 @@ public class ComponentRenderTexturedMaterialsStaticMesh extends ComponentRender
private int GLshininess; private int GLshininess;
private GlLightIndex[] GLlights; private GlLightIndex[] GLlights;
public ComponentRenderTexturedMaterialsStaticMesh(Uri vertexShader, Uri fragmentShader, EngineLight lightEngine) { public ComponentRenderTexturedMaterialsStaticMesh(final Uri vertexShader, final Uri fragmentShader, final EngineLight lightEngine) {
this.lightEngine = lightEngine; this.lightEngine = lightEngine;
this.program = ResourceProgram.create(vertexShader, fragmentShader); this.program = ResourceProgram.create(vertexShader, fragmentShader);
if (this.program != null) { if (this.program != null) {
this.GLMatrixTransformation = this.program.getUniform("in_matrixTransformation"); this.GLMatrixTransformation = this.program.getUniform("in_matrixTransformation");
this.GLMatrixProjection = this.program.getUniform("in_matrixProjection"); this.GLMatrixProjection = this.program.getUniform("in_matrixProjection");
this.GLMatrixView = this.program.getUniform("in_matrixView"); this.GLMatrixView = this.program.getUniform("in_matrixView");
this.GLambientFactor = this.program.getUniform("in_material.ambientFactor"); this.GLambientFactor = this.program.getUniform("in_material.ambientFactor");
this.GLdiffuseFactor = this.program.getUniform("in_material.diffuseFactor"); this.GLdiffuseFactor = this.program.getUniform("in_material.diffuseFactor");
this.GLspecularFactor = this.program.getUniform("in_material.specularFactor"); this.GLspecularFactor = this.program.getUniform("in_material.specularFactor");
this.GLshininess = this.program.getUniform("in_material.shininess"); this.GLshininess = this.program.getUniform("in_material.shininess");
this.GLlights = new GlLightIndex[numberOfLight]; this.GLlights = new GlLightIndex[numberOfLight];
for (int iii=0; iii<numberOfLight; iii++) { for (int iii = 0; iii < numberOfLight; iii++) {
int color = this.program.getUniform("in_lights[" + iii + "].color"); final int color = this.program.getUniform("in_lights[" + iii + "].color");
int position = this.program.getUniform("in_lights[" + iii + "].position"); final int position = this.program.getUniform("in_lights[" + iii + "].position");
int attenuation = this.program.getUniform("in_lights[" + iii + "].attenuation"); final int attenuation = this.program.getUniform("in_lights[" + iii + "].attenuation");
this.GLlights[iii] = new GlLightIndex(color, position, attenuation); this.GLlights[iii] = new GlLightIndex(color, position, attenuation);
} }
} }
} }
@Override @Override
public void addFriendComponent(Component component) { public void addFriendComponent(final Component component) {
if (component.getType().contentEquals("static-mesh")) { if (component.getType().contentEquals("static-mesh")) {
mesh = (ComponentStaticMesh)component; this.mesh = (ComponentStaticMesh) component;
} }
if (component.getType().contentEquals("texture")) { if (component.getType().contentEquals("texture")) {
texture = (ComponentTexture)component; this.texture = (ComponentTexture) component;
} }
if (component.getType().contentEquals("material")) { if (component.getType().contentEquals("material")) {
material = (ComponentMaterial)component; this.material = (ComponentMaterial) component;
} }
if (component.getType().contentEquals("position")) { if (component.getType().contentEquals("position")) {
position = (ComponentPosition)component; this.position = (ComponentPosition) component;
}
if (component.getType().contentEquals("physics")) {
this.playerPhysics = (ComponentPhysics) component;
} }
} }
@Override @Override
public void removeFriendComponent(Component component) { public void removeFriendComponent(final Component component) {
// nothing to do. // nothing to do.
} }
@Override @Override
public void render() { public void render() {
this.program.use(); this.program.use();
Light[] lights = this.lightEngine.getNearest(position.getTransform().getPosition()); Light[] lights = null;
Matrix4f projectionMatrix = OpenGL.getMatrix(); Matrix4f transformationMatrix = null;
Matrix4f viewMatrix = OpenGL.getCameraMatrix(); if (this.position != null) {
Matrix4f transformationMatrix = position.getTransform().getOpenGLMatrix(); lights = this.lightEngine.getNearest(this.position.getTransform().getPosition());
transformationMatrix = this.position.getTransform().getOpenGLMatrix();
} else if (this.playerPhysics != null) {
lights = this.lightEngine.getNearest(this.playerPhysics.getTransform().getPosition());
transformationMatrix = this.playerPhysics.getTransform().getOpenGLMatrix();
}
final Matrix4f projectionMatrix = OpenGL.getMatrix();
final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
this.mesh.bindForRendering(); this.mesh.bindForRendering();
this.texture.bindForRendering(); this.texture.bindForRendering();
Material mat = this.material.getMaterial(); final Material mat = this.material.getMaterial();
this.program.uniformVector(GLambientFactor, mat.getAmbientFactor()); this.program.uniformVector(this.GLambientFactor, mat.getAmbientFactor());
this.program.uniformVector(GLdiffuseFactor, mat.getDiffuseFactor()); this.program.uniformVector(this.GLdiffuseFactor, mat.getDiffuseFactor());
this.program.uniformVector(GLspecularFactor, mat.getSpecularFactor()); this.program.uniformVector(this.GLspecularFactor, mat.getSpecularFactor());
this.program.uniformFloat(GLshininess, mat.getShininess()); this.program.uniformFloat(this.GLshininess, mat.getShininess());
for (int iii=0; iii<numberOfLight; iii++) { for (int iii = 0; iii < numberOfLight; iii++) {
if (lights[iii] != null) { if (lights[iii] != null) {
this.program.uniformVector(this.GLlights[iii].oGLposition, lights[iii].getPositionDelta()); this.program.uniformVector(this.GLlights[iii].oGLposition, lights[iii].getPositionDelta());
this.program.uniformVector(this.GLlights[iii].oGLcolor, lights[iii].getColor()); this.program.uniformVector(this.GLlights[iii].oGLcolor, lights[iii].getColor());
this.program.uniformVector(this.GLlights[iii].oGLattenuation, lights[iii].getAttenuation()); this.program.uniformVector(this.GLlights[iii].oGLattenuation, lights[iii].getAttenuation());
} else { } else {
this.program.uniformVector(this.GLlights[iii].oGLposition, new Vector3f(0,0,0)); this.program.uniformVector(this.GLlights[iii].oGLposition, new Vector3f(0, 0, 0));
this.program.uniformVector(this.GLlights[iii].oGLcolor, new Vector3f(0,0,0)); this.program.uniformVector(this.GLlights[iii].oGLcolor, new Vector3f(0, 0, 0));
this.program.uniformVector(this.GLlights[iii].oGLattenuation, new Vector3f(1,0,0)); this.program.uniformVector(this.GLlights[iii].oGLattenuation, new Vector3f(1, 0, 0));
} }
} }
this.program.uniformMatrix(this.GLMatrixView, viewMatrix); this.program.uniformMatrix(this.GLMatrixView, viewMatrix);
@ -105,4 +120,3 @@ public class ComponentRenderTexturedMaterialsStaticMesh extends ComponentRender
this.program.unUse(); this.program.unUse();
} }
} }

View File

@ -10,42 +10,54 @@ public class ComponentRenderTexturedStaticMesh extends ComponentRender {
ComponentStaticMesh mesh = null; ComponentStaticMesh mesh = null;
ComponentTexture texture = null; ComponentTexture texture = null;
ComponentPosition position = null; ComponentPosition position = null;
private ComponentPhysics playerPhysics = null;
ResourceProgram program = null; ResourceProgram program = null;
private int GLMatrixTransformation; private int GLMatrixTransformation;
private int GLMatrixProjection; private int GLMatrixProjection;
private int GLMatrixView; private int GLMatrixView;
public ComponentRenderTexturedStaticMesh(Uri vertexShader, Uri fragmentShader) { public ComponentRenderTexturedStaticMesh(final Uri vertexShader, final Uri fragmentShader) {
this.program = ResourceProgram.create(vertexShader, fragmentShader); this.program = ResourceProgram.create(vertexShader, fragmentShader);
if (this.program != null) { if (this.program != null) {
this.GLMatrixTransformation = this.program.getUniform("in_matrixTransformation"); this.GLMatrixTransformation = this.program.getUniform("in_matrixTransformation");
this.GLMatrixProjection = this.program.getUniform("in_matrixProjection"); this.GLMatrixProjection = this.program.getUniform("in_matrixProjection");
this.GLMatrixView = this.program.getUniform("in_matrixView"); this.GLMatrixView = this.program.getUniform("in_matrixView");
} }
} }
@Override @Override
public void addFriendComponent(Component component) { public void addFriendComponent(final Component component) {
if (component.getType().contentEquals("static-mesh")) { if (component.getType().contentEquals("static-mesh")) {
mesh = (ComponentStaticMesh)component; this.mesh = (ComponentStaticMesh) component;
} }
if (component.getType().contentEquals("texture")) { if (component.getType().contentEquals("texture")) {
texture = (ComponentTexture)component; this.texture = (ComponentTexture) component;
} }
if (component.getType().contentEquals("position")) { if (component.getType().contentEquals("position")) {
position = (ComponentPosition)component; this.position = (ComponentPosition) component;
}
if (component.getType().contentEquals("physics")) {
this.playerPhysics = (ComponentPhysics) component;
} }
} }
@Override @Override
public void removeFriendComponent(Component component) { public void removeFriendComponent(final Component component) {
// nothing to do. // nothing to do.
} }
@Override @Override
public void render() { public void render() {
this.program.use(); this.program.use();
Matrix4f projectionMatrix = OpenGL.getMatrix(); final Matrix4f projectionMatrix = OpenGL.getMatrix();
Matrix4f viewMatrix = OpenGL.getCameraMatrix(); final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
Matrix4f transformationMatrix = position.getTransform().getOpenGLMatrix(); Matrix4f transformationMatrix = null;
if (this.position != null) {
transformationMatrix = this.position.getTransform().getOpenGLMatrix();
} else if (this.playerPhysics != null) {
transformationMatrix = this.playerPhysics.getTransform().getOpenGLMatrix();
}
this.mesh.bindForRendering(); this.mesh.bindForRendering();
this.texture.bindForRendering(); this.texture.bindForRendering();
this.program.uniformMatrix(this.GLMatrixView, viewMatrix); this.program.uniformMatrix(this.GLMatrixView, viewMatrix);
@ -61,4 +73,3 @@ public class ComponentRenderTexturedStaticMesh extends ComponentRender {
this.program.unUse(); this.program.unUse();
} }
} }

View File

@ -1,7 +1,18 @@
package org.atriasoft.gameengine.engines; package org.atriasoft.gameengine.engines;
import java.util.List;
import java.util.Vector; import java.util.Vector;
import org.atriasoft.ephysics.body.RigidBody;
import org.atriasoft.ephysics.collision.ContactManifold;
import org.atriasoft.ephysics.collision.shapes.AABB;
import org.atriasoft.ephysics.constraint.ContactPoint;
import org.atriasoft.ephysics.constraint.ContactPointInfo;
import org.atriasoft.ephysics.engine.DynamicsWorld;
import org.atriasoft.ephysics.engine.EventListener;
import org.atriasoft.ephysics.engine.Island;
import org.atriasoft.etk.Color;
import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.resource.ResourceColored3DObject; import org.atriasoft.gale.resource.ResourceColored3DObject;
import org.atriasoft.gameengine.Component; import org.atriasoft.gameengine.Component;
@ -11,10 +22,6 @@ import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.components.ComponentPhysics; import org.atriasoft.gameengine.components.ComponentPhysics;
import org.atriasoft.gameengine.internal.Log; import org.atriasoft.gameengine.internal.Log;
import net.jreactphysics3d.constraint.ContactPointInfo;
import net.jreactphysics3d.engine.DynamicsWorld;
import net.jreactphysics3d.engine.EventListener;
public class EnginePhysics extends Engine implements EventListener { public class EnginePhysics extends Engine implements EventListener {
public static final String ENGINE_NAME = "physics"; public static final String ENGINE_NAME = "physics";
// Constant physics time step // Constant physics time step
@ -155,9 +162,34 @@ public class EnginePhysics extends Engine implements EventListener {
it.renderDebug(this.debugDrawProperty, camera); it.renderDebug(this.debugDrawProperty, camera);
} }
} }
final Matrix4f transformationMatrix = Matrix4f.identity();
final Color tmpColor = new Color(0.0f, 0.0f, 1.0f, 0.8f);
final List<Island> islands = this.dynamicsWorld.getIslands();
for (final Island it : islands) {
// TODO compute island AABB to display it ...
final AABB islandElements = new AABB();
for (final RigidBody elem : it.getBodies()) {
final AABB tmp = elem.getAABB();
islandElements.mergeWithAABB(tmp);
}
this.debugDrawProperty.drawCubeLine(islandElements.getMin(), islandElements.getMax(), tmpColor, transformationMatrix, true, true);
}
final List<ContactManifold> listContact = this.dynamicsWorld.getContactsList();
Log.info("nb contact: " + listContact.size());
for (final ContactManifold it : listContact) {
for (int iii = 0; iii < it.getNbContactPoints(); iii++) {
final ContactPoint contact = it.getContactPoint(iii);
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(contact.getWorldPointOnBody1())),
new Color(0, 1, 0, 1));
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(contact.getWorldPointOnBody2())),
new Color(0, 1, 0, 1));
}
}
} }
void setGravity(final Vector3f _axePower) { public void setGravity(final Vector3f _axePower) {
if (this.dynamicsWorld != null) { if (this.dynamicsWorld != null) {
final Vector3f gravity = _axePower.clone(); final Vector3f gravity = _axePower.clone();
this.dynamicsWorld.setGravity(gravity); this.dynamicsWorld.setGravity(gravity);
@ -165,14 +197,19 @@ public class EnginePhysics extends Engine implements EventListener {
} }
@Override @Override
public void update(final long deltaMili) { public void update(long deltaMili) {
Log.error("=================================================================" + deltaMili);
if (deltaMili > 1000) {
deltaMili = (long) (TIME_STEP * 1000.0f);
}
final float deltaTime = deltaMili * 0.0001f; final float deltaTime = deltaMili * 0.0001f;
// Add the time difference in the accumulator // Add the time difference in the accumulator
this.accumulator += deltaTime; this.accumulator += deltaTime;
// While there is enough accumulated time to take one or several physics steps // While there is enough accumulated time to take one or several physics steps
while (this.accumulator >= TIME_STEP) { while (this.accumulator >= TIME_STEP) {
Log.error("---------------------------------------------------" + TIME_STEP);
if (this.dynamicsWorld != null) { if (this.dynamicsWorld != null) {
// call every object to usdate their constant forces applyed // call every object to usdate their constant forces applied
for (final ComponentPhysics it : this.components) { for (final ComponentPhysics it : this.components) {
if (it != null) { if (it != null) {
it.update(TIME_STEP); it.update(TIME_STEP);

View File

@ -2,66 +2,49 @@ package org.atriasoft.gameengine.engines;
import java.util.Vector; import java.util.Vector;
import org.atriasoft.gameengine.internal.Log;
import org.atriasoft.gameengine.Component; import org.atriasoft.gameengine.Component;
import org.atriasoft.gameengine.Engine; import org.atriasoft.gameengine.Engine;
import org.atriasoft.gameengine.Environement; import org.atriasoft.gameengine.Environement;
import org.atriasoft.gameengine.camera.Camera; import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.components.ComponentAI;
import org.atriasoft.gameengine.components.ComponentRender; import org.atriasoft.gameengine.components.ComponentRender;
class ResultNearestElement {
public ComponentRender element;
public float dist;
};
public class EngineRender extends Engine { public class EngineRender extends Engine {
public static final String ENGINE_NAME = "render"; public static final String ENGINE_NAME = "render";
private float accumulator = 0;
private static float TIME_STEP = 5.0f; private static float TIME_STEP = 5.0f;
private Vector<ComponentRender> components = new Vector<ComponentRender>(); private float accumulator = 0;
private Vector<ResultNearestElement> displayElementOrdered = new Vector<ResultNearestElement>(); private final Vector<ComponentRender> components = new Vector<ComponentRender>();
private final Vector<ResultNearestElement> displayElementOrdered = new Vector<ResultNearestElement>();
//private ResourceColored3DObject debugDrawProperty; //private ResourceColored3DObject debugDrawProperty;
public EngineRender(Environement env) { public EngineRender(final Environement env) {
super(env); super(env);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
@Override @Override
public void componentRemove(Component ref) { public void componentAdd(final Component ref) {
components.remove(ref);
}
@Override
public void componentAdd(Component ref) {
if (ref instanceof ComponentRender == false) { if (ref instanceof ComponentRender == false) {
return; return;
} }
components.add((ComponentRender)ref); this.components.add((ComponentRender) ref);
} }
@Override @Override
public void update(long deltaMili) { public void componentRemove(final Component ref) {
// Add the time difference in the accumulator this.components.remove(ref);
accumulator += (float)deltaMili*0.0001f;
// While there is enough accumulated time to take one or several physics steps
while (accumulator >= TIME_STEP) {
// Log.warning("RENDER: Generate for " + accumulator + " / " + TIME_STEP + " for:" + components.size());
// call every object to usdate their constant forces applyed
for (ComponentRender it: components) {
it.update(TIME_STEP);
}
// Decrease the accumulated time
accumulator -= TIME_STEP;
}
} }
@Override @Override
public void render(long deltaMili, Camera camera) { public String getType() {
Log.info("Render ..."); // TODO Auto-generated method stub
return ENGINE_NAME;
}
@Override
public void render(final long deltaMili, final Camera camera) {
//Log.info("Render ...");
//Matrix4f tmpMatrix; //Matrix4f tmpMatrix;
for (ComponentRender it: this.components) { for (final ComponentRender it : this.components) {
//Log.info("Render " + it); //Log.info("Render " + it);
it.render(); it.render();
} }
@ -84,54 +67,65 @@ public class EngineRender extends Engine {
} }
// @Override // @Override
// public void renderDebug(long deltaMili, Camera camera) { // public void renderDebug(long deltaMili, Camera camera) {
// //Log.debug("Draw (start)"); // //Log.debug("Draw (start)");
// Matrix4f tmpMatrix; // Matrix4f tmpMatrix;
// getOrderedElementForDisplay(this.displayElementOrdered, camera->getEye(), camera->getViewVector()); // getOrderedElementForDisplay(this.displayElementOrdered, camera->getEye(), camera->getViewVector());
// Log.verbose("DRAW : " + this.displayElementOrdered.size() + "/" + this.component.size() + " elements"); // Log.verbose("DRAW : " + this.displayElementOrdered.size() + "/" + this.component.size() + " elements");
//// if (propertyDebugPhysic.get() == true) { //// if (propertyDebugPhysic.get() == true) {
//// // Draw debug ... (Object) //// // Draw debug ... (Object)
//// for (int32t iii=this.displayElementOrdered.size()-1; iii >= 0; iii--) { //// for (int32t iii=this.displayElementOrdered.size()-1; iii >= 0; iii--) {
//// this.displayElementOrdered[iii].element->drawDebug(this.debugDrawProperty, camera); //// this.displayElementOrdered[iii].element->drawDebug(this.debugDrawProperty, camera);
//// } //// }
//// // Draw debug ... (Camera) //// // Draw debug ... (Camera)
//// /* //// /*
//// etk::Map<etk::String, ege::Camera>> listCamera = this.env->getCameraList(); //// etk::Map<etk::String, ege::Camera>> listCamera = this.env->getCameraList();
//// for (auto &itCam : listCamera) { //// for (auto &itCam : listCamera) {
//// if (itCam.second != null) { //// if (itCam.second != null) {
//// itCam.second->drawDebug(this.debugDrawProperty, camera); //// itCam.second->drawDebug(this.debugDrawProperty, camera);
//// } //// }
//// } //// }
//// */ //// */
//// } //// }
// if (propertyDebugNormal.get() == true) { // if (propertyDebugNormal.get() == true) {
// // Draw debug ... (Object) // // Draw debug ... (Object)
// for (int32t iii=this.displayElementOrdered.size()-1; iii >= 0; iii--) { // for (int32t iii=this.displayElementOrdered.size()-1; iii >= 0; iii--) {
// this.displayElementOrdered[iii].element.drawNormalDebug(this.debugDrawProperty); // this.displayElementOrdered[iii].element.drawNormalDebug(this.debugDrawProperty);
// } // }
// } // }
//// if (propertyDebugApplication.get() == true) { //// if (propertyDebugApplication.get() == true) {
//// // Draw debug ... (User) //// // Draw debug ... (User)
//// signalDisplayDebug.emit(this.debugDrawProperty); //// signalDisplayDebug.emit(this.debugDrawProperty);
//// } //// }
//// /* TODO set it back ... //// /* TODO set it back ...
//// if (camera != null) { //// if (camera != null) {
//// this.env->getParticuleEngine().draw(*camera); //// this.env->getParticuleEngine().draw(*camera);
//// } //// }
//// */ //// */
// //
// } // }
@Override @Override
public String getType() { public void renderDebug(final long deltaMili, final Camera camera) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return ENGINE_NAME;
} }
@Override @Override
public void renderDebug(long deltaMili, Camera camera) { public void update(final long deltaMili) {
// TODO Auto-generated method stub // Add the time difference in the accumulator
this.accumulator += deltaMili * 0.0001f;
// While there is enough accumulated time to take one or several physics steps
while (this.accumulator >= TIME_STEP) {
// Log.warning("RENDER: Generate for " + accumulator + " / " + TIME_STEP + " for:" + components.size());
// call every object to usdate their constant forces applyed
for (final ComponentRender it : this.components) {
it.update(TIME_STEP);
}
// Decrease the accumulated time
this.accumulator -= TIME_STEP;
}
} }
@ -187,4 +181,9 @@ public class EngineRender extends Engine {
// resultList.pushBack(result); // resultList.pushBack(result);
// } // }
// } // }
// } // };
class ResultNearestElement {
public ComponentRender element;
public float dist;
}

View File

@ -1,49 +0,0 @@
package org.atriasoft.gameengine.physics.shape;
import org.atriasoft.etk.math.Matrix3f;
import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Quaternion;
import org.atriasoft.etk.math.Transform3D;
import org.atriasoft.etk.math.Vector3f;
import net.jreactphysics3d.body.RigidBody;
import net.jreactphysics3d.collision.shapes.CollisionShape;
import net.jreactphysics3d.engine.DynamicsWorld;
public class ProxyShape {
private CollisionShape collisionShape;
private RigidBody rigidBody;
protected void createRigidBody(CollisionShape collisionShape, Transform3D transform, float mass, DynamicsWorld dynamicsWorld) {
this.collisionShape = collisionShape;
Matrix3f inertiaTensor = new Matrix3f();
collisionShape.computeLocalInertiaTensor(inertiaTensor, mass);
rigidBody = dynamicsWorld.createRigidBody(transform, mass, inertiaTensor, collisionShape);
}
public CollisionShape getCollisionShape() {
return collisionShape;
}
public RigidBody getRigidBody() {
return rigidBody;
}
public void updateTransform() {
// Get the interpolated transform of the rigid body
Transform3D transform = rigidBody.getInterpolatedTransform();
// Compute the transform used for rendering the box
Matrix4f glMatrix = transform.getOpenGLMatrix();
// Apply the scaling matrix to have the correct box dimensions
//getWorldTransform().fromOpenGLArray(glMatrix);
//getWorldTransform().multiply(getScalingTransform());
}
}

View File

@ -8,12 +8,56 @@ package org.atriasoft.gameengine.physics.shape;
import org.atriasoft.etk.math.Quaternion; import org.atriasoft.etk.math.Quaternion;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
public class Shape { public class Shape {
private Quaternion orientation = new Quaternion(); private Quaternion orientation = Quaternion.identity();
private float mass = 1; //!< element mass in "g" then 1000 for 1kg private float mass = 1; //!< element mass in "g" then 1000 for 1kg
private Vector3f origin = new Vector3f(0,0,0); private Vector3f origin = new Vector3f(0, 0, 0);
public boolean parse(String _line) {
public void display() {
}
public float getMass() {
return this.mass;
}
public Quaternion getOrientation() {
return this.orientation.clone();
}
public Vector3f getOrigin() {
return this.origin;
}
public boolean isBox() {
return this instanceof Box;
};
public boolean isCapsule() {
return this instanceof Capsule;
}
public boolean isConcave() {
return this instanceof Concave;
}
public boolean isCone() {
return this instanceof Cone;
}
public boolean isConvexHull() {
return this instanceof ConvexHull;
};
public boolean isCylinder() {
return this instanceof Cylinder;
};
public boolean isSphere() {
return this instanceof Sphere;
};
public boolean parse(final String _line) {
/* /*
if(strncmp(_line, "origin:", 7) == 0) { if(strncmp(_line, "origin:", 7) == 0) {
sscanf(&_line[7], "%f %f %f", &m_origin.m_floats[0], &m_origin.m_floats[1], &m_origin.m_floats[2] ); sscanf(&_line[7], "%f %f %f", &m_origin.m_floats[0], &m_origin.m_floats[1], &m_origin.m_floats[2] );
@ -32,48 +76,18 @@ public class Shape {
} }
*/ */
return false; return false;
} };
public void display() {
} public void setMass(final float mass) {
public Quaternion getOrientation() {
return this.orientation.clone();
}
public void setOrientation(Quaternion orientation) {
this.orientation = orientation;
}
public Vector3f getOrigin() {
return this.origin;
};
public void setOrigin(Vector3f origin) {
this.origin = origin;
}
public float getMass() {
return this.mass;
}
public void setMass(float mass) {
this.mass = mass; this.mass = mass;
}
public boolean isBox() {
return this instanceof Box;
}; };
public boolean isCylinder() {
return this instanceof Cylinder; public void setOrientation(final Quaternion orientation) {
this.orientation = orientation;
}; };
public boolean isCapsule() {
return this instanceof Capsule; public void setOrigin(final Vector3f origin) {
}; this.origin = origin;
public boolean isCone() {
return this instanceof Cone;
};
public boolean isConvexHull() {
return this instanceof ConvexHull;
};
public boolean isSphere() {
return this instanceof Sphere;
};
public boolean isConcave() {
return this instanceof Concave;
}; };
} }
/* /*

View File

@ -21,6 +21,7 @@ import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType; import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceColored3DObject; import org.atriasoft.gale.resource.ResourceColored3DObject;
import org.atriasoft.gameengine.ControlCameraPlayer; import org.atriasoft.gameengine.ControlCameraPlayer;
import org.atriasoft.gameengine.Engine;
import org.atriasoft.gameengine.Entity; import org.atriasoft.gameengine.Entity;
import org.atriasoft.gameengine.Environement; import org.atriasoft.gameengine.Environement;
import org.atriasoft.gameengine.GameStatus; import org.atriasoft.gameengine.GameStatus;
@ -40,7 +41,9 @@ import org.atriasoft.gameengine.components.ComponentRenderTexturedMaterialsStati
import org.atriasoft.gameengine.components.ComponentRenderTexturedStaticMesh; import org.atriasoft.gameengine.components.ComponentRenderTexturedStaticMesh;
import org.atriasoft.gameengine.components.ComponentStaticMesh; import org.atriasoft.gameengine.components.ComponentStaticMesh;
import org.atriasoft.gameengine.components.ComponentTexture; import org.atriasoft.gameengine.components.ComponentTexture;
import org.atriasoft.gameengine.components.PhysicBodyType;
import org.atriasoft.gameengine.engines.EngineLight; import org.atriasoft.gameengine.engines.EngineLight;
import org.atriasoft.gameengine.engines.EnginePhysics;
import org.atriasoft.gameengine.map.MapVoxel; import org.atriasoft.gameengine.map.MapVoxel;
import org.atriasoft.gameengine.physics.shape.Box; import org.atriasoft.gameengine.physics.shape.Box;
import org.atriasoft.gameengine.tools.MeshGenerator; import org.atriasoft.gameengine.tools.MeshGenerator;
@ -109,14 +112,32 @@ public class LoxelApplication extends Application {
{ {
// add a cube to test collision ... // add a cube to test collision ...
final Entity localBox = new Entity(this.env); final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(-2, -2, 14))));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj"))); localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png"))); localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentLight(new Light(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0.03f, 0.002f)))); localBox.addComponent(new ComponentLight(new Light(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0.03f, 0.002f))));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag"))); localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env); final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(0, 0, 5)));
final Box box2 = new Box(); final Box box2 = new Box();
box2.setSize(new Vector3f(1, 1, 1)); box2.setSize(new Vector3f(0.5f, 0.5f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
/*
{
// add a cube to test collision ...
final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentLight(new Light(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0.03f, 0.002f))));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(0, 4, 12.5f)));
final Box box2 = new Box();
box2.setSize(new Vector3f(0.5f, 0.5f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0)); box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1); box2.setMass(1);
physics2.addShape(box2); physics2.addShape(box2);
@ -126,30 +147,13 @@ public class LoxelApplication extends Application {
{ {
// add a cube to test collision ... // add a cube to test collision ...
final Entity localBox = new Entity(this.env); final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(0, 4, 12.5f))));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentLight(new Light(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0.03f, 0.002f))));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
final Box box2 = new Box();
box2.setSize(new Vector3f(1, 1, 1));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
{
// add a cube to test collision ...
final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(-2, 2, 14.5f))));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj"))); localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png"))); localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag"))); localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env); final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(-2, 2, 14.5f)));
final Box box2 = new Box(); final Box box2 = new Box();
box2.setSize(new Vector3f(1, 1, 1)); box2.setSize(new Vector3f(0.5f, 0.5f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0)); box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1); box2.setMass(1);
physics2.addShape(box2); physics2.addShape(box2);
@ -160,11 +164,29 @@ public class LoxelApplication extends Application {
{ {
// add a cube to test collision ... // add a cube to test collision ...
final Entity localBox = new Entity(this.env); final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(-5, -5, 14))));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj"))); localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png"))); localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag"))); localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env); final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(-5, -5, 14)));
final Box box2 = new Box();
box2.setSize(new Vector3f(2, 2, 2));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
{
// add a cube to test collision ...
final Entity localBox = new Entity(this.env);
final Quaternion orientation = new Quaternion(0.5f, 0.2f, 0.4f, 1);
orientation.normalize();
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(15, 15, 14), orientation));
final Box box2 = new Box(); final Box box2 = new Box();
box2.setSize(new Vector3f(4, 4, 4)); box2.setSize(new Vector3f(4, 4, 4));
box2.setOrigin(new Vector3f(0, 0, 0)); box2.setOrigin(new Vector3f(0, 0, 0));
@ -176,53 +198,37 @@ public class LoxelApplication extends Application {
{ {
// add a cube to test collision ... // add a cube to test collision ...
final Entity localBox = new Entity(this.env); final Entity localBox = new Entity(this.env);
final Quaternion transform = new Quaternion(0.5f, 0.2f, 0.4f, 1); final Quaternion orientation = new Quaternion(0.3f, 0.3f, 0.4f, 1);
transform.normalize(); orientation.normalize();
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(15, 15, 14), transform)));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj"))); localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png"))); localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag"))); localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env); final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(2, -2, 14.2f), orientation));
final Box box2 = new Box(); final Box box2 = new Box();
box2.setSize(new Vector3f(8, 8, 8)); box2.setSize(new Vector3f(0.5f, 0.5f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0)); box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1); box2.setMass(1);
physics2.addShape(box2); physics2.addShape(box2);
localBox.addComponent(physics2); localBox.addComponent(physics2);
this.env.addEntity(localBox); this.env.addEntity(localBox);
} }
*/
{ {
// add a cube to test collision ... // this is the floor
final Entity localBox = new Entity(this.env); final Entity localBox = new Entity(this.env);
final Quaternion transform = new Quaternion(0.3f, 0.3f, 0.4f, 1); final Quaternion orientation = new Quaternion(0, 0, 0, 1);
transform.normalize(); orientation.normalize();
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(2, -2, 14.2f), transform)));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj"))); localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png"))); localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/dirt.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag"))); localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env); final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setBodyType(PhysicBodyType.BODY_STATIC);
physics2.setTransform(new Transform3D(new Vector3f(0, 0, 0.0f), orientation));
final Box box2 = new Box(); final Box box2 = new Box();
box2.setSize(new Vector3f(1, 1, 1)); box2.setSize(new Vector3f(20.0f, 20.0f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0)); box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1); box2.setMass(0);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
{
// add a cube to test collision ...
final Entity localBox = new Entity(this.env);
final Quaternion transform = new Quaternion(0, 0, 1, 1);
transform.normalize();
localBox.addComponent(new ComponentPosition(new Transform3D(new Vector3f(2, 2, 14.2f), transform)));
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
final Box box2 = new Box();
box2.setSize(new Vector3f(1, 1, 1));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(1);
physics2.addShape(box2); physics2.addShape(box2);
localBox.addComponent(physics2); localBox.addComponent(physics2);
this.env.addEntity(localBox); this.env.addEntity(localBox);
@ -259,31 +265,47 @@ public class LoxelApplication extends Application {
// } // }
final Entity gird = new Entity(this.env); final Entity gird = new Entity(this.env);
gird.addComponent(new ComponentPosition(new Transform3D(new Vector3f(0, 0, 13)))); gird.addComponent(new ComponentPosition(new Transform3D(new Vector3f(0, 0, 0))));
gird.addComponent(new ComponentStaticMesh(MeshGenerator.createGrid(5))); gird.addComponent(new ComponentStaticMesh(MeshGenerator.createGrid(5)));
gird.addComponent(new ComponentRenderColoredStaticMesh(new Uri("DATA_EGE", "wireColor.vert"), new Uri("DATA_EGE", "wireColor.frag"))); gird.addComponent(new ComponentRenderColoredStaticMesh(new Uri("DATA_EGE", "wireColor.vert"), new Uri("DATA_EGE", "wireColor.frag")));
this.env.addEntity(gird); this.env.addEntity(gird);
final Entity player = new Entity(this.env); final Entity player = new Entity(this.env);
this.objectPosition = new ComponentPositionPlayer(new Transform3D(new Vector3f(5, 5, 13))); if (false) {
player.addComponent(this.objectPosition); final Transform3D playerTransform = new Transform3D(new Vector3f(0, -5, 13));
this.objectPlayer = new ComponentPlayer(); //this.objectPosition = new ComponentPositionPlayer();
player.addComponent(this.objectPlayer); //player.addComponent(this.objectPosition);
player.addComponent(new ComponentMaterial(new Material())); this.objectPlayer = new ComponentPlayer();
//player.addComponent(new ComponentStaticMesh(new Uri("RES", "person.obj"))); player.addComponent(this.objectPlayer);
player.addComponent(new ComponentStaticMesh(new Uri("RES", "person_-yfw_zup.obj"))); player.addComponent(new ComponentMaterial(new Material()));
player.addComponent(new ComponentTexture(new Uri("RES", "playerTexture.png"))); //player.addComponent(new ComponentStaticMesh(new Uri("RES", "person.obj")));
player.addComponent(new ComponentRenderTexturedMaterialsStaticMesh(new Uri("DATA", "basicMaterial.vert"), new Uri("DATA", "basicMaterial.frag"), player.addComponent(new ComponentStaticMesh(new Uri("RES", "person_-yfw_zup.obj")));
(EngineLight) this.env.getEngine(EngineLight.ENGINE_NAME))); player.addComponent(new ComponentTexture(new Uri("RES", "playerTexture.png")));
final ComponentPhysics physics = new ComponentPhysics(this.env); player.addComponent(new ComponentRenderTexturedMaterialsStaticMesh(new Uri("DATA", "basicMaterial.vert"), new Uri("DATA", "basicMaterial.frag"),
final Box box = new Box(); (EngineLight) this.env.getEngine(EngineLight.ENGINE_NAME)));
box.setSize(new Vector3f(0.6f, 0.6f, 1.8f)); final ComponentPhysics physics = new ComponentPhysics(this.env, playerTransform);
box.setOrigin(new Vector3f(0, 0, 0.9f)); physics.setBodyType(PhysicBodyType.BODY_DYNAMIC);
box.setMass(1); final Box box = new Box();
physics.addShape(box); box.setSize(new Vector3f(0.3f, 0.3f, 0.9f));
player.addComponent(physics); box.setOrigin(new Vector3f(0, 0, 0.9f));
this.env.addEntity(player); box.setMass(1);
physics.addShape(box);
player.addComponent(physics);
this.env.addEntity(player);
} else {
final Transform3D playerTransform = new Transform3D(new Vector3f(0, -5, 0));
this.objectPosition = new ComponentPositionPlayer();
player.addComponent(this.objectPosition);
this.objectPlayer = new ComponentPlayer();
player.addComponent(this.objectPlayer);
player.addComponent(new ComponentMaterial(new Material()));
//player.addComponent(new ComponentStaticMesh(new Uri("RES", "person.obj")));
player.addComponent(new ComponentStaticMesh(new Uri("RES", "person_-yfw_zup.obj")));
player.addComponent(new ComponentTexture(new Uri("RES", "playerTexture.png")));
player.addComponent(new ComponentRenderTexturedMaterialsStaticMesh(new Uri("DATA", "basicMaterial.vert"), new Uri("DATA", "basicMaterial.frag"),
(EngineLight) this.env.getEngine(EngineLight.ENGINE_NAME)));
this.env.addEntity(player);
}
final Camera mainView = new Camera(); final Camera mainView = new Camera();
this.env.addCamera("default", mainView); this.env.addCamera("default", mainView);
mainView.setPitch((float) Math.PI * -0.25f); mainView.setPitch((float) Math.PI * -0.25f);
@ -297,6 +319,14 @@ public class LoxelApplication extends Application {
this.basicRotation.setEulerAngles(new Vector3f(0.005f, 0.005f, 0.01f)); this.basicRotation.setEulerAngles(new Vector3f(0.005f, 0.005f, 0.01f));
this.basicRotation2.setEulerAngles(new Vector3f(0.003f, 0.01f, 0.001f)); this.basicRotation2.setEulerAngles(new Vector3f(0.003f, 0.01f, 0.001f));
final Engine tmpEngine = this.env.getEngine("physics");
if (tmpEngine != null) {
final EnginePhysics physicsEngine = (EnginePhysics) tmpEngine;
//Disable gravity for test ...
physicsEngine.setGravity(new Vector3f(0.0f, 0.0f, -0.3f));
}
// ready to let Gale & Ege manage the display // ready to let Gale & Ege manage the display
Log.info("==> Init APPL (END)"); Log.info("==> Init APPL (END)");
this.creationDone = true; this.creationDone = true;
@ -372,12 +402,12 @@ public class LoxelApplication extends Application {
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14))); //Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14))); //Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14))); //Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
final Matrix4f trensformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x, testRpos.y, testRpos.z)).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14))) final Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x, testRpos.y, testRpos.z)).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14)))
.multiply(testQTransfert.getMatrix4()); .multiply(testQTransfert.getMatrix4());
// OK sans la box1 orientation ... // OK sans la box1 orientation ...
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14))); //Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14))); //Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
this.debugDrawProperty.drawSquare(box2HalfSize, trensformation, new Color(0, 1, 0, 0.5f)); this.debugDrawProperty.drawSquare(box2HalfSize, transformation, new Color(0, 1, 0, 0.5f));
this.debugDrawProperty.drawSquare(box1HalfSize, Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14)), new Color(0, 0, 1, 0.5f)); this.debugDrawProperty.drawSquare(box1HalfSize, Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14)), new Color(0, 0, 1, 0.5f));
} }

View File

@ -4,7 +4,7 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.gale.Gale; import org.atriasoft.gale.Gale;
public class MainLoxelEngine { public class MainLoxelEngine {
public static void main(String[] args) { public static void main(final String[] args) {
Uri.setGroup("DATA", "src/org/atriasoft/gameengine/samples/LoxelEngine/res/"); Uri.setGroup("DATA", "src/org/atriasoft/gameengine/samples/LoxelEngine/res/");
Uri.setGroup("DATA_EGE", "src/org/atriasoft/gameengine/data/"); Uri.setGroup("DATA_EGE", "src/org/atriasoft/gameengine/data/");
Uri.setGroup("RES", "res"); Uri.setGroup("RES", "res");

View File

@ -0,0 +1,331 @@
package org.atriasoft.gameengine.samples.collisiontest;
import java.util.ArrayList;
import java.util.List;
import org.atriasoft.etk.Color;
import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Quaternion;
import org.atriasoft.etk.math.Transform3D;
import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.Application;
import org.atriasoft.gale.Gale;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.Flag;
import org.atriasoft.gale.context.Context;
import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceColored3DObject;
import org.atriasoft.gameengine.ControlCameraPlayer;
import org.atriasoft.gameengine.Engine;
import org.atriasoft.gameengine.Entity;
import org.atriasoft.gameengine.Environement;
import org.atriasoft.gameengine.GameStatus;
import org.atriasoft.gameengine.Light;
import org.atriasoft.gameengine.Material;
import org.atriasoft.gameengine.camera.Camera;
import org.atriasoft.gameengine.components.ComponentGravityStatic;
import org.atriasoft.gameengine.components.ComponentLight;
import org.atriasoft.gameengine.components.ComponentLightSun;
import org.atriasoft.gameengine.components.ComponentMaterial;
import org.atriasoft.gameengine.components.ComponentPhysics;
import org.atriasoft.gameengine.components.ComponentPlayer;
import org.atriasoft.gameengine.components.ComponentPosition;
import org.atriasoft.gameengine.components.ComponentPositionPlayer;
import org.atriasoft.gameengine.components.ComponentRenderColoredStaticMesh;
import org.atriasoft.gameengine.components.ComponentRenderTexturedMaterialsStaticMesh;
import org.atriasoft.gameengine.components.ComponentRenderTexturedStaticMesh;
import org.atriasoft.gameengine.components.ComponentStaticMesh;
import org.atriasoft.gameengine.components.ComponentTexture;
import org.atriasoft.gameengine.components.PhysicBodyType;
import org.atriasoft.gameengine.engines.EngineLight;
import org.atriasoft.gameengine.engines.EnginePhysics;
import org.atriasoft.gameengine.map.MapVoxel;
import org.atriasoft.gameengine.physics.shape.Box;
import org.atriasoft.gameengine.tools.MeshGenerator;
public class CollisionTestApplication extends Application {
// public static ComponentPosition relativeTestPos;
// public static Box boxTest;
public static List<Vector3f> testPoints = new ArrayList<Vector3f>();
public static List<Vector3f> testPointsBox = new ArrayList<Vector3f>();
public static List<Boolean> testPointsCollide = new ArrayList<Boolean>();
public static Vector3f testRpos;
public static Quaternion testQTransfert;
public static Vector3f box1HalfSize;
public static Vector3f box2HalfSize;
private Environement env;
private ComponentPosition objectPosition;
private final Quaternion basicRotation = Quaternion.identity();
private final Quaternion basicRotation2 = Quaternion.identity();
private boolean creationDone;
private ControlCameraPlayer simpleControl;
private ComponentPosition lightPosition;
private float angleLight = 0;
private MapVoxel map;
private ComponentPlayer objectPlayer;
private ResourceColored3DObject debugDrawProperty;
public CollisionTestApplication() {
this.creationDone = false;
}
@Override
public void onCreate(final Context context) {
// set the system global max speed
//ComponentPhysics.globalMaxSpeed = 3;
Gale.getContext().grabPointerEvents(true, new Vector2f(0, 0));
this.env = new Environement();
this.canDraw = true;
setSize(new Vector2f(1500, 1500));
setTitle("Loxel sample");
this.map = new MapVoxel(this.env);
// this.env.addEngine(map);
// map.init();
// simple sun to have a global light ...
final Entity globalGravity = new Entity(this.env);
globalGravity.addComponent(new ComponentGravityStatic(new Vector3f(0, 0, -1)));
this.env.addEntity(globalGravity);
// simple sun to have a global light ...
final Entity sun = new Entity(this.env);
sun.addComponent(new ComponentPosition(new Transform3D(new Vector3f(1000, 1000, 1000))));
sun.addComponent(new ComponentLightSun(new Light(new Vector3f(0.4f, 0.4f, 0.4f), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0, 0))));
this.env.addEntity(sun);
// add a cube to show where in the light ...
final Entity localLight = new Entity(this.env);
this.lightPosition = new ComponentPosition(new Transform3D(new Vector3f(-10, -10, 17)));
// localLight.addComponent(lightPosition);
// localLight.addComponent(new ComponentStaticMesh(new Uri("RES", "cube.obj")));
// localLight.addComponent(new ComponentTexture(new Uri("RES", "grass.png")));
// localLight.addComponent(new ComponentLight(new Light(new Vector3f(0,1,0), new Vector3f(0,0,0), new Vector3f(0.8f,0.03f,0.002f))));
// localLight.addComponent(new ComponentRenderTexturedStaticMesh(
// new Uri("DATA", "basic.vert"),
// new Uri("DATA", "basic.frag")));
// env.addEntity(localLight);
{
// this is the floor
final Entity localBox = new Entity(this.env);
final Quaternion orientation = new Quaternion(0, 0, 0, 1);
orientation.normalize();
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/dirt.png")));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setBodyType(PhysicBodyType.BODY_STATIC);
physics2.setTransform(new Transform3D(new Vector3f(0, 0, 0.0f), orientation));
final Box box2 = new Box();
box2.setSize(new Vector3f(5.0f, 5.0f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(0);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
{
// add a cube to test collision ...
final Entity localBox = new Entity(this.env);
localBox.addComponent(new ComponentStaticMesh(new Uri("RES", "cube-one.obj")));
localBox.addComponent(new ComponentTexture(new Uri("DATA", "blocks/clay.png")));
localBox.addComponent(new ComponentLight(new Light(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.8f, 0.03f, 0.002f))));
localBox.addComponent(new ComponentRenderTexturedStaticMesh(new Uri("DATA", "basic.vert"), new Uri("DATA", "basic.frag")));
final ComponentPhysics physics2 = new ComponentPhysics(this.env);
physics2.setTransform(new Transform3D(new Vector3f(0, 0, 0.90f)));
final Box box2 = new Box();
box2.setSize(new Vector3f(0.5f, 0.5f, 0.5f));
box2.setOrigin(new Vector3f(0, 0, 0));
box2.setMass(100);
physics2.addShape(box2);
localBox.addComponent(physics2);
this.env.addEntity(localBox);
}
final Entity gird = new Entity(this.env);
gird.addComponent(new ComponentPosition(new Transform3D(new Vector3f(0, 0, 0))));
gird.addComponent(new ComponentStaticMesh(MeshGenerator.createGrid(5)));
gird.addComponent(new ComponentRenderColoredStaticMesh(new Uri("DATA_EGE", "wireColor.vert"), new Uri("DATA_EGE", "wireColor.frag")));
this.env.addEntity(gird);
final Entity player = new Entity(this.env);
if (false) {
final Transform3D playerTransform = new Transform3D(new Vector3f(0, -5, 13));
//this.objectPosition = new ComponentPositionPlayer();
//player.addComponent(this.objectPosition);
this.objectPlayer = new ComponentPlayer();
player.addComponent(this.objectPlayer);
player.addComponent(new ComponentMaterial(new Material()));
//player.addComponent(new ComponentStaticMesh(new Uri("RES", "person.obj")));
player.addComponent(new ComponentStaticMesh(new Uri("RES", "person_-yfw_zup.obj")));
player.addComponent(new ComponentTexture(new Uri("RES", "playerTexture.png")));
player.addComponent(new ComponentRenderTexturedMaterialsStaticMesh(new Uri("DATA", "basicMaterial.vert"), new Uri("DATA", "basicMaterial.frag"),
(EngineLight) this.env.getEngine(EngineLight.ENGINE_NAME)));
final ComponentPhysics physics = new ComponentPhysics(this.env, playerTransform);
physics.setBodyType(PhysicBodyType.BODY_DYNAMIC);
final Box box = new Box();
box.setSize(new Vector3f(0.3f, 0.3f, 0.9f));
box.setOrigin(new Vector3f(0, 0, 0.9f));
box.setMass(100);
physics.addShape(box);
player.addComponent(physics);
this.env.addEntity(player);
} else {
final Transform3D playerTransform = new Transform3D(new Vector3f(0, -5, 0));
this.objectPosition = new ComponentPositionPlayer();
player.addComponent(this.objectPosition);
this.objectPlayer = new ComponentPlayer();
player.addComponent(this.objectPlayer);
player.addComponent(new ComponentMaterial(new Material()));
//player.addComponent(new ComponentStaticMesh(new Uri("RES", "person.obj")));
player.addComponent(new ComponentStaticMesh(new Uri("RES", "person_-yfw_zup.obj")));
player.addComponent(new ComponentTexture(new Uri("RES", "playerTexture.png")));
player.addComponent(new ComponentRenderTexturedMaterialsStaticMesh(new Uri("DATA", "basicMaterial.vert"), new Uri("DATA", "basicMaterial.frag"),
(EngineLight) this.env.getEngine(EngineLight.ENGINE_NAME)));
this.env.addEntity(player);
}
final Camera mainView = new Camera();
this.env.addCamera("default", mainView);
mainView.setPitch((float) Math.PI * -0.25f);
mainView.setPosition(new Vector3f(0, -5, 5));
this.simpleControl = new ControlCameraPlayer(mainView, player);
this.env.addControlInterface(this.simpleControl);
// start the engine.
this.env.setPropertyStatus(GameStatus.gameStart);
this.basicRotation.setEulerAngles(new Vector3f(0.005f, 0.005f, 0.01f));
this.basicRotation2.setEulerAngles(new Vector3f(0.003f, 0.01f, 0.001f));
final Engine tmpEngine = this.env.getEngine("physics");
if (tmpEngine != null) {
final EnginePhysics physicsEngine = (EnginePhysics) tmpEngine;
//Disable gravity for test ...
physicsEngine.setGravity(new Vector3f(0.0f, 0.0f, -0.3f));
}
// ready to let Gale & Ege manage the display
Log.info("==> Init APPL (END)");
this.creationDone = true;
}
@Override
public void onDraw(final Context context) {
//Log.info("==> appl Draw ...");
final Vector2f size = getSize();
if (!this.creationDone) {
OpenGL.setViewPort(new Vector2f(0, 0), size);
final Color bgColor = new Color(0.8f, 0.5f, 0.5f, 1.0f);
OpenGL.clearColor(bgColor);
Log.info("==> appl clear ==> not created ...");
return;
}
// Store openGl context.
OpenGL.push();
// set projection matrix:
final Matrix4f tmpProjection = Matrix4f.createMatrixPerspective(3.14f * 0.5f, getAspectRatio(), 0.1f, 50000);
OpenGL.setMatrix(tmpProjection);
// set the basic openGL view port: (Draw in all the windows...)
OpenGL.setViewPort(new Vector2f(0, 0), size);
// clear background
final Color bgColor = new Color(0.18f, 0.43f, 0.95f, 1.0f);
OpenGL.clearColor(bgColor);
// real clear request:
OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer);
OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer);
OpenGL.enable(Flag.flag_depthTest);
//Log.info("==> appl Draw ...");
this.env.render(20, "default");
if (this.debugDrawProperty == null) {
this.debugDrawProperty = ResourceColored3DObject.create();
}
// now render the point test collision ...
for (int iii = 0; iii < CollisionTestApplication.testPoints.size(); iii++) {
final Vector3f elem = CollisionTestApplication.testPoints.get(iii);
final boolean collide = CollisionTestApplication.testPointsCollide.get(iii);
if (collide) {
this.debugDrawProperty.drawSquare(new Vector3f(0.1f, 0.1f, 0.1f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(1, 0, 0, 1));
} else if (iii == 0) {
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(0, 1, 0, 1));
} else if (iii == 7) {
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(1, 1, 0, 1));
} else {
this.debugDrawProperty.drawSquare(new Vector3f(0.1f, 0.1f, 0.1f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(1, 1, 1, 1));
}
}
for (int iii = 0; iii < CollisionTestApplication.testPointsBox.size(); iii++) {
final Vector3f elem = CollisionTestApplication.testPointsBox.get(iii);
if (iii == 0) {
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(0, 1, 0, 1));
} else if (iii == 7) {
this.debugDrawProperty.drawSquare(new Vector3f(0.05f, 0.05f, 0.05f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(1, 1, 0, 1));
} else {
this.debugDrawProperty.drawSquare(new Vector3f(0.1f, 0.1f, 0.1f), Matrix4f.identity().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(elem.x, elem.y, elem.z + 14))),
new Color(0, 0, 1, 1));
}
}
if (testRpos != null) {
//debugDrawProperty.drawSquare(box2HalfSize, testQTransfert.getMatrix4().multiplyNew(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z+14))), new Color(0,1,0,0.5f));
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = testQTransfert.getMatrix4().multiply(Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z))).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
final Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x, testRpos.y, testRpos.z)).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14)))
.multiply(testQTransfert.getMatrix4());
// OK sans la box1 orientation ...
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
//Matrix4f transformation = Matrix4f.createMatrixTranslate(new Vector3f(testRpos.x,testRpos.y,testRpos.z)).multiply(testQTransfert.getMatrix4()).multiply(Matrix4f.createMatrixTranslate(new Vector3f(0,0,14)));
this.debugDrawProperty.drawSquare(box2HalfSize, transformation, new Color(0, 1, 0, 0.5f));
this.debugDrawProperty.drawSquare(box1HalfSize, Matrix4f.createMatrixTranslate(new Vector3f(0, 0, 14)), new Color(0, 0, 1, 0.5f));
}
// Restore context of matrix
OpenGL.pop();
}
@Override
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) {
if (type == KeyKeyboard.f1) {
Gale.getContext().grabPointerEvents(false, new Vector2f(0, 0));
}
if (type == KeyKeyboard.f2) {
Gale.getContext().grabPointerEvents(true, new Vector2f(0, 0));
}
if (type == KeyKeyboard.f12) {
Gale.getContext().setFullScreen(!Gale.getContext().getFullScreen());
}
this.env.onKeyboard(special, type, value, state);
}
@Override
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) {
this.env.onPointer(special, type, pointerID, pos, state);
}
@Override
public void onRegenerateDisplay(final Context context) {
//Log.verbose("Regenerate Gale Application");
if (!this.creationDone) {
return;
}
this.angleLight += 0.01;
this.lightPosition.getTransform().getPosition().x = 5 + (float) Math.cos(this.angleLight) * 7.0f;
this.lightPosition.getTransform().getPosition().y = 5 + (float) Math.sin(this.angleLight) * 7.0f;
this.env.periodicCall();
markDrawingIsNeeded();
}
}

View File

@ -0,0 +1,30 @@
package org.atriasoft.gameengine.samples.collisiontest;
public class Log {
private Log() {}
private static final String LIBNAME = "LoxelEngine";
public static void print(String data) {
System.out.println(data);
}
public static void critical(String data) {
System.out.println("[C] " + LIBNAME + " | " + data);
}
public static void error(String data) {
System.out.println("[E] " + LIBNAME + " | " + data);
}
public static void warning(String data) {
System.out.println("[W] " + LIBNAME + " | " + data);
}
public static void info(String data) {
System.out.println("[I] " + LIBNAME + " | " + data);
}
public static void debug(String data) {
System.out.println("[D] " + LIBNAME + " | " + data);
}
public static void verbose(String data) {
System.out.println("[V] " + LIBNAME + " | " + data);
}
public static void todo(String data) {
System.out.println("[TODO] " + LIBNAME + " | " + data);
}
}

View File

@ -0,0 +1,13 @@
package org.atriasoft.gameengine.samples.collisiontest;
import org.atriasoft.etk.Uri;
import org.atriasoft.gale.Gale;
public class MainCollisionTest {
public static void main(final String[] args) {
Uri.setGroup("DATA", "src/org/atriasoft/gameengine/samples/LoxelEngine/res/");
Uri.setGroup("DATA_EGE", "src/org/atriasoft/gameengine/data/");
Uri.setGroup("RES", "res");
Gale.run(new CollisionTestApplication(), args);
}
}