Big skeletal animation update

Added MeshInfos demo
Added MD5Mesh/MD5Anim loader support
Added Node class
Fixed ResourceParams not being exported
Added support for skeletal animation
(Animation/Mesh/Joint/SkeletalMesh/Skeleton)
Meshes are now only stored with VertexStruct_XYZ_Normal_UV_Tangent type
Moved Sequence declaration to Sequence.hpp

-Animation:
Renamed Create to Create[Keyframe|Skeletal]

-AxisAlignedBox:
Added Contains method
Added GetCorner method
Added GetCube method
Added Transform method

-Cube/Rect:
Added GetPosition method
Added GetSize method
(Almost) Fixed ExtendTo method
Fixed GetCenter method

-File:
Added GetDirectory static function
Added GetPath method
Renamed GetDirectoryPath method to GetDirectory

-Math module:
Fixed constructor/methods taking a non-const array
GetNormal/Normalize methods now takes an optionnal integer pointer
(returning length)
Made all classes default constructor trivial
Inverse, MakeIdentity, MakeZero, Normalize, Set methods now returns
reference to object

-Matrix4:
Modified methods to avoid copies
Removed COW (Too much overhead)
Removed Concatenate[Affine] static function

-Mesh:
Renamed Create to Create[Keyframe|Skeletal|Static]
Renamed Skin to Material

-MeshParams:
No longer takes declaration argument
Renamed loadAnimations to animated
Storage default to BufferStorage_Hardware if supported and
BufferStorage_Software otherwise

-OpenGL:
Added glGetBooleanv function
Added glIsEnabled function

-Quaternion:
Added ComputeW method
Added Conjugate method

-Renderer:
Added IsEnabled static function
Fixed GetLineWidth function not being static
Removed SetVertexDeclaration

-RenderWindow:
Made CopyTo[Image|Texture] method constant

-Resource
Fixed RemoveResourceListener crash

-ResourceLoader:
Loaders are now used in a LIFO context

-Stream:
Renamed GetLine method to ReadLine

-String:
Fixed Simplified

-Utility module
Added configuration define for strict resource parsing

-VertexBuffer
Now takes a VertexDeclaration pointer

-VertexDeclaration
No longer throw an error when getting a non-existing element


Former-commit-id: f7358c1231d6af48b799d2f24f077a001e16785b
This commit is contained in:
Lynix
2012-11-21 17:23:50 +01:00
parent 84f73f2b6a
commit 70ef422950
99 changed files with 6270 additions and 1983 deletions

View File

@@ -7,7 +7,6 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <vector>
struct md2_header
{
@@ -51,14 +50,6 @@ struct md2_triangle
nzUInt16 texCoords[3];
};
struct md2_frame
{
NzVector3f scale;
NzVector3f translate;
char name[16];
std::vector<md2_vertex> vertices;
};
extern const nzUInt32 md2Ident;
extern const NzVector3f md2Normals[162];

View File

