Friday, March 25, 2016

lwjgl - Java JBullet Mesh collsion problem


I have a problem with JBullet mesh collsion. Everything works fine when I create a mesh from my object without scaling, but the problem starts when I want to scale the object. I also tried scaling in Blender, but it has the same problem. Here is my code for creating a mesh from an object:


    int numtriangles = mesh.vertices.length / 3;
int numverts = mesh.vertices.length;

ByteBuffer indexBuffer = BufferUtils.createByteBuffer(numverts * 3 * 4).order(ByteOrder.nativeOrder());

indexBuffer.clear();
for(int i=0;i indexBuffer.putInt(i);
indexBuffer.putInt(i);
indexBuffer.putInt(i);
}

ByteBuffer geometry = BufferUtils.createByteBuffer(numtriangles * 3 * 4).order(ByteOrder.nativeOrder());
geometry.clear();
for(int i=0;i
geometry.putFloat(mesh.vertices[i].getPos().x);
geometry.putFloat(mesh.vertices[i].getPos().y);
geometry.putFloat(mesh.vertices[i].getPos().z);
}

geometry.rewind();
indexBuffer.rewind();

TriangleIndexVertexArray trimesh = new TriangleIndexVertexArray(numtriangles, indexBuffer, 3 * 4, numtriangles, geometry, 3 * 4);
BvhTriangleMeshShape shape = new BvhTriangleMeshShape(trimesh,true);

return shape;

My scaling was something like this:


    for(int i = 0; i < vertices.length; i++) {
Vertex acc = vertices[i];

Vector3 pos = acc.getPos();
pos.x *= scale.x;
pos.y *= scale.y;
pos.z *= scale.z;

acc.setPos(pos);

Vector2 tex_coord = acc.getTexCords();
tex_coord.x *= scale.x;
tex_coord.y *= scale.z;
acc.setTexCords(tex_coord);

vertices[i] = acc;
}


The problem is when I scale the object, it no longer collides with other objects.



Answer



The scaling looks fine, but the calculation of indices doesn't look correct. I think it just happens to somewhat work by accident when the objects are small enough. This code:


for(int i=0;i   indexBuffer.putInt(i);
indexBuffer.putInt(i);
indexBuffer.putInt(i);
}

adds the same vertex index three times for the triangle meaning that only the first 1/3 of the vertices are referenced. As you are not sharing vertices between triangles, perhaps the code should be:



for(int i=0;i   indexBuffer.putInt(i);
}

Note that you probably don't want to scale the texture coordinates, although that doesn't matter for physics. Also the scaling code redundantly assigns the modified vertex back to the array even though in Java the variable is just a reference and you are modifying the original data. This should be enough:


for(int i = 0; i < vertices.length; i++) {
Vertex acc = vertices[i];

Vector3 pos = acc.getPos();
pos.x *= scale.x;

pos.y *= scale.y;
pos.z *= scale.z;
//acc.setPos(pos); // This is not needed either if getPos() doesn't create a copy. Most likely it doesn't.
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...