Source

ogreassimp / src / AssimpLoader.cpp

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
#include "AssimpLoader.h"
#include "assimp/DefaultLogger.h"
#include "OgreDataStream.h"
#include "OgreImage.h"
#include "OgreTexture.h"
#include "OgreTextureManager.h"
#include "OgreMaterial.h"
#include "OgreMaterialManager.h"
#include "OgreLog.h"
#include "OgreLogManager.h"
#include "OgreHardwareBuffer.h"
#include "OgreMesh.h"
#include "OgreSubMesh.h"
#include "OgreDefaultHardwareBufferManager.h"
#include "OgreMeshManager.h"
#include "OgreSceneManager.h"
#include <OgreStringConverter.h>
#include <OgreSkeletonManager.h>
#include "OgreMeshSerializer.h"
#include "OgreSkeletonSerializer.h"
#include "OgreAnimation.h"
#include "OgreAnimationTrack.h"
#include "OgreKeyFrame.h"
#include <boost/tuple/tuple.hpp>
//#include "OgreXMLSkeletonSerializer.h"

Ogre::String toString(const aiColor4D& colour)
{
    return	Ogre::StringConverter::toString(Ogre::Real(colour.r)) + " " +
    Ogre::StringConverter::toString(Ogre::Real(colour.g)) + " " +
    Ogre::StringConverter::toString(Ogre::Real(colour.b)) + " " +
    Ogre::StringConverter::toString(Ogre::Real(colour.a));
}

int AssimpLoader::msBoneCount = 0;

AssimpLoader::AssimpLoader()
{
    //mSkeletonRootNode = NULL;
}

AssimpLoader::~AssimpLoader()
{
}

bool AssimpLoader::convert(const Ogre::String& filename,
						   const Ogre::String& customAnimationName,
						   int loaderParams,
                           const Ogre::String& filedest,
                           const Ogre::Real animationSpeed)
{
    mLoaderParams = loaderParams;
    mAnimationSpeed = animationSpeed;
    mQuietMode = ((mLoaderParams & LP_QUIET_MODE) == 0) ? false : true;
    mCustomAnimationName = customAnimationName;
	if ((mLoaderParams & LP_USE_LAST_RUN_NODE_DERIVED_TRANSFORMS) == false)
	{
		mNodeDerivedTransformByName.clear();
	}

	Ogre::String extension;
    Ogre::StringUtil::splitFullFilename(filename, mBasename, extension, mPath);
	mBasename = mBasename + "_" + extension;

    if(!filedest.empty())
    {
        mPath = filedest + "/";
    }

    Assimp::DefaultLogger::create("asslogger.log",Assimp::Logger::VERBOSE);
	Assimp::DefaultLogger::get()->info("Logging asses");

    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("*** Loading ass file... ***");
        Ogre::LogManager::getSingleton().logMessage("Filename " + filename);
    }
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(mPath, "FileSystem");
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./resources", "FileSystem");

    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    const aiScene *scene;

    Assimp::Importer importer;
    scene = importer.ReadFile( filename.c_str(), aiProcessPreset_TargetRealtime_Quality | aiProcess_TransformUVCoords | aiProcess_FlipUVs);

    // If the import failed, report it
	if( !scene)
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("AssImp importer failed with the following message:");
            Ogre::LogManager::getSingleton().logMessage(importer.GetErrorString() );
        }
		return false;
	}

    grabNodeNamesFromNode(scene, scene->mRootNode);
    grabBoneNamesFromNode(scene, scene->mRootNode);

	computeNodesDerivedTransform(scene, scene->mRootNode, scene->mRootNode->mTransformation);

    if(mBonesByName.size())
    {
		mSkeleton = Ogre::SkeletonManager::getSingleton().create("conversion", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

		msBoneCount = 0;
		createBonesFromNode(scene, scene->mRootNode);
		msBoneCount = 0;
        createBoneHiearchy(scene, scene->mRootNode);

        if(scene->HasAnimations())
        {
            for(int i = 0; i < scene->mNumAnimations; ++i)
            {
                parseAnimation(scene, i, scene->mAnimations[i]);
            }
        }
    }

    loadDataFromNode(scene, scene->mRootNode, mPath);

    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("*** Finished loading ass file ***");
    }
	Assimp::DefaultLogger::kill();

    if(!mSkeleton.isNull())
    {


		unsigned short numBones = mSkeleton->getNumBones();
        unsigned short i;
        for (i = 0; i < numBones; ++i)
        {
			Ogre::Bone* pBone = mSkeleton->getBone(i);
			assert(pBone);
        }



	    Ogre::SkeletonSerializer binSer;
	    binSer.exportSkeleton(mSkeleton.getPointer(), mPath + mBasename + ".skeleton");
    }

	Ogre::MeshSerializer meshSer;
	for(MeshVector::iterator it = mMeshes.begin(); it != mMeshes.end(); ++it)
	{
		Ogre::MeshPtr mMesh = *it;
		if(mBonesByName.size())
		{
			mMesh->setSkeletonName(mBasename + ".skeleton");
		}

		Ogre::Mesh::SubMeshIterator smIt = mMesh->getSubMeshIterator();
		while (smIt.hasMoreElements())
		{
			Ogre::SubMesh* sm = smIt.getNext();
			if (!sm->useSharedVertices)
			{
				// Automatic
						Ogre::VertexDeclaration* newDcl =
							sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(mMesh->hasSkeleton(), mMesh->hasVertexAnimation(), false); //FIXME: last arg should be false always??
				if (*newDcl != *(sm->vertexData->vertexDeclaration))
				{
					// Usages don't matter here since we're only exporting
					Ogre::BufferUsageList bufferUsages;
					for (size_t u = 0; u <= newDcl->getMaxSource(); ++u)
						bufferUsages.push_back(Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
					sm->vertexData->reorganiseBuffers(newDcl, bufferUsages);
				}
			}
		}
		meshSer.exportMesh(mMesh.getPointer(), mPath + mBasename + ".mesh");
	}



    // serialise the materials
    if((mLoaderParams & LP_GENERATE_MATERIALS_AS_CODE) == 0)
	{
		Ogre::MaterialSerializer ms;
		std::vector<Ogre::String> exportedNames;

		for(MeshVector::iterator it = mMeshes.begin(); it != mMeshes.end(); ++it)
		{
			Ogre::MeshPtr mMesh = *it;

			// queue up the materials for serialise
			Ogre::MaterialManager *mmptr = Ogre::MaterialManager::getSingletonPtr();
			Ogre::Mesh::SubMeshIterator smIt = mMesh->getSubMeshIterator();
			while(smIt.hasMoreElements())
			{
				Ogre::SubMesh* sm = smIt.getNext();
				Ogre::String matName(sm->getMaterialName());
				if (std::find(exportedNames.begin(), exportedNames.end(), matName) == exportedNames.end())
				{
					Ogre::MaterialPtr materialPtr = mmptr->getByName(matName);
					ms.queueForExport(materialPtr);
					exportedNames.push_back(matName);
				}
			}
		}

		if(exportedNames.size())
		{
			ms.exportQueued(mPath + mBasename + ".material", true);
		}
	}
	else
	{
		std::ofstream stream;
		stream.open( (mPath + mBasename + ".material").c_str(), std::ios::out | std::ios::binary);
		//stream << "import * from base.material\n\n";
		stream << mMaterialCode;
		stream.close();
	}


	// clean up
	mMeshes.clear();
	mMaterialCode = "";
	mBonesByName.clear();
	mBoneNodesByName.clear();
	boneMap.clear();
	mSkeleton = Ogre::SkeletonPtr(NULL);
	mCustomAnimationName = "";
	// etc...

	Ogre::MeshManager::getSingleton().removeUnreferencedResources();
	Ogre::SkeletonManager::getSingleton().removeUnreferencedResources();

	return true;
}





