X3DImporter.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /// \file X3DImporter.cpp
  34. /// \brief X3D-format files importer for Assimp: main algorithm implementation.
  35. /// \date 2015-2016
  36. /// \author [email protected]
  37. #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER
  38. #include "X3DImporter.hpp"
  39. #include "X3DImporter_Macro.hpp"
  40. #include <assimp/DefaultIOSystem.h>
  41. // Header files, stdlib.
  42. #include <iterator>
  43. #include <memory>
  44. namespace Assimp {
  45. /// Constant which holds the importer description
  46. const aiImporterDesc X3DImporter::Description = {
  47. "Extensible 3D(X3D) Importer",
  48. "smalcom",
  49. "",
  50. "See documentation in source code. Chapter: Limitations.",
  51. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "x3d x3db"
  57. };
  58. bool X3DImporter::isNodeEmpty(XmlNode &node) {
  59. return node.first_child().empty();
  60. }
  61. void X3DImporter::checkNodeMustBeEmpty(XmlNode &node) {
  62. if (!isNodeEmpty(node)) throw DeadlyImportError(std::string("Node <") + node.name() + "> must be empty.");
  63. }
  64. void X3DImporter::skipUnsupportedNode(const std::string &pParentNodeName, XmlNode &node) {
  65. static const size_t Uns_Skip_Len = 192;
  66. static const char *Uns_Skip[Uns_Skip_Len] = {
  67. // CAD geometry component
  68. "CADAssembly", "CADFace", "CADLayer", "CADPart", "IndexedQuadSet", "QuadSet",
  69. // Core
  70. "ROUTE", "ExternProtoDeclare", "ProtoDeclare", "ProtoInstance", "ProtoInterface", "WorldInfo",
  71. // Distributed interactive simulation (DIS) component
  72. "DISEntityManager", "DISEntityTypeMapping", "EspduTransform", "ReceiverPdu", "SignalPdu", "TransmitterPdu",
  73. // Cube map environmental texturing component
  74. "ComposedCubeMapTexture", "GeneratedCubeMapTexture", "ImageCubeMapTexture",
  75. // Environmental effects component
  76. "Background", "Fog", "FogCoordinate", "LocalFog", "TextureBackground",
  77. // Environmental sensor component
  78. "ProximitySensor", "TransformSensor", "VisibilitySensor",
  79. // Followers component
  80. "ColorChaser", "ColorDamper", "CoordinateChaser", "CoordinateDamper", "OrientationChaser", "OrientationDamper", "PositionChaser", "PositionChaser2D",
  81. "PositionDamper", "PositionDamper2D", "ScalarChaser", "ScalarDamper", "TexCoordChaser2D", "TexCoordDamper2D",
  82. // Geospatial component
  83. "GeoCoordinate", "GeoElevationGrid", "GeoLocation", "GeoLOD", "GeoMetadata", "GeoOrigin", "GeoPositionInterpolator", "GeoProximitySensor",
  84. "GeoTouchSensor", "GeoTransform", "GeoViewpoint",
  85. // Humanoid Animation (H-Anim) component
  86. "HAnimDisplacer", "HAnimHumanoid", "HAnimJoint", "HAnimSegment", "HAnimSite",
  87. // Interpolation component
  88. "ColorInterpolator", "CoordinateInterpolator", "CoordinateInterpolator2D", "EaseInEaseOut", "NormalInterpolator", "OrientationInterpolator",
  89. "PositionInterpolator", "PositionInterpolator2D", "ScalarInterpolator", "SplinePositionInterpolator", "SplinePositionInterpolator2D",
  90. "SplineScalarInterpolator", "SquadOrientationInterpolator",
  91. // Key device sensor component
  92. "KeySensor", "StringSensor",
  93. // Layering component
  94. "Layer", "LayerSet", "Viewport",
  95. // Layout component
  96. "Layout", "LayoutGroup", "LayoutLayer", "ScreenFontStyle", "ScreenGroup",
  97. // Navigation component
  98. "Billboard", "Collision", "LOD", "NavigationInfo", "OrthoViewpoint", "Viewpoint", "ViewpointGroup",
  99. // Networking component
  100. "EXPORT", "IMPORT", "Anchor", "LoadSensor",
  101. // NURBS component
  102. "Contour2D", "ContourPolyline2D", "CoordinateDouble", "NurbsCurve", "NurbsCurve2D", "NurbsOrientationInterpolator", "NurbsPatchSurface",
  103. "NurbsPositionInterpolator", "NurbsSet", "NurbsSurfaceInterpolator", "NurbsSweptSurface", "NurbsSwungSurface", "NurbsTextureCoordinate",
  104. "NurbsTrimmedSurface",
  105. // Particle systems component
  106. "BoundedPhysicsModel", "ConeEmitter", "ExplosionEmitter", "ForcePhysicsModel", "ParticleSystem", "PointEmitter", "PolylineEmitter", "SurfaceEmitter",
  107. "VolumeEmitter", "WindPhysicsModel",
  108. // Picking component
  109. "LinePickSensor", "PickableGroup", "PointPickSensor", "PrimitivePickSensor", "VolumePickSensor",
  110. // Pointing device sensor component
  111. "CylinderSensor", "PlaneSensor", "SphereSensor", "TouchSensor",
  112. // Rendering component
  113. "ClipPlane",
  114. // Rigid body physics
  115. "BallJoint", "CollidableOffset", "CollidableShape", "CollisionCollection", "CollisionSensor", "CollisionSpace", "Contact", "DoubleAxisHingeJoint",
  116. "MotorJoint", "RigidBody", "RigidBodyCollection", "SingleAxisHingeJoint", "SliderJoint", "UniversalJoint",
  117. // Scripting component
  118. "Script",
  119. // Programmable shaders component
  120. "ComposedShader", "FloatVertexAttribute", "Matrix3VertexAttribute", "Matrix4VertexAttribute", "PackagedShader", "ProgramShader", "ShaderPart",
  121. "ShaderProgram",
  122. // Shape component
  123. "FillProperties", "LineProperties", "TwoSidedMaterial",
  124. // Sound component
  125. "AudioClip", "Sound",
  126. // Text component
  127. "FontStyle", "Text",
  128. // Texturing3D Component
  129. "ComposedTexture3D", "ImageTexture3D", "PixelTexture3D", "TextureCoordinate3D", "TextureCoordinate4D", "TextureTransformMatrix3D", "TextureTransform3D",
  130. // Texturing component
  131. "MovieTexture", "MultiTexture", "MultiTextureCoordinate", "MultiTextureTransform", "PixelTexture", "TextureCoordinateGenerator", "TextureProperties",
  132. // Time component
  133. "TimeSensor",
  134. // Event Utilities component
  135. "BooleanFilter", "BooleanSequencer", "BooleanToggle", "BooleanTrigger", "IntegerSequencer", "IntegerTrigger", "TimeTrigger",
  136. // Volume rendering component
  137. "BlendedVolumeStyle", "BoundaryEnhancementVolumeStyle", "CartoonVolumeStyle", "ComposedVolumeStyle", "EdgeEnhancementVolumeStyle", "IsoSurfaceVolumeData",
  138. "OpacityMapVolumeStyle", "ProjectionVolumeStyle", "SegmentedVolumeData", "ShadedVolumeStyle", "SilhouetteEnhancementVolumeStyle", "ToneMappedVolumeStyle",
  139. "VolumeData"
  140. };
  141. const std::string nn = node.name();
  142. if (nn.empty()) {
  143. const std::string nv = node.value();
  144. if (!nv.empty()) {
  145. LogInfo("Ignoring comment \"" + nv + "\" in " + pParentNodeName + ".");
  146. return;
  147. }
  148. }
  149. bool found = false;
  150. for (size_t i = 0; i < Uns_Skip_Len; i++) {
  151. if (nn == Uns_Skip[i]) {
  152. found = true;
  153. }
  154. }
  155. if (!found) throw DeadlyImportError("Unknown node \"" + nn + "\" in " + pParentNodeName + ".");
  156. LogInfo("Skipping node \"" + nn + "\" in " + pParentNodeName + ".");
  157. }
  158. X3DImporter::X3DImporter() :
  159. mNodeElementCur(nullptr),
  160. mScene(nullptr),
  161. mpIOHandler(nullptr) {
  162. // empty
  163. }
  164. X3DImporter::~X3DImporter() {
  165. // Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
  166. Clear();
  167. }
  168. void X3DImporter::Clear() {
  169. mNodeElementCur = nullptr;
  170. // Delete all elements
  171. if (!NodeElement_List.empty()) {
  172. for (std::list<X3DNodeElementBase *>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); ++it) {
  173. delete *it;
  174. }
  175. NodeElement_List.clear();
  176. }
  177. }
  178. void X3DImporter::ParseFile(const std::string &file, IOSystem *pIOHandler) {
  179. ai_assert(nullptr != pIOHandler);
  180. static const std::string mode = "rb";
  181. std::unique_ptr<IOStream> fileStream(pIOHandler->Open(file, mode));
  182. if (!fileStream.get()) {
  183. throw DeadlyImportError("Failed to open file " + file + ".");
  184. }
  185. XmlParser theParser;
  186. if (!theParser.parse(fileStream.get())) {
  187. return;
  188. }
  189. XmlNode *node = theParser.findNode("X3D");
  190. if (nullptr == node) {
  191. return;
  192. }
  193. for (auto &currentNode : node->children()) {
  194. const std::string &currentName = currentNode.name();
  195. if (currentName == "head") {
  196. readHead(currentNode);
  197. } else if (currentName == "Scene") {
  198. readScene(currentNode);
  199. } else {
  200. skipUnsupportedNode("X3D", currentNode);
  201. }
  202. }
  203. }
  204. bool X3DImporter::CanRead(const std::string &pFile, IOSystem * /*pIOHandler*/, bool checkSig) const {
  205. if (checkSig) {
  206. if (GetExtension(pFile) == "x3d")
  207. return true;
  208. }
  209. return false;
  210. }
  211. void X3DImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  212. mpIOHandler = pIOHandler;
  213. Clear();
  214. std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile, "rb"));
  215. if (!stream) {
  216. throw DeadlyImportError("Could not open file for reading");
  217. }
  218. std::string::size_type slashPos = pFile.find_last_of("\\/");
  219. mScene = pScene;
  220. pScene->mRootNode = new aiNode(pFile);
  221. pScene->mRootNode->mParent = nullptr;
  222. pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
  223. pIOHandler->PushDirectory(slashPos == std::string::npos ? std::string() : pFile.substr(0, slashPos + 1));
  224. ParseFile(pFile, pIOHandler);
  225. pIOHandler->PopDirectory();
  226. //search for root node element
  227. mNodeElementCur = NodeElement_List.front();
  228. if (mNodeElementCur == nullptr) {
  229. return;
  230. }
  231. while (mNodeElementCur->Parent != nullptr) {
  232. mNodeElementCur = mNodeElementCur->Parent;
  233. }
  234. { // fill aiScene with objects.
  235. std::list<aiMesh *> mesh_list;
  236. std::list<aiMaterial *> mat_list;
  237. std::list<aiLight *> light_list;
  238. // create nodes tree
  239. Postprocess_BuildNode(*mNodeElementCur, *pScene->mRootNode, mesh_list, mat_list, light_list);
  240. // copy needed data to scene
  241. if (!mesh_list.empty()) {
  242. std::list<aiMesh *>::const_iterator it = mesh_list.begin();
  243. pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
  244. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  245. for (size_t i = 0; i < pScene->mNumMeshes; i++)
  246. pScene->mMeshes[i] = *it++;
  247. }
  248. if (!mat_list.empty()) {
  249. std::list<aiMaterial *>::const_iterator it = mat_list.begin();
  250. pScene->mNumMaterials = static_cast<unsigned int>(mat_list.size());
  251. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  252. for (size_t i = 0; i < pScene->mNumMaterials; i++)
  253. pScene->mMaterials[i] = *it++;
  254. }
  255. if (!light_list.empty()) {
  256. std::list<aiLight *>::const_iterator it = light_list.begin();
  257. pScene->mNumLights = static_cast<unsigned int>(light_list.size());
  258. pScene->mLights = new aiLight *[pScene->mNumLights];
  259. for (size_t i = 0; i < pScene->mNumLights; i++)
  260. pScene->mLights[i] = *it++;
  261. }
  262. }
  263. }
  264. const aiImporterDesc *X3DImporter::GetInfo() const {
  265. return &Description;
  266. }
  267. struct meta_entry {
  268. std::string name;
  269. std::string value;
  270. };
  271. void X3DImporter::readHead(XmlNode &node) {
  272. std::vector<meta_entry> metaArray;
  273. for (auto currentNode : node.children()) {
  274. const std::string &currentName = currentNode.name();
  275. if (currentName == "meta") {
  276. //checkNodeMustBeEmpty(node);
  277. meta_entry entry;
  278. if (XmlParser::getStdStrAttribute(currentNode, "name", entry.name)) {
  279. XmlParser::getStdStrAttribute(currentNode, "content", entry.value);
  280. metaArray.emplace_back(entry);
  281. }
  282. }
  283. // TODO: check if other node types in head should be supported
  284. }
  285. mScene->mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(metaArray.size()));
  286. unsigned int i = 0;
  287. for (auto currentMeta : metaArray) {
  288. mScene->mMetaData->Set(i, currentMeta.name, aiString(currentMeta.value));
  289. ++i;
  290. }
  291. }
  292. void X3DImporter::readChildNodes(XmlNode &node, const std::string &pParentNodeName) {
  293. if (node.empty()) {
  294. return;
  295. }
  296. for (auto currentNode : node.children()) {
  297. const std::string &currentName = currentNode.name();
  298. if (currentName == "Shape")
  299. readShape(currentNode);
  300. else if (currentName == "Group") {
  301. startReadGroup(currentNode);
  302. readChildNodes(currentNode, "Group");
  303. endReadGroup();
  304. } else if (currentName == "StaticGroup") {
  305. startReadStaticGroup(currentNode);
  306. readChildNodes(currentNode, "StaticGroup");
  307. endReadStaticGroup();
  308. } else if (currentName == "Transform") {
  309. startReadTransform(currentNode);
  310. readChildNodes(currentNode, "Transform");
  311. endReadTransform();
  312. } else if (currentName == "Switch") {
  313. startReadSwitch(currentNode);
  314. readChildNodes(currentNode, "Switch");
  315. endReadSwitch();
  316. } else if (currentName == "DirectionalLight") {
  317. readDirectionalLight(currentNode);
  318. } else if (currentName == "PointLight") {
  319. readPointLight(currentNode);
  320. } else if (currentName == "SpotLight") {
  321. readSpotLight(currentNode);
  322. } else if (currentName == "Inline") {
  323. readInline(currentNode);
  324. } else if (!checkForMetadataNode(currentNode)) {
  325. skipUnsupportedNode(pParentNodeName, currentNode);
  326. }
  327. }
  328. }
  329. void X3DImporter::readScene(XmlNode &node) {
  330. ParseHelper_Group_Begin(true);
  331. readChildNodes(node, "Scene");
  332. ParseHelper_Node_Exit();
  333. }
  334. /*********************************************************************************************************************************************/
  335. /************************************************************ Functions: find set ************************************************************/
  336. /*********************************************************************************************************************************************/
  337. bool X3DImporter::FindNodeElement_FromRoot(const std::string &pID, const X3DElemType pType, X3DNodeElementBase **pElement) {
  338. for (std::list<X3DNodeElementBase *>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); ++it) {
  339. if (((*it)->Type == pType) && ((*it)->ID == pID)) {
  340. if (pElement != nullptr) *pElement = *it;
  341. return true;
  342. }
  343. } // for(std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++)
  344. return false;
  345. }
  346. bool X3DImporter::FindNodeElement_FromNode(X3DNodeElementBase *pStartNode, const std::string &pID,
  347. const X3DElemType pType, X3DNodeElementBase **pElement) {
  348. bool found = false; // flag: true - if requested element is found.
  349. // Check if pStartNode - this is the element, we are looking for.
  350. if ((pStartNode->Type == pType) && (pStartNode->ID == pID)) {
  351. found = true;
  352. if (pElement != nullptr) {
  353. *pElement = pStartNode;
  354. }
  355. goto fne_fn_end;
  356. } // if((pStartNode->Type() == pType) && (pStartNode->ID() == pID))
  357. // Check childs of pStartNode.
  358. for (std::list<X3DNodeElementBase *>::iterator ch_it = pStartNode->Children.begin(); ch_it != pStartNode->Children.end(); ++ch_it) {
  359. found = FindNodeElement_FromNode(*ch_it, pID, pType, pElement);
  360. if (found) {
  361. break;
  362. }
  363. } // for(std::list<CX3DImporter_NodeElement*>::iterator ch_it = it->Children.begin(); ch_it != it->Children.end(); ch_it++)
  364. fne_fn_end:
  365. return found;
  366. }
  367. bool X3DImporter::FindNodeElement(const std::string &pID, const X3DElemType pType, X3DNodeElementBase **pElement) {
  368. X3DNodeElementBase *tnd = mNodeElementCur; // temporary pointer to node.
  369. bool static_search = false; // flag: true if searching in static node.
  370. // At first check if we have deal with static node. Go up through parent nodes and check flag.
  371. while (tnd != nullptr) {
  372. if (tnd->Type == X3DElemType::ENET_Group) {
  373. if (((X3DNodeElementGroup *)tnd)->Static) {
  374. static_search = true; // Flag found, stop walking up. Node with static flag will holded in tnd variable.
  375. break;
  376. }
  377. }
  378. tnd = tnd->Parent; // go up in graph.
  379. } // while (tnd != nullptr)
  380. // at now call appropriate search function.
  381. if (static_search) {
  382. return FindNodeElement_FromNode(tnd, pID, pType, pElement);
  383. } else {
  384. return FindNodeElement_FromRoot(pID, pType, pElement);
  385. }
  386. }
  387. /*********************************************************************************************************************************************/
  388. /************************************************************ Functions: parse set ***********************************************************/
  389. /*********************************************************************************************************************************************/
  390. void X3DImporter::ParseHelper_Group_Begin(const bool pStatic) {
  391. X3DNodeElementGroup *new_group = new X3DNodeElementGroup(mNodeElementCur, pStatic); // create new node with current node as parent.
  392. // if we are adding not the root element then add new element to current element child list.
  393. if (mNodeElementCur != nullptr) {
  394. mNodeElementCur->Children.push_back(new_group);
  395. }
  396. NodeElement_List.push_back(new_group); // it's a new element - add it to list.
  397. mNodeElementCur = new_group; // switch current element to new one.
  398. }
  399. void X3DImporter::ParseHelper_Node_Enter(X3DNodeElementBase *pNode) {
  400. ai_assert(nullptr != pNode);
  401. mNodeElementCur->Children.push_back(pNode); // add new element to current element child list.
  402. mNodeElementCur = pNode; // switch current element to new one.
  403. }
  404. void X3DImporter::ParseHelper_Node_Exit() {
  405. // check if we can walk up.
  406. if (mNodeElementCur != nullptr) {
  407. mNodeElementCur = mNodeElementCur->Parent;
  408. } else {
  409. int i = 0;
  410. ++i;
  411. }
  412. }
  413. } // namespace Assimp
  414. #endif // !ASSIMP_BUILD_NO_X3D_IMPORTER