LWSLoader.cpp 33 KB

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