typedef boost::tuple< aiVectorKey*, aiQuatKey*, aiVectorKey* > KeyframeData;
typedef std::map< float, KeyframeData > KeyframesMap;

template <int v>
struct Int2Type
{
	enum { value = v };
};

// T should be a Loki::Int2Type<>
template< typename T > void GetInterpolationIterators(KeyframesMap& keyframes,
													  KeyframesMap::iterator it,
													  KeyframesMap::reverse_iterator& front,
													  KeyframesMap::iterator& back)
{
	front = KeyframesMap::reverse_iterator(it);

	front++;
	for(front; front != keyframes.rend(); front++)
	{
		if(boost::get< T::value >(front->second) != NULL)
		{
			break;
		}
	}

	back = it;
	back++;
	for(back; back != keyframes.end(); back++)
	{
		if(boost::get< T::value >(back->second) != NULL)
		{
			break;
		}
	}
}

aiVector3D getTranslate(aiNodeAnim* node_anim, KeyframesMap& keyframes, KeyframesMap::iterator it)
{
	aiVectorKey* translateKey = boost::get<0>(it->second);
	aiVector3D vect;
	if(translateKey)
	{
		vect = translateKey->mValue;
	}
	else
	{
		KeyframesMap::reverse_iterator front;
		KeyframesMap::iterator back;


		GetInterpolationIterators< Int2Type<0> > (keyframes, it, front, back);

		KeyframesMap::reverse_iterator rend = keyframes.rend();
		KeyframesMap::iterator end = keyframes.end();
		aiVectorKey* frontKey = NULL;
		aiVectorKey* backKey = NULL;

		if(front != rend)
			frontKey = boost::get<0>(front->second);

		if(back != end)
			backKey = boost::get<0>(back->second);

		// got 2 keys can interpolate
		if(frontKey && backKey)
		{
			float prop = (it->first - frontKey->mTime) / (backKey->mTime - frontKey->mTime);
			vect = ((backKey->mValue - frontKey->mValue) * prop) + frontKey->mValue;
		}

		else if(frontKey)
		{
			vect = frontKey->mValue;
		}
		else if(backKey)
		{
			vect = backKey->mValue;
		}
	}

	return vect;
}

aiQuaternion getRotate(aiNodeAnim* node_anim, KeyframesMap& keyframes, KeyframesMap::iterator it)
{
	aiQuatKey* rotationKey = boost::get<1>(it->second);
	aiQuaternion rot;
	if(rotationKey)
	{
		rot = rotationKey->mValue;
	}
	else
	{
		KeyframesMap::reverse_iterator front;
		KeyframesMap::iterator back;

		GetInterpolationIterators< Int2Type<1> > (keyframes, it, front, back);

		KeyframesMap::reverse_iterator rend = keyframes.rend();
		KeyframesMap::iterator end = keyframes.end();
		aiQuatKey* frontKey = NULL;
		aiQuatKey* backKey = NULL;

		if(front != rend)
			frontKey = boost::get<1>(front->second);

		if(back != end)
			backKey = boost::get<1>(back->second);

		// got 2 keys can interpolate
		if(frontKey && backKey)
		{
			float prop = (it->first - frontKey->mTime) / (backKey->mTime - frontKey->mTime);
			aiQuaternion::Interpolate(rot, frontKey->mValue, backKey->mValue, prop);
		}

		else if(frontKey)
		{
			rot = frontKey->mValue;
		}
		else if(backKey)
		{
			rot = backKey->mValue;
		}
	}

	return rot;
}

