source: trunk/src/formats/md5_loader.cc @ 191

Last change on this file since 191 was 191, checked in by epyon, 12 years ago
  • formats - md3_animation works!
File size: 16.1 KB
Line 
1// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz
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/md5_loader.hh"
8
9#include <glm/gtc/constants.hpp>
10#include <glm/gtx/string_cast.hpp>
11#include "nv/logging.hh"
12#include "nv/io/std_stream.hh"
13#include <cstring>
14
15using namespace nv;
16
17// based on http://tfc.duke.free.fr/coding/md5-specs-en.html
18
19static void next_line( std::istream& stream )
20{
21        stream.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
22}
23
24static inline void discard( std::istream& stream, const std::string& token )
25{
26        std::string discarded;
27        stream >> discarded;
28        assert( discarded == token );
29}
30
31
32static void remove_quotes( std::string& str )
33{
34        size_t n;
35        while ( ( n = str.find('\"') ) != std::string::npos ) str.erase(n,1);
36}
37
38void unit_quat_w( glm::quat& quat )
39{
40        float t = 1.0f - ( quat.x * quat.x ) - ( quat.y * quat.y ) - ( quat.z * quat.z );
41        quat.w = ( t < 0.0f ? 0.0f : -sqrtf(t) );
42}
43
44bool md5_loader::load( stream& source )
45{
46        std_stream sstream( &source );
47        std::string command;
48
49        sstream >> command;
50        while ( !sstream.eof() )
51        {
52                if ( command == "MD5Version" )
53                {
54                        sstream >> m_md5_version;
55                        assert( m_md5_version == 10 );
56                }
57                else if ( command == "commandline" )
58                {
59                        next_line( sstream );
60                }
61                else if ( command == "numJoints" )
62                {
63                        sstream >> m_num_joints;
64                        m_joints.reserve( m_num_joints );
65                }
66                else if ( command == "numMeshes" )
67                {
68                        sstream >> m_num_meshes;
69                        m_meshes.reserve( m_num_meshes );
70                }
71                else if ( command == "joints" )
72                {
73                        discard( sstream, "{" );
74                        md5_joint joint;
75                        for ( size_t i = 0; i < m_num_joints; ++i )
76                        {
77                                sstream >> joint.name >> joint.parent_id;
78                                discard( sstream, "(" );
79                                sstream >> joint.pos.x >> joint.pos.y >> joint.pos.z;
80                                discard( sstream, ")" );
81                                discard( sstream, "(" );
82                                sstream >> joint.orient.x >> joint.orient.y >> joint.orient.z;
83                                remove_quotes( joint.name );
84                                unit_quat_w( joint.orient );
85                                m_joints.push_back( joint );
86                                next_line( sstream );
87                        }
88                        discard( sstream, "}" );
89                }
90                else if ( command == "mesh" )
91                {
92                        // TODO : efficiency dammit
93                        md5_mesh mesh;
94                        int num_verts, num_tris, num_weights;
95
96                        discard( sstream, "{" );
97                        sstream >> command;
98                        while ( command != "}" )
99                        {
100                                if ( command == "shader" )
101                                {
102                                        sstream >> mesh.shader;
103                                        remove_quotes( mesh.shader );
104                                        // texturePath.replace_extension( ".tga" );
105                                        next_line( sstream );
106                                }
107                                else if ( command == "numverts")
108                                {
109                                        sstream >> num_verts;
110                                        next_line( sstream );
111                                        for ( int i = 0; i < num_verts; ++i )
112                                        {
113                                                md5_vertex vert;
114                                                std::string ignore;
115                                                discard( sstream, "vert" );
116                                                sstream >> ignore;
117                                                discard( sstream, "(" );
118                                                sstream >> vert.texcoord.x >> vert.texcoord.y;
119                                                discard( sstream, ")" );
120                                                sstream >> vert.start_weight >> vert.weight_count;
121                                                next_line( sstream );
122
123                                                mesh.verts.push_back(vert);
124                                                mesh.texcoord_buffer.push_back( vert.texcoord );
125                                        } 
126                                }
127                                else if ( command == "numtris" )
128                                {
129                                        sstream >> num_tris;
130                                        next_line( sstream );
131                                        for ( int i = 0; i < num_tris; ++i )
132                                        {
133                                                md5_triangle tri;
134                                                std::string ignore;
135                                                discard( sstream, "tri" );
136                                                sstream >> ignore >> tri.indices[0] >> tri.indices[1] >> tri.indices[2];
137                                                next_line( sstream );
138
139                                                mesh.tris.push_back( tri );
140                                                mesh.index_buffer.push_back( (uint32)tri.indices[0] );
141                                                mesh.index_buffer.push_back( (uint32)tri.indices[1] );
142                                                mesh.index_buffer.push_back( (uint32)tri.indices[2] );
143                                        }             
144                                }
145                                else if ( command == "numweights" )
146                                {
147                                        sstream >> num_weights;
148                                        next_line( sstream );
149                                        for ( int i = 0; i < num_weights; ++i )
150                                        {
151                                                md5_weight weight;
152                                                std::string ignore;
153                                                discard( sstream, "weight" );
154                                                sstream >> ignore >> weight.joint_id >> weight.bias;
155                                                discard( sstream, "(" );
156                                                sstream >> weight.pos.x >> weight.pos.y >> weight.pos.z;
157                                                discard( sstream, ")" );
158                                                next_line( sstream );
159                                                mesh.weights.push_back(weight);
160                                        }
161                                }
162                                else
163                                {
164                                        next_line( sstream );
165                                }
166
167                                sstream >> command;
168                        }
169
170                        prepare_mesh( mesh );
171                        prepare_normals( mesh );
172
173                        m_meshes.push_back(mesh);
174                }
175                sstream >> command;
176        }
177
178        assert( m_joints.size() == m_num_joints );
179        assert( m_meshes.size() == m_num_meshes );
180        return true;
181}
182
183bool md5_loader::prepare_mesh( md5_mesh& mesh )
184{
185        mesh.position_buffer.clear();
186        mesh.texcoord_buffer.clear();
187
188        for ( uint32 i = 0; i < mesh.verts.size(); ++i )
189        {
190                md5_vertex& vert = mesh.verts[i];
191
192                vert.position = glm::vec3(0);
193                vert.normal   = glm::vec3(0);
194                vert.tangent  = glm::vec3(0);
195
196                for ( int j = 0; j < vert.weight_count; ++j )
197                {
198                        md5_weight& weight = mesh.weights[vert.start_weight + j];
199                        md5_joint&  joint  = m_joints[weight.joint_id];
200
201                        glm::vec3 rot_pos = joint.orient * weight.pos;
202
203                        vert.position += ( joint.pos + rot_pos ) * weight.bias;
204                }
205
206                mesh.position_buffer.push_back(vert.position);
207                mesh.texcoord_buffer.push_back(vert.texcoord);
208        }
209
210        return true;
211}
212
213bool md5_loader::prepare_normals( md5_mesh& mesh )
214{
215        mesh.normal_buffer.clear();
216
217        for ( unsigned int i = 0; i < mesh.tris.size(); ++i )
218        {
219                const md5_triangle& tri = mesh.tris[i];
220                glm::vec3 v1 = mesh.verts[ tri.indices[0] ].position;
221                glm::vec3 v2 = mesh.verts[ tri.indices[1] ].position;
222                glm::vec3 v3 = mesh.verts[ tri.indices[2] ].position;
223                glm::vec3 xyz1 = v3 - v1;
224                glm::vec3 xyz2 = v2 - v1;
225
226                glm::vec3 normal = glm::cross( xyz1, xyz2 );
227
228                mesh.verts[ tri.indices[0] ].normal += normal;
229                mesh.verts[ tri.indices[1] ].normal += normal;
230                mesh.verts[ tri.indices[2] ].normal += normal;
231
232                const vec2& w1 = mesh.verts[ tri.indices[0] ].texcoord;
233                const vec2& w2 = mesh.verts[ tri.indices[1] ].texcoord;
234                const vec2& w3 = mesh.verts[ tri.indices[2] ].texcoord;
235
236                vec2 st1 = w3 - w1;
237                vec2 st2 = w2 - w1;
238
239                float coef = 1.0f / (st1.x * st2.y - st2.x * st1.y);
240
241                vec3 tangent = (( xyz1 * st2.y ) - ( xyz2 * st1.y )) * coef;
242
243                mesh.verts[ tri.indices[0] ].tangent += tangent;
244                mesh.verts[ tri.indices[1] ].tangent += tangent;
245                mesh.verts[ tri.indices[2] ].tangent += tangent;
246        }
247
248        for ( unsigned int i = 0; i < mesh.verts.size(); ++i )
249        {
250                md5_vertex& vert = mesh.verts[i];
251
252                glm::vec3 normal  = glm::normalize( vert.normal );
253                glm::vec3 tangent = glm::normalize( vert.tangent );
254                mesh.normal_buffer.push_back( normal );
255                mesh.tangent_buffer.push_back( tangent );
256
257                vert.normal  = glm::vec3(0);
258                vert.tangent = glm::vec3(0);
259
260                for ( int j = 0; j < vert.weight_count; ++j )
261                {
262                        const md5_weight& weight = mesh.weights[vert.start_weight + j];
263                        const md5_joint&  joint  = m_joints[weight.joint_id];
264                        vert.normal  += ( normal  * joint.orient ) * weight.bias;
265                        vert.tangent += ( tangent * joint.orient ) * weight.bias;
266                }
267        }
268
269        return true;
270}
271
272mesh* md5_loader::release_mesh()
273{
274        mesh* m = new mesh();
275        auto position = m->add_attribute< vec3 >( "nv_position" );
276        auto normal   = m->add_attribute< vec3 >( "nv_normal" );
277        auto texcoord = m->add_attribute< vec2 >( "nv_texcoord" );
278        auto tangent  = m->add_attribute< vec2 >( "nv_tangent" );
279        auto indices  = m->add_indices< uint32 >();
280
281        position->get().assign( m_meshes[0].position_buffer.begin(), m_meshes[0].position_buffer.end() );
282        normal  ->get().assign( m_meshes[0].normal_buffer.begin(),   m_meshes[0].normal_buffer.end() );
283        texcoord->get().assign( m_meshes[0].texcoord_buffer.begin(), m_meshes[0].texcoord_buffer.end() );
284        tangent ->get().assign( m_meshes[0].tangent_buffer.begin(),  m_meshes[0].tangent_buffer.end() );
285        indices ->get().assign( m_meshes[0].index_buffer.begin(),    m_meshes[0].index_buffer.end() );
286
287        m_size = m_meshes[0].index_buffer.size();
288        return m;
289}
290
291md5_animation::md5_animation()
292        : m_md5_version( 0 )
293        , m_num_frames( 0 )
294        , m_num_joints( 0 )
295        , m_frame_rate( 0 )
296        , m_num_animated_components( 0 )
297        , m_anim_duration( 0 )
298        , m_frame_duration( 0 )
299        , m_anim_time( 0 )
300{
301
302}
303
304md5_animation::~md5_animation()
305{
306
307}
308
309bool md5_animation::load_animation( stream& source )
310{
311        m_joint_infos.clear();
312        m_bounds.clear();
313        m_base_frames.clear();
314        m_frames.clear();
315        m_animated_skeleton.joints.clear();
316        m_num_frames = 0;
317
318        std_stream sstream( &source );
319        std::string command;
320
321        sstream >> command;
322        while ( !sstream.eof() )
323        {
324                if ( command == "MD5Version" )
325                {
326                        sstream >> m_md5_version;
327                        assert( m_md5_version == 10 );
328                }
329                else if ( command == "commandline" )
330                {
331                        next_line( sstream );
332                }
333                else if ( command == "numFrames" )
334                {
335                        sstream >> m_num_frames;
336                        next_line( sstream );
337                }
338                else if ( command == "numJoints" )
339                {
340                        sstream >> m_num_joints;
341                        next_line( sstream );
342                }
343                else if ( command == "frameRate" )
344                {
345                        sstream >> m_frame_rate;
346                        next_line( sstream );
347                }
348                else if ( command == "numAnimatedComponents" )
349                {
350                        sstream >> m_num_animated_components;
351                        next_line( sstream );
352                }
353                else if ( command == "hierarchy" )
354                {
355                        discard( sstream, "{" );
356                        for ( int i = 0; i < m_num_joints; ++i )
357                        {
358                                md5_joint_info joint;
359                                sstream >> joint.name >> joint.parent_id >> joint.flags >> joint.start_index;
360                                remove_quotes( joint.name );
361                                m_joint_infos.push_back( joint );
362                                next_line( sstream );
363                        }
364                        discard( sstream, "}" );
365                }
366                else if ( command == "bounds" )
367                {
368                        discard( sstream, "{" );
369                        next_line( sstream );
370                        for ( int i = 0; i < m_num_frames; ++i )
371                        {
372                                md5_bound bound;
373                                discard( sstream, "(" );
374                                sstream >> bound.min.x >> bound.min.y >> bound.min.z;
375                                discard( sstream, ")" );
376                                discard( sstream, "(" );
377                                sstream >> bound.max.x >> bound.max.y >> bound.max.z;
378
379                                m_bounds.push_back( bound );
380
381                                next_line( sstream );
382                        }
383
384                        discard( sstream, "}" );
385                        next_line( sstream );
386                }
387                else if ( command == "baseframe" )
388                {
389                        discard( sstream, "{" );
390                        next_line( sstream );
391
392                        for ( int i = 0; i < m_num_joints; ++i )
393                        {
394                                md5_base_frame base_frame;
395                                discard( sstream, "(" );
396                                sstream >> base_frame.pos.x >> base_frame.pos.y >> base_frame.pos.z;
397                                discard( sstream, ")" );
398                                discard( sstream, "(" );
399                                sstream >> base_frame.orient.x >> base_frame.orient.y >> base_frame.orient.z;
400                                next_line( sstream );
401
402                                m_base_frames.push_back( base_frame );
403                        }
404                        discard( sstream, "}" );
405                        next_line( sstream );
406                }
407                else if ( command == "frame" )
408                {
409                        md5_frame_data frame;
410                        sstream >> frame.frame_id;
411                        discard( sstream, "{" );
412                        next_line( sstream );
413
414                        for ( int i = 0; i < m_num_animated_components; ++i )
415                        {
416                                float frameData;
417                                sstream >> frameData;
418                                frame.frame_data.push_back(frameData);
419                        }
420
421                        m_frames.push_back(frame);
422
423                        build_frame_skeleton( m_skeletons, m_joint_infos, m_base_frames, frame );
424
425                        discard( sstream, "}" );
426                        next_line( sstream );
427                }
428
429                sstream >> command;
430        }
431
432        m_animated_skeleton.joints.assign( m_num_joints, md5_skeleton_joint() );
433
434        m_frame_duration = 1.0f / (float)m_frame_rate;
435        m_anim_duration = ( m_frame_duration * (float)m_num_frames );
436        m_anim_time = 0.0f;
437
438        assert( m_joint_infos.size() == (size_t)m_num_joints );
439        assert( m_bounds.size()      == (size_t)m_num_frames );
440        assert( m_base_frames.size() == (size_t)m_num_joints );
441        assert( m_frames.size()      == (size_t)m_num_frames );
442        assert( m_skeletons.size()   == (size_t)m_num_frames );
443
444        return true;
445}
446
447void md5_animation::update( float delta_time )
448{
449        if ( m_num_frames < 1 ) return;
450
451        m_anim_time += delta_time;
452
453        while ( m_anim_time > m_anim_duration ) m_anim_time -= m_anim_duration;
454        while ( m_anim_time < 0.0f ) m_anim_time += m_anim_duration;
455
456        float frame_num = m_anim_time * (float)m_frame_rate;
457        int frame0 = (int)floorf( frame_num );
458        int frame1 = (int)ceilf( frame_num );
459        frame0 = frame0 % m_num_frames;
460        frame1 = frame1 % m_num_frames;
461
462        float interpolate = fmodf( m_anim_time, m_frame_duration ) / m_frame_duration;
463
464        interpolate_skeletons( m_animated_skeleton, m_skeletons[frame0], m_skeletons[frame1], interpolate );
465}
466
467void md5_animation::build_frame_skeleton( md5_frame_skeleton_list& skeletons, const md5_joint_info_list& joint_infos, const md5_base_frame_list& base_frames, const md5_frame_data& frame_data )
468{
469        md5_frame_skeleton skeleton;
470
471        for ( unsigned int i = 0; i < joint_infos.size(); ++i )
472        {
473                unsigned int j = 0;
474
475                const md5_joint_info& jinfo = joint_infos[i];
476                md5_skeleton_joint animated_joint = base_frames[i];
477
478                animated_joint.parent = jinfo.parent_id;
479
480                if ( jinfo.flags & 1 )  animated_joint.pos.x    = frame_data.frame_data[ jinfo.start_index + j++ ];
481                if ( jinfo.flags & 2 )  animated_joint.pos.y    = frame_data.frame_data[ jinfo.start_index + j++ ];
482                if ( jinfo.flags & 4 )  animated_joint.pos.z    = frame_data.frame_data[ jinfo.start_index + j++ ];
483                if ( jinfo.flags & 8 )  animated_joint.orient.x = frame_data.frame_data[ jinfo.start_index + j++ ];
484                if ( jinfo.flags & 16 ) animated_joint.orient.y = frame_data.frame_data[ jinfo.start_index + j++ ];
485                if ( jinfo.flags & 32 ) animated_joint.orient.z = frame_data.frame_data[ jinfo.start_index + j++ ];
486
487                unit_quat_w( animated_joint.orient );
488
489                if ( animated_joint.parent >= 0 ) // Has a parent joint
490                {
491                        md5_skeleton_joint& pjoint = skeleton.joints[animated_joint.parent];
492                        glm::vec3 rot_pos = pjoint.orient * animated_joint.pos;
493
494                        animated_joint.pos    = pjoint.pos + rot_pos;
495                        animated_joint.orient = pjoint.orient * animated_joint.orient;
496
497                        animated_joint.orient = glm::normalize( animated_joint.orient );
498                }
499
500                skeleton.joints.push_back( animated_joint );
501        }
502
503        skeletons.push_back( skeleton );
504}
505
506void md5_animation::interpolate_skeletons( md5_frame_skeleton& final_skeleton, const md5_frame_skeleton& skeleton0, const md5_frame_skeleton& skeleton1, float interpolate )
507{
508        for ( int i = 0; i < m_num_joints; ++i )
509        {
510                md5_skeleton_joint& final_joint = final_skeleton.joints[i];
511                const md5_skeleton_joint& joint0 = skeleton0.joints[i];
512                const md5_skeleton_joint& joint1 = skeleton1.joints[i];
513
514                final_joint.parent = joint0.parent;
515
516                final_joint.pos    = glm::mix( joint0.pos, joint1.pos, interpolate );
517                final_joint.orient = glm::mix( joint0.orient, joint1.orient, interpolate );
518        }
519}
520
521bool md5_loader::check_animation( const md5_animation& animation ) const
522{
523        if ( m_num_joints != animation.get_num_joints() )
524        {
525                return false;
526        }
527
528        for ( uint32 i = 0; i < m_joints.size(); ++i )
529        {
530                const md5_joint& mjoint = m_joints[i];
531                const md5_animation::md5_joint_info& ajoint = animation.get_joint_info( i );
532
533                if ( mjoint.name != ajoint.name || mjoint.parent_id != ajoint.parent_id )
534                {
535                        return false;
536                }
537        }
538
539        return true;
540}
541
542bool md5_loader::prepare_animated_mesh( md5_mesh& mesh, const md5_animation::md5_frame_skeleton& skel )
543{
544        for ( unsigned int i = 0; i < mesh.verts.size(); ++i )
545        {
546                const md5_vertex& vert = mesh.verts[i];
547                glm::vec3& pos     = mesh.position_buffer[i];
548                glm::vec3& normal  = mesh.normal_buffer[i];
549                glm::vec3& tangent = mesh.tangent_buffer[i];
550
551                pos     = glm::vec3(0);
552                normal  = glm::vec3(0);
553                tangent = glm::vec3(0);
554
555                for ( int j = 0; j < vert.weight_count; ++j )
556                {
557                        const md5_weight& weight = mesh.weights[vert.start_weight + j];
558                        const md5_animation::md5_skeleton_joint& joint = skel.joints[weight.joint_id];
559
560                        glm::vec3 rot_pos = joint.orient * weight.pos;
561                        pos += ( joint.pos + rot_pos ) * weight.bias;
562
563                        normal  += ( joint.orient * vert.normal  ) * weight.bias;
564                        tangent += ( joint.orient * vert.tangent ) * weight.bias;
565                }
566        }
567        return true;
568}
569
570void md5_loader::apply( const md5_animation& animation )
571{
572        const md5_animation::md5_frame_skeleton& skeleton = animation.get_skeleton();
573
574        for ( unsigned int i = 0; i < m_meshes.size(); ++i )
575        {
576                prepare_animated_mesh( m_meshes[i], skeleton );
577        }
578}
579
580size_t nv::md5_loader::get_size()
581{
582        return m_size;
583}
Note: See TracBrowser for help on using the repository browser.