LWSLoader.cpp 35 KB

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