void AssimpLoader::parseAnimation (const aiScene* mScene, int index, aiAnimation* anim)
{
    //TODO: use mAnimationSpeed to scale the animation speed!

    // DefBonePose a matrix that represents the local bone transform (can build from Ogre bone components)
	// PoseToKey a matrix representing the keyframe translation
	// What assimp stores aiNodeAnim IS the decomposed form of the transform (DefBonePose * PoseToKey)
	// To get PoseToKey which is what Ogre needs we'ed have to build the transform from components in
	// aiNodeAnim and then DefBonePose.Inverse() * aiNodeAnim(generated transform) will be the right transform

    Ogre::String animName;
	if(mCustomAnimationName != "")
	{
		animName = mCustomAnimationName;
		if(index >= 1)
		{
			animName += Ogre::StringConverter::toString(index);
		}
	}
	else
	{
		animName = Ogre::String(anim->mName.data);
	}
	if(animName.length() < 1)
    {
        animName = "Animation" + Ogre::StringConverter::toString(index);
    }

    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("Animation name = '" + animName + "'");
        Ogre::LogManager::getSingleton().logMessage("duration = " + Ogre::StringConverter::toString(Ogre::Real(anim->mDuration)));
        Ogre::LogManager::getSingleton().logMessage("tick/sec = " + Ogre::StringConverter::toString(Ogre::Real(anim->mTicksPerSecond)));
        Ogre::LogManager::getSingleton().logMessage("channels = " + Ogre::StringConverter::toString(anim->mNumChannels));
    }
	Ogre::Animation* animation;

	float cutTime = 0.0;
	if(mLoaderParams & LP_CUT_ANIMATION_WHERE_NO_FURTHER_CHANGE)
	{
		for (int i = 1; i < (int)anim->mNumChannels; i++)
		{
			aiNodeAnim* node_anim = anim->mChannels[i];

			// times of the equality check
			float timePos = 0.0;
			float timeRot = 0.0;

			for(int i = 1; i < node_anim->mNumPositionKeys; i++)
			{
				if( node_anim->mPositionKeys[i] != node_anim->mPositionKeys[i-1])
				{
					timePos = node_anim->mPositionKeys[i].mTime;
				}
			}

			for(int i = 1; i < node_anim->mNumRotationKeys; i++)
			{
				if( node_anim->mRotationKeys[i] != node_anim->mRotationKeys[i-1])
				{
					timeRot = node_anim->mRotationKeys[i].mTime;
				}
			}

			if(timePos > cutTime){ cutTime = timePos; }
			if(timeRot > cutTime){ cutTime = timeRot; }
		}

		animation = mSkeleton->createAnimation(Ogre::String(animName), Ogre::Real(cutTime));
	}
	else
	{
		cutTime = Ogre::Math::POS_INFINITY;
		animation = mSkeleton->createAnimation(Ogre::String(animName), Ogre::Real(anim->mDuration));
	}

	animation->setInterpolationMode(Ogre::Animation::IM_LINEAR);

    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("Cut Time " + Ogre::StringConverter::toString(cutTime));
    }

    for (int i = 0; i < (int)anim->mNumChannels; i++)
    {
        Ogre::TransformKeyFrame* keyframe;

        aiNodeAnim* node_anim = anim->mChannels[i];
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("Channel " + Ogre::StringConverter::toString(i));
            Ogre::LogManager::getSingleton().logMessage("affecting node: " + Ogre::String(node_anim->mNodeName.data));
            //Ogre::LogManager::getSingleton().logMessage("position keys: " + Ogre::StringConverter::toString(node_anim->mNumPositionKeys));
            //Ogre::LogManager::getSingleton().logMessage("rotation keys: " + Ogre::StringConverter::toString(node_anim->mNumRotationKeys));
            //Ogre::LogManager::getSingleton().logMessage("scaling keys: " + Ogre::StringConverter::toString(node_anim->mNumScalingKeys));
        }

        Ogre::String boneName = Ogre::String(node_anim->mNodeName.data);

        if(mSkeleton->hasBone(boneName))
        {
			Ogre::Bone* bone = mSkeleton->getBone(boneName);
			Ogre::Matrix4 defBonePoseInv;
			defBonePoseInv.makeInverseTransform(bone->getPosition(), bone->getScale(), bone->getOrientation());

			Ogre::NodeAnimationTrack* track = animation->createNodeTrack(i, bone);

			// Ogre needs translate rotate and scale for each keyframe in the track
			KeyframesMap keyframes;

			for(int i = 0; i < node_anim->mNumPositionKeys; i++)
			{
				keyframes[ node_anim->mPositionKeys[i].mTime ] = KeyframeData( &(node_anim->mPositionKeys[i]), NULL, NULL);
			}

			for(int i = 0; i < node_anim->mNumRotationKeys; i++)
			{
				KeyframesMap::iterator it = keyframes.find(node_anim->mRotationKeys[i].mTime);
				if(it != keyframes.end())
				{
					boost::get<1>(it->second) = &(node_anim->mRotationKeys[i]);
				}
				else
				{
					keyframes[ node_anim->mRotationKeys[i].mTime ] = KeyframeData( NULL, &(node_anim->mRotationKeys[i]), NULL );
				}
			}

			for(int i = 0; i < node_anim->mNumScalingKeys; i++)
			{
				KeyframesMap::iterator it = keyframes.find(node_anim->mScalingKeys[i].mTime);
				if(it != keyframes.end())
				{
					boost::get<2>(it->second) = &(node_anim->mScalingKeys[i]);
				}
				else
				{
					keyframes[ node_anim->mRotationKeys[i].mTime ] = KeyframeData( NULL, NULL, &(node_anim->mScalingKeys[i]) );
				}
			}

			KeyframesMap::iterator it = keyframes.begin();
			KeyframesMap::iterator it_end = keyframes.end();
			for(it; it != it_end; ++it)
			{
				if(it->first <= cutTime)	// or should it be <=
				{
					aiVector3D aiTrans = getTranslate( node_anim, keyframes, it );

					Ogre::Vector3 trans(aiTrans.x, aiTrans.y, aiTrans.z);

					aiQuaternion aiRot = getRotate(node_anim, keyframes, it);
					Ogre::Quaternion rot(aiRot.w, aiRot.x, aiRot.y, aiRot.z);
					Ogre::Vector3 scale(1,1,1);	// ignore scale for now

					Ogre::Vector3 transCopy = trans;

					Ogre::Matrix4 fullTransform;
					fullTransform.makeTransform(trans, scale, rot);

					Ogre::Matrix4 poseTokey = defBonePoseInv * fullTransform;
					poseTokey.decomposition(trans, scale, rot);

					keyframe = track->createNodeKeyFrame(Ogre::Real(it->first));

					// weirdness with the root bone, But this seems to work
					if(mSkeleton->getRootBone()->getName() == boneName)
					{
						trans = transCopy - bone->getPosition();
					}

					keyframe->setTranslate(trans);
					keyframe->setRotation(rot);
				}
			}

        } // if bone exists

    } // loop through channels

    mSkeleton->optimiseAllAnimations();

}