@@ -7,16 +7,18 @@
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Utility/KeyframeMesh.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/Loaders/MD2/Constants.hpp>
#include <Nazara/Utility/Loaders/MD2/Mesh.hpp>
#include <cstddef>
#include <cstring>
#include <memory>
#include <Nazara/Utility/Debug.hpp>
namespace
{
bool NzLoader_MD2_Check(NzInputStream& stream, const NzMeshParams& parameters)
bool Check(NzInputStream& stream, const NzMeshParams& parameters)
{
NazaraUnused(parameters);
@@ -24,7 +26,7 @@ namespace
if (stream.Read(&magic[0], 2*sizeof(nzUInt32)) != 2*sizeof(nzUInt32))
return false;
#if defined(NAZARA_BIG_ENDIAN)
#ifdef NAZARA_BIG_ENDIAN
NzByteSwap(&magic[0], sizeof(nzUInt32));
NzByteSwap(&magic[1], sizeof(nzUInt32));
#endif
@@ -32,7 +34,7 @@ namespace
return magic[0] == md2Ident && magic[1] == 8;
}
bool NzLoader_MD2_Load(NzMesh* mesh, NzInputStream& stream, const NzMeshParams& parameters)
bool Load(NzMesh* mesh, NzInputStream& stream, const NzMeshParams& parameters)
{
md2_header header;
if (stream.Read(&header, sizeof(md2_header)) != sizeof(md2_header))
@@ -41,7 +43,7 @@ namespace
return false;
}
#if defined(NAZARA_BIG_ENDIAN)
#ifdef NAZARA_BIG_ENDIAN
NzByteSwap(&header.skinwidth, sizeof(nzUInt32));
NzByteSwap(&header.skinheight, sizeof(nzUInt32));
NzByteSwap(&header.framesize, sizeof(nzUInt32));
@@ -67,16 +69,16 @@ namespace
/// Création du mesh
// Animé ou statique, c'est la question
bool animated;
unsigned int startFrame = NzClamp(parameters.animation.startFrame, 0U, static_cast<unsigned int>(header.num_frames-1));
unsigned int endFrame = NzClamp(parameters.animation.endFrame, 0U, static_cast<unsigned int>(header.num_frames-1));
if (parameters.loadAnimations && startFrame != endFrame)
animated = true;
bool animated = (parameters.animated && startFrame != endFrame);
if (animated)
mesh->CreateKeyframe();
else
animated = false;
mesh->CreateStatic();
if (!mesh->Create((animated) ? nzAnimationType_Keyframe : nzAnimationType_Static)) // Ne devrait jamais échouer
if (!mesh->IsValid()) // Ne devrait jamais échouer
{
NazaraInternalError("Failed to create mesh");
return false;
@@ -87,11 +89,12 @@ namespace
{
stream.SetCursorPos(header.offset_skins);
{
NzString baseDir = stream.GetDirectory();
char skin[68];
for (unsigned int i = 0; i < header.num_skins; ++i)
{
stream.Read(skin, 68*sizeof(char));
mesh->AddSkin(skin);
mesh->AddMaterial(baseDir + skin);
}
}
}
@@ -100,16 +103,13 @@ namespace
if (animated)
{
NzAnimation* animation = new NzAnimation;
if (animation->Create(nzAnimationType_Keyframe, endFrame-startFrame+1))
if (animation->CreateKeyframe(endFrame-startFrame+1))
{
// Décodage des séquences
NzString frameName;
///TODO: Optimiser le calcul
char last[16];
NzSequence sequence;
sequence.framePerSecond = 10; // Par défaut pour les animations MD2
char name[16], last[16];
stream.SetCursorPos(header.offset_frames + startFrame*header.framesize + offsetof(md2_frame, name));
stream.SetCursorPos(header.offset_frames + startFrame*header.framesize + 2*sizeof(NzVector3f));
stream.Read(last, 16*sizeof(char));
int pos = std::strlen(last)-1;
@@ -122,10 +122,16 @@ namespace
}
last[pos+1] = '\0';
unsigned int numFrames = 0;
NzSequence sequence;
sequence.firstFrame = startFrame;
sequence.frameCount = 0;
sequence.frameRate = 10; // Par défaut pour les animations MD2
sequence.name = last;
char name[16];
for (unsigned int i = startFrame; i <= endFrame; ++i)
{
stream.SetCursorPos(header.offset_frames + i*header.framesize + offsetof(md2_frame, name));
stream.SetCursorPos(header.offset_frames + i*header.framesize + 2*sizeof(NzVector3f));
stream.Read(name, 16*sizeof(char));
pos = std::strlen(name)-1;
@@ -140,24 +146,20 @@ namespace
if (std::strcmp(name, last) != 0) // Si les deux frames n'ont pas le même nom
{
// Alors on enregistre la séquence
sequence.firstFrame = i-numFrames;
sequence.lastFrame = i-1;
sequence.name = last;
animation->AddSequence(sequence);
std::strcpy(last, name);
numFrames = 0;
// Alors on enregistre la séquence actuelle
animation->AddSequence(sequence);
// Et on initialise la séquence suivante
sequence.firstFrame = i;
sequence.frameCount = 0;
sequence.name = last;
}
numFrames++;
sequence.frameCount++;
}
// On ajoute la dernière frame (Qui n'a pas été traitée par la boucle)
sequence.firstFrame = endFrame-numFrames;
sequence.lastFrame = endFrame;
sequence.name = last;
animation->AddSequence(sequence);
mesh->SetAnimation(animation);
@@ -169,15 +171,118 @@ namespace
/// Chargement des submesh
// Actuellement le loader ne charge qu'un submesh
// TODO: Utiliser les commandes OpenGL pour accélérer le rendu
NzMD2Mesh* subMesh = new NzMD2Mesh(mesh);
if (!subMesh->Create(header, stream, parameters))
// TODO: Utiliser les commandes OpenGL pour créer des indices et accélérer le rendu
unsigned int frameCount = endFrame - startFrame + 1;
unsigned int vertexCount = header.num_tris * 3;
std::unique_ptr<NzVertexBuffer> vertexBuffer(new NzVertexBuffer(NzMesh::GetDeclaration(), vertexCount, parameters.storage, nzBufferUsage_Dynamic));
std::unique_ptr<NzKeyframeMesh> subMesh(new NzKeyframeMesh(mesh));
if (!subMesh->Create(vertexBuffer.get(), frameCount))
{
NazaraError("Failed to create MD2 mesh");
NazaraError("Failed to create SubMesh");
return false;
}
mesh->AddSubMesh(subMesh);
vertexBuffer->SetPersistent(false);
vertexBuffer.release();
/// Lecture des triangles
std::vector<md2_triangle> triangles(header.num_tris);
stream.SetCursorPos(header.offset_tris);
stream.Read(&triangles[0], header.num_tris*sizeof(md2_triangle));
#ifdef NAZARA_BIG_ENDIAN
for (unsigned int i = 0; i < header.num_tris; ++i)
{
NzByteSwap(&triangles[i].vertices[0], sizeof(nzUInt16));
NzByteSwap(&triangles[i].texCoords[0], sizeof(nzUInt16));
NzByteSwap(&triangles[i].vertices[1], sizeof(nzUInt16));
NzByteSwap(&triangles[i].texCoords[1], sizeof(nzUInt16));
NzByteSwap(&triangles[i].vertices[2], sizeof(nzUInt16));
NzByteSwap(&triangles[i].texCoords[2], sizeof(nzUInt16));
}
#endif
/// Lecture des coordonnées de texture
std::vector<md2_texCoord> texCoords(header.num_st);
// Lecture des coordonnées de texture
stream.SetCursorPos(header.offset_st);
stream.Read(&texCoords[0], header.num_st*sizeof(md2_texCoord));
#ifdef NAZARA_BIG_ENDIAN
for (unsigned int i = 0; i < header.num_st; ++i)
{
NzByteSwap(&texCoords[i].u, sizeof(nzInt16));
NzByteSwap(&texCoords[i].v, sizeof(nzInt16));
}
#endif
/// Chargement des frames
stream.SetCursorPos(header.offset_frames + header.framesize*startFrame);
// Pour que le modèle soit correctement aligné, on génère un quaternion que nous appliquerons à chacune des vertices
NzQuaternionf rotationQuat = NzEulerAnglesf(-90.f, 90.f, 0.f);
md2_vertex* vertices = new md2_vertex[header.num_vertices];
for (unsigned int f = 0; f < frameCount; ++f)
{
NzVector3f scale, translate;
stream.Read(scale, sizeof(NzVector3f));
stream.Read(translate, sizeof(NzVector3f));
stream.Read(nullptr, 16*sizeof(char));
stream.Read(vertices, header.num_vertices*sizeof(md2_vertex));
#ifdef NAZARA_BIG_ENDIAN
NzByteSwap(&scale.x, sizeof(float));
NzByteSwap(&scale.y, sizeof(float));
NzByteSwap(&scale.z, sizeof(float));
NzByteSwap(&translate.x, sizeof(float));
NzByteSwap(&translate.y, sizeof(float));
NzByteSwap(&translate.z, sizeof(float));
#endif
NzAxisAlignedBox aabb;
for (unsigned int t = 0; t < header.num_tris; ++t)
{
for (unsigned int v = 0; v < 3; ++v)
{
const md2_vertex& vert = vertices[triangles[t].vertices[v]];
NzVector3f position = rotationQuat * NzVector3f(vert.x * scale.x + translate.x, vert.y * scale.y + translate.y, vert.z * scale.z + translate.z);
// On fait en sorte d'étendre l'AABB pour qu'il contienne ce sommet
aabb.ExtendTo(position);
// Et on finit par copier les éléments dans le buffer
NzMeshVertex vertex;
vertex.normal = md2Normals[vert.n];
vertex.position = position;
// On ne définit les coordonnées de texture que pour la première frame
bool firstFrame = (f == 0);
if (firstFrame)
{
const md2_texCoord& texC = texCoords[triangles[t].texCoords[v]];
vertex.uv.Set(texC.u / static_cast<float>(header.skinwidth), 1.f - texC.v / static_cast<float>(header.skinheight));
}
subMesh->SetVertex(vertex, f, vertexCount - (t*3 + v) - 1, firstFrame);
}
}
subMesh->SetAABB(f, aabb);
}
delete[] vertices;
subMesh->Unlock();
subMesh->SetMaterialIndex(0);
mesh->AddSubMesh(subMesh.release());
return true;
}
@@ -185,14 +290,10 @@ namespace
void NzLoaders_MD2_Register()
{
NzMD2Mesh::Initialize();
NzMeshLoader::RegisterLoader("md2", NzLoader_MD2_Check, NzLoader_MD2_Load);
NzMeshLoader::RegisterLoader("md2", Check, Load);
}
void NzLoaders_MD2_Unregister()
{
NzMeshLoader::UnregisterLoader("md2", NzLoader_MD2_Check, NzLoader_MD2_Load);
NzMD2Mesh::Uninitialize();
NzMeshLoader::UnregisterLoader("md2", Check, Load);
}

View File

@@ -1,292 +0,0 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Loaders/MD2/Mesh.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Utility/IndexBuffer.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/VertexBuffer.hpp>
#include <Nazara/Utility/Debug.hpp>
NzMD2Mesh::NzMD2Mesh(const NzMesh* parent) :
NzKeyframeMesh(parent),
m_frames(nullptr),
m_indexBuffer(nullptr),
m_vertexBuffer(nullptr)
{
}
NzMD2Mesh::~NzMD2Mesh()
{
Destroy();
}
bool NzMD2Mesh::Create(const md2_header& header, NzInputStream& stream, const NzMeshParams& parameters)
{
Destroy();
unsigned int startFrame = NzClamp(parameters.animation.startFrame, 0U, static_cast<unsigned int>(header.num_frames-1));
unsigned int endFrame = NzClamp(parameters.animation.endFrame, 0U, static_cast<unsigned int>(header.num_frames-1));
m_frameCount = endFrame - startFrame + 1;
m_vertexCount = header.num_tris * 3;
/// Chargement des vertices
std::vector<md2_texCoord> texCoords(header.num_st);
std::vector<md2_triangle> triangles(header.num_tris);
// Lecture des coordonnées de texture
stream.SetCursorPos(header.offset_st);
stream.Read(&texCoords[0], header.num_st*sizeof(md2_texCoord));
#if defined(NAZARA_BIG_ENDIAN)
for (unsigned int i = 0; i < header.num_st; ++i)
{
NzByteSwap(&texCoords[i].u, sizeof(nzInt16));
NzByteSwap(&texCoords[i].v, sizeof(nzInt16));
}
#endif
stream.SetCursorPos(header.offset_tris);
stream.Read(&triangles[0], header.num_tris*sizeof(md2_triangle));
#if defined(NAZARA_BIG_ENDIAN)
for (unsigned int i = 0; i < header.num_tris; ++i)
{
NzByteSwap(&triangles[i].vertices[0], sizeof(nzUInt16));
NzByteSwap(&texCoords[i].texCoords[0], sizeof(nzUInt16));
NzByteSwap(&triangles[i].vertices[1], sizeof(nzUInt16));
NzByteSwap(&texCoords[i].texCoords[1], sizeof(nzUInt16));
NzByteSwap(&triangles[i].vertices[2], sizeof(nzUInt16));
NzByteSwap(&texCoords[i].texCoords[2], sizeof(nzUInt16));
}
#endif
stream.SetCursorPos(header.offset_frames + header.framesize*startFrame);
md2_frame frame;
frame.vertices.resize(header.num_vertices);
// Pour que le modèle soit correctement aligné, on génère un quaternion que nous appliquerons à chacune des vertices
NzQuaternionf rotationQuat = NzEulerAnglesf(-90.f, 90.f, 0.f);
//NzMatrix4f rotationMatrix = NzMatrix4f::Rotate(NzEulerAnglesf(-90.f, -90.f, 0.f));
unsigned int stride = s_declaration.GetStride(nzElementStream_VertexData);
m_frames = new Frame[m_frameCount];
for (unsigned int i = 0; i < m_frameCount; ++i)
{
stream.Read(&frame.scale, sizeof(NzVector3f));
stream.Read(&frame.translate, sizeof(NzVector3f));
stream.Read(&frame.name, 16*sizeof(char));
stream.Read(&frame.vertices[0], header.num_vertices*sizeof(md2_vertex));
#if defined(NAZARA_BIG_ENDIAN)
NzByteSwap(&frame.scale.x, sizeof(float));
NzByteSwap(&frame.scale.y, sizeof(float));
NzByteSwap(&frame.scale.z, sizeof(float));
NzByteSwap(&frame.translate.x, sizeof(float));
NzByteSwap(&frame.translate.y, sizeof(float));
NzByteSwap(&frame.translate.z, sizeof(float));
#endif
m_frames[i].normal = new nzUInt8[m_vertexCount]; // Nous stockons l'indice MD2 de la normale plutôt que la normale (gain d'espace)
m_frames[i].vertices = new NzVector3f[m_vertexCount];
NzVector3f max, min;
for (unsigned int t = 0; t < header.num_tris; ++t)
{
for (unsigned int v = 0; v < 3; ++v)
{
const md2_vertex& vert = frame.vertices[triangles[t].vertices[v]];
NzVector3f vertex = rotationQuat * NzVector3f(vert.x * frame.scale.x + frame.translate.x, vert.y * frame.scale.y + frame.translate.y, vert.z * frame.scale.z + frame.translate.z);
// On fait en sorte d'avoir deux vertices de délimitation, définissant un rectangle dans l'espace
max.Maximize(vertex);
min.Minimize(vertex);
// Le MD2 ne définit pas ses vertices dans le bon ordre, il nous faut donc les ajouter dans l'ordre inverse
unsigned int index = m_vertexCount - (t*3 + v) - 1;
m_frames[i].normal[index] = vert.n;
m_frames[i].vertices[index] = vertex;
}
}
m_frames[i].aabb.SetExtends(min, max);
}
m_indexBuffer = nullptr; // Pas d'indexbuffer pour l'instant
m_vertexBuffer = new NzVertexBuffer(m_vertexCount, (3+3+2)*sizeof(float), parameters.storage, nzBufferUsage_Dynamic);
nzUInt8* ptr = reinterpret_cast<nzUInt8*>(m_vertexBuffer->Map(nzBufferAccess_WriteOnly));
if (!ptr)
{
NazaraError("Failed to map vertex buffer");
Destroy();
return false;
}
// On avance jusqu'aux dernières coordonnées de texture et on les définit dans l'ordre inverse
ptr += s_declaration.GetElement(nzElementStream_VertexData, nzElementUsage_TexCoord)->offset + stride * (m_vertexCount-1);
for (unsigned int t = 0; t < header.num_tris; ++t)
{
for (unsigned int v = 0; v < 3; ++v)
{
const md2_texCoord& texC = texCoords[triangles[t].texCoords[v]];
NzVector2f* coords = reinterpret_cast<NzVector2f*>(ptr);
coords->x = texC.u / static_cast<float>(header.skinwidth);
coords->y = 1.f - texC.v / static_cast<float>(header.skinheight);
ptr -= stride;
}
}
if (!m_vertexBuffer->Unmap())
{
NazaraError("Failed to unmap buffer");
Destroy();
return false;
}
m_vertexBuffer->AddResourceReference();
m_vertexBuffer->SetPersistent(false);
AnimateImpl(0, 0, 0.f);
return true;
}
void NzMD2Mesh::Destroy()
{
if (m_frames)
{
for (unsigned int i = 0; i < m_frameCount; ++i)
{
delete[] m_frames[i].normal;
delete[] m_frames[i].vertices;
}
delete[] m_frames;
m_frames = nullptr;
}
if (m_indexBuffer)
{
m_indexBuffer->RemoveResourceReference();
m_indexBuffer = nullptr;
}
if (m_vertexBuffer)
{
m_vertexBuffer->RemoveResourceReference();
m_vertexBuffer = nullptr;
}
}
const NzAxisAlignedBox& NzMD2Mesh::GetAABB() const
{
return m_aabb;
}
nzAnimationType NzMD2Mesh::GetAnimationType() const
{
if (m_frameCount > 1)
return nzAnimationType_Keyframe;
else
return nzAnimationType_Static;
}
unsigned int NzMD2Mesh::GetFrameCount() const
{
return m_frameCount;
}
const NzIndexBuffer* NzMD2Mesh::GetIndexBuffer() const
{
return nullptr;
//return m_indexBuffer;
}
nzPrimitiveType NzMD2Mesh::GetPrimitiveType() const
{
return nzPrimitiveType_TriangleList;
}
const NzVertexBuffer* NzMD2Mesh::GetVertexBuffer() const
{
return m_vertexBuffer;
}
const NzVertexDeclaration* NzMD2Mesh::GetVertexDeclaration() const
{
return &s_declaration;
}
void NzMD2Mesh::Initialize()
{
NzVertexElement elements[3];
elements[0].offset = 0;
elements[0].type = nzElementType_Float3;
elements[0].usage = nzElementUsage_Position;
elements[1].offset = 3*sizeof(float);
elements[1].type = nzElementType_Float3;
elements[1].usage = nzElementUsage_Normal;
elements[2].offset = 3*sizeof(float) + 3*sizeof(float);
elements[2].type = nzElementType_Float2;
elements[2].usage = nzElementUsage_TexCoord;
s_declaration.Create(elements, 3);
}
void NzMD2Mesh::Uninitialize()
{
s_declaration.Destroy();
}
void NzMD2Mesh::AnimateImpl(unsigned int frameA, unsigned int frameB, float interpolation)
{
nzUInt8* ptr = reinterpret_cast<nzUInt8*>(m_vertexBuffer->Map(nzBufferAccess_WriteOnly));
if (!ptr)
{
NazaraError("Failed to map vertex buffer");
return;
}
unsigned int stride = s_declaration.GetStride(nzElementStream_VertexData);
unsigned int positionOffset = s_declaration.GetElement(nzElementStream_VertexData, nzElementUsage_Position)->offset;
unsigned int normalOffset = s_declaration.GetElement(nzElementStream_VertexData, nzElementUsage_Normal)->offset;
Frame* fA = &m_frames[frameA];
Frame* fB = &m_frames[frameB];
for (unsigned int i = 0; i < m_vertexCount; ++i)
{
NzVector3f* position = reinterpret_cast<NzVector3f*>(ptr + positionOffset);
NzVector3f* normal = reinterpret_cast<NzVector3f*>(ptr + normalOffset);
*position = fA->vertices[i] + interpolation * (fB->vertices[i] - fA->vertices[i]);
*normal = md2Normals[fA->normal[i]] + interpolation * (md2Normals[fB->normal[i]] - md2Normals[fA->normal[i]]);
ptr += stride;
}
if (!m_vertexBuffer->Unmap())
NazaraWarning("Failed to unmap vertex buffer, expect mesh corruption");
// Interpolation de l'AABB
NzVector3f max1 = fA->aabb.GetMaximum();
NzVector3f min1 = fA->aabb.GetMinimum();
m_aabb.SetExtends(min1 + interpolation * (fB->aabb.GetMinimum() - min1), max1 + interpolation * (fB->aabb.GetMaximum() - max1));
}
NzVertexDeclaration NzMD2Mesh::s_declaration;

View File

@@ -1,65 +0,0 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_LOADERS_MD2_MESH_HPP
#define NAZARA_LOADERS_MD2_MESH_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Utility/KeyframeMesh.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utility/Loaders/MD2/Constants.hpp>
class NzIndexBuffer;
class NzInputStream;
class NzVertexBuffer;
struct NzMeshParams;
class NAZARA_API NzMD2Mesh : public NzKeyframeMesh
{
public:
NzMD2Mesh(const NzMesh* parent);
~NzMD2Mesh();
bool Create(const md2_header& header, NzInputStream& stream, const NzMeshParams& parameters);
void Destroy();
const NzAxisAlignedBox& GetAABB() const;
nzAnimationType GetAnimationType() const;
unsigned int GetFrameCount() const;
const NzIndexBuffer* GetIndexBuffer() const;
nzPrimitiveType GetPrimitiveType() const;
const NzVertexBuffer* GetVertexBuffer() const;
const NzVertexDeclaration* GetVertexDeclaration() const;
bool IsAnimated() const;
static void Initialize();
static void Uninitialize();
private:
void AnimateImpl(unsigned int frameA, unsigned int frameB, float interpolation);
struct Frame
{
NzAxisAlignedBox aabb;
nzUInt8* normal;
NzVector3f* tangents;
NzVector3f* vertices;
char name[16];
};
NzAxisAlignedBox m_aabb;
Frame* m_frames;
NzIndexBuffer* m_indexBuffer;
NzVertexBuffer* m_vertexBuffer;
unsigned int m_frameCount;
unsigned int m_vertexCount;
static NzVertexDeclaration s_declaration;
};
#endif // NAZARA_LOADERS_MD2_MESH_HPP

View File

@@ -0,0 +1,15 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_LOADERS_MD5ANIM_HPP
#define NAZARA_LOADERS_MD5ANIM_HPP
#include <Nazara/Prerequesites.hpp>
void NzLoaders_MD5Anim_Register();
void NzLoaders_MD5Anim_Unregister();
#endif // NAZARA_LOADERS_MD5ANIM_HPP

View File

@@ -0,0 +1,32 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Loaders/MD5Anim.hpp>
#include <Nazara/Utility/Loaders/MD5Anim/Parser.hpp>
#include <Nazara/Utility/Debug.hpp>
namespace
{
bool Check(NzInputStream& stream, const NzAnimationParams& parameters)
{
NzMD5AnimParser parser(stream, parameters);
return parser.Check();
}
bool Load(NzAnimation* animation, NzInputStream& stream, const NzAnimationParams& parameters)
{
NzMD5AnimParser parser(stream, parameters);
return parser.Parse(animation);
}
}
void NzLoaders_MD5Anim_Register()
{
NzAnimationLoader::RegisterLoader("md5anim", Check, Load);
}
void NzLoaders_MD5Anim_Unregister()
{
NzAnimationLoader::UnregisterLoader("md5anim", Check, Load);
}

View File

@@ -0,0 +1,529 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Loaders/MD5Anim/Parser.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/SkeletalMesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <cstdio>
#include <cstring>
#include <limits>
#include <Nazara/Utility/Debug.hpp>
NzMD5AnimParser::NzMD5AnimParser(NzInputStream& stream, const NzAnimationParams& parameters) :
m_stream(stream),
m_parameters(parameters),
m_keepLastLine(false),
m_frameIndex(0),
m_frameRate(0),
m_lineCount(0),
m_streamFlags(stream.GetStreamOptions())
{
if ((m_streamFlags & nzStreamOption_Text) == 0)
m_stream.SetStreamOptions(m_streamFlags | nzStreamOption_Text);
}
NzMD5AnimParser::~NzMD5AnimParser()
{
if ((m_streamFlags & nzStreamOption_Text) == 0)
m_stream.SetStreamOptions(m_streamFlags);
}
bool NzMD5AnimParser::Check()
{
if (!Advance(false))
return false;
unsigned int version;
if (std::sscanf(&m_currentLine[0], " MD5Version %u", &version) != 1)
return false;
return version == 10;
}
bool NzMD5AnimParser::Parse(NzAnimation* animation)
{
while (Advance(false))
{
switch (m_currentLine[0])
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
case 'M': // MD5Version
if (m_currentLine.GetWord(0) != "MD5Version")
UnrecognizedLine();
break;
#endif
case 'b': // baseframe/bounds
if (m_currentLine.StartsWith("baseframe {"))
{
if (!ParseBaseframe())
{
Error("Failed to parse baseframe");
return false;
}
}
else if (m_currentLine.StartsWith("bounds {"))
{
if (!ParseBounds())
{
Error("Failed to parse bounds");
return false;
}
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
break;
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
case 'c': // commandline
if (m_currentLine.GetWord(0) != "commandline")
UnrecognizedLine();
break;
#endif
case 'f':
{
unsigned int index;
if (std::sscanf(&m_currentLine[0], "frame %u {", &index) == 1)
{
if (m_frameIndex != index)
{
Error("Unexpected frame index (expected " + NzString::Number(m_frameIndex) + ", got " + NzString::Number(index) + ')');
return false;
}
if (!ParseFrame())
{
Error("Failed to parse frame");
return false;
}
m_frameIndex++;
}
else if (std::sscanf(&m_currentLine[0], "frameRate %u", &m_frameRate) != 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
UnrecognizedLine();
#endif
}
break;
}
case 'h': // hierarchy
if (m_currentLine.StartsWith("hierarchy {"))
{
if (!ParseHierarchy())
{
Error("Failed to parse hierarchy");
return false;
}
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
break;
case 'n': // num[Frames/Joints]
{
unsigned int count;
if (std::sscanf(&m_currentLine[0], "numAnimatedComponents %u", &count) == 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_animatedComponents.empty())
Warning("Animated components count is already defined");
#endif
m_animatedComponents.resize(count);
}
else if (std::sscanf(&m_currentLine[0], "numFrames %u", &count) == 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_frames.empty())
Warning("Frame count is already defined");
#endif
m_frames.resize(count);
}
else if (std::sscanf(&m_currentLine[0], "numJoints %u", &count) == 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_joints.empty())
Warning("Joint count is already defined");
#endif
m_joints.resize(count);
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
break;
}
default:
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
UnrecognizedLine();
#endif
break;
}
}
unsigned int frameCount = m_frames.size();
if (frameCount == 0)
{
NazaraError("Frame count is invalid or missing");
return false;
}
unsigned int jointCount = m_joints.size();
if (jointCount == 0)
{
NazaraError("Joint count is invalid or missing");
return false;
}
if (m_frameIndex != frameCount)
{
NazaraError("Missing frame infos: [" + NzString::Number(m_frameIndex) + ',' + NzString::Number(frameCount) + ']');
return false;
}
if (m_frameRate == 0)
{
NazaraWarning("Framerate is either invalid or missing, assuming a default value of 24");
m_frameRate = 24;
}
// À ce stade, nous sommes censés avoir assez d'informations pour créer l'animation
if (!animation->CreateSkeletal(frameCount, jointCount))
{
NazaraError("Failed to create animation");
return false;
}
NzSequence sequence;
sequence.firstFrame = 0;
sequence.frameCount = m_frames.size();
sequence.frameRate = m_frameRate;
sequence.name = m_stream.GetPath().SubstrFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true);
if (!animation->AddSequence(sequence))
NazaraWarning("Failed to add sequence");
NzSequenceJoint* sequenceJoints = animation->GetSequenceJoints();
// Pour que le squelette soit correctement aligné, il faut appliquer un quaternion "de correction" aux joints à la base du squelette
NzQuaternionf rotationQuat = NzEulerAnglesf(-90.f, 90.f, 0.f);
for (unsigned int i = 0; i < jointCount; ++i)
{
int parent = m_joints[i].parent;
for (unsigned int j = 0; j < frameCount; ++j)
{
NzSequenceJoint& sequenceJoint = sequenceJoints[j*jointCount + i];
if (parent >= 0)
sequenceJoint.rotation = m_frames[j].joints[i].orient;
else
sequenceJoint.rotation = rotationQuat * m_frames[j].joints[i].orient;
sequenceJoint.scale = NzVector3f(1.f, 1.f, 1.f);
if (parent >= 0)
sequenceJoint.translation = m_frames[j].joints[i].pos;
else
sequenceJoint.translation = rotationQuat * m_frames[j].joints[i].pos;
}
}
return true;
}
bool NzMD5AnimParser::Advance(bool required)
{
if (!m_keepLastLine)
{
do
{
if (m_stream.EndOfStream())
{
if (required)
Error("Incomplete MD5 file");
return false;
}
m_lineCount++;
m_currentLine = m_stream.ReadLine();
m_currentLine = m_currentLine.SubstrTo("//"); // On ignore les commentaires
m_currentLine.Simplify(); // Pour un traitement plus simple
}
while (m_currentLine.IsEmpty());
}
else
m_keepLastLine = false;
return true;
}
void NzMD5AnimParser::Error(const NzString& message)
{
NazaraError(message + " at line #" + NzString::Number(m_lineCount));
}
bool NzMD5AnimParser::ParseBaseframe()
{
unsigned int jointCount = m_joints.size();
if (jointCount == 0)
{
Error("Joint count is invalid or missing");
return false;
}
for (unsigned int i = 0; i < jointCount; ++i)
{
if (!Advance())
return false;
if (std::sscanf(&m_currentLine[0], "( %f %f %f ) ( %f %f %f )", &m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z,
&m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 6)
{
UnrecognizedLine(true);
return false;
}
}
if (!Advance())
return false;
if (m_currentLine != '}')
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("Bounds braces closing not found");
#endif
// On tente de survivre à l'erreur
m_keepLastLine = true;
}
return true;
}
bool NzMD5AnimParser::ParseBounds()
{
unsigned int frameCount = m_frames.size();
if (frameCount == 0)
{
Error("Frame count is invalid or missing");
return false;
}
for (unsigned int i = 0; i < frameCount; ++i)
{
if (!Advance())
return false;
NzVector3f min, max;
if (std::sscanf(&m_currentLine[0], "( %f %f %f ) ( %f %f %f )", &min.x, &min.y, &min.z, &max.x, &max.y, &max.z) != 6)
{
UnrecognizedLine(true);
return false;
}
m_frames[i].aabb.SetExtends(min, max);
}
if (!Advance())
return false;
if (m_currentLine != '}')
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("Bounds braces closing not found");
#endif
// On tente de survivre à l'erreur
m_keepLastLine = true;
}
return true;
}
bool NzMD5AnimParser::ParseFrame()
{
unsigned int animatedComponentsCount = m_animatedComponents.size();
if (animatedComponentsCount == 0)
{
Error("Animated components count is missing or invalid");
return false;
}
unsigned int jointCount = m_joints.size();
if (jointCount == 0)
{
Error("Joint count is invalid or missing");
return false;
}
NzString line;
unsigned int count = 0;
do
{
if (!Advance())
return false;
unsigned int index = 0;
unsigned int size = m_currentLine.GetSize();
do
{
float f;
int read;
if (std::sscanf(&m_currentLine[index], "%f%n", &f, &read) != 1)
{
UnrecognizedLine(true);
return false;
}
index += read;
m_animatedComponents[count] = f;
count++;
}
while (index < size);
}
while (count < animatedComponentsCount);
m_frames[m_frameIndex].joints.resize(jointCount);
for (unsigned int i = 0; i < jointCount; ++i)
{
NzQuaternionf jointOrient = m_joints[i].bindOrient;
NzVector3f jointPos = m_joints[i].bindPos;
unsigned int j = 0;
if (m_joints[i].flags & 1) // Px
jointPos.x = m_animatedComponents[m_joints[i].index + j++];
if (m_joints[i].flags & 2) // Py
jointPos.y = m_animatedComponents[m_joints[i].index + j++];
if (m_joints[i].flags & 4) // Pz
jointPos.z = m_animatedComponents[m_joints[i].index + j++];
if (m_joints[i].flags & 8) // Qx
jointOrient.x = m_animatedComponents[m_joints[i].index + j++];
if (m_joints[i].flags & 16) // Qy
jointOrient.y = m_animatedComponents[m_joints[i].index + j++];
if (m_joints[i].flags & 32) // Qz
jointOrient.z = m_animatedComponents[m_joints[i].index + j++];
jointOrient.ComputeW();
m_frames[m_frameIndex].joints[i].orient = jointOrient;
m_frames[m_frameIndex].joints[i].pos = jointPos;
}
if (!Advance(false))
return true;
if (m_currentLine != '}')
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("Hierarchy braces closing not found");
#endif
// On tente de survivre à l'erreur
m_keepLastLine = true;
}
return true;
}
bool NzMD5AnimParser::ParseHierarchy()
{
unsigned int jointCount = m_joints.size();
if (jointCount == 0)
{
Error("Joint count is invalid or missing");
return false;
}
for (unsigned int i = 0; i < jointCount; ++i)
{
if (!Advance())
return false;
unsigned int pos = m_currentLine.Find(' ');
if (pos == NzString::npos)
{
UnrecognizedLine(true);
return false;
}
if (pos >= 64)
{
NazaraError("Joint name is too long (>= 64 characters)");
return false;
}
char name[64];
if (std::sscanf(&m_currentLine[0], "%s %d %u %u", &name[0], &m_joints[i].parent, &m_joints[i].flags, &m_joints[i].index) != 4)
{
UnrecognizedLine(true);
return false;
}
m_joints[i].name = name;
m_joints[i].name.Trim('"');
int parent = m_joints[i].parent;
if (parent >= 0)
{
if (static_cast<unsigned int>(parent) >= jointCount)
{
Error("Joint's parent is out of bounds (" + NzString::Number(parent) + " >= " + NzString::Number(jointCount) + ')');
return false;
}
}
}
if (!Advance())
return false;
if (m_currentLine != '}')
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("Hierarchy braces closing not found");
#endif
// On tente de survivre à l'erreur
m_keepLastLine = true;
}
return true;
}
void NzMD5AnimParser::Warning(const NzString& message)
{
NazaraWarning(message + " at line #" + NzString::Number(m_lineCount));
}
void NzMD5AnimParser::UnrecognizedLine(bool error)
{
NzString message = "Unrecognized \"" + m_currentLine + '"';
if (error)
Error(message);
else
Warning(message);
}

