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

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