void AssimpLoader::markAllChildNodesAsNeeded(const aiNode *pNode)
{
    flagNodeAsNeeded(pNode->mName.data);
    // Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; ++childIdx )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        markAllChildNodesAsNeeded(pChildNode);
	}
}

void AssimpLoader::grabNodeNamesFromNode(const aiScene* mScene, const aiNode* pNode)
{
	boneNode bNode;
	bNode.node = const_cast<aiNode*>(pNode);
    if(NULL != pNode->mParent)
    {
        bNode.parent = const_cast<aiNode*>(pNode->mParent);
    }
    bNode.isNeeded = false;
	boneMap.insert(std::pair<Ogre::String, boneNode>(Ogre::String(pNode->mName.data), bNode));
    mBoneNodesByName[pNode->mName.data] = pNode;
    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("Node " + Ogre::String(pNode->mName.data) + " found.");
    }

    // Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; ++childIdx )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        grabNodeNamesFromNode(mScene, pChildNode);
	}
}


void AssimpLoader::computeNodesDerivedTransform(const aiScene* mScene,  const aiNode *pNode, const aiMatrix4x4 accTransform)
{
	if(mNodeDerivedTransformByName.find(pNode->mName.data) == mNodeDerivedTransformByName.end())
	{
		mNodeDerivedTransformByName[pNode->mName.data] = accTransform;
	}
	for ( int childIdx=0; childIdx<pNode->mNumChildren; ++childIdx )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        computeNodesDerivedTransform(mScene, pChildNode, accTransform * pChildNode->mTransformation);
	}
}

void AssimpLoader::createBonesFromNode(const aiScene* mScene,  const aiNode *pNode)
{
	if(isNodeNeeded(pNode->mName.data))
    {
		Ogre::Bone* bone = mSkeleton->createBone(Ogre::String(pNode->mName.data), msBoneCount);

		aiQuaternion rot;
	    aiVector3D pos;
	    aiVector3D scale;

		/*
		aiMatrix4x4 aiM = mNodeDerivedTransformByName.find(pNode->mName.data)->second;

		const aiNode* parentNode = NULL;
		{
			boneMapType::iterator it = boneMap.find(pNode->mName.data);
			if(it != boneMap.end())
			{
				parentNode = it->second.parent;
			}
		}
		if(parentNode)
		{
			aiMatrix4x4 aiMParent = mNodeDerivedTransformByName.find(parentNode->mName.data)->second;
			aiM = aiMParent.Inverse() * aiM;
		}
		*/

		// above should be the same as
		aiMatrix4x4 aiM = pNode->mTransformation;

		aiM.Decompose(scale, rot, pos);


		/*
		// debug render
		Ogre::SceneNode* sceneNode = NULL;
		if(parentNode)
		{
			Ogre::SceneNode* parent = static_cast<Ogre::SceneNode*>(
				GOOF::NodeUtils::GetNodeMatch(getSceneManager()->getRootSceneNode(), parentNode->mName.data, false));
			assert(parent);
			sceneNode = parent->createChildSceneNode(pNode->mName.data);
		}
		else
		{
			sceneNode = getSceneManager()->getRootSceneNode()->createChildSceneNode(pNode->mName.data);
		}

		sceneNode->setScale(scale.x, scale.y, scale.z);
		sceneNode->setPosition(pos.x, pos.y, pos.z);
		sceneNode->setOrientation(rot.w, rot.x, rot.y, rot.z);

		sceneNode = sceneNode->createChildSceneNode();
		sceneNode->setScale(0.01, 0.01, 0.01);
		sceneNode->attachObject(getSceneManager()->createEntity("Box1m.mesh"));
		*/

	    if (!aiM.IsIdentity())
	    {
		    bone->setPosition(pos.x, pos.y, pos.z);
		    bone->setOrientation(rot.w, rot.x, rot.y, rot.z);
	    }

        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(msBoneCount) + ") Creating bone '" + Ogre::String(pNode->mName.data) + "'");
        }
        msBoneCount++;
    }
    // Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; ++childIdx )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        createBonesFromNode(mScene, pChildNode);
	}
}

