LWSLoader.cpp 30 KB

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