LWSLoader.cpp 34 KB

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