void AssimpLoader::createBoneHiearchy(const aiScene* mScene,  const aiNode *pNode)
{
    if(isNodeNeeded(pNode->mName.data))
    {
		Ogre::Bone* parent = 0;
		Ogre::Bone* child = 0;
        if(pNode->mParent)
        {
		    if(mSkeleton->hasBone(pNode->mParent->mName.data))
		    {
			    parent = mSkeleton->getBone(pNode->mParent->mName.data);
		    }
        }
		if(mSkeleton->hasBone(pNode->mName.data))
		{
			child = mSkeleton->getBone(pNode->mName.data);
		}
		if(parent && child)
		{
			parent->addChild(child);
        }
    }
    // Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; childIdx++ )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        createBoneHiearchy(mScene, pChildNode);
	}
}

void AssimpLoader::flagNodeAsNeeded(const char* name)
{
	boneMapType::iterator iter = boneMap.find(Ogre::String(name));
	if( iter != boneMap.end())
	{
        iter->second.isNeeded = true;
    }
}

bool AssimpLoader::isNodeNeeded(const char* name)
{
	boneMapType::iterator iter = boneMap.find(Ogre::String(name));
	if( iter != boneMap.end())
	{
        return iter->second.isNeeded;
    }
    return false;
}

void AssimpLoader::grabBoneNamesFromNode(const aiScene* mScene,  const aiNode *pNode)
{
	static int meshNum = 0;
	meshNum++;
	if(pNode->mNumMeshes > 0)
	{
		for ( int idx=0; idx<pNode->mNumMeshes; ++idx )
		{
			aiMesh *pAIMesh = mScene->mMeshes[ pNode->mMeshes[ idx ] ];

			if(pAIMesh->HasBones())
			{
	            for ( Ogre::uint32 i=0; i < pAIMesh->mNumBones; ++i )
	            {
		            aiBone *pAIBone = pAIMesh->mBones[ i ];
		            if ( NULL != pAIBone )
		            {
                        mBonesByName[pAIBone->mName.data] = pAIBone;

                        if(!mQuietMode)
                        {
                            Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(i) + ") REAL BONE with name : " + Ogre::String(pAIBone->mName.data));
                        }

                        // flag this node and all parents of this node as needed, until we reach the node holding the mesh, or the parent.
                        aiNode* node = mScene->mRootNode->FindNode(pAIBone->mName.data);
                        while(node)
                        {
                            if(node->mName.data == pNode->mName.data)
                            {
								// flagNodeAsNeeded(node->mName.data);
                                // Set mSkeletonRootNode to this node, which is the same node as the one holding the mesh
                                //mSkeletonRootNode = node;
                                break;
                            }
                            if(node->mName.data == pNode->mParent->mName.data)
                            {
                                //flagNodeAsNeeded(node->mName.data);
                                // Set mSkeletonRootNode to this node, which is the parent node to the node holding the mesh
                                //mSkeletonRootNode = node;
                                break;
                            }

                            // Not a root node, flag this as needed and continue to the parent
                            flagNodeAsNeeded(node->mName.data);
                            node = node->mParent;
                        }

                        // Flag all children of this node as needed
                        node = mScene->mRootNode->FindNode(pAIBone->mName.data);
                        markAllChildNodesAsNeeded(node);

                    } // if we have a valid bone
                } // loop over bones
            } // if this mesh has bones
		} // loop over meshes
	} // if this node has meshes

	// Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; childIdx++ )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
        grabBoneNamesFromNode(mScene, pChildNode);
	}
}

Ogre::String ReplaceSpaces(const Ogre::String& s)
{
	Ogre::String res(s);
	replace(res.begin(), res.end(), ' ', '_');

	return res;
}


