I have created a bullet vehicle with a attached turret at the top like this:
gEngineForce = 0.f;
gBreakingFrontForce = 0.f;
gBreakingBackForce = 0.f;
maxEngineForce = 20000.f;
minEngineForce = -2000.f;
maxBreakingFrontForce = 4000.f;
maxBreakingBackForce = 600.f;
gVehicleSteering = 0.f;
steeringIncrement = 0.002f;
steeringClamp = 0.6f;
wheelRadius = 0.5f;
wheelWidth = 0.4f;
wheelFriction = 50;
suspensionStiffness = 10.f;
suspensionDamping = 1.3f;
suspensionCompression = 4.4f;
rollInfluence = 0.1f;//1.0f
btScalar suspensionRestLength(0.6);
btVector3 wheelDirectionCS0(0, -1, 0);
btVector3 wheelAxleCS(-1, 0, 0);
btTransform tr;
tr.setIdentity();
chassisShape = new btBoxShape(btVector3(1.f, 0.5f, 2.f));
bulletCollisionShapes.push_back(chassisShape);
compound = new btCompoundShape();
bulletCollisionShapes.push_back(compound);
btTransform chassisTrans;
chassisTrans.setIdentity();
//localTrans effectively shifts the center of mass with respect to the chassis
chassisTrans.setOrigin(btVector3(0, 1.3, 0));
compound->addChildShape(chassisTrans, chassisShape);
tr.setOrigin(btVector3(0, 0.f, 0));
//m_carChassis = CreateRigidBody(2000, tr, compound);
//m_carChassis->setDamping(0.2,0.2);
m_wheelShape = new btCylinderShapeX(btVector3(wheelWidth, wheelRadius, wheelRadius));
m_carChassis = CreateRigidBody(2000, tr, compound);
// create turret
turretShape = new btBoxShape(btVector3(0.4f, 0.2f, 0.8f));
bulletCollisionShapes.push_back(turretShape);
btTransform turretTrans;
turretTrans.setIdentity();
turretTrans.setOrigin(btVector3(0.0f, 0.7f, 0.0f));
turretBody = CreateRigidBody(1, turretTrans, turretShape);
// add some data to build constraint frames
btVector3 axisA(0.f, 1.f, 0.f);
btVector3 axisB(0.f, 0.f, 0.f);
btVector3 pivotA(0.f, 1.f, 0.f);
btVector3 pivotB(0.f, 0.f, 0.f);
hinge = new btHingeConstraint(*m_carChassis, *turretBody, pivotA, pivotB, axisA, axisB);
//hinge->setLimit(-SIMD_HALF_PI * 0.5f, SIMD_HALF_PI * 0.5f);
hinge->enableAngularMotor(true, 0, 1);
// add constraint to world
bt_dynamicsWorld->addConstraint(hinge, true);
{
btTransform something;
something.setIdentity();
something.setOrigin(btVector3(0, 10, 0));
m_carChassis->setWorldTransform(something);
m_vehicleRayCaster = new btDefaultVehicleRaycaster(bt_dynamicsWorld);
m_vehicle = new btRaycastVehicle(m_tuning, m_carChassis, m_vehicleRayCaster);
m_carChassis->setActivationState(DISABLE_DEACTIVATION);
bt_dynamicsWorld->addVehicle(m_vehicle);
float connectionHeight = 1.2f;
//choose coordinate system
m_vehicle->setCoordinateSystem(rightIndex, upIndex, forwardIndex);
bool isFrontWheel = true;
btVector3 connectionPointCS0(1 - (-0.8*wheelWidth), connectionHeight, 3 * 1 - wheelRadius);
m_vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, m_tuning, isFrontWheel);
connectionPointCS0 = btVector3(-1 + (-0.8*wheelWidth), connectionHeight, 3 * 1 - wheelRadius);
m_vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, m_tuning, isFrontWheel);
isFrontWheel = false;
connectionPointCS0 = btVector3(-1 + (-0.8*wheelWidth), connectionHeight, -3 * 1 + wheelRadius);
m_vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, m_tuning, isFrontWheel);
connectionPointCS0 = btVector3(1 - (-0.8*wheelWidth), connectionHeight, -3 * 1 + wheelRadius);
m_vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, suspensionRestLength, wheelRadius, m_tuning, isFrontWheel);
for (int i = 0; i < m_vehicle->getNumWheels(); i++)
{
btWheelInfo& wheel = m_vehicle->getWheelInfo(i);
wheel.m_suspensionStiffness = suspensionStiffness;
wheel.m_wheelsDampingRelaxation = suspensionDamping;
wheel.m_wheelsDampingCompression = suspensionCompression;
wheel.m_frictionSlip = wheelFriction;
wheel.m_rollInfluence = rollInfluence;
}
}
int wheelIndex = 2;
m_vehicle->applyEngineForce(gEngineForce, wheelIndex);
m_vehicle->setBrake(gBreakingBackForce, wheelIndex);
wheelIndex = 3;
m_vehicle->applyEngineForce(gEngineForce, wheelIndex);
m_vehicle->setBrake(gBreakingBackForce, wheelIndex);
wheelIndex = 0;
m_vehicle->setSteeringValue(gVehicleSteering, wheelIndex);
m_vehicle->setBrake(gBreakingFrontForce, wheelIndex);
wheelIndex = 1;
m_vehicle->setSteeringValue(gVehicleSteering, wheelIndex);
m_vehicle->setBrake(gBreakingFrontForce, wheelIndex);
This is how I render the vehicle:
// render wheels
btScalar mwheel[16];
for (int i = 0; i<m_vehicle->getNumWheels(); i++){
//synchronize the wheels with the (interpolated) chassis worldtransform
m_vehicle->updateWheelTransform(i, true);
//draw wheels
m_vehicle->getWheelInfo(i).m_worldTransform.getOpenGLMatrix(mwheel);
RenderWheel(m_wheelShape, mwheel);
}
// render car chassis
btScalar mchassis[16];
m_vehicle->getChassisWorldTransform().getOpenGLMatrix(mchassis);
RenderBox(chassisShape, mchassis);
// render turret
btScalar mturret[16];
// get chassis and turret transforms
btTransform chassisTransform = m_vehicle->getChassisWorldTransform();
//btTransform turretTransform = compound->getChildTransform(1);
btTransform turretTransform = turretBody->getWorldTransform();
// multiply transforms to get updated turret transform
//turretTransform *= chassisTransform;
turretTransform.getOpenGLMatrix(mturret);
RenderBox(turretShape, mturret);
Using the arrow keys I apply break or acceleration forces like this:
bullet.gEngineForce = bullet.maxEngineForce;
bullet.gBreakingFrontForce = 0.f;
bullet.gBreakingBackForce = 0.f;
etc.
The camera is attached to the turret on top of the car, therefore attached to the car itself.
The issue is that when the car starts moving and as it gain speed, the wheels seem to fall behind and the chassis going forward. I would like make the wheels and the chassis more tight, but playing around with the car suspension settings did not help.
Here is a video demonstrating this behaviour: click
I have also noticed another strange behaviour related to the way the car pitches when moving, breaking and turning.
Increasing the gravity accentuates this behaviour. when I accelerate, the chassis pitches forward and when I brake it goes backwards. This is obviously wrong as it should be the other way around. Same happens when turning left, the car pitches left instead of right, and the other way around.
Here is another video demonstrating this behaviour: click
i had this kind of problem. it turned out that wheels were rendered using transformation not from the same frame as chassis. i.e. from frame n-1 while chassis used frame n.
things werent apparent bcause wheel meshes were child nodes of chassis node, as it was how it was implemented by me in rendering engine, while in bullet physics, wheel coordinates are global, the same way chassis is.
but that wasnt all, when converting wheel coords from global to local vehicle space, there was accuracy loss that, still caused problems. it was fixed by making wheel meshes as global nodes.
Related
The idea is to present a drawn 3D object "centered" in the screen. After loading the object with WaveFrontReader I got an array of vertices:
float bmin[3], bmax[3];
bmin[0] = bmin[1] = bmin[2] = std::numeric_limits<float>::max();
bmax[0] = bmax[1] = bmax[2] = -std::numeric_limits<float>::max();
for (int k = 0; k < 3; k++)
{
for (auto& v : objx->wfr.vertices)
{
if (k == 0)
{
bmin[k] = std::min(v.position.x, bmin[k]);
bmax[k] = std::max(v.position.x, bmax[k]);
}
if (k == 1)
{
bmin[k] = std::min(v.position.y, bmin[k]);
bmax[k] = std::max(v.position.y, bmax[k]);
}
if (k == 2)
{
bmin[k] = std::min(v.position.z, bmin[k]);
bmax[k] = std::max(v.position.z, bmax[k]);
}
}
}
I got the idea from the Viewer in TinyObjLoader (which uses OpenGL though), and then:
float maxExtent = 0.5f * (bmax[0] - bmin[0]);
if (maxExtent < 0.5f * (bmax[1] - bmin[1])) {
maxExtent = 0.5f * (bmax[1] - bmin[1]);
}
if (maxExtent < 0.5f * (bmax[2] - bmin[2])) {
maxExtent = 0.5f * (bmax[2] - bmin[2]);
}
_3dp.scale[0] = maxExtent;
_3dp.scale[1] = maxExtent;
_3dp.scale[2] = maxExtent;
_3dp.translation[0] = -0.5 * (bmax[0] + bmin[0]);
_3dp.translation[1] = -0.5 * (bmax[1] + bmin[1]);
_3dp.translation[2] = -0.5 * (bmax[2] + bmin[2]);
However this doesn't work. With an object like this spider which has vertices that the coordinates do not extend +/-100, the scale gets to about 100x by the above formula and yet, with the current view set to 0,0,0 the object is too close and I have to put the Z translation manually to something like 50000 to view it into a full box with a D3D11_VIEWPORT viewport = { 0.0f, 0.0f, w, h, 0.0f, 1.0f };, Not to mention that the Y is not centered as well.
Is there a proper algorithm to center the object into view?
Thanks a lot
You can actually change the position of the camera itself and not the objects.
Its recommended that you edit the camera position in OpenGL tutorials.
In games the camera (which is what captures the viewpoint which the rendered objects are viewed from) are not in the middle of the view but actually further way so you can see everything going on in the view/scene.
i'm making a side-scrolling car game with box2D.
I'm currently working on the car and it seems that i'm stuck.
The chassis of my car isn't rotating when for example the car is trying to climb a hill. I don't know if its normal or if i should set the angle of the body.
Here's a quick video that shows the problem : https://streamable.com/d802n
This is my code :
b2BodyDef carBox = b2BodyDef();
carBox.position = b2Vec2(bodyCenterPosition.x, bodyCenterPosition.y);
carBox.type = b2_dynamicBody;
car = game->getWorld()->CreateBody(&carBox);
b2PolygonShape carPolygon = b2PolygonShape();
carPolygon.SetAsBox(bodySize.x, bodySize.y);
b2FixtureDef carFix = b2FixtureDef();
carFix.density = 0.0f;
carFix.shape = &carPolygon;
car->CreateFixture(&carFix);
b2PolygonShape headPolygon = b2PolygonShape();
headPolygon.SetAsBox(headSize.x, headSize.y);
for (int i = 0; i < 8; i++) {
headPolygon.m_vertices[i].x -= 8.0f / RATIO;
headPolygon.m_vertices[i].y -= 24.0f / RATIO;
}
b2FixtureDef headFix = b2FixtureDef();
headFix.density = 0.0f;
headFix.shape = &headPolygon;
car->CreateFixture(&headFix);
b2CircleShape circleShape;
circleShape.m_radius = 0.35f;
circleShape.m_p.SetZero();
b2FixtureDef fd;
fd.shape = &circleShape;
fd.density = 1.0f;
fd.friction = 0.9f;
b2BodyDef wheel1Def;
wheel1Def.type = b2_dynamicBody;
wheel1Def.position = b2Vec2(backWheelCenterPosition.x, backWheelCenterPosition.y);
backWheel = game->getWorld()->CreateBody(&wheel1Def);
backWheel->CreateFixture(&fd);
b2BodyDef wheel2Def;
wheel2Def.type = b2_dynamicBody;
wheel2Def.position = b2Vec2(frontWheelCenterPosition.x, frontWheelCenterPosition.y);
frontWheel = game->getWorld()->CreateBody(&wheel2Def);
frontWheel->CreateFixture(&fd);
b2WheelJointDef springDef1;
springDef1.dampingRatio = 50.0f;
springDef1.maxMotorTorque = 1.0f;
springDef1.frequencyHz = 15.0f;
springDef1.motorSpeed = 0.0f;
springDef1.enableMotor = true;
springDef1.Initialize(car, backWheel, backWheel->GetPosition(), sfVecToB2Vec(sf::Vector2f(0.0f, 1.0f)));
backSpring = (b2WheelJoint*) game->getWorld()->CreateJoint(&springDef1);
springDef1.Initialize(car, frontWheel, frontWheel->GetPosition(), sfVecToB2Vec(sf::Vector2f(0.0f, 1.0f)));
frontSpring = (b2WheelJoint*) game->getWorld()->CreateJoint(&springDef1);
It is normal for a body with a fixture having a zero density to behave like an infinite mass. Sounds like that's not what you intended however.
Looking at the code presented, we see that the carFix.density and headFix.density are being set to 0.0f. Set these to a positive non-zero value, like 1.0f, and the dynamic body they're created on should behave more like a physical mass would. That's assuming all of the other fixtures created on that body also have a density that's greater than zero as well.
For a tutorial on fixtures and density, I'd recommend taking a look at iforce2d's Box2D C++ tutorials - Fixtures.
Hope this solves the problem or at least helps.
By the way, I loved the artwork shown in the video!
I'm trying to do a first cam person using OPENGL. But here's my problem.
Let me introduce you my code.
First of all, I have this function that allows me to get the mouse X and Y position:
case WM_MOUSEMOVE:
CameraManager.oldMouseX = CameraManager.mouseX;
CameraManager.oldMouseY = CameraManager.mouseY;
CameraManager.mouseX = GET_X_LPARAM(lParam);
CameraManager.mouseY = GET_Y_LPARAM(lParam);
mousePoint.x = CameraManager.mouseX - CameraManager.oldMouseX;
mousePoint.y = CameraManager.mouseY - CameraManager.oldMouseY;
mousePoint.z = 0.f;
CameraManager.lookAt(mousePoint);
App.onRender();
break;
Here I get the difference between the old mouse position and the new one (just because I want to know when I have to increase/decrease the angle). Then, I call the lookAt function on my CameraManager.
Here I do the following:
if (point.x > 0.f) {
camAngle.x -= 0.3f;
}
else if (point.x < 0.f) {
camAngle.x += 0.3f ;
}
float radiansX = MathUtils::CalculateRadians(camAngle.x);
//eye.x = sinf(radiansX);
//center.x += sinf(radiansX);
//center.z += (-cosf(radiansX));
Update();
And then my update does:
glLoadIdentity();
gluLookAt(eye.x, eye.y, eye.z,
center.x, center.y, center.z,
up.x, up.y, up.z);
I've read a lot of stuff on how to refresh the eye and center, but I couldn't get anything to work.
Any advices?
I have been developing a 3d chessboard and I have been stuck trying to drag the pieces for a few days now.
Once I select an object using my ray-caster, I start my dragging function which calculates the difference between the current location of the mouse (in world coordinates) and its previous location, I then translate my object by the difference of these coordinates.
I debug my ray-caster by drawing lines so I am sure those coordinates are accurate.
Translating my object based on the ray-caster coordinates only moves the object a fraction of the distance it should actually go.
Am I missing a step?
-Calvin
I believe my issue is in this line of code....
glm::vec3 World_Delta = Current_World_Location - World_Start_Location;
If I multiply the equation by 20 the object start to move more like I would expect it to, but it is never completely accurate.
Below is some relevent code
RAY-CASTING:
void CastRay(int mouse_x, int mouse_y) {
int Object_Selected = -1;
float Closest_Object = -1;
//getWorldCoordinates calls glm::unproject
nearPoint = Input_Math.getWorldCoordinates(glm::vec3(mouse_x, Window_Input_Info.getScreenHeight()-mouse_y, 0.0f));
farPoint = Input_Math.getWorldCoordinates(glm::vec3(mouse_x, Window_Input_Info.getScreenHeight()-mouse_y, 1.0f));
glm::vec3 direction = Input_Math.normalize(farPoint - nearPoint);
//getObjectStack() Retrieves all objects in the current scene
std::vector<LoadOBJ> objectList = Object_Input_Info.getObjectStack();
for (int i = 0; i < objectList.size(); i++) {
std::vector<glm::vec3> Vertices = objectList[i].getVertices();
for(int j = 0; j < Vertices.size(); j++) {
if ( ( j + 1 ) % 3 == 0 ) {
glm::vec3 face_normal = Input_Math.normalize(Input_Math.CrossProduct(Vertices[j-1] - Vertices[j-2], Vertices[j] - Vertices[j-2]));
float nDotL = glm::dot(direction, face_normal);
if (nDotL <= 0.0f ) { //if nDotL == 0 { Perpindicular } else if nDotL < 0 { SameDirection } else { OppositeDirection }
float distance = glm::dot(face_normal, (Vertices[j-2] - nearPoint)) / nDotL;
glm::vec3 p = nearPoint + distance * direction;
glm::vec3 n1 = Input_Math.CrossProduct(Vertices[j-1] - Vertices[j-2], p - Vertices[j-2]);
glm::vec3 n2 = Input_Math.CrossProduct(Vertices[j] - Vertices[j-1], p - Vertices[j-1]);
glm::vec3 n3 = Input_Math.CrossProduct(Vertices[j-2] - Vertices[j], p - Vertices[j]);
if( glm::dot(face_normal, n1) >= 0.0f && glm::dot(face_normal, n2) >= 0.0f && glm::dot(face_normal, n3) >= 0.0f ) {
if(p.z > Closest_Object) {
//I Create this "dragplane" to be used by my dragging function.
Drag_Plane[0] = (glm::vec3(Vertices[j-2].x, Vertices[j-2].y, p.z ));
Drag_Plane[1] = (glm::vec3(Vertices[j-1].x, Vertices[j-1].y, p.z ));
Drag_Plane[2] = (glm::vec3(Vertices[j].x , Vertices[j].y , p.z ));
//This is the object the we selected in the scene
Object_Selected = i;
//These are the coordinate the ray intersected the object
World_Start_Location = p;
}
}
}
}
}
}
if(Object_Selected >= 0) { //If an object was intersected by the ray
//selectObject -> Simply sets the boolean "dragging" to true
selectObject(Object_Selected, mouse_x, mouse_y);
}
DRAGGING
void DragObject(int mouse_x, int mouse_y) {
if(dragging) {
//Finds the Coordinates where the ray intersects the "DragPlane" set by original object intersection
farPoint = Input_Math.getWorldCoordinates(glm::vec3(mouse_x, Window_Input_Info.getScreenHeight()-mouse_y, 1.0f));
nearPoint = Input_Math.getWorldCoordinates(glm::vec3(mouse_x, Window_Input_Info.getScreenHeight()-mouse_y, 0.0f));
glm::vec3 direction = Input_Math.normalize(farPoint - nearPoint);
glm::vec3 face_normal = Input_Math.normalize(Input_Math.CrossProduct(Drag_Plane[1] - Drag_Plane[0], Drag_Plane[2] - Drag_Plane[0]));
float nDotL = glm::dot(direction, face_normal);
float distance = glm::dot(face_normal, (Drag_Plane[0] - nearPoint)) / nDotL;
glm::vec3 Current_World_Location = nearPoint + distance * direction;
//Calculate the difference between the current mouse location and its previous location
glm::vec3 World_Delta = Current_World_Location - World_Start_Location;
//Set the "start location" to the current location for the next loop
World_Start_Location = Current_World_Location;
//get the current object
Object_Input_Info = Object_Input_Info.getObject(currentObject);
//adds a translation matrix to the stack
Object_Input_Info.TranslateVertices(World_Delta.x, World_Delta.y, World_Delta.z);
//calculates the new vertices
Object_Input_Info.Load_Data();
//puts the new object back
Object_Input_Info.Update_Object_Stack(currentObject);
}
}
I have already faced similar problems to what your reporting.
Instead of keeping track of the translation during mouse movement, you can do the following:
In your mouse button callback, store a 'Delta' vector from the mouse position (in world coordinates) (P_mouse) to your object position (P_object). It would be something like:
Delta = P_object - P_mouse;
For every call of your mouse motion callback, you just need to update the object position by:
P_object = P_mouse + Delta;
Notice that Delta is constant during the whole dragging process.
in my game project Im using the MD5 model files, but I feel I'm doing something wrong...
At every frame I update almost 30~40 animated meshes, (updating each joint and their respectives vertices) but doing like this im using always 25% of the CPU speed and my FPS always stay at 70~80 (when I should have 200~300).
I know that maybe I should use instancing but i dont know how to do this with animated meshes.
And even if I would use, as far as I know, this only works with the same meshes, but I need something around 30 different meshes for scene (and these would be repeated using instancing).
What I do every frame is, make the new skeleton for every animated mesh, put every joint at the new position (if the joint needs update) and update all vertices that should be updated.
My video card is ok, here is the update code:
bool AnimationModelClass::UpdateMD5Model(float deltaTime, int animation)
{
MD5Model.m_animations[animation].currAnimTime += deltaTime; // Update the current animation time
if(MD5Model.m_animations[animation].currAnimTime > MD5Model.m_animations[animation].totalAnimTime)
MD5Model.m_animations[animation].currAnimTime = 0.0f;
// Which frame are we on
float currentFrame = MD5Model.m_animations[animation].currAnimTime * MD5Model.m_animations[animation].frameRate;
int frame0 = floorf( currentFrame );
int frame1 = frame0 + 1;
// Make sure we don't go over the number of frames
if(frame0 == MD5Model.m_animations[animation].numFrames-1)
frame1 = 0;
float interpolation = currentFrame - frame0; // Get the remainder (in time) between frame0 and frame1 to use as interpolation factor
std::vector<Joint> interpolatedSkeleton; // Create a frame skeleton to store the interpolated skeletons in
// Compute the interpolated skeleton
for( int i = 0; i < MD5Model.m_animations[animation].numJoints; i++)
{
Joint tempJoint;
Joint joint0 = MD5Model.m_animations[animation].frameSkeleton[frame0][i]; // Get the i'th joint of frame0's skeleton
Joint joint1 = MD5Model.m_animations[animation].frameSkeleton[frame1][i]; // Get the i'th joint of frame1's skeleton
tempJoint.parentID = joint0.parentID; // Set the tempJoints parent id
// Turn the two quaternions into XMVECTORs for easy computations
D3DXQUATERNION joint0Orient = D3DXQUATERNION(joint0.orientation.x, joint0.orientation.y, joint0.orientation.z, joint0.orientation.w);
D3DXQUATERNION joint1Orient = D3DXQUATERNION(joint1.orientation.x, joint1.orientation.y, joint1.orientation.z, joint1.orientation.w);
// Interpolate positions
tempJoint.pos.x = joint0.pos.x + (interpolation * (joint1.pos.x - joint0.pos.x));
tempJoint.pos.y = joint0.pos.y + (interpolation * (joint1.pos.y - joint0.pos.y));
tempJoint.pos.z = joint0.pos.z + (interpolation * (joint1.pos.z - joint0.pos.z));
// Interpolate orientations using spherical interpolation (Slerp)
D3DXQUATERNION qtemp;
D3DXQuaternionSlerp(&qtemp, &joint0Orient, &joint1Orient, interpolation);
tempJoint.orientation.x = qtemp.x;
tempJoint.orientation.y = qtemp.y;
tempJoint.orientation.z = qtemp.z;
tempJoint.orientation.w = qtemp.w;
// Push the joint back into our interpolated skeleton
interpolatedSkeleton.push_back(tempJoint);
}
for ( int k = 0; k < MD5Model.numSubsets; k++)
{
for ( int i = 0; i < MD5Model.m_subsets[k].numVertices; ++i )
{
Vertex tempVert = MD5Model.m_subsets[k].m_vertices[i];
// Make sure the vertex's pos is cleared first
tempVert.x = 0;
tempVert.y = 0;
tempVert.z = 0;
// Clear vertices normal
tempVert.nx = 0;
tempVert.ny = 0;
tempVert.nz = 0;
// Sum up the joints and weights information to get vertex's position and normal
for ( int j = 0; j < tempVert.WeightCount; ++j )
{
Weight tempWeight = MD5Model.m_subsets[k].m_weights[tempVert.StartWeight + j];
Joint tempJoint = interpolatedSkeleton[tempWeight.jointID];
// Convert joint orientation and weight pos to vectors for easier computation
D3DXQUATERNION tempJointOrientation = D3DXQUATERNION(tempJoint.orientation.x, tempJoint.orientation.y, tempJoint.orientation.z, tempJoint.orientation.w);
D3DXQUATERNION tempWeightPos = D3DXQUATERNION(tempWeight.pos.x, tempWeight.pos.y, tempWeight.pos.z, 0.0f);
// We will need to use the conjugate of the joint orientation quaternion
D3DXQUATERNION tempJointOrientationConjugate;
D3DXQuaternionInverse(&tempJointOrientationConjugate, &tempJointOrientation);
// Calculate vertex position (in joint space, eg. rotate the point around (0,0,0)) for this weight using the joint orientation quaternion and its conjugate
// We can rotate a point using a quaternion with the equation "rotatedPoint = quaternion * point * quaternionConjugate"
D3DXVECTOR3 rotatedPoint;
D3DXQUATERNION qqtemp;
D3DXQuaternionMultiply(&qqtemp, &tempJointOrientation, &tempWeightPos);
D3DXQuaternionMultiply(&qqtemp, &qqtemp, &tempJointOrientationConjugate);
rotatedPoint.x = qqtemp.x;
rotatedPoint.y = qqtemp.y;
rotatedPoint.z = qqtemp.z;
// Now move the verices position from joint space (0,0,0) to the joints position in world space, taking the weights bias into account
tempVert.x += ( tempJoint.pos.x + rotatedPoint.x ) * tempWeight.bias;
tempVert.y += ( tempJoint.pos.y + rotatedPoint.y ) * tempWeight.bias;
tempVert.z += ( tempJoint.pos.z + rotatedPoint.z ) * tempWeight.bias;
// Compute the normals for this frames skeleton using the weight normals from before
// We can comput the normals the same way we compute the vertices position, only we don't have to translate them (just rotate)
D3DXQUATERNION tempWeightNormal = D3DXQUATERNION(tempWeight.normal.x, tempWeight.normal.y, tempWeight.normal.z, 0.0f);
D3DXQuaternionMultiply(&qqtemp, &tempJointOrientation, &tempWeightNormal);
D3DXQuaternionMultiply(&qqtemp, &qqtemp, &tempJointOrientationConjugate);
// Rotate the normal
rotatedPoint.x = qqtemp.x;
rotatedPoint.y = qqtemp.y;
rotatedPoint.z = qqtemp.z;
// Add to vertices normal and ake weight bias into account
tempVert.nx -= rotatedPoint.x * tempWeight.bias;
tempVert.ny -= rotatedPoint.y * tempWeight.bias;
tempVert.nz -= rotatedPoint.z * tempWeight.bias;
}
// Store the vertices position in the position vector instead of straight into the vertex vector
MD5Model.m_subsets[k].m_positions[i].x = tempVert.x;
MD5Model.m_subsets[k].m_positions[i].y = tempVert.y;
MD5Model.m_subsets[k].m_positions[i].z = tempVert.z;
// Store the vertices normal
MD5Model.m_subsets[k].m_vertices[i].nx = tempVert.nx;
MD5Model.m_subsets[k].m_vertices[i].ny = tempVert.ny;
MD5Model.m_subsets[k].m_vertices[i].nz = tempVert.nz;
// Create the temp D3DXVECTOR3 for normalize
D3DXVECTOR3 dtemp = D3DXVECTOR3(0,0,0);
dtemp.x = MD5Model.m_subsets[k].m_vertices[i].nx;
dtemp.y = MD5Model.m_subsets[k].m_vertices[i].ny;
dtemp.z = MD5Model.m_subsets[k].m_vertices[i].nz;
D3DXVec3Normalize(&dtemp, &dtemp);
MD5Model.m_subsets[k].m_vertices[i].nx = dtemp.x;
MD5Model.m_subsets[k].m_vertices[i].ny = dtemp.y;
MD5Model.m_subsets[k].m_vertices[i].nz = dtemp.z;
// Put the positions into the vertices for this subset
MD5Model.m_subsets[k].m_vertices[i].x = MD5Model.m_subsets[k].m_positions[i].x;
MD5Model.m_subsets[k].m_vertices[i].y = MD5Model.m_subsets[k].m_positions[i].y;
MD5Model.m_subsets[k].m_vertices[i].z = MD5Model.m_subsets[k].m_positions[i].z;
}
// Update the subsets vertex buffer
// First lock the buffer
void* mappedVertBuff;
bool result;
result = MD5Model.m_subsets[k].vertBuff->Map(D3D10_MAP_WRITE_DISCARD, 0, &mappedVertBuff);
if(FAILED(result))
{
return false;
}
// Copy the data into the vertex buffer.
memcpy(mappedVertBuff, &MD5Model.m_subsets[k].m_vertices[0], (sizeof(Vertex) * MD5Model.m_subsets[k].numVertices));
MD5Model.m_subsets[k].vertBuff->Unmap();
}
return true;
}
Maybe I can fix some things in that code but I wonder if I'm doing it right...
I wonder also if there are other better ways to do this, if other types of animations would be better (different things from .x extension).
Thanks and sorry for my bad english :D
Doing bones transformation at shaders would be a good solution? (like this)
Are all of the meshes in the viewing frustum at the same time? If not you should only be updating the animations of the objects which are on screen and which you can see. If you're updating all the meshes in the scene regardless of if the are in view or not you are wasting a lot of cycles. It sounds to me like you are not doing any frustum culling at all that is probably the best place to start.