LWSLoader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file LWSLoader.cpp
  35. * @brief Implementation of the LWS importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #include "LWSLoader.h"
  39. #include "ParsingUtils.h"
  40. #include "fast_atof.h"
  41. #include "SceneCombiner.h"
  42. #include "GenericProperty.h"
  43. #include "SkeletonMeshBuilder.h"
  44. #include "ConvertToLHProcess.h"
  45. #include "Importer.h"
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "LightWave Scene Importer",
  49. "",
  50. "",
  51. "http://www.newtek.com/lightwave.html=",
  52. aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "lws mot"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Recursive parsing of LWS files
  61. void LWS::Element::Parse (const char*& buffer)
  62. {
  63. for (;SkipSpacesAndLineEnd(&buffer);SkipLine(&buffer)) {
  64. // begin of a new element with children
  65. bool sub = false;
  66. if (*buffer == '{') {
  67. ++buffer;
  68. SkipSpaces(&buffer);
  69. sub = true;
  70. }
  71. else if (*buffer == '}')
  72. return;
  73. children.push_back(Element());
  74. // copy data line - read token per token
  75. const char* cur = buffer;
  76. while (!IsSpaceOrNewLine(*buffer)) ++buffer;
  77. children.back().tokens[0] = std::string(cur,(size_t) (buffer-cur));
  78. SkipSpaces(&buffer);
  79. if (children.back().tokens[0] == "Plugin")
  80. {
  81. DefaultLogger::get()->debug("LWS: Skipping over plugin-specific data");
  82. // strange stuff inside Plugin/Endplugin blocks. Needn't
  83. // follow LWS syntax, so we skip over it
  84. for (;SkipSpacesAndLineEnd(&buffer);SkipLine(&buffer)) {
  85. if (!::strncmp(buffer,"EndPlugin",9)) {
  86. //SkipLine(&buffer);
  87. break;
  88. }
  89. }
  90. continue;
  91. }
  92. cur = buffer;
  93. while (!IsLineEnd(*buffer)) ++buffer;
  94. children.back().tokens[1] = std::string(cur,(size_t) (buffer-cur));
  95. // parse more elements recursively
  96. if (sub)
  97. children.back().Parse(buffer);
  98. }
  99. }
  100. // ------------------------------------------------------------------------------------------------
  101. // Constructor to be privately used by Importer
  102. LWSImporter::LWSImporter()
  103. {
  104. // nothing to do here
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. // Destructor, private as well
  108. LWSImporter::~LWSImporter()
  109. {
  110. // nothing to do here
  111. }
  112. // ------------------------------------------------------------------------------------------------
  113. // Returns whether the class can handle the format of the given file.
  114. bool LWSImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler,bool checkSig) const
  115. {
  116. const std::string extension = GetExtension(pFile);
  117. if (extension == "lws" || extension == "mot")
  118. return true;
  119. // if check for extension is not enough, check for the magic tokens LWSC and LWMO
  120. if (!extension.length() || checkSig) {
  121. uint32_t tokens[2];
  122. tokens[0] = AI_MAKE_MAGIC("LWSC");
  123. tokens[1] = AI_MAKE_MAGIC("LWMO");
  124. return CheckMagicToken(pIOHandler,pFile,tokens,2);
  125. }
  126. return false;
  127. }
  128. // ------------------------------------------------------------------------------------------------
  129. // Get list of file extensions
  130. const aiImporterDesc* LWSImporter::GetInfo () const
  131. {
  132. return &desc;
  133. }
  134. // ------------------------------------------------------------------------------------------------
  135. // Setup configuration properties
  136. void LWSImporter::SetupProperties(const Importer* pImp)
  137. {
  138. // AI_CONFIG_FAVOUR_SPEED
  139. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  140. // AI_CONFIG_IMPORT_LWS_ANIM_START
  141. first = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_START,
  142. 150392 /* magic hack */);
  143. // AI_CONFIG_IMPORT_LWS_ANIM_END
  144. last = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_LWS_ANIM_END,
  145. 150392 /* magic hack */);
  146. if (last < first) {
  147. std::swap(last,first);
  148. }
  149. }
  150. // ------------------------------------------------------------------------------------------------
  151. // Read an envelope description
  152. void LWSImporter::ReadEnvelope(const LWS::Element& dad, LWO::Envelope& fill )
  153. {
  154. if (dad.children.empty()) {
  155. DefaultLogger::get()->error("LWS: Envelope descriptions must not be empty");
  156. return;
  157. }
  158. // reserve enough storage
  159. std::list< LWS::Element >::const_iterator it = dad.children.begin();;
  160. fill.keys.reserve(strtoul10(it->tokens[1].c_str()));
  161. for (++it; it != dad.children.end(); ++it) {
  162. const char* c = (*it).tokens[1].c_str();
  163. if ((*it).tokens[0] == "Key") {
  164. fill.keys.push_back(LWO::Key());
  165. LWO::Key& key = fill.keys.back();
  166. float f;
  167. SkipSpaces(&c);
  168. c = fast_atoreal_move<float>(c,key.value);
  169. SkipSpaces(&c);
  170. c = fast_atoreal_move<float>(c,f);
  171. key.time = f;
  172. unsigned int span = strtoul10(c,&c), num = 0;
  173. switch (span) {
  174. case 0:
  175. key.inter = LWO::IT_TCB;
  176. num = 5;
  177. break;
  178. case 1:
  179. case 2:
  180. key.inter = LWO::IT_HERM;
  181. num = 5;
  182. break;
  183. case 3:
  184. key.inter = LWO::IT_LINE;
  185. num = 0;
  186. break;
  187. case 4:
  188. key.inter = LWO::IT_STEP;
  189. num = 0;
  190. break;
  191. case 5:
  192. key.inter = LWO::IT_BEZ2;
  193. num = 4;
  194. break;
  195. default:
  196. DefaultLogger::get()->error("LWS: Unknown span type");
  197. }
  198. for (unsigned int i = 0; i < num;++i) {
  199. SkipSpaces(&c);
  200. c = fast_atoreal_move<float>(c,key.params[i]);
  201. }
  202. }
  203. else if ((*it).tokens[0] == "Behaviors") {
  204. SkipSpaces(&c);
  205. fill.pre = (LWO::PrePostBehaviour) strtoul10(c,&c);
  206. SkipSpaces(&c);
  207. fill.post = (LWO::PrePostBehaviour) strtoul10(c,&c);
  208. }
  209. }
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. // Read animation channels in the old LightWave animation format
  213. void LWSImporter::ReadEnvelope_Old(
  214. std::list< LWS::Element >::const_iterator& it,
  215. const std::list< LWS::Element >::const_iterator& end,
  216. LWS::NodeDesc& nodes,
  217. unsigned int /*version*/)
  218. {
  219. unsigned int num,sub_num;
  220. if (++it == end)goto unexpected_end;
  221. num = strtoul10((*it).tokens[0].c_str());
  222. for (unsigned int i = 0; i < num; ++i) {
  223. nodes.channels.push_back(LWO::Envelope());
  224. LWO::Envelope& envl = nodes.channels.back();
  225. envl.index = i;
  226. envl.type = (LWO::EnvelopeType)(i+1);
  227. if (++it == end)goto unexpected_end;
  228. sub_num = strtoul10((*it).tokens[0].c_str());
  229. for (unsigned int n = 0; n < sub_num;++n) {
  230. if (++it == end)goto unexpected_end;
  231. // parse value and time, skip the rest for the moment.
  232. LWO::Key key;
  233. const char* c = fast_atoreal_move<float>((*it).tokens[0].c_str(),key.value);
  234. SkipSpaces(&c);
  235. float f;
  236. fast_atoreal_move<float>((*it).tokens[0].c_str(),f);
  237. key.time = f;
  238. envl.keys.push_back(key);
  239. }
  240. }
  241. return;
  242. unexpected_end:
  243. DefaultLogger::get()->error("LWS: Encountered unexpected end of file while parsing object motion");
  244. }
  245. // ------------------------------------------------------------------------------------------------
  246. // Setup a nice name for a node
  247. void LWSImporter::SetupNodeName(aiNode* nd, LWS::NodeDesc& src)
  248. {
  249. const unsigned int combined = src.number | ((unsigned int)src.type) << 28u;
  250. // the name depends on the type. We break LWS's strange naming convention
  251. // and return human-readable, but still machine-parsable and unique, strings.
  252. if (src.type == LWS::NodeDesc::OBJECT) {
  253. if (src.path.length()) {
  254. std::string::size_type s = src.path.find_last_of("\\/");
  255. if (s == std::string::npos)
  256. s = 0;
  257. else ++s;
  258. std::string::size_type t = src.path.substr(s).find_last_of(".");
  259. nd->mName.length = ::sprintf(nd->mName.data,"%s_(%08X)",src.path.substr(s).substr(0,t).c_str(),combined);
  260. return;
  261. }
  262. }
  263. nd->mName.length = ::sprintf(nd->mName.data,"%s_(%08X)",src.name,combined);
  264. }
  265. // ------------------------------------------------------------------------------------------------
  266. // Recursively build the scenegraph
  267. void LWSImporter::BuildGraph(aiNode* nd, LWS::NodeDesc& src, std::vector<AttachmentInfo>& attach,
  268. BatchLoader& batch,
  269. aiCamera**& camOut,
  270. aiLight**& lightOut,
  271. std::vector<aiNodeAnim*>& animOut)
  272. {
  273. // Setup a very cryptic name for the node, we want the user to be happy
  274. SetupNodeName(nd,src);
  275. aiNode* ndAnim = nd;
  276. // If the node is an object
  277. if (src.type == LWS::NodeDesc::OBJECT) {
  278. // If the object is from an external file, get it
  279. aiScene* obj = NULL;
  280. if (src.path.length() ) {
  281. obj = batch.GetImport(src.id);
  282. if (!obj) {
  283. DefaultLogger::get()->error("LWS: Failed to read external file " + src.path);
  284. }
  285. else {
  286. if (obj->mRootNode->mNumChildren == 1) {
  287. //If the pivot is not set for this layer, get it from the external object
  288. if (!src.isPivotSet) {
  289. src.pivotPos.x = +obj->mRootNode->mTransformation.a4;
  290. src.pivotPos.y = +obj->mRootNode->mTransformation.b4;
  291. src.pivotPos.z = -obj->mRootNode->mTransformation.c4; //The sign is the RH to LH back conversion
  292. }
  293. //Remove first node from obj (the old pivot), reset transform of second node (the mesh node)
  294. aiNode* newRootNode = obj->mRootNode->mChildren[0];
  295. obj->mRootNode->mChildren[0] = NULL;
  296. delete obj->mRootNode;
  297. obj->mRootNode = newRootNode;
  298. obj->mRootNode->mTransformation.a4 = 0.0;
  299. obj->mRootNode->mTransformation.b4 = 0.0;
  300. obj->mRootNode->mTransformation.c4 = 0.0;
  301. }
  302. }
  303. }
  304. //Setup the pivot node (also the animation node), the one we received
  305. nd->mName = std::string("Pivot:") + nd->mName.data;
  306. ndAnim = nd;
  307. //Add the attachment node to it
  308. nd->mNumChildren = 1;
  309. nd->mChildren = new aiNode*[1];
  310. nd->mChildren[0] = new aiNode();
  311. nd->mChildren[0]->mParent = nd;
  312. nd->mChildren[0]->mTransformation.a4 = -src.pivotPos.x;
  313. nd->mChildren[0]->mTransformation.b4 = -src.pivotPos.y;
  314. nd->mChildren[0]->mTransformation.c4 = -src.pivotPos.z;
  315. SetupNodeName(nd->mChildren[0], src);
  316. //Update the attachment node
  317. nd = nd->mChildren[0];
  318. //Push attachment, if the object came from an external file
  319. if (obj) {
  320. attach.push_back(AttachmentInfo(obj,nd));
  321. }
  322. }
  323. // If object is a light source - setup a corresponding ai structure
  324. else if (src.type == LWS::NodeDesc::LIGHT) {
  325. aiLight* lit = *lightOut++ = new aiLight();
  326. // compute final light color
  327. lit->mColorDiffuse = lit->mColorSpecular = src.lightColor*src.lightIntensity;
  328. // name to attach light to node -> unique due to LWs indexing system
  329. lit->mName = nd->mName;
  330. // detemine light type and setup additional members
  331. if (src.lightType == 2) { /* spot light */
  332. lit->mType = aiLightSource_SPOT;
  333. lit->mAngleInnerCone = (float)AI_DEG_TO_RAD( src.lightConeAngle );
  334. lit->mAngleOuterCone = lit->mAngleInnerCone+(float)AI_DEG_TO_RAD( src.lightEdgeAngle );
  335. }
  336. else if (src.lightType == 1) { /* directional light source */
  337. lit->mType = aiLightSource_DIRECTIONAL;
  338. }
  339. else lit->mType = aiLightSource_POINT;
  340. // fixme: no proper handling of light falloffs yet
  341. if (src.lightFalloffType == 1)
  342. lit->mAttenuationConstant = 1.f;
  343. else if (src.lightFalloffType == 1)
  344. lit->mAttenuationLinear = 1.f;
  345. else
  346. lit->mAttenuationQuadratic = 1.f;
  347. }
  348. // If object is a camera - setup a corresponding ai structure
  349. else if (src.type == LWS::NodeDesc::CAMERA) {
  350. aiCamera* cam = *camOut++ = new aiCamera();
  351. // name to attach cam to node -> unique due to LWs indexing system
  352. cam->mName = nd->mName;
  353. }
  354. // Get the node transformation from the LWO key
  355. LWO::AnimResolver resolver(src.channels,fps);
  356. resolver.ExtractBindPose(ndAnim->mTransformation);
  357. // .. and construct animation channels
  358. aiNodeAnim* anim = NULL;
  359. if (first != last) {
  360. resolver.SetAnimationRange(first,last);
  361. resolver.ExtractAnimChannel(&anim,AI_LWO_ANIM_FLAG_SAMPLE_ANIMS|AI_LWO_ANIM_FLAG_START_AT_ZERO);
  362. if (anim) {
  363. anim->mNodeName = ndAnim->mName;
  364. animOut.push_back(anim);
  365. }
  366. }
  367. // Add children
  368. if (src.children.size()) {
  369. nd->mChildren = new aiNode*[src.children.size()];
  370. for (std::list<LWS::NodeDesc*>::iterator it = src.children.begin(); it != src.children.end(); ++it) {
  371. aiNode* ndd = nd->mChildren[nd->mNumChildren++] = new aiNode();
  372. ndd->mParent = nd;
  373. BuildGraph(ndd,**it,attach,batch,camOut,lightOut,animOut);
  374. }
  375. }
  376. }
  377. // ------------------------------------------------------------------------------------------------
  378. // Determine the exact location of a LWO file
  379. std::string LWSImporter::FindLWOFile(const std::string& in)
  380. {
  381. // insert missing directory seperator if necessary
  382. std::string tmp;
  383. if (in.length() > 3 && in[1] == ':'&& in[2] != '\\' && in[2] != '/')
  384. {
  385. tmp = in[0] + ":\\" + in.substr(2);
  386. }
  387. else tmp = in;
  388. if (io->Exists(tmp)) {
  389. return in;
  390. }
  391. // file is not accessible for us ... maybe it's packed by
  392. // LightWave's 'Package Scene' command?
  393. // Relevant for us are the following two directories:
  394. // <folder>\Objects\<hh>\<*>.lwo
  395. // <folder>\Scenes\<hh>\<*>.lws
  396. // where <hh> is optional.
  397. std::string test = ".." + io->getOsSeparator() + tmp;
  398. if (io->Exists(test))
  399. return test;
  400. test = ".." + io->getOsSeparator() + test;
  401. if (io->Exists(test)) {
  402. return test;
  403. }
  404. // return original path, maybe the IOsystem knows better
  405. return tmp;
  406. }
  407. // ------------------------------------------------------------------------------------------------
  408. // Read file into given scene data structure
  409. void LWSImporter::InternReadFile( const std::string& pFile, aiScene* pScene,
  410. IOSystem* pIOHandler)
  411. {
  412. io = pIOHandler;
  413. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  414. // Check whether we can read from the file
  415. if( file.get() == NULL) {
  416. throw DeadlyImportError( "Failed to open LWS file " + pFile + ".");
  417. }
  418. // Allocate storage and copy the contents of the file to a memory buffer
  419. std::vector< char > mBuffer;
  420. TextFileToBuffer(file.get(),mBuffer);
  421. // Parse the file structure
  422. LWS::Element root; const char* dummy = &mBuffer[0];
  423. root.Parse(dummy);
  424. // Construct a Batchimporter to read more files recursively
  425. BatchLoader batch(pIOHandler);
  426. // batch.SetBasePath(pFile);
  427. // Construct an array to receive the flat output graph
  428. std::list<LWS::NodeDesc> nodes;
  429. unsigned int cur_light = 0, cur_camera = 0, cur_object = 0;
  430. unsigned int num_light = 0, num_camera = 0, num_object = 0;
  431. // check magic identifier, 'LWSC'
  432. bool motion_file = false;
  433. std::list< LWS::Element >::const_iterator it = root.children.begin();
  434. if ((*it).tokens[0] == "LWMO")
  435. motion_file = true;
  436. if ((*it).tokens[0] != "LWSC" && !motion_file)
  437. throw DeadlyImportError("LWS: Not a LightWave scene, magic tag LWSC not found");
  438. // get file format version and print to log
  439. ++it;
  440. unsigned int version = strtoul10((*it).tokens[0].c_str());
  441. DefaultLogger::get()->info("LWS file format version is " + (*it).tokens[0]);
  442. first = 0.;
  443. last = 60.;
  444. fps = 25.; /* seems to be a good default frame rate */
  445. // Now read all elements in a very straghtforward manner
  446. for (; it != root.children.end(); ++it) {
  447. const char* c = (*it).tokens[1].c_str();
  448. // 'FirstFrame': begin of animation slice
  449. if ((*it).tokens[0] == "FirstFrame") {
  450. if (150392. != first /* see SetupProperties() */)
  451. first = strtoul10(c,&c)-1.; /* we're zero-based */
  452. }
  453. // 'LastFrame': end of animation slice
  454. else if ((*it).tokens[0] == "LastFrame") {
  455. if (150392. != last /* see SetupProperties() */)
  456. last = strtoul10(c,&c)-1.; /* we're zero-based */
  457. }
  458. // 'FramesPerSecond': frames per second
  459. else if ((*it).tokens[0] == "FramesPerSecond") {
  460. fps = strtoul10(c,&c);
  461. }
  462. // 'LoadObjectLayer': load a layer of a specific LWO file
  463. else if ((*it).tokens[0] == "LoadObjectLayer") {
  464. // get layer index
  465. const int layer = strtoul10(c,&c);
  466. // setup the layer to be loaded
  467. BatchLoader::PropertyMap props;
  468. SetGenericProperty(props.ints,AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,layer);
  469. // add node to list
  470. LWS::NodeDesc d;
  471. d.type = LWS::NodeDesc::OBJECT;
  472. if (version >= 4) { // handle LWSC 4 explicit ID
  473. SkipSpaces(&c);
  474. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  475. }
  476. else d.number = cur_object++;
  477. // and add the file to the import list
  478. SkipSpaces(&c);
  479. std::string path = FindLWOFile( c );
  480. d.path = path;
  481. d.id = batch.AddLoadRequest(path,0,&props);
  482. nodes.push_back(d);
  483. num_object++;
  484. }
  485. // 'LoadObject': load a LWO file into the scenegraph
  486. else if ((*it).tokens[0] == "LoadObject") {
  487. // add node to list
  488. LWS::NodeDesc d;
  489. d.type = LWS::NodeDesc::OBJECT;
  490. if (version >= 4) { // handle LWSC 4 explicit ID
  491. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  492. SkipSpaces(&c);
  493. }
  494. else d.number = cur_object++;
  495. std::string path = FindLWOFile( c );
  496. d.id = batch.AddLoadRequest(path,0,NULL);
  497. d.path = path;
  498. nodes.push_back(d);
  499. num_object++;
  500. }
  501. // 'AddNullObject': add a dummy node to the hierarchy
  502. else if ((*it).tokens[0] == "AddNullObject") {
  503. // add node to list
  504. LWS::NodeDesc d;
  505. d.type = LWS::NodeDesc::OBJECT;
  506. if (version >= 4) { // handle LWSC 4 explicit ID
  507. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  508. SkipSpaces(&c);
  509. }
  510. else d.number = cur_object++;
  511. d.name = c;
  512. nodes.push_back(d);
  513. num_object++;
  514. }
  515. // 'NumChannels': Number of envelope channels assigned to last layer
  516. else if ((*it).tokens[0] == "NumChannels") {
  517. // ignore for now
  518. }
  519. // 'Channel': preceedes any envelope description
  520. else if ((*it).tokens[0] == "Channel") {
  521. if (nodes.empty()) {
  522. if (motion_file) {
  523. // LightWave motion file. Add dummy node
  524. LWS::NodeDesc d;
  525. d.type = LWS::NodeDesc::OBJECT;
  526. d.name = c;
  527. d.number = cur_object++;
  528. nodes.push_back(d);
  529. }
  530. else DefaultLogger::get()->error("LWS: Unexpected keyword: \'Channel\'");
  531. }
  532. // important: index of channel
  533. nodes.back().channels.push_back(LWO::Envelope());
  534. LWO::Envelope& env = nodes.back().channels.back();
  535. env.index = strtoul10(c);
  536. // currently we can just interpret the standard channels 0...9
  537. // (hack) assume that index-i yields the binary channel type from LWO
  538. env.type = (LWO::EnvelopeType)(env.index+1);
  539. }
  540. // 'Envelope': a single animation channel
  541. else if ((*it).tokens[0] == "Envelope") {
  542. if (nodes.empty() || nodes.back().channels.empty())
  543. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Envelope\'");
  544. else {
  545. ReadEnvelope((*it),nodes.back().channels.back());
  546. }
  547. }
  548. // 'ObjectMotion': animation information for older lightwave formats
  549. else if (version < 3 && ((*it).tokens[0] == "ObjectMotion" ||
  550. (*it).tokens[0] == "CameraMotion" ||
  551. (*it).tokens[0] == "LightMotion")) {
  552. if (nodes.empty())
  553. DefaultLogger::get()->error("LWS: Unexpected keyword: \'<Light|Object|Camera>Motion\'");
  554. else {
  555. ReadEnvelope_Old(it,root.children.end(),nodes.back(),version);
  556. }
  557. }
  558. // 'Pre/PostBehavior': pre/post animation behaviour for LWSC 2
  559. else if (version == 2 && (*it).tokens[0] == "Pre/PostBehavior") {
  560. if (nodes.empty())
  561. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Pre/PostBehavior'");
  562. else {
  563. for (std::list<LWO::Envelope>::iterator it = nodes.back().channels.begin(); it != nodes.back().channels.end(); ++it) {
  564. // two ints per envelope
  565. LWO::Envelope& env = *it;
  566. env.pre = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  567. env.post = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  568. }
  569. }
  570. }
  571. // 'ParentItem': specifies the parent of the current element
  572. else if ((*it).tokens[0] == "ParentItem") {
  573. if (nodes.empty())
  574. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentItem\'");
  575. else nodes.back().parent = strtoul16(c,&c);
  576. }
  577. // 'ParentObject': deprecated one for older formats
  578. else if (version < 3 && (*it).tokens[0] == "ParentObject") {
  579. if (nodes.empty())
  580. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentObject\'");
  581. else {
  582. nodes.back().parent = strtoul10(c,&c) | (1u << 28u);
  583. }
  584. }
  585. // 'AddCamera': add a camera to the scenegraph
  586. else if ((*it).tokens[0] == "AddCamera") {
  587. // add node to list
  588. LWS::NodeDesc d;
  589. d.type = LWS::NodeDesc::CAMERA;
  590. if (version >= 4) { // handle LWSC 4 explicit ID
  591. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  592. }
  593. else d.number = cur_camera++;
  594. nodes.push_back(d);
  595. num_camera++;
  596. }
  597. // 'CameraName': set name of currently active camera
  598. else if ((*it).tokens[0] == "CameraName") {
  599. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::CAMERA)
  600. DefaultLogger::get()->error("LWS: Unexpected keyword: \'CameraName\'");
  601. else nodes.back().name = c;
  602. }
  603. // 'AddLight': add a light to the scenegraph
  604. else if ((*it).tokens[0] == "AddLight") {
  605. // add node to list
  606. LWS::NodeDesc d;
  607. d.type = LWS::NodeDesc::LIGHT;
  608. if (version >= 4) { // handle LWSC 4 explicit ID
  609. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  610. }
  611. else d.number = cur_light++;
  612. nodes.push_back(d);
  613. num_light++;
  614. }
  615. // 'LightName': set name of currently active light
  616. else if ((*it).tokens[0] == "LightName") {
  617. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  618. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightName\'");
  619. else nodes.back().name = c;
  620. }
  621. // 'LightIntensity': set intensity of currently active light
  622. else if ((*it).tokens[0] == "LightIntensity" || (*it).tokens[0] == "LgtIntensity" ) {
  623. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  624. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightIntensity\'");
  625. else fast_atoreal_move<float>(c, nodes.back().lightIntensity );
  626. }
  627. // 'LightType': set type of currently active light
  628. else if ((*it).tokens[0] == "LightType") {
  629. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  630. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightType\'");
  631. else nodes.back().lightType = strtoul10(c);
  632. }
  633. // 'LightFalloffType': set falloff type of currently active light
  634. else if ((*it).tokens[0] == "LightFalloffType") {
  635. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  636. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightFalloffType\'");
  637. else nodes.back().lightFalloffType = strtoul10(c);
  638. }
  639. // 'LightConeAngle': set cone angle of currently active light
  640. else if ((*it).tokens[0] == "LightConeAngle") {
  641. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  642. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightConeAngle\'");
  643. else nodes.back().lightConeAngle = fast_atof(c);
  644. }
  645. // 'LightEdgeAngle': set area where we're smoothing from min to max intensity
  646. else if ((*it).tokens[0] == "LightEdgeAngle") {
  647. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  648. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightEdgeAngle\'");
  649. else nodes.back().lightEdgeAngle = fast_atof(c);
  650. }
  651. // 'LightColor': set color of currently active light
  652. else if ((*it).tokens[0] == "LightColor") {
  653. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  654. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightColor\'");
  655. else {
  656. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.r );
  657. SkipSpaces(&c);
  658. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.g );
  659. SkipSpaces(&c);
  660. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.b );
  661. }
  662. }
  663. // 'PivotPosition': position of local transformation origin
  664. else if ((*it).tokens[0] == "PivotPosition" || (*it).tokens[0] == "PivotPoint") {
  665. if (nodes.empty())
  666. DefaultLogger::get()->error("LWS: Unexpected keyword: \'PivotPosition\'");
  667. else {
  668. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.x );
  669. SkipSpaces(&c);
  670. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.y );
  671. SkipSpaces(&c);
  672. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.z );
  673. // Mark pivotPos as set
  674. nodes.back().isPivotSet = true;
  675. }
  676. }
  677. }
  678. // resolve parenting
  679. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  680. // check whether there is another node which calls us a parent
  681. for (std::list<LWS::NodeDesc>::iterator dit = nodes.begin(); dit != nodes.end(); ++dit) {
  682. if (dit != it && *it == (*dit).parent) {
  683. if ((*dit).parent_resolved) {
  684. // fixme: it's still possible to produce an overflow due to cross references ..
  685. DefaultLogger::get()->error("LWS: Found cross reference in scenegraph");
  686. continue;
  687. }
  688. (*it).children.push_back(&*dit);
  689. (*dit).parent_resolved = &*it;
  690. }
  691. }
  692. }
  693. // find out how many nodes have no parent yet
  694. unsigned int no_parent = 0;
  695. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  696. if (!(*it).parent_resolved)
  697. ++ no_parent;
  698. }
  699. if (!no_parent)
  700. throw DeadlyImportError("LWS: Unable to find scene root node");
  701. // Load all subsequent files
  702. batch.LoadAll();
  703. // and build the final output graph by attaching the loaded external
  704. // files to ourselves. first build a master graph
  705. aiScene* master = new aiScene();
  706. aiNode* nd = master->mRootNode = new aiNode();
  707. // allocate storage for cameras&lights
  708. if (num_camera) {
  709. master->mCameras = new aiCamera*[master->mNumCameras = num_camera];
  710. }
  711. aiCamera** cams = master->mCameras;
  712. if (num_light) {
  713. master->mLights = new aiLight*[master->mNumLights = num_light];
  714. }
  715. aiLight** lights = master->mLights;
  716. std::vector<AttachmentInfo> attach;
  717. std::vector<aiNodeAnim*> anims;
  718. nd->mName.Set("<LWSRoot>");
  719. nd->mChildren = new aiNode*[no_parent];
  720. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  721. if (!(*it).parent_resolved) {
  722. aiNode* ro = nd->mChildren[ nd->mNumChildren++ ] = new aiNode();
  723. ro->mParent = nd;
  724. // ... and build the scene graph. If we encounter object nodes,
  725. // add then to our attachment table.
  726. BuildGraph(ro,*it, attach, batch, cams, lights, anims);
  727. }
  728. }
  729. // create a master animation channel for us
  730. if (anims.size()) {
  731. master->mAnimations = new aiAnimation*[master->mNumAnimations = 1];
  732. aiAnimation* anim = master->mAnimations[0] = new aiAnimation();
  733. anim->mName.Set("LWSMasterAnim");
  734. // LWS uses seconds as time units, but we convert to frames
  735. anim->mTicksPerSecond = fps;
  736. anim->mDuration = last-(first-1); /* fixme ... zero or one-based?*/
  737. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = anims.size()];
  738. std::copy(anims.begin(),anims.end(),anim->mChannels);
  739. }
  740. // convert the master scene to RH
  741. MakeLeftHandedProcess monster_cheat;
  742. monster_cheat.Execute(master);
  743. // .. ccw
  744. FlipWindingOrderProcess flipper;
  745. flipper.Execute(master);
  746. // OK ... finally build the output graph
  747. SceneCombiner::MergeScenes(&pScene,master,attach,
  748. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (
  749. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) : 0));
  750. // Check flags
  751. if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
  752. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  753. if (pScene->mNumAnimations) {
  754. // construct skeleton mesh
  755. SkeletonMeshBuilder builder(pScene);
  756. }
  757. }
  758. }