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

Last change on this file since 413 was 413, checked in by epyon, 10 years ago
  • data_descriptor creators ( buggy )
File size: 15.3 KB
RevLine 
[395]1// Copyright (C) 2012-2015 ChaosForge Ltd
2// http://chaosforge.org/
3//
4// This file is part of Nova libraries.
5// For conditions of distribution and use, see copying.txt file in root folder.
[190]6
7#include "nv/formats/md5_loader.hh"
8
[319]9#include "nv/core/logging.hh"
[392]10#include "nv/stl/vector.hh"
[190]11#include "nv/io/std_stream.hh"
12
[401]13#include <stdio.h>  // sscanf
14#include <stdlib.h> // atof
15
[190]16using namespace nv;
17
18static void next_line( std::istream& stream )
19{
[367]20        stream.ignore( 1024*1024, '\n' );
[190]21}
22
23static inline void discard( std::istream& stream, const std::string& token )
24{
25        std::string discarded;
26        stream >> discarded;
27        assert( discarded == token );
28}
29
30static void remove_quotes( std::string& str )
31{
[376]32        nv::size_t n;
[190]33        while ( ( n = str.find('\"') ) != std::string::npos ) str.erase(n,1);
34}
35
[398]36static void unit_quat_w( nv::quat& quat )
[190]37{
38        float t = 1.0f - ( quat.x * quat.x ) - ( quat.y * quat.y ) - ( quat.z * quat.z );
39        quat.w = ( t < 0.0f ? 0.0f : -sqrtf(t) );
40}
41
42bool md5_loader::load( stream& source )
43{
[289]44        reset();
[190]45        std_stream sstream( &source );
46        std::string command;
[289]47        mesh_node_data* nodes = nullptr;
48        size_t num_joints = 0;
49
50        // MESH data
[261]51        dynamic_array< md5_weight > weights;
52        dynamic_array< md5_weight_info > weight_info;
[289]53        size_t num_meshes = 0;
[190]54
[289]55        // MESH data
[383]56        dynamic_array< md5_joint_info > joint_infos;
57        vector< transform >             base_frames;
[289]58        size_t num_animated_components = 0;
59        size_t frame_rate = 0;
60        size_t num_frames = 0;
61
[190]62        sstream >> command;
63        while ( !sstream.eof() )
64        {
65                if ( command == "MD5Version" )
66                {
67                        sstream >> m_md5_version;
68                        assert( m_md5_version == 10 );
69                }
70                else if ( command == "commandline" )
71                {
72                        next_line( sstream );
73                }
74                else if ( command == "numJoints" )
75                {
[289]76                        sstream >> num_joints;
77                        next_line( sstream );
[190]78                }
79                else if ( command == "numMeshes" )
80                {
[289]81                        assert( m_type == UNKNOWN );
82                        m_type = MESH;
83                        sstream >> num_meshes;
84                        m_meshes.resize( num_meshes );
85                        num_meshes = 0;
[190]86                }
[289]87                else if ( command == "numFrames" )
88                {
89                        assert( m_type == UNKNOWN || m_type == ANIMATION );
90                        m_type = ANIMATION;
91                        sstream >> num_frames;
92                        next_line( sstream );
93                }
94                else if ( command == "frameRate" )
95                {
96                        assert( m_type == UNKNOWN || m_type == ANIMATION );
97                        m_type = ANIMATION;
98                        sstream >> frame_rate;
99                        next_line( sstream );
100                }
101                else if ( command == "numAnimatedComponents" )
102                {
103                        assert( m_type == UNKNOWN || m_type == ANIMATION );
104                        m_type = ANIMATION;
105                        sstream >> num_animated_components;
106                        next_line( sstream );
107                }
[190]108                else if ( command == "joints" )
109                {
[289]110                        assert( m_type == MESH );
111                        assert( m_nodes == nullptr );
112                        nodes = new mesh_node_data[ num_joints ];
113                        m_nodes = new mesh_nodes_data( "md5_bones", num_joints, nodes );
[190]114                        discard( sstream, "{" );
[289]115                        for ( size_t i = 0; i < m_nodes->get_count(); ++i )
[190]116                        {
[289]117                                sstream >> nodes[i].name >> nodes[i].parent_id;
118                                vec3 pos;
119                                quat orient;
[190]120                                discard( sstream, "(" );
[289]121                                sstream >> pos.x >> pos.y >> pos.z;
[190]122                                discard( sstream, ")" );
123                                discard( sstream, "(" );
[289]124                                sstream >> orient.x >> orient.y >> orient.z;
125                                unit_quat_w( orient );
126                                remove_quotes( nodes[i].name );
127                                nodes[i].target_id       = -1;
128                                nodes[i].parent_id       = -1;
129                                nodes[i].transform       = transform( pos, orient ).inverse().extract();
130                                nodes[i].data            = nullptr;
[190]131                                next_line( sstream );
132                        }
133                        discard( sstream, "}" );
134                }
135                else if ( command == "mesh" )
136                {
[289]137                        assert( m_type == MESH );
[287]138                        mesh_data* mesh = new mesh_data("md5_mesh");
[412]139                        raw_data_channel* ch_pntiw = nullptr;
[239]140
[323]141                        uint32 num_verts   = 0;
142                        uint32 num_tris    = 0;
143                        uint32 num_weights = 0;
[190]144
145                        discard( sstream, "{" );
146                        sstream >> command;
147                        while ( command != "}" )
148                        {
149                                if ( command == "shader" )
150                                {
[287]151                                        std::string shader;
152                                        sstream >> shader;
153                                        remove_quotes( shader );
[190]154                                        next_line( sstream );
155                                }
156                                else if ( command == "numverts")
157                                {
158                                        sstream >> num_verts;
[239]159
[287]160                                        md5_vtx_t* tdata = nullptr;
[239]161                                        {
[413]162                                                data_channel_creator<md5_vtx_pnt> ch_pnt( num_verts );
163                                                data_channel_creator<md5_vtx_t>   ch_t( num_verts );
[412]164                                                ch_pntiw = raw_data_channel::create<md5_vtx_pntiw>( num_verts );
[413]165                                                tdata = ch_t.data();
166                                                mesh->add_channel( ch_pnt.release() );
167                                                mesh->add_channel( ch_t.release() );
[287]168                                                // TODO: hack to prevent rendering
[412]169                                                //ch_pntiw->m_count = 0;
[287]170                                                mesh->add_channel( ch_pntiw );
[239]171                                        }
[259]172                                        weight_info.resize( num_verts );
[239]173
[190]174                                        next_line( sstream );
[226]175                                        std::string line;
[323]176                                        for ( uint32 i = 0; i < num_verts; ++i )
[190]177                                        {
[239]178                                                size_t weight_count;
179                                                size_t start_weight;
180                                                vec2 texcoord;
[190]181
[226]182                                                std::getline( sstream, line );
[239]183                                                sscanf( line.c_str(), "%*s %*u ( %f %f ) %u %u", &(texcoord.x), &(texcoord.y), &(start_weight), &(weight_count) );
[259]184                                                weight_info[i].start_weight = start_weight;
185                                                weight_info[i].weight_count = weight_count;
[287]186                                                tdata[i].texcoord = texcoord;
[190]187                                        } 
188                                }
189                                else if ( command == "numtris" )
190                                {
191                                        sstream >> num_tris;
[239]192
[413]193                                        data_channel_creator< index_u32 > ch_i( num_tris * 3 );
194                                        uint32* vtx_i                = reinterpret_cast< uint32* >( ch_i.raw_data() );
[239]195                                        uint32 idx = 0;
196
[190]197                                        next_line( sstream );
[226]198                                        std::string line;
[323]199                                        for ( uint32 i = 0; i < num_tris; ++i )
[190]200                                        {
[406]201                                                unsigned ti0;
202                                                unsigned ti1;
203                                                unsigned ti2;
[190]204
[226]205                                                std::getline( sstream, line );
[239]206                                                sscanf( line.c_str(), "%*s %*u %u %u %u )", &(ti0), &(ti1), &(ti2));
[226]207
[406]208                                                vtx_i[idx++] = ti0;
209                                                vtx_i[idx++] = ti1;
210                                                vtx_i[idx++] = ti2;
[190]211                                        }             
[413]212
213                                        mesh->add_channel( ch_i.release() );
[190]214                                }
215                                else if ( command == "numweights" )
216                                {
217                                        sstream >> num_weights;
[261]218                                        weights.resize( num_weights );
[190]219                                        next_line( sstream );
[226]220                                        std::string line;
[323]221                                        for ( uint32 i = 0; i < num_weights; ++i )
[190]222                                        {
223                                                md5_weight weight;
[226]224
225                                                std::getline( sstream, line );
226                                                sscanf( line.c_str(), "%*s %*u %u %f ( %f %f %f )", &(weight.joint_id), &(weight.bias), &(weight.pos.x), &(weight.pos.y), &(weight.pos.z));
[261]227                                                weights[i] = weight;
[190]228                                        }
229                                }
230                                else
231                                {
232                                        next_line( sstream );
233                                }
234
235                                sstream >> command;
236                        }
237
[413]238                        prepare_mesh( reinterpret_cast< md5_vtx_pntiw* >( const_cast< uint8* >( ch_pntiw->raw_data() ) ), nodes, weight_info.size(), mesh, weights.data(), weight_info.data() );
[190]239
[289]240                        m_meshes[ num_meshes ] = mesh;
241                        num_meshes++;
242                } // mesh
243                else if ( command == "hierarchy" )
244                {
245                        assert( m_type == ANIMATION );
246                        assert( nodes == nullptr );
247                        nodes = new mesh_node_data[ num_joints ];
[406]248                        m_nodes = new mesh_nodes_data( "md5_animation", num_joints, nodes, static_cast< nv::uint16 >( frame_rate ), static_cast< float >( num_frames ), true );
[289]249                        joint_infos.resize( num_joints );
250
251                        discard( sstream, "{" );
252                        for ( size_t i = 0; i < m_nodes->get_count(); ++i )
253                        {
254                                std::string    name;
255                                sstream >> nodes[i].name >> nodes[i].parent_id >> joint_infos[i].flags >> joint_infos[i].start_index;
256                                remove_quotes( name );
257                                nodes[i].transform = mat4();
258                                nodes[i].target_id = -1;
259                                nodes[i].data      = new key_data;
[411]260                                nodes[i].data->add_channel( raw_data_channel::create< md5_key_t >( num_frames ) );
[289]261                                next_line( sstream );
262                        }
263                        discard( sstream, "}" );
[190]264                }
[289]265                else if ( command == "bounds" )
266                {
267                        assert( m_type == ANIMATION );
268                        discard( sstream, "{" );
269                        next_line( sstream );
270                        for ( size_t i = 0; i < num_frames; ++i )
271                        {
272                                //                              vec3 min;
273                                //                              vec3 max;
274                                //                              discard( sstream, "(" );
275                                //                              sstream >> min.x >> min.y >> min.z;
276                                //                              discard( sstream, ")" );
277                                //                              discard( sstream, "(" );
278                                //                              sstream >> max.x >> max.y >> max.z;
279                                //                              m_bounds.push_back( bound );
280                                next_line( sstream );
281                        }
282
283                        discard( sstream, "}" );
284                        next_line( sstream );
285                }
286                else if ( command == "baseframe" )
287                {
288                        assert( m_type == ANIMATION );
289                        discard( sstream, "{" );
290                        next_line( sstream );
291
292                        for ( size_t i = 0; i < m_nodes->get_count(); ++i )
293                        {
294                                transform base_frame;
295                                vec3 pos;
296                                quat orient;
297                                discard( sstream, "(" );
298                                sstream >> pos.x >> pos.y >> pos.z;
299                                discard( sstream, ")" );
300                                discard( sstream, "(" );
301                                sstream >> orient.x >> orient.y >> orient.z;
302                                next_line( sstream );
303
304                                base_frames.emplace_back( pos, orient );
305                        }
306                        discard( sstream, "}" );
307                        next_line( sstream );
308                }
309                else if ( command == "frame" )
310                {
[383]311                        vector<float> frame;
[289]312                        uint32 frame_id;
313                        sstream >> frame_id;
314                        discard( sstream, "{" );
315                        next_line( sstream );
316
317                        frame.reserve( num_animated_components );
318                        char buf[50];
319                        for ( size_t i = 0; i < num_animated_components; ++i )
320                        {
321                                sstream >> buf;
[406]322                                frame.push_back( static_cast< float >( atof(buf) ) );
[289]323                        }
324
325                        build_frame_skeleton( nodes, frame_id, joint_infos, base_frames, frame );
326
327                        discard( sstream, "}" );
328                        next_line( sstream );
329                }
330
[190]331                sstream >> command;
332        }
333
334        return true;
335}
336
[412]337bool md5_loader::prepare_mesh( md5_vtx_pntiw* vtx_data, mesh_node_data* nodes, uint32 vtx_count, mesh_data* mdata, md5_weight* weights, md5_weight_info* weight_info )
[190]338{
[289]339        assert( m_type == MESH );
[413]340        data_channel_creator< md5_vtx_pnt > pnt( const_cast< raw_data_channel* >( mdata->get_channel< md5_vtx_pnt >() ) );
341        md5_vtx_pnt* vtcs       = pnt.data();
[190]342
[239]343        for ( uint32 i = 0; i < vtx_count; ++i )
[190]344        {
[259]345                size_t start_weight = weight_info[i].start_weight;
346                size_t weight_count = weight_info[i].weight_count;
[287]347                md5_vtx_pntiw& vdata = vtx_data[i];
[239]348                md5_vtx_pnt& vtc = vtcs[i];
[190]349
[398]350                vtc.position = vec3(0);
351                vtc.normal   = vec3(0);
352                vtc.tangent  = vec3(0);
[190]353
[374]354                stable_sort( weights + start_weight, weights + start_weight + weight_count, [] ( const md5_weight& a, const md5_weight& b ) -> bool { return a.bias > b.bias; } );
355                //std::sort( weights + start_weight, weights + start_weight + weight_count, [](const md5_weight& a, const md5_weight& b) -> bool { return a.bias > b.bias; } );
[258]356
[259]357                if ( weight_count > 4 )
[258]358                {
359                        float sum = 0.0f;
360                        for ( size_t j = 0; j < 4; ++j )
361                        {
[259]362                                sum += weights[start_weight + j].bias;
[258]363                        }
364                        float ratio = 1.0f / sum;
365                        for ( size_t j = 0; j < 4; ++j )
366                        {
[259]367                                weights[start_weight + j].bias = ratio * weights[start_weight + j].bias;
[258]368                        }
[259]369                        weight_count = 4;
[258]370                }
371
[406]372                for ( int j = 0; j < 4; ++j )
[190]373                {
[406]374                        if ( j < int(weight_count) )
[259]375                        {
[406]376                                vdata.boneindex[j]  = int( weights[int(start_weight) + j].joint_id );
377                                vdata.boneweight[j] = weights[int(start_weight) + j].bias;
[259]378                        }
379                        else
380                        {
381                                vdata.boneindex[j]  = 0;
382                                vdata.boneweight[j] = 0.0f;
383                        }
384                }
[190]385
[259]386                for ( size_t j = 0; j < 4; ++j )
387                {
388                        if ( j < weight_count )
389                        {
[289]390                                md5_weight& weight           = weights[start_weight + j];
391                                const mesh_node_data&  joint = nodes[weight.joint_id];
392                                const transform tr = transform( joint.transform ).inverse();
[398]393                                vec3 rot_pos = tr.get_orientation() * weight.pos;
[190]394
[289]395                                vtc.position += ( tr.get_position() + rot_pos ) * weight.bias;
[259]396                        }
[190]397                }
398        }
399
[413]400        const uint32*    idata = reinterpret_cast< uint32* >( const_cast< uint8* >( mdata->get_index_channel()->raw_data() ) );
[287]401        const md5_vtx_t* tdata = mdata->get_channel_data<md5_vtx_t>();
402
[239]403        // Prepare normals
404        uint32 tri_count = mdata->get_count() / 3;
405        for ( unsigned int i = 0; i < tri_count; ++i )
[190]406        {
[287]407                uint32 ti0 = idata[ i * 3 ];
408                uint32 ti1 = idata[ i * 3 + 1 ];
409                uint32 ti2 = idata[ i * 3 + 2 ];
[239]410 
[398]411                vec3 v1 = vtcs[ ti0 ].position;
412                vec3 v2 = vtcs[ ti1 ].position;
413                vec3 v3 = vtcs[ ti2 ].position;
414                vec3 xyz1 = v3 - v1;
415                vec3 xyz2 = v2 - v1;
[190]416
[398]417                vec3 normal = glm::cross( xyz1, xyz2 );
[190]418
[239]419                vtcs[ ti0 ].normal += normal;
420                vtcs[ ti1 ].normal += normal;
421                vtcs[ ti2 ].normal += normal;
[190]422
[287]423                const vec2& w1 = tdata[ ti0 ].texcoord;
424                const vec2& w2 = tdata[ ti1 ].texcoord;
425                const vec2& w3 = tdata[ ti2 ].texcoord;
[190]426
427                vec2 st1 = w3 - w1;
428                vec2 st2 = w2 - w1;
429
430                float coef = 1.0f / (st1.x * st2.y - st2.x * st1.y);
431
432                vec3 tangent = (( xyz1 * st2.y ) - ( xyz2 * st1.y )) * coef;
433
[239]434                vtcs[ ti0 ].tangent += tangent;
435                vtcs[ ti1 ].tangent += tangent;
436                vtcs[ ti2 ].tangent += tangent;
[190]437        }
438
[239]439        for ( size_t i = 0; i < vtx_count; ++i )
[190]440        {
[287]441                md5_vtx_pntiw& vdata = vtx_data[i];
[190]442
[398]443                vec3 normal  = glm::normalize( vtcs[i].normal );
444                vec3 tangent = glm::normalize( vtcs[i].tangent );
[239]445                vtcs[i].normal   = normal;
446                vtcs[i].tangent  = tangent;
[190]447
[259]448                vdata.position = vtcs[i].position;
[398]449                vdata.normal   = vec3(0);
450                vdata.tangent  = vec3(0);
[239]451 
[406]452                for ( int j = 0; j < 4; ++j )
[239]453                {
[289]454                        const mesh_node_data&  joint = nodes[vdata.boneindex[j]];
455                        const transform tr = transform( joint.transform ).inverse();
456                        vdata.normal  += ( normal  * tr.get_orientation() ) * vdata.boneweight[j];
457                        vdata.tangent += ( tangent * tr.get_orientation() ) * vdata.boneweight[j];
[239]458                }
[190]459        }
460
461        return true;
462}
463
[399]464void md5_loader::build_frame_skeleton( mesh_node_data* nodes, uint32 index, const array_view<md5_joint_info>& joint_infos, const array_view<transform>& base_frames, const array_view<float>& frame_data )
[191]465{
[289]466        assert( m_type == ANIMATION );
[191]467        for ( unsigned int i = 0; i < joint_infos.size(); ++i )
468        {
469                unsigned int j = 0;
470
471                const md5_joint_info& jinfo = joint_infos[i];
[289]472                mesh_node_data& joint = nodes[i];
473                int parent_id         = joint.parent_id;
[191]474
[241]475                vec3 pos    = base_frames[i].get_position();
476                quat orient = base_frames[i].get_orientation();
477                if ( jinfo.flags & 1 )  pos.x    = frame_data[ jinfo.start_index + j++ ];
478                if ( jinfo.flags & 2 )  pos.y    = frame_data[ jinfo.start_index + j++ ];
479                if ( jinfo.flags & 4 )  pos.z    = frame_data[ jinfo.start_index + j++ ];
480                if ( jinfo.flags & 8 )  orient.x = frame_data[ jinfo.start_index + j++ ];
481                if ( jinfo.flags & 16 ) orient.y = frame_data[ jinfo.start_index + j++ ];
482                if ( jinfo.flags & 32 ) orient.z = frame_data[ jinfo.start_index + j++ ];
483                unit_quat_w( orient );
[191]484
[241]485                if ( parent_id >= 0 ) // Has a parent joint
[191]486                {
[289]487                        const mesh_node_data& pjoint = nodes[parent_id];
[413]488                        const transform* ptv = reinterpret_cast< const transform* >( pjoint.data->get_channel(0)->raw_data() );
[241]489                        transform ptr;
[412]490                        if ( pjoint.data->get_channel(0)->element_count() > index ) ptr = ptv[ index ];
[398]491                        vec3 rot_pos = ptr.get_orientation() * pos;
[191]492
[241]493                        pos    = ptr.get_position() + rot_pos;
494                        orient = ptr.get_orientation() * orient;
[191]495
[241]496                        orient = glm::normalize( orient );
[191]497                }
498
[413]499                reinterpret_cast< transform* >( const_cast< uint8* >( joint.data->get_channel(0)->raw_data() ) )[index] = transform( pos, orient );
[191]500        }
[241]501}
[191]502
[241]503mesh_data* nv::md5_loader::release_mesh_data( size_t index )
504{
505        mesh_data* result = m_meshes[ index ];
506        m_meshes[ index ] = nullptr;
507        return result;
[191]508}
509
[291]510mesh_nodes_data* nv::md5_loader::release_mesh_nodes_data( size_t )
[191]511{
[289]512        mesh_nodes_data* nodes = m_nodes;
513        m_nodes = nullptr;
514        return nodes;
[191]515}
516
[287]517mesh_data_pack* nv::md5_loader::release_mesh_data_pack()
[191]518{
[287]519        uint32 size = m_meshes.size();
520        mesh_data* meshes = new mesh_data[ size ];
521        for ( uint32 i = 0; i < size; ++i )
522        {
523                m_meshes[i]->move_to( meshes[i] );
524                delete m_meshes[i];
525                m_meshes[i] = nullptr;
526        }
527        return new mesh_data_pack( size, meshes, release_mesh_nodes_data() );
[191]528}
529
[287]530
531nv::md5_loader::~md5_loader()
[191]532{
[289]533        reset();
534}
535
536void nv::md5_loader::reset()
537{
538        if ( m_nodes ) delete m_nodes;
[287]539        for ( auto m : m_meshes ) { if (m) delete m; }
[289]540        m_meshes.resize(0);
541        m_nodes = nullptr;
[239]542}
543
Note: See TracBrowser for help on using the repository browser.