LWSLoader.cpp 30 KB

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