LWSLoader.cpp 34 KB

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