View File

@@ -0,0 +1,72 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_LOADERS_MD5ANIM_PARSER_HPP
#define NAZARA_LOADERS_MD5ANIM_PARSER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Utility/Animation.hpp>
#include <Nazara/Utility/AxisAlignedBox.hpp>
#include <vector>
class NzMD5AnimParser
{
public:
NzMD5AnimParser(NzInputStream& stream, const NzAnimationParams& parameters);
~NzMD5AnimParser();
bool Check();
bool Parse(NzAnimation* animation);
private:
struct Frame
{
struct Joint
{
NzQuaternionf orient;
NzVector3f pos;
};
std::vector<Joint> joints;
NzAxisAlignedBox aabb;
};
struct Joint
{
NzQuaternionf bindOrient;
NzString name;
NzVector3f bindPos;
int parent;
unsigned int flags;
unsigned int index;
};
bool Advance(bool required = true);
void Error(const NzString& message);
bool ParseBaseframe();
bool ParseBounds();
bool ParseFrame();
bool ParseHierarchy();
void Warning(const NzString& message);
void UnrecognizedLine(bool error = false);
std::vector<float> m_animatedComponents;
std::vector<Frame> m_frames;
std::vector<Joint> m_joints;
NzInputStream& m_stream;
NzString m_currentLine;
const NzAnimationParams& m_parameters;
bool m_keepLastLine;
unsigned int m_frameIndex;
unsigned int m_frameRate;
unsigned int m_lineCount;
unsigned int m_streamFlags;
};
#endif // NAZARA_LOADERS_MD5ANIM_PARSER_HPP