Ogre::MaterialPtr AssimpLoader::createMaterialByScript(int index, const aiMaterial* mat)
{
	// Create a material in code as using script inheritance variable substitution and other goodies

	Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr();
	Ogre::String materialName = mBasename + "#" + Ogre::StringConverter::toString(index);
	if(matMgr->resourceExists(materialName))
	{
		Ogre::MaterialPtr matPtr = matMgr->getByName(materialName);
		if(matPtr->isLoaded())
		{
			return matPtr;
		}
	}

	Ogre::String code;

	aiColor4D c;
    if(aiGetMaterialColor(mat, AI_MATKEY_COLOR_AMBIENT,  &c) == aiReturn_SUCCESS)
        code += "\t\t\tambient " + toString(c) + "\n";

    if(aiGetMaterialColor(mat, AI_MATKEY_COLOR_DIFFUSE, &c) == aiReturn_SUCCESS)
        code += "\t\t\tdiffuse " + toString(c) + "\n";

    if(aiGetMaterialColor(mat, AI_MATKEY_COLOR_SPECULAR, &c) == aiReturn_SUCCESS)
        code += "\t\t\tspecular " + toString(c) + "\n";

    if(aiGetMaterialColor(mat, AI_MATKEY_COLOR_EMISSIVE, &c) == aiReturn_SUCCESS)
        code += "\t\t\temmissive " + toString(c) + "\n";


	// Specifies the type of the texture to be retrieved ( e.g. diffuse, specular, height map ...)
	enum aiTextureType type = aiTextureType_DIFFUSE;

	// Index of the texture to be retrieved. The function fails if there is no texture of that type with this index.
	// GetTextureCount() can be used to determine the number of textures per texture type.

	// Receives the path to the texture. NULL is a valid value.
	aiString path;

	// The texture mapping. NULL is allowed as value.
	aiTextureMapping mapping = aiTextureMapping_UV;

	// Receives the UV index of the texture. NULL is a valid value.
	unsigned int uvindex = 0;

	// Receives the blend factor for the texture NULL is a valid value.
	float blend = 1.0f;

	// Receives the texture operation to be performed between this texture and the previous texture. NULL is allowed as value.
	aiTextureOp op = aiTextureOp_Multiply;

	// Receives the mapping modes to be used for the texture. The parameter may be NULL but if it is a valid pointer it
	// MUST point to an array of 3 aiTextureMapMode's (one for each axis: UVW order (=XYZ)).
	aiTextureMapMode mapmode =  aiTextureMapMode_Wrap;

	// For now assuming at most that only one diffuse texture exists
	if (mat->GetTexture(type, 0, &path, &mapping, &uvindex, &blend, &op, &mapmode) == AI_SUCCESS)
	{
		Ogre::String texBasename, texExtention, texPath;
		Ogre::StringUtil::splitFullFilename(Ogre::String(path.data), texBasename, texExtention, texPath);

		Ogre::String texName = texBasename + "." + texExtention;

		//code += "\tset $diffuse_map " + texName + "\n";
        code += "\n\t\t\ttexture_unit\n\t\t\t{\n\t\t\t\ttexture " + texName + "\n";

		int twoSided = 0;
		mat->Get(AI_MATKEY_TWOSIDED, twoSided);
		if(twoSided != 0)
		{
            code += "\t\t\t\tcull_hardware none\n";
		}

		/*
		int blendFunc = 0;
		mat->Get(AI_MATKEY_BLEND_FUNC, blendFunc);
		if(blendFunc != 0)
		{
			assert(false);
		}

		float opacity = 1.0f;
		if(AI_SUCCESS == aiGetMaterialFloat(mat, AI_MATKEY_OPACITY, &opacity) && opacity != 1.0)
		{
			// modify the alpha channel in diffuse?
			//printf("opacity %f\n", opacity);
		}
		*/

		// no infomation on the alpha channel in the texture will have to load the texture and look at it
		code += "\t\t\t}\n";
	}


	//code = "material " + materialName + " : base\n{\n" + code + "}\n\n";
	code = "material " + materialName + "\n{\n\ttechnique\n\t{\n\t\tpass\n\t\t{\n" + code + "\t\t}\n\t}\n}\n\n";
    mMaterialCode += code;

	// compile the material
	//code = "import * from base.material\n" + code;

/*    std::cout << "-------------------------------------------code" << std::endl;
    std::cout << code << std::endl;
    std::cout << "-------------------------------------------code" << std::endl;*/

	Ogre::DataStreamPtr stream(OGRE_NEW Ogre::MemoryDataStream(const_cast<void*>(static_cast<const void*>(code.c_str())),
												   code.length() * sizeof(char), false));
	Ogre::MaterialManager::getSingleton().parseScript(stream, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::MaterialPtr omat = Ogre::MaterialManager::getSingleton().getByName(materialName);
	//omat->compile(false);
	//omat->load();

	return omat;
}

Ogre::MaterialPtr AssimpLoader::createMaterial(int index, const aiMaterial* mat, const Ogre::String& mDir)
{
	static int dummyMatCount = 0;

	// extreme fallback texture -- 2x2 hot pink
	static Ogre::uint8 s_RGB[] = {128, 0, 255, 128, 0, 255, 128, 0, 255, 128, 0, 255};

	std::ostringstream matname;
	Ogre::MaterialManager* omatMgr =  Ogre::MaterialManager::getSingletonPtr();
	enum aiTextureType type = aiTextureType_DIFFUSE;
	static aiString path;
	aiTextureMapping mapping = aiTextureMapping_UV;       // the mapping (should be uv for now)
	unsigned int uvindex = 0;                             // the texture uv index channel
	float blend = 1.0f;                                   // blend
	aiTextureOp op = aiTextureOp_Multiply;                // op
	aiTextureMapMode mapmode[2] =  { aiTextureMapMode_Wrap, aiTextureMapMode_Wrap };    // mapmode
	std::ostringstream texname;

	aiString szPath;
	if(AI_SUCCESS == aiGetMaterialString(mat, AI_MATKEY_TEXTURE_DIFFUSE(0), &szPath))
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("Using aiGetMaterialString : Found texture " + Ogre::String(szPath.data) + " for channel " + Ogre::StringConverter::toString(uvindex));
        }
	}
	if(szPath.length < 1)
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("Didn't find any texture units...");
        }
		szPath = Ogre::String("dummyMat" + Ogre::StringConverter::toString(dummyMatCount)).c_str();
		dummyMatCount++;
	}

    Ogre::String basename;
    Ogre::String outPath;
    Ogre::StringUtil::splitFilename(Ogre::String(szPath.data), basename, outPath);
    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage("Creating " + basename);
    }

    Ogre::ResourceManager::ResourceCreateOrRetrieveResult status = omatMgr->createOrRetrieve(ReplaceSpaces(basename), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
	Ogre::MaterialPtr omat = status.first;
	if (!status.second)
		return omat;

	// ambient
	aiColor4D clr(1.0f, 1.0f, 1.0f, 1.0);
	//Ambient is usually way too low! FIX ME!
	if (mat->GetTexture(type, 0, &path) != AI_SUCCESS)
		aiGetMaterialColor(mat, AI_MATKEY_COLOR_AMBIENT,  &clr);
	omat->setAmbient(clr.r, clr.g, clr.b);

	// diffuse
	clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f);
	if(AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_DIFFUSE, &clr))
    {
	    omat->setDiffuse(clr.r, clr.g, clr.b, clr.a);
    }

	// specular
	clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f);
	if(AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_SPECULAR, &clr))
    {
	    omat->setSpecular(clr.r, clr.g, clr.b, clr.a);
    }

	// emissive
	clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f);
	if(AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_EMISSIVE, &clr))
    {
    	omat->setSelfIllumination(clr.r, clr.g, clr.b);
    }

	float fShininess;
	if(AI_SUCCESS == aiGetMaterialFloat(mat, AI_MATKEY_SHININESS, &fShininess))
	{
        omat->setShininess(Ogre::Real(fShininess));
	}

    if (mat->GetTexture(type, 0, &path) == AI_SUCCESS)
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("Found texture " + Ogre::String(path.data) + " for channel " + Ogre::StringConverter::toString(uvindex));
        }
		if(AI_SUCCESS == aiGetMaterialString(mat, AI_MATKEY_TEXTURE_DIFFUSE(0), &szPath))
		{
            if(!mQuietMode)
            {
                Ogre::LogManager::getSingleton().logMessage("Using aiGetMaterialString : Found texture " + Ogre::String(szPath.data) + " for channel " + Ogre::StringConverter::toString(uvindex));
            }
		}

		// attempt to load the image
		Ogre::Image image;

		// possibly if we fail to actually find it, pop up a box?
		Ogre::String pathname(mDir + "\\" + path.data);

		std::ifstream imgstream;
		imgstream.open(path.data, std::ios::binary);
		if(!imgstream.is_open())
			imgstream.open(Ogre::String(mPath + Ogre::String("\\") + Ogre::String(path.data)).c_str(), std::ios::binary);

		if (imgstream.is_open())
		{
			// Wrap as a stream
			Ogre::DataStreamPtr strm(OGRE_NEW Ogre::FileStreamDataStream(path.data, &imgstream, false));

			if (!strm->size() || strm->size() == 0xffffffff)
			{
				// fall back to our very simple and very hardcoded hot-pink version
				Ogre::DataStreamPtr altStrm(OGRE_NEW Ogre::MemoryDataStream(s_RGB, sizeof(s_RGB)));
				image.loadRawData(altStrm, 2, 2, Ogre::PF_R8G8B8);
                if(!mQuietMode)
                {
                    Ogre::LogManager::getSingleton().logMessage("Could not load texture, falling back to hotpink");
                }
			} else
			{
				// extract extension from filename
				size_t pos = pathname.find_last_of('.');
				Ogre::String ext = pathname.substr(pos+1);
				image.load(strm, ext);
				imgstream.close();
			}
		} else {
			// fall back to our very simple and very hardcoded hot-pink version
			Ogre::DataStreamPtr altStrm(OGRE_NEW Ogre::MemoryDataStream(s_RGB, sizeof(s_RGB)));
			image.loadRawData(altStrm, 2, 2, Ogre::PF_R8G8B8);
            if(!mQuietMode)
            {
                Ogre::LogManager::getSingleton().logMessage("Could not load texture, falling back to hotpink - 2");
            }
		}

