Collision mesh generation in scene loader

This commit is contained in:
austin 2022-12-11 12:28:53 -05:00
parent 9e2b0d396e
commit ac2d76cd01
15 changed files with 277 additions and 34 deletions

View File

@ -21,6 +21,7 @@
],
"files" : [
"Data/objects/floatingisland.json"
"Data/objects/floatingisland.json",
"Data/objects/testscene1objects.json"
]
}

View File

@ -0,0 +1,37 @@
{
"objects" : [
{
"objectId" : "terrain1",
"modelPath" : "Models/startingarea1.fbx",
"tokens" : [
"DISABLE_COLLISION_REACTION",
"GENERATE_COLLISION_TERRAIN"
],
"collidable": null,
"graphicsTemplate": null
},
{
"objectId" : "smoke1",
"modelPath" : "Models/unitcube.fbx",
"tokens" : [
"DRAW_TRANSPARENT_PASS"
],
"collidable": null,
"graphicsTemplate": {
"shaderOverrideMeshList": [
"Cube"
],
"shaderMap": {
"Cube": {
"vertexPath": "Shaders/smoke1/smoke1.vs",
"geometryPath": null,
"fragmentPath": "Shaders/smoke1/smoke1.fs"
}
}
}
}
],
"files" : []
}

View File

@ -1,16 +0,0 @@
{
"terrainObjects" : [
{
"objectId" : "terrain1",
"modelPath" : "Models/startingarea1.fbx",
"tokens" : [
],
"collidable": null
}
],
"files" : [
"Data/objects/floatingisland.json"
]
}

View File