View File

@@ -0,0 +1,15 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_LOADERS_MD5MESH_HPP
#define NAZARA_LOADERS_MD5MESH_HPP
#include <Nazara/Prerequesites.hpp>
void NzLoaders_MD5Mesh_Register();
void NzLoaders_MD5Mesh_Unregister();
#endif // NAZARA_LOADERS_MD5MESH_HPP

View File

@@ -0,0 +1,32 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Loaders/MD5Mesh.hpp>
#include <Nazara/Utility/Loaders/MD5Mesh/Parser.hpp>
#include <Nazara/Utility/Debug.hpp>
namespace
{
bool Check(NzInputStream& stream, const NzMeshParams& parameters)
{
NzMD5MeshParser parser(stream, parameters);
return parser.Check();
}
bool Load(NzMesh* mesh, NzInputStream& stream, const NzMeshParams& parameters)
{
NzMD5MeshParser parser(stream, parameters);
return parser.Parse(mesh);
}
}
void NzLoaders_MD5Mesh_Register()
{
NzMeshLoader::RegisterLoader("md5mesh", Check, Load);
}
void NzLoaders_MD5Mesh_Unregister()
{
NzMeshLoader::UnregisterLoader("md5mesh", Check, Load);
}

View File

@@ -0,0 +1,756 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Loaders/MD5Mesh/Parser.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/SkeletalMesh.hpp>
#include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <cstdio>
#include <cstring>
#include <limits>
#include <memory>
#include <Nazara/Utility/Debug.hpp>
NzMD5MeshParser::NzMD5MeshParser(NzInputStream& stream, const NzMeshParams& parameters) :
m_stream(stream),
m_parameters(parameters),
m_keepLastLine(false),
m_lineCount(0),
m_meshIndex(0),
m_streamFlags(stream.GetStreamOptions())
{
if ((m_streamFlags & nzStreamOption_Text) == 0)
m_stream.SetStreamOptions(m_streamFlags | nzStreamOption_Text);
}
NzMD5MeshParser::~NzMD5MeshParser()
{
if ((m_streamFlags & nzStreamOption_Text) == 0)
m_stream.SetStreamOptions(m_streamFlags);
}
bool NzMD5MeshParser::Check()
{
if (!Advance(false))
return false;
unsigned int version;
if (std::sscanf(&m_currentLine[0], "MD5Version %u", &version) != 1)
return false;
return version == 10;
}
bool NzMD5MeshParser::Parse(NzMesh* mesh)
{
while (Advance(false))
{
switch (m_currentLine[0])
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
case 'M': // MD5Version
if (m_currentLine.GetWord(0) != "MD5Version")
UnrecognizedLine();
break;
case 'c': // commandline
if (m_currentLine.GetWord(0) != "commandline")
UnrecognizedLine();
break;
#endif
case 'j': // joints
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_currentLine.StartsWith("joints {"))
{
UnrecognizedLine();
break;
}
#endif
if (!ParseJoints())
{
Error("Failed to parse joints");
return false;
}
break;
case 'm': // mesh
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (m_currentLine != "mesh {")
{
UnrecognizedLine();
break;
}
#endif
if (m_meshIndex >= m_meshes.size())
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("More meshes than registred");
#endif
m_meshes.push_back(Mesh());
}
if (!ParseMesh())
{
NazaraError("Failed to parse mesh");
return false;
}
m_meshIndex++;
break;
}
case 'n': // num[Frames/Joints]
{
unsigned int count;
if (std::sscanf(&m_currentLine[0], "numJoints %u", &count) == 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_joints.empty())
Warning("Joint count is already defined");
#endif
m_joints.resize(count);
}
else if (std::sscanf(&m_currentLine[0], "numMeshes %u", &count) == 1)
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_meshes.empty())
Warning("Mesh count is already defined");
#endif
m_meshes.resize(count);
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
break;
}
default:
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
UnrecognizedLine();
#endif
break;
}
}
// Pour que le squelette soit correctement aligné, il faut appliquer un quaternion "de correction" aux joints à la base du squelette
NzQuaternionf rotationQuat = NzEulerAnglesf(-90.f, 180.f, 0.f);
NzString baseDir = m_stream.GetDirectory();
if (m_parameters.animated)
{
if (!mesh->CreateSkeletal(m_joints.size())) // Ne devrait jamais échouer
{
NazaraInternalError("Failed to create mesh");
return false;
}
NzSkeleton* skeleton = mesh->GetSkeleton();
for (unsigned int i = 0; i < m_joints.size(); ++i)
{
NzJoint* joint = skeleton->GetJoint(i);
int parent = m_joints[i].parent;
if (parent >= 0)
joint->SetParent(skeleton->GetJoint(parent));
joint->SetName(m_joints[i].name);
NzMatrix4f bindMatrix;
bindMatrix.MakeRotation((parent >= 0) ? m_joints[i].bindOrient : rotationQuat * m_joints[i].bindOrient);
bindMatrix.SetTranslation(m_joints[i].bindPos); // Plus rapide que de multiplier par une matrice de translation
joint->SetInverseBindMatrix(bindMatrix.InverseAffine());
}
for (const Mesh& md5Mesh : m_meshes)
{
void* ptr;
unsigned int indexCount = md5Mesh.triangles.size()*3;
unsigned int vertexCount = md5Mesh.vertices.size();
unsigned int weightCount = md5Mesh.weights.size();
// Index buffer
nzUInt8 indexSize;
if (vertexCount > std::numeric_limits<nzUInt16>::max())
indexSize = 4;
else if (vertexCount > std::numeric_limits<nzUInt8>::max())
indexSize = 2;
else
indexSize = 1;
std::unique_ptr<NzIndexBuffer> indexBuffer(new NzIndexBuffer(indexCount, indexSize, m_parameters.storage));
if (!indexBuffer->GetBuffer()->IsValid())
{
NazaraError("Failed to create index buffer");
continue;
}
ptr = indexBuffer->Map(nzBufferAccess_WriteOnly);
if (!ptr)
{
NazaraError("Failed to map index buffer");
continue;
}
switch (indexSize)
{
case 1:
{
nzUInt8* index = reinterpret_cast<nzUInt8*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
case 2:
{
nzUInt16* index = reinterpret_cast<nzUInt16*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
case 4:
{
nzUInt32* index = reinterpret_cast<nzUInt32*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
}
if (!indexBuffer->Unmap())
NazaraWarning("Failed to unmap index buffer");
std::unique_ptr<NzVertexBuffer> vertexBuffer(new NzVertexBuffer(NzMesh::GetDeclaration(), vertexCount, m_parameters.storage, nzBufferUsage_Dynamic));
std::unique_ptr<NzSkeletalMesh> subMesh(new NzSkeletalMesh(mesh));
if (!subMesh->Create(vertexBuffer.get(), weightCount))
{
NazaraError("Failed to create skeletal mesh");
continue;
}
subMesh->SetIndexBuffer(indexBuffer.get());
indexBuffer->SetPersistent(false);
indexBuffer.release();
vertexBuffer->SetPersistent(false);
vertexBuffer.release();
NzWeight* weights = subMesh->GetWeight();
for (unsigned int i = 0; i < weightCount; ++i)
{
weights->jointIndex = md5Mesh.weights[i].joint;
weights->weight = md5Mesh.weights[i].bias;
weights++;
}
NzMeshVertex* bindPosVertex = reinterpret_cast<NzMeshVertex*>(subMesh->GetBindPoseBuffer());
NzVertexWeight* vertexWeight = subMesh->GetVertexWeight();
for (const Mesh::Vertex& vertex : md5Mesh.vertices)
{
// Skinning MD5 (Formule d'Id Tech)
NzVector3f finalPos(NzVector3f::Zero());
vertexWeight->weights.resize(vertex.weightCount);
for (unsigned int j = 0; j < vertex.weightCount; ++j)
{
const Mesh::Weight& weight = md5Mesh.weights[vertex.startWeight + j];
const Joint& joint = m_joints[weight.joint];
finalPos += (joint.bindPos + joint.bindOrient*weight.pos) * weight.bias;
vertexWeight->weights[j] = vertex.startWeight + j;
}
bindPosVertex->position = finalPos;
bindPosVertex->uv.Set(vertex.uv.x, 1.f-vertex.uv.y);
bindPosVertex++;
vertexWeight++;
}
// Material
if (!md5Mesh.shader.IsEmpty())
{
unsigned int skinIndex;
if (mesh->AddMaterial(baseDir + md5Mesh.shader, &skinIndex))
subMesh->SetMaterialIndex(skinIndex);
else
NazaraWarning("Failed to add mesh shader");
}
if (!mesh->AddSubMesh(subMesh.get()))
{
NazaraError("Failed to add submesh");
continue;
}
subMesh.release();
// Animation
// Il est peut-être éventuellement possible que la probabilité que l'animation ait le même nom soit non-nulle.
NzString animationPath = m_stream.GetPath();
if (!animationPath.IsEmpty())
{
animationPath.Replace(".md5mesh", ".md5anim", -8, NzString::CaseInsensitive);
if (NzFile::Exists(animationPath))
{
std::unique_ptr<NzAnimation> animation(new NzAnimation);
if (animation->LoadFromFile(animationPath) && mesh->SetAnimation(animation.get()))
animation.release();
else
NazaraWarning("Failed to load mesh's animation");
}
}
}
}
else
{
if (!mesh->CreateStatic()) // Ne devrait jamais échouer
{
NazaraInternalError("Failed to create mesh");
return false;
}
for (const Mesh& md5Mesh : m_meshes)
{
void* ptr;
unsigned int indexCount = md5Mesh.triangles.size()*3;
unsigned int vertexCount = md5Mesh.vertices.size();
// Index buffer
nzUInt8 indexSize;
if (vertexCount > std::numeric_limits<nzUInt16>::max())
indexSize = 4;
else if (vertexCount > std::numeric_limits<nzUInt8>::max())
indexSize = 2;
else
indexSize = 1;
std::unique_ptr<NzIndexBuffer> indexBuffer(new NzIndexBuffer(indexCount, indexSize, m_parameters.storage));
if (!indexBuffer->GetBuffer()->IsValid())
{
NazaraError("Failed to create index buffer");
continue;
}
ptr = indexBuffer->Map(nzBufferAccess_WriteOnly);
if (!ptr)
{
NazaraError("Failed to map index buffer");
continue;
}
switch (indexSize)
{
case 1:
{
nzUInt8* index = reinterpret_cast<nzUInt8*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
case 2:
{
nzUInt16* index = reinterpret_cast<nzUInt16*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
case 4:
{
nzUInt32* index = reinterpret_cast<nzUInt32*>(ptr);
for (const Mesh::Triangle& triangle : md5Mesh.triangles)
{
// On les respécifie dans le bon ordre
*index++ = triangle.x;
*index++ = triangle.z;
*index++ = triangle.y;
}
break;
}
}
if (!indexBuffer->Unmap())
NazaraWarning("Failed to unmap index buffer");
// Vertex buffer
std::unique_ptr<NzVertexBuffer> vertexBuffer(new NzVertexBuffer(NzMesh::GetDeclaration(), vertexCount, m_parameters.storage, nzBufferUsage_Dynamic));
if (!vertexBuffer->GetBuffer()->IsValid())
{
NazaraError("Failed to create vertex buffer");
continue;
}
ptr = vertexBuffer->Map(nzBufferAccess_WriteOnly);
if (!ptr)
{
NazaraError("Failed to map vertex buffer");
continue;
}
NzAxisAlignedBox aabb;
NzMeshVertex* vertex = reinterpret_cast<NzMeshVertex*>(ptr);
for (const Mesh::Vertex& md5Vertex : md5Mesh.vertices)
{
// Skinning MD5 (Formule d'Id Tech)
NzVector3f finalPos(NzVector3f::Zero());
for (unsigned int j = 0; j < md5Vertex.weightCount; ++j)
{
const Mesh::Weight& weight = md5Mesh.weights[md5Vertex.startWeight + j];
const Joint& joint = m_joints[weight.joint];
finalPos += (joint.bindPos + joint.bindOrient*weight.pos) * weight.bias;
}
// On retourne le modèle dans le bon sens
finalPos = rotationQuat * finalPos;
aabb.ExtendTo(finalPos);
vertex->position = finalPos;
vertex->uv.Set(md5Vertex.uv.x, 1.f - md5Vertex.uv.y);
vertex++;
}
if (!vertexBuffer->Unmap())
NazaraWarning("Failed to unmap vertex buffer");
// Submesh
std::unique_ptr<NzStaticMesh> subMesh(new NzStaticMesh(mesh));
if (!subMesh->Create(vertexBuffer.get()))
{
NazaraError("Failed to create static submesh");
continue;
}
vertexBuffer->SetPersistent(false);
vertexBuffer.release();
subMesh->SetAABB(aabb);
subMesh->SetIndexBuffer(indexBuffer.get());
indexBuffer->SetPersistent(false);
indexBuffer.release();
// Material
if (!md5Mesh.shader.IsEmpty())
{
unsigned int skinIndex;
if (mesh->AddMaterial(baseDir + md5Mesh.shader, &skinIndex))
subMesh->SetMaterialIndex(skinIndex);
else
NazaraWarning("Failed to add mesh shader");
}
if (!mesh->AddSubMesh(subMesh.get()))
{
NazaraError("Failed to add submesh");
continue;
}
subMesh.release();
}
}
return true;
}
bool NzMD5MeshParser::Advance(bool required)
{
if (!m_keepLastLine)
{
do
{
if (m_stream.EndOfStream())
{
if (required)
Error("Incomplete MD5 file");
return false;
}
m_lineCount++;
m_currentLine = m_stream.ReadLine();
m_currentLine = m_currentLine.SubstrTo("//"); // On ignore les commentaires
m_currentLine.Simplify(); // Pour un traitement plus simple
}
while (m_currentLine.IsEmpty());
}
else
m_keepLastLine = false;
return true;
}
void NzMD5MeshParser::Error(const NzString& message)
{
NazaraError(message + " at line #" + NzString::Number(m_lineCount));
}
bool NzMD5MeshParser::ParseJoints()
{
unsigned int jointCount = m_joints.size();
if (jointCount == 0)
{
Error("Joint count is invalid or missing");
return false;
}
for (unsigned int i = 0; i < jointCount; ++i)
{
if (!Advance())
return false;
unsigned int pos = m_currentLine.Find(' ');
if (pos == NzString::npos)
{
UnrecognizedLine(true);
return false;
}
if (pos >= 64)
{
NazaraError("Joint name is too long (>= 64 characters)");
return false;
}
char name[64];
if (std::sscanf(&m_currentLine[0], "%s %d ( %f %f %f ) ( %f %f %f )", &name[0], &m_joints[i].parent,
&m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z,
&m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 8)
{
UnrecognizedLine(true);
return false;
}
m_joints[i].name = name;
m_joints[i].name.Trim('"');
int parent = m_joints[i].parent;
if (parent >= 0)
{
if (static_cast<unsigned int>(parent) >= jointCount)
{
Error("Joint's parent is out of bounds (" + NzString::Number(parent) + " >= " + NzString::Number(jointCount) + ')');
return false;
}
}
m_joints[i].bindOrient.ComputeW(); // On calcule la composante W
}
if (!Advance())
return false;
if (m_currentLine != '}')
{
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
Warning("Hierarchy braces closing not found");
#endif
// On tente de survivre à l'erreur
m_keepLastLine = true;
}
return true;
}
bool NzMD5MeshParser::ParseMesh()
{
bool finished = false;
while (!finished && Advance(false))
{
switch (m_currentLine[0])
{
case '}':
finished = true;
break;
case 's': // shader
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!m_currentLine.StartsWith("shader "))
{
UnrecognizedLine();
break;
}
#endif
m_meshes[m_meshIndex].shader = m_currentLine.Substr(7);
m_meshes[m_meshIndex].shader.Trim('"');
break;
case 'n': // num[tris/verts]
{
unsigned int count;
if (std::sscanf(&m_currentLine[0], "numtris %u", &count) == 1)
{
m_meshes[m_meshIndex].triangles.resize(count);
for (unsigned int i = 0; i < count; ++i)
{
if (!Advance())
return false;
Mesh::Triangle& triangle = m_meshes[m_meshIndex].triangles[i];
unsigned int index;
if (std::sscanf(&m_currentLine[0], "tri %u %u %u %u", &index, &triangle.x, &triangle.y, &triangle.z) != 4)
{
UnrecognizedLine(true);
return false;
}
if (index != i)
{
Error("Unexpected triangle index (expected " + NzString::Number(i) + ", got " + NzString::Number(index) + ')');
return false;
}
}
}
else if (std::sscanf(&m_currentLine[0], "numverts %u", &count) == 1)
{
m_meshes[m_meshIndex].vertices.resize(count);
for (unsigned int i = 0; i < count; ++i)
{
if (!Advance())
return false;
Mesh::Vertex& vertex = m_meshes[m_meshIndex].vertices[i];
unsigned int index;
if (std::sscanf(&m_currentLine[0], "vert %u ( %f %f ) %u %u", &index, &vertex.uv.x, &vertex.uv.y, &vertex.startWeight, &vertex.weightCount) != 5)
{
UnrecognizedLine(true);
return false;
}
if (index != i)
{
Error("Unexpected vertex index (expected " + NzString::Number(i) + ", got " + NzString::Number(index) + ')');
return false;
}
}
}
else if (std::sscanf(&m_currentLine[0], "numweights %u", &count) == 1)
{
m_meshes[m_meshIndex].weights.resize(count);
for (unsigned int i = 0; i < count; ++i)
{
if (!Advance())
return false;
Mesh::Weight& weight = m_meshes[m_meshIndex].weights[i];
unsigned int index;
if (std::sscanf(&m_currentLine[0], "weight %u %u %f ( %f %f %f )", &index, &weight.joint, &weight.bias,
&weight.pos.x, &weight.pos.y, &weight.pos.z) != 6)
{
UnrecognizedLine(true);
return false;
}
if (index != i)
{
Error("Unexpected weight index (expected " + NzString::Number(i) + ", got " + NzString::Number(index) + ')');
return false;
}
}
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
break;
}
default:
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
UnrecognizedLine();
#endif
break;
}
}
if (m_meshes[m_meshIndex].triangles.size() == 0)
{
NazaraError("Mesh has no triangles");
return false;
}
if (m_meshes[m_meshIndex].vertices.size() == 0)
{
NazaraError("Mesh has no vertices");
return false;
}
if (m_meshes[m_meshIndex].weights.size() == 0)
{
NazaraError("Mesh has no weights");
return false;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
if (!finished)
Warning("Mesh braces closing not found");
#endif
return true;
}
void NzMD5MeshParser::Warning(const NzString& message)
{
NazaraWarning(message + " at line #" + NzString::Number(m_lineCount));
}
void NzMD5MeshParser::UnrecognizedLine(bool error)
{
NzString message = "Unrecognized \"" + m_currentLine + '"';
if (error)
Error(message);
else
Warning(message);
}

View File

@@ -0,0 +1,78 @@
// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_LOADERS_MD5MESH_PARSER_HPP
#define NAZARA_LOADERS_MD5MESH_PARSER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <vector>
class NzMD5MeshParser
{
public:
NzMD5MeshParser(NzInputStream& stream, const NzMeshParams& parameters);
~NzMD5MeshParser();
bool Check();
bool Parse(NzMesh* mesh);
private:
struct Joint
{
NzQuaternionf bindOrient;
NzString name;
NzVector3f bindPos;
int parent;
};
struct Mesh
{
typedef NzVector3ui Triangle;
struct Vertex
{
NzVector2f uv;
unsigned int startWeight;
unsigned int weightCount;
};
struct Weight
{
NzVector3f pos;
float bias;
unsigned int joint;
};
std::vector<Triangle> triangles;
std::vector<Vertex> vertices;
std::vector<Weight> weights;
NzString shader;
};
bool Advance(bool required = true);
void Error(const NzString& message);
bool ParseJoints();
bool ParseMesh();
void Warning(const NzString& message);
void UnrecognizedLine(bool error = false);
std::vector<Joint> m_joints;
std::vector<Mesh> m_meshes;
NzInputStream& m_stream;
NzString m_currentLine;
const NzMeshParams& m_parameters;
bool m_keepLastLine;
unsigned int m_lineCount;
unsigned int m_meshIndex;
unsigned int m_streamFlags;
};
#endif // NAZARA_LOADERS_MD5MESH_PARSER_HPP

View File

@@ -37,6 +37,8 @@ namespace
nzUInt8 padding[54];
};
//static_assert(sizeof(pcx_header) == 1024, "PCX header must be 1024 bytes sized");
bool Check(NzInputStream& stream, const NzImageParams& parameters)
{
NazaraUnused(parameters);