/*		Ogre::TextureManager::getSingleton().loadImage(Ogre::String(szPath.data), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image);*/
        //TODO: save this to materials/textures ?
		Ogre::TextureUnitState* texUnitState = omat->getTechnique(0)->getPass(0)->createTextureUnitState(basename);

	}
	omat->load();
	return omat;
}





bool AssimpLoader::createSubMesh(const Ogre::String& name, int index, const aiNode* pNode, const aiMesh *mesh, const aiMaterial* mat, Ogre::MeshPtr mMesh, Ogre::AxisAlignedBox& mAAB, const Ogre::String& mDir)
{
	// if animated all submeshes must have bone weights
	if(mBonesByName.size() && !mesh->HasBones())
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage("Skipping Mesh " + Ogre::String(mesh->mName.data) + "with no bone weights");
        }
		return false;
	}

	Ogre::MaterialPtr matptr;

	if((mLoaderParams & LP_GENERATE_MATERIALS_AS_CODE) == 0)
	{
		matptr = createMaterial(mesh->mMaterialIndex, mat, mDir);
	}
	else
	{
		matptr = createMaterialByScript(mesh->mMaterialIndex, mat);
	}

	// now begin the object definition
	// We create a submesh per material
	Ogre::SubMesh* submesh = mMesh->createSubMesh(name + Ogre::StringConverter::toString(index));

	// prime pointers to vertex related data
	aiVector3D *vec = mesh->mVertices;
	aiVector3D *norm = mesh->mNormals;
	aiVector3D *uv = mesh->mTextureCoords[0];
	//aiColor4D *col = mesh->mColors[0];

	// We must create the vertex data, indicating how many vertices there will be
	submesh->useSharedVertices = false;
	submesh->vertexData = new Ogre::VertexData();
	submesh->vertexData->vertexStart = 0;
	submesh->vertexData->vertexCount = mesh->mNumVertices;

	// We must now declare what the vertex data contains
	Ogre::VertexDeclaration* declaration = submesh->vertexData->vertexDeclaration;
	static const unsigned short source = 0;
	size_t offset = 0;
	offset += declaration->addElement(source,offset,Ogre::VET_FLOAT3,Ogre::VES_POSITION).getSize();

	//mLog->logMessage((boost::format(" %d vertices ") % m->mNumVertices).str());
    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(mesh->mNumVertices) + " vertices");
    }
	if (norm)
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(mesh->mNumVertices) + " normals");
        }
		//mLog->logMessage((boost::format(" %d normals ") % m->mNumVertices).str() );
		offset += declaration->addElement(source,offset,Ogre::VET_FLOAT3,Ogre::VES_NORMAL).getSize();
	}

	if (uv)
	{
        if(!mQuietMode)
        {
            Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(mesh->mNumVertices) + " uvs");
        }
		//mLog->logMessage((boost::format(" %d uvs ") % m->mNumVertices).str() );
		offset += declaration->addElement(source,offset,Ogre::VET_FLOAT2,Ogre::VES_TEXTURE_COORDINATES).getSize();
	}

	/*
	if (col)
	{
		Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(mesh->mNumVertices) + " colours");
		//mLog->logMessage((boost::format(" %d colours ") % m->mNumVertices).str() );
		offset += declaration->addElement(source,offset,Ogre::VET_FLOAT3,Ogre::VES_DIFFUSE).getSize();
	}
	*/


	// We create the hardware vertex buffer
	Ogre::HardwareVertexBufferSharedPtr vbuffer =
		Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(declaration->getVertexSize(source), // == offset
		submesh->vertexData->vertexCount,   // == nbVertices
		Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	aiMatrix4x4 aiM = mNodeDerivedTransformByName.find(pNode->mName.data)->second;


	// Now we get access to the buffer to fill it.  During so we record the bounding box.
	float* vdata = static_cast<float*>(vbuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD));
	for (size_t i=0;i < mesh->mNumVertices; ++i)
	{
		// Position
        aiVector3D vect;
        vect.x = vec->x;
        vect.y = vec->y;
        vect.z = vec->z;

		vect *= aiM;

		/*
        if(NULL != mSkeletonRootNode)
        {
            vect *= mSkeletonRootNode->mTransformation;
        }
		*/

        Ogre::Vector3 position( vect.x, vect.y, vect.z );
        *vdata++ = vect.x;
		*vdata++ = vect.y;
		*vdata++ = vect.z;
		mAAB.merge(position);
		vec++;

		// Normal
		if (norm)
		{
			vect.x = norm->x;
			vect.y = norm->y;
			vect.z = norm->z;

			vect *= aiM;

			*vdata++ = vect.x;
			*vdata++ = vect.y;
			*vdata++ = vect.z;
			norm++;

			//*vdata++ = norm->x;
			//*vdata++ = norm->y;
			//*vdata++ = norm->z;
			//norm++;
		}

		// uvs
		if (uv)
		{
			*vdata++ = uv->x;
			*vdata++ = uv->y;
			uv++;
		}

		/*
		if (col)
		{
			*vdata++ = col->r;
			*vdata++ = col->g;
			*vdata++ = col->b;
			//*vdata++ = col->a;
			//col++;
		}
		*/
	}

	vbuffer->unlock();
	submesh->vertexData->vertexBufferBinding->setBinding(source,vbuffer);

    if(!mQuietMode)
    {
        Ogre::LogManager::getSingleton().logMessage(Ogre::StringConverter::toString(mesh->mNumFaces) + " faces");
    }
	aiFace *f = mesh->mFaces;

	// Creates the index data
	submesh->indexData->indexStart = 0;
	submesh->indexData->indexCount = mesh->mNumFaces * 3;
	submesh->indexData->indexBuffer =
		Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT,
		submesh->indexData->indexCount,
		Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
	Ogre::uint16* idata = static_cast<Ogre::uint16*>(submesh->indexData->indexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD));

	// poke in the face data
	for (size_t i=0; i < mesh->mNumFaces;++i)
	{
		//		wxASSERT(f->mNumIndices == 3);
		*idata++ = f->mIndices[0];
		*idata++ = f->mIndices[1];
		*idata++ = f->mIndices[2];
		f++;
	}
	submesh->indexData->indexBuffer->unlock();

    // set bone weigths
    if(mesh->HasBones())
    {
	    for ( Ogre::uint32 i=0; i < mesh->mNumBones; i++ )
	    {
		    aiBone *pAIBone = mesh->mBones[ i ];
		    if ( NULL != pAIBone )
		    {
                Ogre::String bname = pAIBone->mName.data;
			    for ( Ogre::uint32 weightIdx = 0; weightIdx < pAIBone->mNumWeights; weightIdx++ )
			    {
				    aiVertexWeight aiWeight = pAIBone->mWeights[ weightIdx ];

				    Ogre::VertexBoneAssignment vba;
				    vba.vertexIndex = aiWeight.mVertexId;
				    vba.boneIndex = mSkeleton->getBone(bname)->getHandle();
				    vba.weight= aiWeight.mWeight;

                    submesh->addBoneAssignment(vba);
			    }
		    }
	    }
    } // if mesh has bones

    // Finally we set a material to the submesh
    submesh->setMaterialName(matptr->getName());

	return true;
}