@ -1,15 +1,15 @@
{
"entities": [
{
"type": "item",
"subtype": "Katana",
"type": "object",
"subtype": "terrain1",
"posX": 3,
"posY": 5,
"posZ": 5,
"rotX": 0,
"rotX": -0.7071068,
"rotY": 0,
"rotZ": 0,
"rotW": 1
"rotW": 0.7071068
}
],
"scriptPaths": [

BIN
docs/phyicsForDummies.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

View File

@ -1,6 +1,8 @@
package electrosphere.engine.assetmanager;
import electrosphere.audio.AudioBuffer;
import electrosphere.collision.dispatch.CollisionObject;
import electrosphere.game.collision.PhysicsUtils;
import electrosphere.renderer.Mesh;
import electrosphere.renderer.Model;
import electrosphere.renderer.ShaderProgram;
@ -15,6 +17,8 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.lwjgl.assimp.AIScene;
/**
*
* @author amaterasu
@ -34,8 +38,8 @@ public class AssetManager {
Map<String,ShaderProgram> shadersLoadedIntoMemory = new ConcurrentHashMap<String,ShaderProgram>();
List<ActorShaderMask> shadersInQueue = new CopyOnWriteArrayList<ActorShaderMask>();
Map<String,CollisionObject> physicsMeshesLoadedIntoMemory = new ConcurrentHashMap<String,CollisionObject>();
List<String> physicsMeshesToLoad = new CopyOnWriteArrayList<String>();
@ -47,7 +51,13 @@ public class AssetManager {
public void loadAssetsInQueue(){
for(String currentPath : modelsInQueue){
modelsInQueue.remove(currentPath);
modelsLoadedIntoMemory.put(currentPath, ModelLoader.load_Model_From_File(currentPath));
AIScene scene = ModelLoader.loadAIScene(currentPath);
modelsLoadedIntoMemory.put(currentPath, ModelLoader.createModelFromAiScene(scene,currentPath));
if(physicsMeshesToLoad.contains(currentPath)){
//create physics
physicsMeshesToLoad.remove(currentPath);
physicsMeshesLoadedIntoMemory.put(currentPath,PhysicsUtils.generateRigidBodyFromAISCene(scene));
}
}
for(String currentPath : texturesInQueue){
texturesInQueue.remove(currentPath);

View File

@ -4,6 +4,7 @@ import electrosphere.entity.Entity;
import electrosphere.entity.EntityUtils;
import electrosphere.entity.types.creature.CreatureUtils;
import electrosphere.entity.types.item.ItemUtils;
import electrosphere.entity.types.object.ObjectUtils;
import electrosphere.main.Globals;
import electrosphere.util.FileUtils;
@ -35,7 +36,11 @@ public class SceneLoader {
EntityUtils.getRotation(newEntity).set((float)descriptor.rotX, (float)descriptor.rotY, (float)descriptor.rotZ, (float)descriptor.rotW);
} break;
case EntityDescriptor.TYPE_OBJECT:
case EntityDescriptor.TYPE_OBJECT: {
Entity newEntity = ObjectUtils.spawnBasicObject(descriptor.subtype);
EntityUtils.getPosition(newEntity).set(descriptor.posX,descriptor.posY,descriptor.posZ);
EntityUtils.getRotation(newEntity).set((float)descriptor.rotX, (float)descriptor.rotY, (float)descriptor.rotZ, (float)descriptor.rotW);
} break;
default:
throw new UnsupportedOperationException();
}

View File

@ -37,7 +37,7 @@ public class GravityTree {
int fallFrame = 1;
float gravityVelocity = 0;
float gravityAccel = 0.0002f;
float gravityAccel = 0.0007f;
CollisionObject body;
Collidable collidable;

View File

@ -28,7 +28,7 @@ public class JumpTree implements BehaviorTree {
int jumpFrames = 0;
int currentFrame = 0;
float jumpForce = 1.0f;
float jumpForce = 10.0f;
float currentJumpForce = jumpForce;
static final float jumpFalloff = 0.99f;

View File

@ -36,6 +36,9 @@ public class ObjectUtils {
case "DISABLE_COLLISION_REACTION": {
collisionMakeDynamic = false;
} break;
case "GENERATE_COLLISION_TERRAIN": {
} break;
}
}
//main entity construction

View File

@ -22,6 +22,11 @@ import java.nio.IntBuffer;
import org.joml.Quaternionf;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.lwjgl.PointerBuffer;
import org.lwjgl.assimp.AIFace;
import org.lwjgl.assimp.AIMesh;
import org.lwjgl.assimp.AIScene;
import org.lwjgl.assimp.AIVector3D;
/**
*
@ -171,6 +176,151 @@ public class PhysicsUtils {
return terrainRigidBody;
}
public static RigidBody generateRigidBodyFromAISCene(AIScene scene){
Vector3d position = EntityUtils.getPosition(terrain);
int arrayLength = heightfield.length;
int arrayWidth = heightfield[0].length;
float collisionMargin = 0.08f;
/*
Traditional buffer code not working for some reason
the approach of
https://stackoverflow.com/questions/40855945/lwjgl-mesh-to-jbullet-collider
works much better
IDK why
*/
PointerBuffer meshesBuffer = scene.mMeshes();
while(meshesBuffer.hasRemaining()){
AIMesh aiMesh = AIMesh.create(meshesBuffer.get());
//read vertices
AIVector3D.Buffer vertexBuffer = aiMesh.mVertices();
while(vertexBuffer.hasRemaining()){
vertexBuffer.get();
// numVertices++;
}
//read faces
AIFace.Buffer faceBuffer = aiMesh.mFaces();
while(faceBuffer.hasRemaining()){
AIFace currentFace = faceBuffer.get();
IntBuffer indexBuffer = currentFace.mIndices();
while(indexBuffer.hasRemaining()){
int index = indexBuffer.get();
}
}
}
int numberTriangles = (arrayLength - 1) * (arrayWidth - 1) * 2;
int triangleStride = 0;
int numberVertices = arrayLength * arrayWidth;
int vertexStride = 0;
float[] vertices = new float[numberVertices * 3];
int vertexInserterPos = 0;
int[] indices = new int[numberTriangles * 3];
int indexInserterPos = 0;
for(int x = 0; x < arrayLength; x++){
for(int y = 0; y < arrayWidth; y++){
vertices[vertexInserterPos] = x;
vertexInserterPos++;
vertices[vertexInserterPos] = heightfield[x][y] - collisionMargin;
vertexInserterPos++;
vertices[vertexInserterPos] = y;
vertexInserterPos++;
if(x < arrayLength - 1 && y < arrayWidth - 1){
//if we should also add a triangle index
/*
as copied from ModelUtil's terrain mesh generation function
faces.put((x / stride + 0) * actualHeight + (y / stride + 0));
faces.put((x / stride + 0) * actualHeight + (y / stride + 1));
faces.put((x / stride + 1) * actualHeight + (y / stride + 0));
faces.put((x / stride + 1) * actualHeight + (y / stride + 0));
faces.put((x / stride + 0) * actualHeight + (y / stride + 1));
faces.put((x / stride + 1) * actualHeight + (y / stride + 1));
*/
indices[indexInserterPos] = (x + 0) * arrayWidth + (y + 0);
indexInserterPos++;
indices[indexInserterPos] = (x + 0) * arrayWidth + (y + 1);
indexInserterPos++;
indices[indexInserterPos] = (x + 1) * arrayWidth + (y + 0);
indexInserterPos++;
indices[indexInserterPos] = (x + 1) * arrayWidth + (y + 0);
indexInserterPos++;
indices[indexInserterPos] = (x + 0) * arrayWidth + (y + 1);
indexInserterPos++;
indices[indexInserterPos] = (x + 1) * arrayWidth + (y + 1);
indexInserterPos++;
}
}
}
javax.vecmath.Vector3f aabbMin = new javax.vecmath.Vector3f();
javax.vecmath.Vector3f aabbMax = new javax.vecmath.Vector3f();
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/IndexedMesh.html
electrosphere.collision.shapes.IndexedMesh indexedMesh = new electrosphere.collision.shapes.IndexedMesh();
indexedMesh.numTriangles = indices.length / 3;
indexedMesh.triangleIndexBase = ByteBuffer.allocateDirect(indices.length*Float.BYTES).order(ByteOrder.nativeOrder());
indexedMesh.triangleIndexBase.asIntBuffer().put(indices);
indexedMesh.triangleIndexStride = 3 * Float.BYTES;
indexedMesh.numVertices = vertices.length / 3;
indexedMesh.vertexBase = ByteBuffer.allocateDirect(vertices.length*Float.BYTES).order(ByteOrder.nativeOrder());
indexedMesh.vertexBase.asFloatBuffer().put(vertices);
indexedMesh.vertexStride = 3 * Float.BYTES;
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shpaes/TriangleIndexVertexArray.html
electrosphere.collision.shapes.TriangleIndexVertexArray triangleIndexArray = new electrosphere.collision.shapes.TriangleIndexVertexArray();
triangleIndexArray.addIndexedMesh(indexedMesh); //this assumes the scalar type is integer (assumes bytebuffer is actually integer
// triangleIndexArray.calculateAabbBruteForce(aabbMin, aabbMax);
//http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/BvhTriangleMeshShape.html
electrosphere.collision.shapes.BvhTriangleMeshShape terrainShape = new electrosphere.collision.shapes.BvhTriangleMeshShape(
triangleIndexArray,
true // "useQuantizedAabbCompression" -- apparently means better memory usage ( http://jbullet.advel.cz/javadoc/com/bulletphysics/collision/shapes/BvhTriangleMeshShape.html )
);
//uncomment if we start falling through things again
terrainShape.setMargin(collisionMargin);
DefaultMotionState defaultMotionState = new DefaultMotionState(new Transform(new javax.vecmath.Matrix4f(new javax.vecmath.Quat4f(0,0,0,1),new javax.vecmath.Vector3f((float)position.x,(float)position.y,(float)position.z),1.0f)));
RigidBodyConstructionInfo terrainRigidBodyCI = new RigidBodyConstructionInfo(0, defaultMotionState, terrainShape);
RigidBody terrainRigidBody = new RigidBody(terrainRigidBodyCI);
// terrainRigidBody.setFriction(1f);
Globals.collisionEngine.registerCollisionObject(terrainRigidBody, new Collidable(terrain,Collidable.TYPE_TERRAIN));
// terrainRigidBody.getAabb(aabbMin, aabbMax);
//
// System.out.println("aabbMin: " + aabbMin + " aabbMax: " + aabbMax);
terrain.putData(EntityDataStrings.PHYSICS_COLLISION_BODY, terrainRigidBody);
return terrainRigidBody;
}
public static void addTestPlaneRigidBody(){

View File

@ -0,0 +1,21 @@
package electrosphere.game.data.graphics;
import java.util.List;
import java.util.Map;
public class GraphicsTemplate {
List<String> shaderOverrideMeshList;
Map<String,ShaderSet> shaderMap;
public List<String> getShaderOverrideMeshList(){
return shaderOverrideMeshList;
}
public Map<String,ShaderSet> getShaderMap(){
return shaderMap;
}
}

View File

@ -0,0 +1,21 @@
package electrosphere.game.data.graphics;
public class ShaderSet {
String vertexPath;
String geometryPath;
String fragmentPath;
public String getVertexPath(){
return vertexPath;
}
public String getGeometryPath(){
return geometryPath;
}
public String getFragmentPath(){
return fragmentPath;
}
}

View File

@ -2,6 +2,8 @@ package electrosphere.game.data.object.type;
import electrosphere.entity.types.hitbox.HitboxData;
import electrosphere.game.data.creature.type.CollidableTemplate;
import electrosphere.game.data.graphics.GraphicsTemplate;
import java.util.List;
public class ObjectData {
@ -10,6 +12,7 @@ public class ObjectData {
String modelPath;
List<String> tokens;
CollidableTemplate collidable;
GraphicsTemplate graphicsTemplate;
public String getObjectId() {
return objectId;
@ -26,5 +29,9 @@ public class ObjectData {
public CollidableTemplate getCollidable(){
return collidable;
}
public GraphicsTemplate getGraphicsTemplate(){
return graphicsTemplate;
}
}

View File

@ -26,23 +26,27 @@ import static org.lwjgl.assimp.Assimp.*;
import static org.lwjgl.assimp.Assimp.aiImportFile;
public class ModelLoader {
public static Model load_Model_From_File(String fileName){
Model rVal;
AIScene scene;
public static AIScene loadAIScene(String path){
AIScene rVal;
// File file = new File(Thread.currentThread().getContextClassLoader().getResource(fileName).getFile());
// Main.class.getResourceAsStream(fileName).readAllBytes();
File toRead = FileUtils.getAssetFile(fileName);
scene = aiImportFile(toRead.getAbsolutePath(),
File toRead = FileUtils.getAssetFile(path);
rVal = aiImportFile(toRead.getAbsolutePath(),
aiProcess_GenSmoothNormals |
aiProcess_JoinIdenticalVertices |
aiProcess_Triangulate |
aiProcess_FixInfacingNormals |
aiProcess_LimitBoneWeights);
if(scene == null){
if(rVal == null){
throw new IllegalStateException(aiGetErrorString());
}
return rVal;
}
public static Model createModelFromAiScene(AIScene scene, String path){
Model rVal;
rVal = Model.createModelFromAiscene(scene);
attemptAddTexturesFromPathname(fileName, rVal);
attemptAddTexturesFromPathname(path, rVal);
return rVal;
}