source: trunk/src/formats/assimp_loader.cc @ 285

Last change on this file since 285 was 285, checked in by epyon, 11 years ago
  • full pure data model for animation
  • all loaders now use pure data model instead of the template/virtual one
File size: 15.3 KB
Line 
1// Copyright (C) 2014 ChaosForge Ltd
2// http://chaosforge.org/
3//
4// This file is part of NV Libraries.
5// For conditions of distribution and use, see copyright notice in nv.hh
6
7#include "nv/formats/assimp_loader.hh"
8#include <unordered_map>
9#include <glm/gtx/transform.hpp>
10#include "nv/io/std_stream.hh"
11#include "nv/lib/assimp.hh"
12
13using namespace nv;
14
15const int MAX_BONES = 64;
16
17nv::assimp_loader::assimp_loader( const string& a_ext, const mat3& a_rotate_transform, float a_scale, uint32 a_assimp_flags /*= 0 */ ) : m_mesh_count(0), m_scene( nullptr )
18{
19        initialize( a_ext, a_rotate_transform, a_scale, a_assimp_flags );
20}
21
22nv::assimp_loader::assimp_loader( const string& a_ext, uint32 a_assimp_flags /*= 0 */ ) : m_mesh_count(0), m_scene( nullptr )
23{
24        initialize( a_ext, mat3(), 1.0f, a_assimp_flags );
25}
26
27
28void nv::assimp_loader::initialize( const string& a_ext, const mat3& a_rotate_transform, float a_scale, uint32 a_assimp_flags )
29{
30        m_ext   = a_ext;
31        m_r33   = a_rotate_transform;
32        m_ri33  = glm::transpose( m_r33 );
33        m_scale = a_scale;
34        m_assimp_flags = a_assimp_flags;
35        if ( m_assimp_flags == 0 )
36        {
37                m_assimp_flags = (
38                        aiProcess_CalcTangentSpace                              | 
39                        aiProcess_GenSmoothNormals                              | 
40                        aiProcess_JoinIdenticalVertices                 |   
41                        aiProcess_ImproveCacheLocality                  | 
42                        aiProcess_LimitBoneWeights                              | 
43                        aiProcess_RemoveRedundantMaterials      | 
44                        aiProcess_SplitLargeMeshes                              | 
45                        aiProcess_Triangulate                                   | 
46                        aiProcess_GenUVCoords                   | 
47                        aiProcess_SortByPType                   | 
48                        aiProcess_FindDegenerates               | 
49                        aiProcess_FindInvalidData               | 
50                        0 );
51        }
52}
53
54
55bool nv::assimp_loader::load( stream& source )
56{
57        if ( m_scene != nullptr ) aiReleaseImport( (const aiScene*)m_scene );
58        m_scene = nullptr;
59        m_mesh_count = 0;
60        load_assimp_library();
61        NV_LOG( nv::LOG_NOTICE, "AssImp loading file..." );
62        int size = (int)source.size();
63        char* data  = new char[ size ];
64        source.read( data, size, 1 );
65        const aiScene* scene = aiImportFileFromMemory( data, size, m_assimp_flags, m_ext.c_str() );
66
67        if( !scene)
68        {
69                NV_LOG( nv::LOG_ERROR, aiGetErrorString() );
70                return false;
71        }
72        m_scene      = scene;
73        m_mesh_count = scene->mNumMeshes;
74        NV_LOG( nv::LOG_NOTICE, "Loading successfull" );
75        return true;
76}
77
78mesh_data* nv::assimp_loader::release_mesh_data( size_t index /*= 0 */ )
79{
80        if ( index >= m_mesh_count ) return nullptr;
81        mesh_data* result = new mesh_data();
82        const aiScene* scene = (const aiScene*)m_scene;
83        const aiMesh*  mesh  = scene->mMeshes[ index ];
84
85        vec3 vertex_offset     = glm::vec3();
86        mat3 vertex_transform  = m_scale * m_r33;
87        mat3 normal_transform  = m_r33;
88
89        bool skinned = mesh->mNumBones > 0;
90        mesh_raw_channel* channel = nullptr;
91        if ( skinned )
92                channel = mesh_raw_channel::create< assimp_skinned_vtx >( mesh->mNumVertices );
93        else
94                channel = mesh_raw_channel::create< assimp_plain_vtx >( mesh->mNumVertices );
95
96        result->add_channel( channel );
97        for (unsigned int i=0; i<mesh->mNumVertices; i++)
98        {
99                vec3 v = vertex_transform * assimp_vec3_cast( mesh->mVertices[ i ] ) + vertex_offset;
100                vec3 n = glm::normalize( normal_transform * assimp_vec3_cast( mesh->mNormals[ i ] ) );
101                vec3 t = glm::normalize( normal_transform * assimp_vec3_cast( mesh->mTangents[ i ] ) );
102                vec3 b = glm::normalize( normal_transform * assimp_vec3_cast( mesh->mBitangents[ i ] ) );
103                vec2 s = assimp_st_cast( mesh->mTextureCoords[ 0 ][ i ] );
104
105                glm::vec3 t_i = glm::normalize (t - n * glm::dot (n, t));
106                float det = (glm::dot (glm::cross (n, t), b));
107                det = (det < 0.0f ? -1.0f : 1.0f );
108                nv::vec4 vt ( t_i[0], t_i[1], t_i[2], det );
109                if ( skinned )
110                        ((assimp_skinned_vtx*)channel->data)[i] = assimp_skinned_vtx( v, s, n, vt );
111                else
112                        ((assimp_plain_vtx*)channel->data)[i] = assimp_plain_vtx( v, s, n, vt );
113        }
114
115        if ( skinned )
116        {
117                assimp_skinned_vtx* vtx = (assimp_skinned_vtx*)channel->data;
118                for (unsigned int m=0; m<mesh->mNumBones; m++)
119                {
120                        aiBone* bone  = mesh->mBones[m];
121                        for (unsigned int w=0; w<bone->mNumWeights; w++)
122                        {
123                                assimp_skinned_vtx& v = vtx[ bone->mWeights[w].mVertexId ];
124                                bool found = false;
125                                for (nv::uint32 i = 0 ; i < 4; ++i)
126                                {
127                                        if ( v.boneweight[i] <= 0.0f )
128                                        {
129                                                v.boneindex[i] = m;
130                                                v.boneweight[i] = bone->mWeights[w].mWeight;
131                                                found = true;
132                                                break;
133                                        }
134                                }
135                                NV_ASSERT( found, "Too many weights!" );
136                        }
137                }
138        }
139
140        mesh_raw_channel* ichannel = mesh_raw_channel::create_index( USHORT, mesh->mNumFaces * 3 );
141        result->add_channel( ichannel );
142        uint16* indices = (uint16*)ichannel->data;
143        for (unsigned int i=0; i<mesh->mNumFaces; i++)
144        {
145                const aiFace* face = &mesh->mFaces[i];
146                for (unsigned int j=0; j<face->mNumIndices; j++)
147                {
148                        indices[ i*3 + j ] = (uint16)face->mIndices[j];
149                }
150        }
151
152        return result;
153}
154
155nv::assimp_loader::~assimp_loader()
156{
157        if ( m_scene != nullptr ) aiReleaseImport( (const aiScene*)m_scene );
158}
159
160bool nv::assimp_loader::load_bones( size_t index, std::vector< assimp_bone >& bones )
161{
162        if ( m_scene == nullptr ) return false;
163        const aiScene* scene = (const aiScene*)m_scene;
164        const aiMesh*  mesh  = scene->mMeshes[ index ];
165        if ( mesh->mNumBones == 0 ) return false;
166
167        mat4 bone_transform     = mat4( ( 1.f/m_scale * m_ri33 ) );
168        mat4 bone_pre_transform = mat4( m_scale * m_r33 );
169
170        for (unsigned int m=0; m<mesh->mNumBones; m++)
171        {
172                aiBone* bone   = mesh->mBones[m];
173                mat4    offset = bone_pre_transform * assimp_mat4_cast( bone->mOffsetMatrix ) * bone_transform;
174                bones.emplace_back( bone->mName.data, offset );
175        }
176        return true;
177}
178
179void nv::assimp_loader::scene_report() const
180{
181        const aiScene* scene = (const aiScene*)m_scene;
182        if ( scene == nullptr ) return;
183
184        NV_LOG( nv::LOG_NOTICE, "------------------------" );
185        NV_LOG( nv::LOG_NOTICE, "Texture   count - " << scene->mNumTextures );
186        NV_LOG( nv::LOG_NOTICE, "Animation count - " << scene->mNumAnimations );
187        NV_LOG( nv::LOG_NOTICE, "Material  count - " << scene->mNumMaterials );
188        NV_LOG( nv::LOG_NOTICE, "Meshes    count - " << scene->mNumMeshes );
189        NV_LOG( nv::LOG_NOTICE, "------------------------" );
190
191        aiNode* root = scene->mRootNode;
192        if (root)
193        {
194                NV_LOG( nv::LOG_NOTICE, "Root node  - " << root->mName.data );
195                NV_LOG( nv::LOG_NOTICE, "  meshes   - " << root->mNumMeshes );
196                NV_LOG( nv::LOG_NOTICE, "  children - " << root->mNumChildren );
197        }
198        else
199        {
200                NV_LOG( nv::LOG_NOTICE, "No root node!" );
201        }
202        NV_LOG( nv::LOG_NOTICE, "------------------------" );
203
204        if ( scene->mNumMeshes > 0 )
205        {
206                for ( nv::uint32 mc = 0; mc < scene->mNumMeshes; mc++ )
207                {
208                        aiMesh* mesh = scene->mMeshes[mc];
209
210                        NV_LOG( nv::LOG_NOTICE, "Mesh #"<<mc<<"   - " << std::string( mesh->mName.data ) );
211                        NV_LOG( nv::LOG_NOTICE, "  bones   - " << mesh->mNumBones );
212                        NV_LOG( nv::LOG_NOTICE, "  uvs     - " << mesh->mNumUVComponents[0] );
213                        NV_LOG( nv::LOG_NOTICE, "  verts   - " << mesh->mNumVertices );
214                        NV_LOG( nv::LOG_NOTICE, "  faces   - " << mesh->mNumFaces );
215
216                        //                      NV_LOG( nv::LOG_NOTICE, "Bones:" );
217                        //                      for (unsigned int m=0; m<mesh->mNumBones; m++)
218                        //                      {
219                        //                              aiBone* bone  = mesh->mBones[m];
220                        //                              NV_LOG( nv::LOG_DEBUG, bone->mName.C_Str() );
221                        //                      }
222                }
223        }
224        else
225        {
226                NV_LOG( nv::LOG_NOTICE, "No meshes!" );
227        }
228        NV_LOG( nv::LOG_NOTICE, "------------------------" );
229
230
231        //      if ( scene->mNumMaterials > 0 )
232        //      {
233        //              for (unsigned int m=0; m < scene->mNumMaterials; m++)
234        //              {
235        //                      int texIndex = 0;
236        //                      aiReturn texFound = aiReturn_SUCCESS;
237        //                      aiString path;  // filename
238        //                      while (texFound == aiReturn_SUCCESS)
239        //                      {
240        //                              texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
241        //                              NV_LOG( nv::LOG_NOTICE, "  material - " << path.data );
242        //                              texIndex++;
243        //                      }
244        //              }
245        //      }
246        //      else
247        //      {
248        //              NV_LOG( nv::LOG_NOTICE, "No materials" );
249        //      }
250        //      NV_LOG( nv::LOG_NOTICE, "------------------------" );
251
252}
253
254assimp_model* nv::assimp_loader::release_merged_model()
255{
256        if ( m_scene == nullptr || m_mesh_count == 0 ) return nullptr;
257        assimp_model* model = new assimp_model;
258
259        for ( size_t m = 0; m < m_mesh_count; ++m )
260        {
261                model->meshes.push_back( release_mesh_data(m) );
262        }
263
264        std::unordered_map< std::string, uint16 > names;
265        for ( unsigned int m = 0; m < model->meshes.size(); ++m )
266        {
267                sint16 translate[MAX_BONES];
268                std::vector< assimp_bone > bones;
269                load_bones( m, bones );
270                for ( unsigned int b = 0; b < bones.size(); ++b )
271                {
272
273                        assimp_bone& bone = bones[b];
274                        auto iname = names.find( bone.name );
275                        if ( iname == names.end() )
276                        {
277                                NV_ASSERT( model->bones.size() < MAX_BONES, "Too many bones to merge!" );
278                                sint16 index = (sint16)model->bones.size();
279                                model->bones.push_back( bone );
280                                names[ bone.name ] = index;
281                                translate[b] = index;
282                        }
283                        else
284                        {
285                                translate[b] = (sint16)iname->second;
286                        }
287                }
288                if ( m > 0 && bones.size() > 0 )
289                {
290                        mesh_data* mesh = model->meshes[m];
291                        mesh_raw_channel* channel = mesh->get_raw_channels()[0];
292                        NV_ASSERT( !channel->is_index(), "index channel in release_merged!" );
293                        assimp_skinned_vtx* va = (assimp_skinned_vtx*)channel->data;
294                        for ( unsigned v = 0; v < channel->count; ++v )
295                        {
296                                assimp_skinned_vtx& vertex = va[v];
297
298                                for (uint32 i = 0 ; i < 4; ++i)
299                                {
300                                        if ( vertex.boneweight[i] > 0.0f )
301                                        {
302                                                vertex.boneindex[i] = translate[vertex.boneindex[i]];
303                                        }
304                                }
305                        }
306                }
307        }
308        return model;
309}
310
311assimp_animation* nv::assimp_loader::release_animation( size_t, bool pre_transform )
312{
313        if ( m_scene == nullptr ) return nullptr;
314        const aiScene* scene = (const aiScene*)m_scene;
315        if ( scene->mRootNode == nullptr || scene->mAnimations == nullptr || scene->mAnimations[0] == nullptr) return nullptr;
316        assimp_animation* result = new assimp_animation;
317
318        // need resize not to copy!
319        result->nodes.resize( count_nodes( scene->mRootNode ) );
320
321        const aiNode*      root = scene->mRootNode;
322        const aiAnimation* anim = scene->mAnimations[0]; // if implemented, change in load_node also
323
324        result->fps            = (float)anim->mTicksPerSecond;
325        result->duration       = (float)anim->mDuration;
326        result->pretransformed = pre_transform;
327
328        load_node( result, root, 0, -1 );
329        return result;
330}
331
332nv::uint32 nv::assimp_loader::count_nodes( const void* node ) const
333{
334        const aiNode* ainode = (const aiNode*)node;
335        nv::uint32 count = 1;
336        for ( unsigned i = 0; i < ainode->mNumChildren; ++i )
337        {
338                count += count_nodes( ainode->mChildren[i] );
339        }
340        return count;
341}
342
343nv::uint32 nv::assimp_loader::load_node( assimp_animation* data, const void* vnode, sint32 this_id, sint32 parent_id )
344{
345        const aiScene* scene = (const aiScene*)m_scene;
346        const aiNode*  node  = (const aiNode*)vnode;
347        string name( node->mName.data );
348        const aiAnimation* anim  = scene->mAnimations[0];
349        const aiNodeAnim*  anode = nullptr;
350
351        for ( unsigned i = 0 ; i < anim->mNumChannels ; i++ )
352        {
353                anode = anim->mChannels[i];
354                if ( std::string( anode->mNodeName.data ) == name ) break;
355                anode = nullptr;
356        }
357
358        assimp_animated_node_data& a_data = data->nodes[ this_id ];
359
360        a_data.name      = name;
361        a_data.parent_id = parent_id;
362        // This value is ignored by the create_transformed_keys, but needed by create_direct_keys!
363        // TODO: find a common solution!
364        //       This is bad because create_transformed_keys never uses node-transformations for
365        //       node's without keys
366        a_data.transform = nv::assimp_mat4_cast( node->mTransformation );
367        if (this_id == 0)
368                a_data.transform = mat4();
369        a_data.data = nullptr;
370
371        if (anode)
372        {
373                if ( data->pretransformed )
374                {
375                        create_transformed_keys( &a_data, anode, parent_id >= 0 ? &(data->nodes[ parent_id ]) : nullptr );
376                }
377                else
378                {
379                        create_direct_keys( &a_data, anode );
380                }
381        }
382
383        nv::uint32 next = this_id + 1;
384        for ( unsigned i = 0; i < node->mNumChildren; ++i )
385        {
386                next = load_node( data, node->mChildren[i], next, this_id );
387        }
388        return next;
389}
390
391void nv::assimp_loader::create_transformed_keys( assimp_animated_node_data* data, const void* vnode, const assimp_animated_node_data* parent )
392{
393        const aiNodeAnim* node = (const aiNodeAnim*)vnode;
394        size_t max_keys = glm::max( node->mNumPositionKeys, node->mNumRotationKeys );
395
396        key_raw_channel* raw_channel = key_raw_channel::create<assimp_key_tr>( max_keys );
397        data->data = new key_data;
398        data->data->add_channel( raw_channel );
399        assimp_key_tr* channel = ((assimp_key_tr*)(raw_channel->data));
400
401        for ( unsigned n = 0; n < max_keys; ++n )
402        {
403                size_t pn = glm::min( node->mNumPositionKeys - 1, n );
404                size_t rn = glm::min( node->mNumRotationKeys - 1, n );
405                nv::vec3 pos = m_r33 * nv::assimp_vec3_cast(node->mPositionKeys[pn].mValue) * m_scale;
406                nv::quat rot = glm::quat_cast( m_r33 * glm::mat3_cast( assimp_quat_cast(node->mRotationKeys[rn].mValue ) ) * m_ri33 );
407                // TODO: only do the calculation when a rotate transform is present!
408                nv::transform ptr;
409                if ( parent && parent->data )
410                {
411                        const key_raw_channel* pchannel = parent->data->get_channel(0);
412                        if ( pchannel && pchannel->count > 0 )
413                        {
414                                ptr = ((assimp_key_tr*)pchannel->data)[ glm::min( n, pchannel->count-1 ) ].tform;
415                        }
416                }
417
418                nv::transform key( ptr * nv::transform( pos, rot ) );
419                channel[n].tform = key;
420        }
421}
422
423void nv::assimp_loader::create_direct_keys( assimp_animated_node_data* data, const void* vnode )
424{
425        const aiNodeAnim* node = (const aiNodeAnim*)vnode;
426        if ( node->mNumPositionKeys == 0 && node->mNumRotationKeys == 0 && node->mNumScalingKeys == 0 )
427        {
428                return;
429        }
430
431        data->data = new key_data;
432        key_raw_channel* raw_pchannel = key_raw_channel::create<assimp_key_p>( node->mNumPositionKeys );
433        key_raw_channel* raw_rchannel = key_raw_channel::create<assimp_key_r>( node->mNumRotationKeys );
434        key_raw_channel* raw_schannel = key_raw_channel::create<assimp_key_s>( node->mNumScalingKeys );
435        data->data->add_channel( raw_pchannel );
436        data->data->add_channel( raw_rchannel );
437        data->data->add_channel( raw_schannel );
438        assimp_key_p* pchannel = ((assimp_key_p*)(raw_pchannel->data));
439        assimp_key_r* rchannel = ((assimp_key_r*)(raw_rchannel->data));
440        assimp_key_s* schannel = ((assimp_key_s*)(raw_schannel->data));
441
442        for ( unsigned np = 0; np < node->mNumPositionKeys; ++np )
443        {
444                pchannel[np].time     = (float)node->mPositionKeys[np].mTime;
445                pchannel[np].position = m_r33 * assimp_vec3_cast(node->mPositionKeys[np].mValue) * m_scale;
446        }
447        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
448        {
449                rchannel[np].time     = (float)node->mRotationKeys[np].mTime;
450                rchannel[np].rotation = glm::quat_cast( m_r33 * glm::mat3_cast( assimp_quat_cast(node->mRotationKeys[np].mValue ) ) * m_ri33 );
451        }
452        if ( node->mNumScalingKeys > 0 )
453        {
454                nv::vec3 scale_vec0 = assimp_vec3_cast( node->mScalingKeys[0].mValue );
455                float scale_value   = glm::length( glm::abs( scale_vec0 - nv::vec3(1,1,1) ) );
456                if ( node->mNumScalingKeys > 1 || scale_value > 0.001 )
457                {
458                        NV_LOG( nv::LOG_WARNING, "scale key significant!" );
459                        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
460                        {
461                                schannel[np].time  = (float)node->mScalingKeys[np].mTime;
462                                schannel[np].scale = assimp_vec3_cast(node->mScalingKeys[np].mValue);
463                        }
464                }
465                else
466                {
467                        schannel[0].time  = (float)node->mScalingKeys[0].mTime;
468                        schannel[0].scale = assimp_vec3_cast(node->mScalingKeys[0].mValue);
469                }
470        }
471
472}
473
Note: See TracBrowser for help on using the repository browser.