void AssimpLoader::loadDataFromNode(const aiScene* mScene,  const aiNode *pNode, const Ogre::String& mDir)
{
	if(pNode->mNumMeshes > 0)
	{
		Ogre::MeshPtr mesh;
		Ogre::AxisAlignedBox mAAB;

		if(mLoaderParams & LP_GENERATE_SINGLE_MESH)
		{
			if(mMeshes.size() == 0)
			{
                mesh = Ogre::MeshManager::getSingleton().createManual("ROOTMesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

				mMeshes.push_back(mesh);
			}
			else
			{
				mesh = mMeshes[0];
				mAAB = mesh->getBounds();
			}
		}

		for ( int idx=0; idx<pNode->mNumMeshes; ++idx )
		{
			aiMesh *pAIMesh = mScene->mMeshes[ pNode->mMeshes[ idx ] ];
            if(!mQuietMode)
            {
                Ogre::LogManager::getSingleton().logMessage("SubMesh " + Ogre::StringConverter::toString(idx) + " for mesh '" + Ogre::String(pNode->mName.data) + "'");
            }

			// Create a material instance for the mesh.
			const aiMaterial *pAIMaterial = mScene->mMaterials[ pAIMesh->mMaterialIndex ];
			createSubMesh(pNode->mName.data, idx, pNode, pAIMesh, pAIMaterial, mesh, mAAB, mDir);
		}

		// We must indicate the bounding box
		mesh->_setBounds(mAAB);
		mesh->_setBoundingSphereRadius((mAAB.getMaximum()- mAAB.getMinimum()).length()/2.0);
	}

	// Traverse all child nodes of the current node instance
	for ( int childIdx=0; childIdx<pNode->mNumChildren; childIdx++ )
	{
		const aiNode *pChildNode = pNode->mChildren[ childIdx ];
		loadDataFromNode(mScene, pChildNode, mDir);
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.