Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

925 linhas
29 KiB

  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. }
  404. test = ".." + (io->getOsSeparator() + test);
  405. if (io->Exists(test)) {
  406. return test;
  407. }
  408. // return original path, maybe the IOsystem knows better
  409. return tmp;
  410. }
  411. // ------------------------------------------------------------------------------------------------
  412. // Read file into given scene data structure
  413. void LWSImporter::InternReadFile( const std::string& pFile, aiScene* pScene,
  414. IOSystem* pIOHandler)
  415. {
  416. io = pIOHandler;
  417. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  418. // Check whether we can read from the file
  419. if( file.get() == NULL) {
  420. throw DeadlyImportError( "Failed to open LWS file " + pFile + ".");
  421. }
  422. // Allocate storage and copy the contents of the file to a memory buffer
  423. std::vector< char > mBuffer;
  424. TextFileToBuffer(file.get(),mBuffer);
  425. // Parse the file structure
  426. LWS::Element root; const char* dummy = &mBuffer[0];
  427. root.Parse(dummy);
  428. // Construct a Batchimporter to read more files recursively
  429. BatchLoader batch(pIOHandler);
  430. // batch.SetBasePath(pFile);
  431. // Construct an array to receive the flat output graph
  432. std::list<LWS::NodeDesc> nodes;
  433. unsigned int cur_light = 0, cur_camera = 0, cur_object = 0;
  434. unsigned int num_light = 0, num_camera = 0, num_object = 0;
  435. // check magic identifier, 'LWSC'
  436. bool motion_file = false;
  437. std::list< LWS::Element >::const_iterator it = root.children.begin();
  438. if ((*it).tokens[0] == "LWMO")
  439. motion_file = true;
  440. if ((*it).tokens[0] != "LWSC" && !motion_file)
  441. throw DeadlyImportError("LWS: Not a LightWave scene, magic tag LWSC not found");
  442. // get file format version and print to log
  443. ++it;
  444. unsigned int version = strtoul10((*it).tokens[0].c_str());
  445. DefaultLogger::get()->info("LWS file format version is " + (*it).tokens[0]);
  446. first = 0.;
  447. last = 60.;
  448. fps = 25.; /* seems to be a good default frame rate */
  449. // Now read all elements in a very straghtforward manner
  450. for (; it != root.children.end(); ++it) {
  451. const char* c = (*it).tokens[1].c_str();
  452. // 'FirstFrame': begin of animation slice
  453. if ((*it).tokens[0] == "FirstFrame") {
  454. if (150392. != first /* see SetupProperties() */)
  455. first = strtoul10(c,&c)-1.; /* we're zero-based */
  456. }
  457. // 'LastFrame': end of animation slice
  458. else if ((*it).tokens[0] == "LastFrame") {
  459. if (150392. != last /* see SetupProperties() */)
  460. last = strtoul10(c,&c)-1.; /* we're zero-based */
  461. }
  462. // 'FramesPerSecond': frames per second
  463. else if ((*it).tokens[0] == "FramesPerSecond") {
  464. fps = strtoul10(c,&c);
  465. }
  466. // 'LoadObjectLayer': load a layer of a specific LWO file
  467. else if ((*it).tokens[0] == "LoadObjectLayer") {
  468. // get layer index
  469. const int layer = strtoul10(c,&c);
  470. // setup the layer to be loaded
  471. BatchLoader::PropertyMap props;
  472. SetGenericProperty(props.ints,AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,layer);
  473. // add node to list
  474. LWS::NodeDesc d;
  475. d.type = LWS::NodeDesc::OBJECT;
  476. if (version >= 4) { // handle LWSC 4 explicit ID
  477. SkipSpaces(&c);
  478. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  479. }
  480. else d.number = cur_object++;
  481. // and add the file to the import list
  482. SkipSpaces(&c);
  483. std::string path = FindLWOFile( c );
  484. d.path = path;
  485. d.id = batch.AddLoadRequest(path,0,&props);
  486. nodes.push_back(d);
  487. num_object++;
  488. }
  489. // 'LoadObject': load a LWO file into the scenegraph
  490. else if ((*it).tokens[0] == "LoadObject") {
  491. // add node to list
  492. LWS::NodeDesc d;
  493. d.type = LWS::NodeDesc::OBJECT;
  494. if (version >= 4) { // handle LWSC 4 explicit ID
  495. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  496. SkipSpaces(&c);
  497. }
  498. else d.number = cur_object++;
  499. std::string path = FindLWOFile( c );
  500. d.id = batch.AddLoadRequest(path,0,NULL);
  501. d.path = path;
  502. nodes.push_back(d);
  503. num_object++;
  504. }
  505. // 'AddNullObject': add a dummy node to the hierarchy
  506. else if ((*it).tokens[0] == "AddNullObject") {
  507. // add node to list
  508. LWS::NodeDesc d;
  509. d.type = LWS::NodeDesc::OBJECT;
  510. if (version >= 4) { // handle LWSC 4 explicit ID
  511. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  512. SkipSpaces(&c);
  513. }
  514. else d.number = cur_object++;
  515. d.name = c;
  516. nodes.push_back(d);
  517. num_object++;
  518. }
  519. // 'NumChannels': Number of envelope channels assigned to last layer
  520. else if ((*it).tokens[0] == "NumChannels") {
  521. // ignore for now
  522. }
  523. // 'Channel': preceedes any envelope description
  524. else if ((*it).tokens[0] == "Channel") {
  525. if (nodes.empty()) {
  526. if (motion_file) {
  527. // LightWave motion file. Add dummy node
  528. LWS::NodeDesc d;
  529. d.type = LWS::NodeDesc::OBJECT;
  530. d.name = c;
  531. d.number = cur_object++;
  532. nodes.push_back(d);
  533. }
  534. else DefaultLogger::get()->error("LWS: Unexpected keyword: \'Channel\'");
  535. }
  536. // important: index of channel
  537. nodes.back().channels.push_back(LWO::Envelope());
  538. LWO::Envelope& env = nodes.back().channels.back();
  539. env.index = strtoul10(c);
  540. // currently we can just interpret the standard channels 0...9
  541. // (hack) assume that index-i yields the binary channel type from LWO
  542. env.type = (LWO::EnvelopeType)(env.index+1);
  543. }
  544. // 'Envelope': a single animation channel
  545. else if ((*it).tokens[0] == "Envelope") {
  546. if (nodes.empty() || nodes.back().channels.empty())
  547. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Envelope\'");
  548. else {
  549. ReadEnvelope((*it),nodes.back().channels.back());
  550. }
  551. }
  552. // 'ObjectMotion': animation information for older lightwave formats
  553. else if (version < 3 && ((*it).tokens[0] == "ObjectMotion" ||
  554. (*it).tokens[0] == "CameraMotion" ||
  555. (*it).tokens[0] == "LightMotion")) {
  556. if (nodes.empty())
  557. DefaultLogger::get()->error("LWS: Unexpected keyword: \'<Light|Object|Camera>Motion\'");
  558. else {
  559. ReadEnvelope_Old(it,root.children.end(),nodes.back(),version);
  560. }
  561. }
  562. // 'Pre/PostBehavior': pre/post animation behaviour for LWSC 2
  563. else if (version == 2 && (*it).tokens[0] == "Pre/PostBehavior") {
  564. if (nodes.empty())
  565. DefaultLogger::get()->error("LWS: Unexpected keyword: \'Pre/PostBehavior'");
  566. else {
  567. for (std::list<LWO::Envelope>::iterator it = nodes.back().channels.begin(); it != nodes.back().channels.end(); ++it) {
  568. // two ints per envelope
  569. LWO::Envelope& env = *it;
  570. env.pre = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  571. env.post = (LWO::PrePostBehaviour) strtoul10(c,&c); SkipSpaces(&c);
  572. }
  573. }
  574. }
  575. // 'ParentItem': specifies the parent of the current element
  576. else if ((*it).tokens[0] == "ParentItem") {
  577. if (nodes.empty())
  578. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentItem\'");
  579. else nodes.back().parent = strtoul16(c,&c);
  580. }
  581. // 'ParentObject': deprecated one for older formats
  582. else if (version < 3 && (*it).tokens[0] == "ParentObject") {
  583. if (nodes.empty())
  584. DefaultLogger::get()->error("LWS: Unexpected keyword: \'ParentObject\'");
  585. else {
  586. nodes.back().parent = strtoul10(c,&c) | (1u << 28u);
  587. }
  588. }
  589. // 'AddCamera': add a camera to the scenegraph
  590. else if ((*it).tokens[0] == "AddCamera") {
  591. // add node to list
  592. LWS::NodeDesc d;
  593. d.type = LWS::NodeDesc::CAMERA;
  594. if (version >= 4) { // handle LWSC 4 explicit ID
  595. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  596. }
  597. else d.number = cur_camera++;
  598. nodes.push_back(d);
  599. num_camera++;
  600. }
  601. // 'CameraName': set name of currently active camera
  602. else if ((*it).tokens[0] == "CameraName") {
  603. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::CAMERA)
  604. DefaultLogger::get()->error("LWS: Unexpected keyword: \'CameraName\'");
  605. else nodes.back().name = c;
  606. }
  607. // 'AddLight': add a light to the scenegraph
  608. else if ((*it).tokens[0] == "AddLight") {
  609. // add node to list
  610. LWS::NodeDesc d;
  611. d.type = LWS::NodeDesc::LIGHT;
  612. if (version >= 4) { // handle LWSC 4 explicit ID
  613. d.number = strtoul16(c,&c) & AI_LWS_MASK;
  614. }
  615. else d.number = cur_light++;
  616. nodes.push_back(d);
  617. num_light++;
  618. }
  619. // 'LightName': set name of currently active light
  620. else if ((*it).tokens[0] == "LightName") {
  621. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  622. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightName\'");
  623. else nodes.back().name = c;
  624. }
  625. // 'LightIntensity': set intensity of currently active light
  626. else if ((*it).tokens[0] == "LightIntensity" || (*it).tokens[0] == "LgtIntensity" ) {
  627. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  628. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightIntensity\'");
  629. else fast_atoreal_move<float>(c, nodes.back().lightIntensity );
  630. }
  631. // 'LightType': set type of currently active light
  632. else if ((*it).tokens[0] == "LightType") {
  633. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  634. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightType\'");
  635. else nodes.back().lightType = strtoul10(c);
  636. }
  637. // 'LightFalloffType': set falloff type of currently active light
  638. else if ((*it).tokens[0] == "LightFalloffType") {
  639. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  640. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightFalloffType\'");
  641. else nodes.back().lightFalloffType = strtoul10(c);
  642. }
  643. // 'LightConeAngle': set cone angle of currently active light
  644. else if ((*it).tokens[0] == "LightConeAngle") {
  645. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  646. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightConeAngle\'");
  647. else nodes.back().lightConeAngle = fast_atof(c);
  648. }
  649. // 'LightEdgeAngle': set area where we're smoothing from min to max intensity
  650. else if ((*it).tokens[0] == "LightEdgeAngle") {
  651. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  652. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightEdgeAngle\'");
  653. else nodes.back().lightEdgeAngle = fast_atof(c);
  654. }
  655. // 'LightColor': set color of currently active light
  656. else if ((*it).tokens[0] == "LightColor") {
  657. if (nodes.empty() || nodes.back().type != LWS::NodeDesc::LIGHT)
  658. DefaultLogger::get()->error("LWS: Unexpected keyword: \'LightColor\'");
  659. else {
  660. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.r );
  661. SkipSpaces(&c);
  662. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.g );
  663. SkipSpaces(&c);
  664. c = fast_atoreal_move<float>(c, (float&) nodes.back().lightColor.b );
  665. }
  666. }
  667. // 'PivotPosition': position of local transformation origin
  668. else if ((*it).tokens[0] == "PivotPosition" || (*it).tokens[0] == "PivotPoint") {
  669. if (nodes.empty())
  670. DefaultLogger::get()->error("LWS: Unexpected keyword: \'PivotPosition\'");
  671. else {
  672. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.x );
  673. SkipSpaces(&c);
  674. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.y );
  675. SkipSpaces(&c);
  676. c = fast_atoreal_move<float>(c, (float&) nodes.back().pivotPos.z );
  677. // Mark pivotPos as set
  678. nodes.back().isPivotSet = true;
  679. }
  680. }
  681. }
  682. // resolve parenting
  683. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  684. // check whether there is another node which calls us a parent
  685. for (std::list<LWS::NodeDesc>::iterator dit = nodes.begin(); dit != nodes.end(); ++dit) {
  686. if (dit != it && *it == (*dit).parent) {
  687. if ((*dit).parent_resolved) {
  688. // fixme: it's still possible to produce an overflow due to cross references ..
  689. DefaultLogger::get()->error("LWS: Found cross reference in scenegraph");
  690. continue;
  691. }
  692. (*it).children.push_back(&*dit);
  693. (*dit).parent_resolved = &*it;
  694. }
  695. }
  696. }
  697. // find out how many nodes have no parent yet
  698. unsigned int no_parent = 0;
  699. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  700. if (!(*it).parent_resolved)
  701. ++ no_parent;
  702. }
  703. if (!no_parent)
  704. throw DeadlyImportError("LWS: Unable to find scene root node");
  705. // Load all subsequent files
  706. batch.LoadAll();
  707. // and build the final output graph by attaching the loaded external
  708. // files to ourselves. first build a master graph
  709. aiScene* master = new aiScene();
  710. aiNode* nd = master->mRootNode = new aiNode();
  711. // allocate storage for cameras&lights
  712. if (num_camera) {
  713. master->mCameras = new aiCamera*[master->mNumCameras = num_camera];
  714. }
  715. aiCamera** cams = master->mCameras;
  716. if (num_light) {
  717. master->mLights = new aiLight*[master->mNumLights = num_light];
  718. }
  719. aiLight** lights = master->mLights;
  720. std::vector<AttachmentInfo> attach;
  721. std::vector<aiNodeAnim*> anims;
  722. nd->mName.Set("<LWSRoot>");
  723. nd->mChildren = new aiNode*[no_parent];
  724. for (std::list<LWS::NodeDesc>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
  725. if (!(*it).parent_resolved) {
  726. aiNode* ro = nd->mChildren[ nd->mNumChildren++ ] = new aiNode();
  727. ro->mParent = nd;
  728. // ... and build the scene graph. If we encounter object nodes,
  729. // add then to our attachment table.
  730. BuildGraph(ro,*it, attach, batch, cams, lights, anims);
  731. }
  732. }
  733. // create a master animation channel for us
  734. if (anims.size()) {
  735. master->mAnimations = new aiAnimation*[master->mNumAnimations = 1];
  736. aiAnimation* anim = master->mAnimations[0] = new aiAnimation();
  737. anim->mName.Set("LWSMasterAnim");
  738. // LWS uses seconds as time units, but we convert to frames
  739. anim->mTicksPerSecond = fps;
  740. anim->mDuration = last-(first-1); /* fixme ... zero or one-based?*/
  741. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = anims.size()];
  742. std::copy(anims.begin(),anims.end(),anim->mChannels);
  743. }
  744. // convert the master scene to RH
  745. MakeLeftHandedProcess monster_cheat;
  746. monster_cheat.Execute(master);
  747. // .. ccw
  748. FlipWindingOrderProcess flipper;
  749. flipper.Execute(master);
  750. // OK ... finally build the output graph
  751. SceneCombiner::MergeScenes(&pScene,master,attach,
  752. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES | (!configSpeedFlag ? (
  753. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY | AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES) : 0));
  754. // Check flags
  755. if (!pScene->mNumMeshes || !pScene->mNumMaterials) {
  756. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  757. if (pScene->mNumAnimations && !noSkeletonMesh) {
  758. // construct skeleton mesh
  759. SkeletonMeshBuilder builder(pScene);
  760. }
  761. }
  762. }
  763. #endif // !! ASSIMP_BUILD_NO_LWS_IMPORTER