LWSLoader.cpp 28 KB

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