2
0

X3DImporter.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2018, 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/StringUtils.h>
  41. // Header files, Assimp.
  42. #include <assimp/DefaultIOSystem.h>
  43. #include <assimp/fast_atof.h>
  44. #include "FIReader.hpp"
  45. // Header files, stdlib.
  46. #include <memory>
  47. #include <string>
  48. #include <iterator>
  49. namespace Assimp {
  50. /// \var aiImporterDesc X3DImporter::Description
  51. /// Constant which holds the importer description
  52. const aiImporterDesc X3DImporter::Description = {
  53. "Extensible 3D(X3D) Importer",
  54. "smalcom",
  55. "",
  56. "See documentation in source code. Chapter: Limitations.",
  57. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "x3d x3db"
  63. };
  64. //const std::regex X3DImporter::pattern_nws(R"([^, \t\r\n]+)");
  65. //const std::regex X3DImporter::pattern_true(R"(^\s*(?:true|1)\s*$)", std::regex::icase);
  66. struct WordIterator: public std::iterator<std::input_iterator_tag, const char*> {
  67. static const char *whitespace;
  68. const char *start_, *end_;
  69. WordIterator(const char *start, const char *end): start_(start), end_(end) {
  70. start_ = start + strspn(start, whitespace);
  71. if (start_ >= end_) {
  72. start_ = 0;
  73. }
  74. }
  75. WordIterator(): start_(0), end_(0) {}
  76. WordIterator(const WordIterator &other): start_(other.start_), end_(other.end_) {}
  77. WordIterator &operator=(const WordIterator &other) {
  78. start_ = other.start_;
  79. end_ = other.end_;
  80. return *this;
  81. }
  82. bool operator==(const WordIterator &other) const { return start_ == other.start_; }
  83. bool operator!=(const WordIterator &other) const { return start_ != other.start_; }
  84. WordIterator &operator++() {
  85. start_ += strcspn(start_, whitespace);
  86. start_ += strspn(start_, whitespace);
  87. if (start_ >= end_) {
  88. start_ = 0;
  89. }
  90. return *this;
  91. }
  92. WordIterator operator++(int) {
  93. WordIterator result(*this);
  94. ++(*this);
  95. return result;
  96. }
  97. const char *operator*() const { return start_; }
  98. };
  99. const char *WordIterator::whitespace = ", \t\r\n";
  100. X3DImporter::X3DImporter()
  101. : NodeElement_Cur( nullptr )
  102. , mReader( nullptr ) {
  103. // empty
  104. }
  105. X3DImporter::~X3DImporter() {
  106. // Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
  107. Clear();
  108. }
  109. void X3DImporter::Clear() {
  110. NodeElement_Cur = nullptr;
  111. // Delete all elements
  112. if(NodeElement_List.size()) {
  113. for ( std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++ ) {
  114. delete *it;
  115. }
  116. NodeElement_List.clear();
  117. }
  118. }
  119. /*********************************************************************************************************************************************/
  120. /************************************************************ Functions: find set ************************************************************/
  121. /*********************************************************************************************************************************************/
  122. bool X3DImporter::FindNodeElement_FromRoot(const std::string& pID, const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  123. {
  124. for(std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++)
  125. {
  126. if(((*it)->Type == pType) && ((*it)->ID == pID))
  127. {
  128. if(pElement != nullptr) *pElement = *it;
  129. return true;
  130. }
  131. }// for(std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++)
  132. return false;
  133. }
  134. bool X3DImporter::FindNodeElement_FromNode(CX3DImporter_NodeElement* pStartNode, const std::string& pID,
  135. const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  136. {
  137. bool found = false;// flag: true - if requested element is found.
  138. // Check if pStartNode - this is the element, we are looking for.
  139. if((pStartNode->Type == pType) && (pStartNode->ID == pID))
  140. {
  141. found = true;
  142. if ( pElement != nullptr )
  143. {
  144. *pElement = pStartNode;
  145. }
  146. goto fne_fn_end;
  147. }// if((pStartNode->Type() == pType) && (pStartNode->ID() == pID))
  148. // Check childs of pStartNode.
  149. for(std::list<CX3DImporter_NodeElement*>::iterator ch_it = pStartNode->Child.begin(); ch_it != pStartNode->Child.end(); ch_it++)
  150. {
  151. found = FindNodeElement_FromNode(*ch_it, pID, pType, pElement);
  152. if ( found )
  153. {
  154. break;
  155. }
  156. }// for(std::list<CX3DImporter_NodeElement*>::iterator ch_it = it->Child.begin(); ch_it != it->Child.end(); ch_it++)
  157. fne_fn_end:
  158. return found;
  159. }
  160. bool X3DImporter::FindNodeElement(const std::string& pID, const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  161. {
  162. CX3DImporter_NodeElement* tnd = NodeElement_Cur;// temporary pointer to node.
  163. bool static_search = false;// flag: true if searching in static node.
  164. // At first check if we have deal with static node. Go up through parent nodes and check flag.
  165. while(tnd != nullptr)
  166. {
  167. if(tnd->Type == CX3DImporter_NodeElement::ENET_Group)
  168. {
  169. if(((CX3DImporter_NodeElement_Group*)tnd)->Static)
  170. {
  171. static_search = true;// Flag found, stop walking up. Node with static flag will holded in tnd variable.
  172. break;
  173. }
  174. }
  175. tnd = tnd->Parent;// go up in graph.
  176. }// while(tnd != nullptr)
  177. // at now call appropriate search function.
  178. if ( static_search )
  179. {
  180. return FindNodeElement_FromNode( tnd, pID, pType, pElement );
  181. }
  182. else
  183. {
  184. return FindNodeElement_FromRoot( pID, pType, pElement );
  185. }
  186. }
  187. /*********************************************************************************************************************************************/
  188. /************************************************************ Functions: throw set ***********************************************************/
  189. /*********************************************************************************************************************************************/
  190. void X3DImporter::Throw_ArgOutOfRange(const std::string& pArgument)
  191. {
  192. throw DeadlyImportError("Argument value is out of range for: \"" + pArgument + "\".");
  193. }
  194. void X3DImporter::Throw_CloseNotFound(const std::string& pNode)
  195. {
  196. throw DeadlyImportError("Close tag for node <" + pNode + "> not found. Seems file is corrupt.");
  197. }
  198. void X3DImporter::Throw_ConvertFail_Str2ArrF(const std::string& pAttrValue)
  199. {
  200. throw DeadlyImportError("In <" + std::string(mReader->getNodeName()) + "> failed to convert attribute value \"" + pAttrValue +
  201. "\" from string to array of floats.");
  202. }
  203. void X3DImporter::Throw_DEF_And_USE()
  204. {
  205. throw DeadlyImportError("\"DEF\" and \"USE\" can not be defined both in <" + std::string(mReader->getNodeName()) + ">.");
  206. }
  207. void X3DImporter::Throw_IncorrectAttr(const std::string& pAttrName)
  208. {
  209. throw DeadlyImportError("Node <" + std::string(mReader->getNodeName()) + "> has incorrect attribute \"" + pAttrName + "\".");
  210. }
  211. void X3DImporter::Throw_IncorrectAttrValue(const std::string& pAttrName)
  212. {
  213. throw DeadlyImportError("Attribute \"" + pAttrName + "\" in node <" + std::string(mReader->getNodeName()) + "> has incorrect value.");
  214. }
  215. void X3DImporter::Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription)
  216. {
  217. throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + mReader->getNodeName() + ". Description: " + pDescription);
  218. }
  219. void X3DImporter::Throw_TagCountIncorrect(const std::string& pNode)
  220. {
  221. throw DeadlyImportError("Count of open and close tags for node <" + pNode + "> are not equivalent. Seems file is corrupt.");
  222. }
  223. void X3DImporter::Throw_USE_NotFound(const std::string& pAttrValue)
  224. {
  225. throw DeadlyImportError("Not found node with name \"" + pAttrValue + "\" in <" + std::string(mReader->getNodeName()) + ">.");
  226. }
  227. /*********************************************************************************************************************************************/
  228. /************************************************************* Functions: XML set ************************************************************/
  229. /*********************************************************************************************************************************************/
  230. void X3DImporter::XML_CheckNode_MustBeEmpty()
  231. {
  232. if(!mReader->isEmptyElement()) throw DeadlyImportError(std::string("Node <") + mReader->getNodeName() + "> must be empty.");
  233. }
  234. void X3DImporter::XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
  235. {
  236. static const size_t Uns_Skip_Len = 192;
  237. const char* Uns_Skip[ Uns_Skip_Len ] = {
  238. // CAD geometry component
  239. "CADAssembly", "CADFace", "CADLayer", "CADPart", "IndexedQuadSet", "QuadSet",
  240. // Core
  241. "ROUTE", "ExternProtoDeclare", "ProtoDeclare", "ProtoInstance", "ProtoInterface", "WorldInfo",
  242. // Distributed interactive simulation (DIS) component
  243. "DISEntityManager", "DISEntityTypeMapping", "EspduTransform", "ReceiverPdu", "SignalPdu", "TransmitterPdu",
  244. // Cube map environmental texturing component
  245. "ComposedCubeMapTexture", "GeneratedCubeMapTexture", "ImageCubeMapTexture",
  246. // Environmental effects component
  247. "Background", "Fog", "FogCoordinate", "LocalFog", "TextureBackground",
  248. // Environmental sensor component
  249. "ProximitySensor", "TransformSensor", "VisibilitySensor",
  250. // Followers component
  251. "ColorChaser", "ColorDamper", "CoordinateChaser", "CoordinateDamper", "OrientationChaser", "OrientationDamper", "PositionChaser", "PositionChaser2D",
  252. "PositionDamper", "PositionDamper2D", "ScalarChaser", "ScalarDamper", "TexCoordChaser2D", "TexCoordDamper2D",
  253. // Geospatial component
  254. "GeoCoordinate", "GeoElevationGrid", "GeoLocation", "GeoLOD", "GeoMetadata", "GeoOrigin", "GeoPositionInterpolator", "GeoProximitySensor",
  255. "GeoTouchSensor", "GeoTransform", "GeoViewpoint",
  256. // Humanoid Animation (H-Anim) component
  257. "HAnimDisplacer", "HAnimHumanoid", "HAnimJoint", "HAnimSegment", "HAnimSite",
  258. // Interpolation component
  259. "ColorInterpolator", "CoordinateInterpolator", "CoordinateInterpolator2D", "EaseInEaseOut", "NormalInterpolator", "OrientationInterpolator",
  260. "PositionInterpolator", "PositionInterpolator2D", "ScalarInterpolator", "SplinePositionInterpolator", "SplinePositionInterpolator2D",
  261. "SplineScalarInterpolator", "SquadOrientationInterpolator",
  262. // Key device sensor component
  263. "KeySensor", "StringSensor",
  264. // Layering component
  265. "Layer", "LayerSet", "Viewport",
  266. // Layout component
  267. "Layout", "LayoutGroup", "LayoutLayer", "ScreenFontStyle", "ScreenGroup",
  268. // Navigation component
  269. "Billboard", "Collision", "LOD", "NavigationInfo", "OrthoViewpoint", "Viewpoint", "ViewpointGroup",
  270. // Networking component
  271. "EXPORT", "IMPORT", "Anchor", "LoadSensor",
  272. // NURBS component
  273. "Contour2D", "ContourPolyline2D", "CoordinateDouble", "NurbsCurve", "NurbsCurve2D", "NurbsOrientationInterpolator", "NurbsPatchSurface",
  274. "NurbsPositionInterpolator", "NurbsSet", "NurbsSurfaceInterpolator", "NurbsSweptSurface", "NurbsSwungSurface", "NurbsTextureCoordinate",
  275. "NurbsTrimmedSurface",
  276. // Particle systems component
  277. "BoundedPhysicsModel", "ConeEmitter", "ExplosionEmitter", "ForcePhysicsModel", "ParticleSystem", "PointEmitter", "PolylineEmitter", "SurfaceEmitter",
  278. "VolumeEmitter", "WindPhysicsModel",
  279. // Picking component
  280. "LinePickSensor", "PickableGroup", "PointPickSensor", "PrimitivePickSensor", "VolumePickSensor",
  281. // Pointing device sensor component
  282. "CylinderSensor", "PlaneSensor", "SphereSensor", "TouchSensor",
  283. // Rendering component
  284. "ClipPlane",
  285. // Rigid body physics
  286. "BallJoint", "CollidableOffset", "CollidableShape", "CollisionCollection", "CollisionSensor", "CollisionSpace", "Contact", "DoubleAxisHingeJoint",
  287. "MotorJoint", "RigidBody", "RigidBodyCollection", "SingleAxisHingeJoint", "SliderJoint", "UniversalJoint",
  288. // Scripting component
  289. "Script",
  290. // Programmable shaders component
  291. "ComposedShader", "FloatVertexAttribute", "Matrix3VertexAttribute", "Matrix4VertexAttribute", "PackagedShader", "ProgramShader", "ShaderPart",
  292. "ShaderProgram",
  293. // Shape component
  294. "FillProperties", "LineProperties", "TwoSidedMaterial",
  295. // Sound component
  296. "AudioClip", "Sound",
  297. // Text component
  298. "FontStyle", "Text",
  299. // Texturing3D Component
  300. "ComposedTexture3D", "ImageTexture3D", "PixelTexture3D", "TextureCoordinate3D", "TextureCoordinate4D", "TextureTransformMatrix3D", "TextureTransform3D",
  301. // Texturing component
  302. "MovieTexture", "MultiTexture", "MultiTextureCoordinate", "MultiTextureTransform", "PixelTexture", "TextureCoordinateGenerator", "TextureProperties",
  303. // Time component
  304. "TimeSensor",
  305. // Event Utilities component
  306. "BooleanFilter", "BooleanSequencer", "BooleanToggle", "BooleanTrigger", "IntegerSequencer", "IntegerTrigger", "TimeTrigger",
  307. // Volume rendering component
  308. "BlendedVolumeStyle", "BoundaryEnhancementVolumeStyle", "CartoonVolumeStyle", "ComposedVolumeStyle", "EdgeEnhancementVolumeStyle", "IsoSurfaceVolumeData",
  309. "OpacityMapVolumeStyle", "ProjectionVolumeStyle", "SegmentedVolumeData", "ShadedVolumeStyle", "SilhouetteEnhancementVolumeStyle", "ToneMappedVolumeStyle",
  310. "VolumeData"
  311. };
  312. const std::string nn( mReader->getNodeName() );
  313. bool found = false;
  314. bool close_found = false;
  315. for(size_t i = 0; i < Uns_Skip_Len; i++)
  316. {
  317. if(nn == Uns_Skip[i])
  318. {
  319. found = true;
  320. if(mReader->isEmptyElement())
  321. {
  322. close_found = true;
  323. goto casu_cres;
  324. }
  325. while(mReader->read())
  326. {
  327. if((mReader->getNodeType() == irr::io::EXN_ELEMENT_END) && (nn == mReader->getNodeName()))
  328. {
  329. close_found = true;
  330. goto casu_cres;
  331. }
  332. }
  333. }
  334. }
  335. casu_cres:
  336. if(!found) throw DeadlyImportError("Unknown node \"" + nn + "\" in " + pParentNodeName + ".");
  337. if(close_found)
  338. LogInfo("Skipping node \"" + nn + "\" in " + pParentNodeName + ".");
  339. else
  340. Throw_CloseNotFound(nn);
  341. }
  342. bool X3DImporter::XML_SearchNode(const std::string& pNodeName)
  343. {
  344. while(mReader->read())
  345. {
  346. if((mReader->getNodeType() == irr::io::EXN_ELEMENT) && XML_CheckNode_NameEqual(pNodeName)) return true;
  347. }
  348. return false;
  349. }
  350. bool X3DImporter::XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
  351. {
  352. auto boolValue = std::dynamic_pointer_cast<const FIBoolValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  353. if (boolValue) {
  354. if (boolValue->value.size() == 1) {
  355. return boolValue->value.front();
  356. }
  357. throw DeadlyImportError("Invalid bool value");
  358. }
  359. else {
  360. std::string val(mReader->getAttributeValue(pAttrIdx));
  361. if(val == "false")
  362. return false;
  363. else if(val == "true")
  364. return true;
  365. else
  366. throw DeadlyImportError("Bool attribute value can contain \"false\" or \"true\" not the \"" + val + "\"");
  367. }
  368. }
  369. float X3DImporter::XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
  370. {
  371. auto floatValue = std::dynamic_pointer_cast<const FIFloatValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  372. if (floatValue) {
  373. if (floatValue->value.size() == 1) {
  374. return floatValue->value.front();
  375. }
  376. throw DeadlyImportError("Invalid float value");
  377. }
  378. else {
  379. std::string val;
  380. float tvalf;
  381. ParseHelper_FixTruncatedFloatString(mReader->getAttributeValue(pAttrIdx), val);
  382. fast_atoreal_move(val.c_str(), tvalf, false);
  383. return tvalf;
  384. }
  385. }
  386. int32_t X3DImporter::XML_ReadNode_GetAttrVal_AsI32(const int pAttrIdx)
  387. {
  388. auto intValue = std::dynamic_pointer_cast<const FIIntValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  389. if (intValue) {
  390. if (intValue->value.size() == 1) {
  391. return intValue->value.front();
  392. }
  393. throw DeadlyImportError("Invalid int value");
  394. }
  395. else {
  396. return strtol10(mReader->getAttributeValue(pAttrIdx));
  397. }
  398. }
  399. void X3DImporter::XML_ReadNode_GetAttrVal_AsCol3f(const int pAttrIdx, aiColor3D& pValue)
  400. {
  401. std::vector<float> tlist;
  402. std::vector<float>::iterator it;
  403. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  404. if(tlist.size() != 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  405. it = tlist.begin();
  406. pValue.r = *it++;
  407. pValue.g = *it++;
  408. pValue.b = *it;
  409. }
  410. void X3DImporter::XML_ReadNode_GetAttrVal_AsVec2f(const int pAttrIdx, aiVector2D& pValue)
  411. {
  412. std::vector<float> tlist;
  413. std::vector<float>::iterator it;
  414. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  415. if(tlist.size() != 2) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  416. it = tlist.begin();
  417. pValue.x = *it++;
  418. pValue.y = *it;
  419. }
  420. void X3DImporter::XML_ReadNode_GetAttrVal_AsVec3f(const int pAttrIdx, aiVector3D& pValue)
  421. {
  422. std::vector<float> tlist;
  423. std::vector<float>::iterator it;
  424. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  425. if(tlist.size() != 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  426. it = tlist.begin();
  427. pValue.x = *it++;
  428. pValue.y = *it++;
  429. pValue.z = *it;
  430. }
  431. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrB(const int pAttrIdx, std::vector<bool>& pValue)
  432. {
  433. auto boolValue = std::dynamic_pointer_cast<const FIBoolValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  434. if (boolValue) {
  435. pValue = boolValue->value;
  436. }
  437. else {
  438. const char *val = mReader->getAttributeValue(pAttrIdx);
  439. pValue.clear();
  440. //std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  441. //const std::cregex_iterator wordItEnd;
  442. //std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::regex_match(match.str(), pattern_true); });
  443. WordIterator wordItBegin(val, val + strlen(val));
  444. WordIterator wordItEnd;
  445. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const char *match) { return (::tolower(match[0]) == 't') || (match[0] == '1'); });
  446. }
  447. }
  448. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrI32(const int pAttrIdx, std::vector<int32_t>& pValue)
  449. {
  450. auto intValue = std::dynamic_pointer_cast<const FIIntValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  451. if (intValue) {
  452. pValue = intValue->value;
  453. }
  454. else {
  455. const char *val = mReader->getAttributeValue(pAttrIdx);
  456. pValue.clear();
  457. //std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  458. //const std::cregex_iterator wordItEnd;
  459. //std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stoi(match.str()); });
  460. WordIterator wordItBegin(val, val + strlen(val));
  461. WordIterator wordItEnd;
  462. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const char *match) { return atoi(match); });
  463. }
  464. }
  465. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrF(const int pAttrIdx, std::vector<float>& pValue)
  466. {
  467. auto floatValue = std::dynamic_pointer_cast<const FIFloatValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  468. if (floatValue) {
  469. pValue = floatValue->value;
  470. }
  471. else {
  472. const char *val = mReader->getAttributeValue(pAttrIdx);
  473. pValue.clear();
  474. //std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  475. //const std::cregex_iterator wordItEnd;
  476. //std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stof(match.str()); });
  477. WordIterator wordItBegin(val, val + strlen(val));
  478. WordIterator wordItEnd;
  479. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const char *match) { return static_cast<float>(atof(match)); });
  480. }
  481. }
  482. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrD(const int pAttrIdx, std::vector<double>& pValue)
  483. {
  484. auto doubleValue = std::dynamic_pointer_cast<const FIDoubleValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  485. if (doubleValue) {
  486. pValue = doubleValue->value;
  487. }
  488. else {
  489. const char *val = mReader->getAttributeValue(pAttrIdx);
  490. pValue.clear();
  491. //std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  492. //const std::cregex_iterator wordItEnd;
  493. //std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stod(match.str()); });
  494. WordIterator wordItBegin(val, val + strlen(val));
  495. WordIterator wordItEnd;
  496. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const char *match) { return atof(match); });
  497. }
  498. }
  499. void X3DImporter::XML_ReadNode_GetAttrVal_AsListCol3f(const int pAttrIdx, std::list<aiColor3D>& pValue)
  500. {
  501. std::vector<float> tlist;
  502. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  503. if(tlist.size() % 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  504. // copy data to array
  505. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  506. {
  507. aiColor3D tcol;
  508. tcol.r = *it++;
  509. tcol.g = *it++;
  510. tcol.b = *it++;
  511. pValue.push_back(tcol);
  512. }
  513. }
  514. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol3f(const int pAttrIdx, std::vector<aiColor3D>& pValue)
  515. {
  516. std::list<aiColor3D> tlist;
  517. XML_ReadNode_GetAttrVal_AsListCol3f(pAttrIdx, tlist);// read as list
  518. // and copy to array
  519. if(tlist.size() > 0)
  520. {
  521. pValue.reserve(tlist.size());
  522. for(std::list<aiColor3D>::iterator it = tlist.begin(); it != tlist.end(); it++) pValue.push_back(*it);
  523. }
  524. }
  525. void X3DImporter::XML_ReadNode_GetAttrVal_AsListCol4f(const int pAttrIdx, std::list<aiColor4D>& pValue)
  526. {
  527. std::vector<float> tlist;
  528. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  529. if(tlist.size() % 4) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  530. // copy data to array
  531. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  532. {
  533. aiColor4D tcol;
  534. tcol.r = *it++;
  535. tcol.g = *it++;
  536. tcol.b = *it++;
  537. tcol.a = *it++;
  538. pValue.push_back(tcol);
  539. }
  540. }
  541. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol4f(const int pAttrIdx, std::vector<aiColor4D>& pValue)
  542. {
  543. std::list<aiColor4D> tlist;
  544. XML_ReadNode_GetAttrVal_AsListCol4f(pAttrIdx, tlist);// read as list
  545. // and copy to array
  546. if(tlist.size() > 0)
  547. {
  548. pValue.reserve(tlist.size());
  549. for ( std::list<aiColor4D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  550. {
  551. pValue.push_back( *it );
  552. }
  553. }
  554. }
  555. void X3DImporter::XML_ReadNode_GetAttrVal_AsListVec2f(const int pAttrIdx, std::list<aiVector2D>& pValue)
  556. {
  557. std::vector<float> tlist;
  558. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  559. if ( tlist.size() % 2 )
  560. {
  561. Throw_ConvertFail_Str2ArrF( mReader->getAttributeValue( pAttrIdx ) );
  562. }
  563. // copy data to array
  564. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  565. {
  566. aiVector2D tvec;
  567. tvec.x = *it++;
  568. tvec.y = *it++;
  569. pValue.push_back(tvec);
  570. }
  571. }
  572. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec2f(const int pAttrIdx, std::vector<aiVector2D>& pValue)
  573. {
  574. std::list<aiVector2D> tlist;
  575. XML_ReadNode_GetAttrVal_AsListVec2f(pAttrIdx, tlist);// read as list
  576. // and copy to array
  577. if(tlist.size() > 0)
  578. {
  579. pValue.reserve(tlist.size());
  580. for ( std::list<aiVector2D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  581. {
  582. pValue.push_back( *it );
  583. }
  584. }
  585. }
  586. void X3DImporter::XML_ReadNode_GetAttrVal_AsListVec3f(const int pAttrIdx, std::list<aiVector3D>& pValue)
  587. {
  588. std::vector<float> tlist;
  589. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  590. if ( tlist.size() % 3 )
  591. {
  592. Throw_ConvertFail_Str2ArrF( mReader->getAttributeValue( pAttrIdx ) );
  593. }
  594. // copy data to array
  595. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  596. {
  597. aiVector3D tvec;
  598. tvec.x = *it++;
  599. tvec.y = *it++;
  600. tvec.z = *it++;
  601. pValue.push_back(tvec);
  602. }
  603. }
  604. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec3f(const int pAttrIdx, std::vector<aiVector3D>& pValue)
  605. {
  606. std::list<aiVector3D> tlist;
  607. XML_ReadNode_GetAttrVal_AsListVec3f(pAttrIdx, tlist);// read as list
  608. // and copy to array
  609. if(tlist.size() > 0)
  610. {
  611. pValue.reserve(tlist.size());
  612. for ( std::list<aiVector3D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  613. {
  614. pValue.push_back( *it );
  615. }
  616. }
  617. }
  618. void X3DImporter::XML_ReadNode_GetAttrVal_AsListS(const int pAttrIdx, std::list<std::string>& pValue)
  619. {
  620. // make copy of attribute value - strings list.
  621. const size_t tok_str_len = strlen(mReader->getAttributeValue(pAttrIdx));
  622. if ( 0 == tok_str_len )
  623. {
  624. Throw_IncorrectAttrValue( mReader->getAttributeName( pAttrIdx ) );
  625. }
  626. // get pointer to begin of value.
  627. char *tok_str = const_cast<char*>(mReader->getAttributeValue(pAttrIdx));
  628. char *tok_str_end = tok_str + tok_str_len;
  629. // string list has following format: attr_name='"s1" "s2" "sn"'.
  630. do
  631. {
  632. char* tbeg;
  633. char* tend;
  634. size_t tlen;
  635. std::string tstr;
  636. // find begin of string(element of string list): "sn".
  637. tbeg = strstr(tok_str, "\"");
  638. if(tbeg == nullptr) Throw_IncorrectAttrValue(mReader->getAttributeName(pAttrIdx));
  639. tbeg++;// forward pointer from '\"' symbol to next after it.
  640. tok_str = tbeg;
  641. // find end of string(element of string list): "sn".
  642. tend = strstr(tok_str, "\"");
  643. if(tend == nullptr) Throw_IncorrectAttrValue(mReader->getAttributeName(pAttrIdx));
  644. tok_str = tend + 1;
  645. // create storage for new string
  646. tlen = tend - tbeg;
  647. tstr.resize(tlen);// reserve enough space and copy data
  648. memcpy((void*)tstr.data(), tbeg, tlen);// not strcpy because end of copied string from tok_str has no terminator.
  649. // and store string in output list.
  650. pValue.push_back(tstr);
  651. } while(tok_str < tok_str_end);
  652. }
  653. /*********************************************************************************************************************************************/
  654. /****************************************************** Functions: geometry helper set ******************************************************/
  655. /*********************************************************************************************************************************************/
  656. aiVector3D X3DImporter::GeometryHelper_Make_Point2D(const float pAngle, const float pRadius)
  657. {
  658. return aiVector3D(pRadius * std::cos(pAngle), pRadius * std::sin(pAngle), 0);
  659. }
  660. void X3DImporter::GeometryHelper_Make_Arc2D(const float pStartAngle, const float pEndAngle, const float pRadius, size_t pNumSegments,
  661. std::list<aiVector3D>& pVertices)
  662. {
  663. // check argument values ranges.
  664. if ( ( pStartAngle < -AI_MATH_TWO_PI_F ) || ( pStartAngle > AI_MATH_TWO_PI_F ) )
  665. {
  666. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pStartAngle" );
  667. }
  668. if ( ( pEndAngle < -AI_MATH_TWO_PI_F ) || ( pEndAngle > AI_MATH_TWO_PI_F ) )
  669. {
  670. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pEndAngle" );
  671. }
  672. if ( pRadius <= 0 )
  673. {
  674. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pRadius" );
  675. }
  676. // calculate arc angle and check type of arc
  677. float angle_full = std::fabs(pEndAngle - pStartAngle);
  678. if ( ( angle_full > AI_MATH_TWO_PI_F ) || ( angle_full == 0.0f ) )
  679. {
  680. angle_full = AI_MATH_TWO_PI_F;
  681. }
  682. // calculate angle for one step - angle to next point of line.
  683. float angle_step = angle_full / (float)pNumSegments;
  684. // make points
  685. for(size_t pi = 0; pi <= pNumSegments; pi++)
  686. {
  687. float tangle = pStartAngle + pi * angle_step;
  688. pVertices.push_back(GeometryHelper_Make_Point2D(tangle, pRadius));
  689. }// for(size_t pi = 0; pi <= pNumSegments; pi++)
  690. // if we making full circle then add last vertex equal to first vertex
  691. if(angle_full == AI_MATH_TWO_PI_F) pVertices.push_back(*pVertices.begin());
  692. }
  693. void X3DImporter::GeometryHelper_Extend_PointToLine(const std::list<aiVector3D>& pPoint, std::list<aiVector3D>& pLine)
  694. {
  695. std::list<aiVector3D>::const_iterator pit = pPoint.begin();
  696. std::list<aiVector3D>::const_iterator pit_last = pPoint.end();
  697. pit_last--;
  698. if ( pPoint.size() < 2 )
  699. {
  700. Throw_ArgOutOfRange( "GeometryHelper_Extend_PointToLine.pPoint.size() can not be less than 2." );
  701. }
  702. // add first point of first line.
  703. pLine.push_back(*pit++);
  704. // add internal points
  705. while(pit != pit_last)
  706. {
  707. pLine.push_back(*pit);// second point of previous line
  708. pLine.push_back(*pit);// first point of next line
  709. pit++;
  710. }
  711. // add last point of last line
  712. pLine.push_back(*pit);
  713. }
  714. void X3DImporter::GeometryHelper_Extend_PolylineIdxToLineIdx(const std::list<int32_t>& pPolylineCoordIdx, std::list<int32_t>& pLineCoordIdx)
  715. {
  716. std::list<int32_t>::const_iterator plit = pPolylineCoordIdx.begin();
  717. while(plit != pPolylineCoordIdx.end())
  718. {
  719. // add first point of polyline
  720. pLineCoordIdx.push_back(*plit++);
  721. while((*plit != (-1)) && (plit != pPolylineCoordIdx.end()))
  722. {
  723. std::list<int32_t>::const_iterator plit_next;
  724. plit_next = plit, plit_next++;
  725. pLineCoordIdx.push_back(*plit);// second point of previous line.
  726. pLineCoordIdx.push_back(-1);// delimiter
  727. if((*plit_next == (-1)) || (plit_next == pPolylineCoordIdx.end())) break;// current polyline is finished
  728. pLineCoordIdx.push_back(*plit);// first point of next line.
  729. plit = plit_next;
  730. }// while((*plit != (-1)) && (plit != pPolylineCoordIdx.end()))
  731. }// while(plit != pPolylineCoordIdx.end())
  732. }
  733. #define MESH_RectParallelepiped_CREATE_VERT \
  734. aiVector3D vert_set[8]; \
  735. float x1, x2, y1, y2, z1, z2, hs; \
  736. \
  737. hs = pSize.x / 2, x1 = -hs, x2 = hs; \
  738. hs = pSize.y / 2, y1 = -hs, y2 = hs; \
  739. hs = pSize.z / 2, z1 = -hs, z2 = hs; \
  740. vert_set[0].Set(x2, y1, z2); \
  741. vert_set[1].Set(x2, y2, z2); \
  742. vert_set[2].Set(x2, y2, z1); \
  743. vert_set[3].Set(x2, y1, z1); \
  744. vert_set[4].Set(x1, y1, z2); \
  745. vert_set[5].Set(x1, y2, z2); \
  746. vert_set[6].Set(x1, y2, z1); \
  747. vert_set[7].Set(x1, y1, z1)
  748. void X3DImporter::GeometryHelper_MakeQL_RectParallelepiped(const aiVector3D& pSize, std::list<aiVector3D>& pVertices)
  749. {
  750. MESH_RectParallelepiped_CREATE_VERT;
  751. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 3, 2, 1, 0);// front
  752. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 6, 7, 4, 5);// back
  753. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 7, 3, 0, 4);// left
  754. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 2, 6, 5, 1);// right
  755. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 0, 1, 5, 4);// top
  756. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 7, 6, 2, 3);// bottom
  757. }
  758. #undef MESH_RectParallelepiped_CREATE_VERT
  759. void X3DImporter::GeometryHelper_CoordIdxStr2FacesArr(const std::vector<int32_t>& pCoordIdx, std::vector<aiFace>& pFaces, unsigned int& pPrimitiveTypes) const
  760. {
  761. std::vector<int32_t> f_data(pCoordIdx);
  762. std::vector<unsigned int> inds;
  763. unsigned int prim_type = 0;
  764. if ( f_data.back() != ( -1 ) )
  765. {
  766. f_data.push_back( -1 );
  767. }
  768. // reserve average size.
  769. pFaces.reserve(f_data.size() / 3);
  770. inds.reserve(4);
  771. //PrintVectorSet("build. ci", pCoordIdx);
  772. for(std::vector<int32_t>::iterator it = f_data.begin(); it != f_data.end(); it++)
  773. {
  774. // when face is got count how many indices in it.
  775. if(*it == (-1))
  776. {
  777. aiFace tface;
  778. size_t ts;
  779. ts = inds.size();
  780. switch(ts)
  781. {
  782. case 0: goto mg_m_err;
  783. case 1: prim_type |= aiPrimitiveType_POINT; break;
  784. case 2: prim_type |= aiPrimitiveType_LINE; break;
  785. case 3: prim_type |= aiPrimitiveType_TRIANGLE; break;
  786. default: prim_type |= aiPrimitiveType_POLYGON; break;
  787. }
  788. tface.mNumIndices = static_cast<unsigned int>(ts);
  789. tface.mIndices = new unsigned int[ts];
  790. memcpy(tface.mIndices, inds.data(), ts * sizeof(unsigned int));
  791. pFaces.push_back(tface);
  792. inds.clear();
  793. }// if(*it == (-1))
  794. else
  795. {
  796. inds.push_back(*it);
  797. }// if(*it == (-1)) else
  798. }// for(std::list<int32_t>::iterator it = f_data.begin(); it != f_data.end(); it++)
  799. //PrintVectorSet("build. faces", pCoordIdx);
  800. pPrimitiveTypes = prim_type;
  801. return;
  802. mg_m_err:
  803. for(size_t i = 0, i_e = pFaces.size(); i < i_e; i++) delete [] pFaces.at(i).mIndices;
  804. pFaces.clear();
  805. }
  806. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list<aiColor3D>& pColors, const bool pColorPerVertex) const
  807. {
  808. std::list<aiColor4D> tcol;
  809. // create RGBA array from RGB.
  810. for(std::list<aiColor3D>::const_iterator it = pColors.begin(); it != pColors.end(); it++) tcol.push_back(aiColor4D((*it).r, (*it).g, (*it).b, 1));
  811. // call existing function for adding RGBA colors
  812. MeshGeometry_AddColor(pMesh, tcol, pColorPerVertex);
  813. }
  814. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list<aiColor4D>& pColors, const bool pColorPerVertex) const
  815. {
  816. std::list<aiColor4D>::const_iterator col_it = pColors.begin();
  817. if(pColorPerVertex)
  818. {
  819. if(pColors.size() < pMesh.mNumVertices)
  820. {
  821. throw DeadlyImportError("MeshGeometry_AddColor1. Colors count(" + to_string(pColors.size()) + ") can not be less than Vertices count(" +
  822. to_string(pMesh.mNumVertices) + ").");
  823. }
  824. // copy colors to mesh
  825. pMesh.mColors[0] = new aiColor4D[pMesh.mNumVertices];
  826. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mColors[0][i] = *col_it++;
  827. }// if(pColorPerVertex)
  828. else
  829. {
  830. if(pColors.size() < pMesh.mNumFaces)
  831. {
  832. throw DeadlyImportError("MeshGeometry_AddColor1. Colors count(" + to_string(pColors.size()) + ") can not be less than Faces count(" +
  833. to_string(pMesh.mNumFaces) + ").");
  834. }
  835. // copy colors to mesh
  836. pMesh.mColors[0] = new aiColor4D[pMesh.mNumVertices];
  837. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  838. {
  839. // apply color to all vertices of face
  840. for ( size_t vi = 0, vi_e = pMesh.mFaces[ fi ].mNumIndices; vi < vi_e; vi++ )
  841. {
  842. pMesh.mColors[ 0 ][ pMesh.mFaces[ fi ].mIndices[ vi ] ] = *col_it;
  843. }
  844. col_it++;
  845. }
  846. }// if(pColorPerVertex) else
  847. }
  848. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pColorIdx,
  849. const std::list<aiColor3D>& pColors, const bool pColorPerVertex) const
  850. {
  851. std::list<aiColor4D> tcol;
  852. // create RGBA array from RGB.
  853. for ( std::list<aiColor3D>::const_iterator it = pColors.begin(); it != pColors.end(); it++ )
  854. {
  855. tcol.push_back( aiColor4D( ( *it ).r, ( *it ).g, ( *it ).b, 1 ) );
  856. }
  857. // call existing function for adding RGBA colors
  858. MeshGeometry_AddColor(pMesh, pCoordIdx, pColorIdx, tcol, pColorPerVertex);
  859. }
  860. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pColorIdx,
  861. const std::list<aiColor4D>& pColors, const bool pColorPerVertex) const
  862. {
  863. std::vector<aiColor4D> col_tgt_arr;
  864. std::list<aiColor4D> col_tgt_list;
  865. std::vector<aiColor4D> col_arr_copy;
  866. if ( pCoordIdx.size() == 0 )
  867. {
  868. throw DeadlyImportError( "MeshGeometry_AddColor2. pCoordIdx can not be empty." );
  869. }
  870. // copy list to array because we are need indexed access to colors.
  871. col_arr_copy.reserve(pColors.size());
  872. for ( std::list<aiColor4D>::const_iterator it = pColors.begin(); it != pColors.end(); it++ )
  873. {
  874. col_arr_copy.push_back( *it );
  875. }
  876. if(pColorPerVertex)
  877. {
  878. if(pColorIdx.size() > 0)
  879. {
  880. // check indices array count.
  881. if(pColorIdx.size() < pCoordIdx.size())
  882. {
  883. throw DeadlyImportError("MeshGeometry_AddColor2. Colors indices count(" + to_string(pColorIdx.size()) +
  884. ") can not be less than Coords inidces count(" + to_string(pCoordIdx.size()) + ").");
  885. }
  886. // create list with colors for every vertex.
  887. col_tgt_arr.resize(pMesh.mNumVertices);
  888. for(std::vector<int32_t>::const_iterator colidx_it = pColorIdx.begin(), coordidx_it = pCoordIdx.begin(); colidx_it != pColorIdx.end(); colidx_it++, coordidx_it++)
  889. {
  890. if ( *colidx_it == ( -1 ) )
  891. {
  892. continue;// skip faces delimiter
  893. }
  894. if ( ( unsigned int ) ( *coordidx_it ) > pMesh.mNumVertices )
  895. {
  896. throw DeadlyImportError( "MeshGeometry_AddColor2. Coordinate idx is out of range." );
  897. }
  898. if ( ( unsigned int ) *colidx_it > pMesh.mNumVertices )
  899. {
  900. throw DeadlyImportError( "MeshGeometry_AddColor2. Color idx is out of range." );
  901. }
  902. col_tgt_arr[*coordidx_it] = col_arr_copy[*colidx_it];
  903. }
  904. }// if(pColorIdx.size() > 0)
  905. else
  906. {
  907. // when color indices list is absent use CoordIdx.
  908. // check indices array count.
  909. if(pColors.size() < pMesh.mNumVertices)
  910. {
  911. throw DeadlyImportError("MeshGeometry_AddColor2. Colors count(" + to_string(pColors.size()) + ") can not be less than Vertices count(" +
  912. to_string(pMesh.mNumVertices) + ").");
  913. }
  914. // create list with colors for every vertex.
  915. col_tgt_arr.resize(pMesh.mNumVertices);
  916. for ( size_t i = 0; i < pMesh.mNumVertices; i++ )
  917. {
  918. col_tgt_arr[ i ] = col_arr_copy[ i ];
  919. }
  920. }// if(pColorIdx.size() > 0) else
  921. }// if(pColorPerVertex)
  922. else
  923. {
  924. if(pColorIdx.size() > 0)
  925. {
  926. // check indices array count.
  927. if(pColorIdx.size() < pMesh.mNumFaces)
  928. {
  929. throw DeadlyImportError("MeshGeometry_AddColor2. Colors indices count(" + to_string(pColorIdx.size()) +
  930. ") can not be less than Faces count(" + to_string(pMesh.mNumFaces) + ").");
  931. }
  932. // create list with colors for every vertex using faces indices.
  933. col_tgt_arr.resize(pMesh.mNumFaces);
  934. std::vector<int32_t>::const_iterator colidx_it = pColorIdx.begin();
  935. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  936. {
  937. if((unsigned int)*colidx_it > pMesh.mNumFaces) throw DeadlyImportError("MeshGeometry_AddColor2. Face idx is out of range.");
  938. col_tgt_arr[fi] = col_arr_copy[*colidx_it++];
  939. }
  940. }// if(pColorIdx.size() > 0)
  941. else
  942. {
  943. // when color indices list is absent use CoordIdx.
  944. // check indices array count.
  945. if(pColors.size() < pMesh.mNumFaces)
  946. {
  947. throw DeadlyImportError("MeshGeometry_AddColor2. Colors count(" + to_string(pColors.size()) + ") can not be less than Faces count(" +
  948. to_string(pMesh.mNumFaces) + ").");
  949. }
  950. // create list with colors for every vertex using faces indices.
  951. col_tgt_arr.resize(pMesh.mNumFaces);
  952. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++) col_tgt_arr[fi] = col_arr_copy[fi];
  953. }// if(pColorIdx.size() > 0) else
  954. }// if(pColorPerVertex) else
  955. // copy array to list for calling function that add colors.
  956. for(std::vector<aiColor4D>::const_iterator it = col_tgt_arr.begin(); it != col_tgt_arr.end(); it++) col_tgt_list.push_back(*it);
  957. // add prepared colors list to mesh.
  958. MeshGeometry_AddColor(pMesh, col_tgt_list, pColorPerVertex);
  959. }
  960. void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pNormalIdx,
  961. const std::list<aiVector3D>& pNormals, const bool pNormalPerVertex) const
  962. {
  963. std::vector<size_t> tind;
  964. std::vector<aiVector3D> norm_arr_copy;
  965. // copy list to array because we are need indexed access to normals.
  966. norm_arr_copy.reserve(pNormals.size());
  967. for ( std::list<aiVector3D>::const_iterator it = pNormals.begin(); it != pNormals.end(); it++ )
  968. {
  969. norm_arr_copy.push_back( *it );
  970. }
  971. if(pNormalPerVertex)
  972. {
  973. if(pNormalIdx.size() > 0)
  974. {
  975. // check indices array count.
  976. if(pNormalIdx.size() != pCoordIdx.size()) throw DeadlyImportError("Normals and Coords inidces count must be equal.");
  977. tind.reserve(pNormalIdx.size());
  978. for(std::vector<int32_t>::const_iterator it = pNormalIdx.begin(); it != pNormalIdx.end(); it++)
  979. {
  980. if(*it != (-1)) tind.push_back(*it);
  981. }
  982. // copy normals to mesh
  983. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  984. for(size_t i = 0; (i < pMesh.mNumVertices) && (i < tind.size()); i++)
  985. {
  986. if(tind[i] >= norm_arr_copy.size())
  987. throw DeadlyImportError("MeshGeometry_AddNormal. Normal index(" + to_string(tind[i]) +
  988. ") is out of range. Normals count: " + to_string(norm_arr_copy.size()) + ".");
  989. pMesh.mNormals[i] = norm_arr_copy[tind[i]];
  990. }
  991. }
  992. else
  993. {
  994. if(pNormals.size() != pMesh.mNumVertices) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and vertices count must be equal.");
  995. // copy normals to mesh
  996. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  997. std::list<aiVector3D>::const_iterator norm_it = pNormals.begin();
  998. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mNormals[i] = *norm_it++;
  999. }
  1000. }// if(pNormalPerVertex)
  1001. else
  1002. {
  1003. if(pNormalIdx.size() > 0)
  1004. {
  1005. if(pMesh.mNumFaces != pNormalIdx.size()) throw DeadlyImportError("Normals faces count must be equal to mesh faces count.");
  1006. std::vector<int32_t>::const_iterator normidx_it = pNormalIdx.begin();
  1007. tind.reserve(pNormalIdx.size());
  1008. for(size_t i = 0, i_e = pNormalIdx.size(); i < i_e; i++) tind.push_back(*normidx_it++);
  1009. }
  1010. else
  1011. {
  1012. tind.reserve(pMesh.mNumFaces);
  1013. for(size_t i = 0; i < pMesh.mNumFaces; i++) tind.push_back(i);
  1014. }
  1015. // copy normals to mesh
  1016. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  1017. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  1018. {
  1019. aiVector3D tnorm;
  1020. tnorm = norm_arr_copy[tind[fi]];
  1021. for(size_t vi = 0, vi_e = pMesh.mFaces[fi].mNumIndices; vi < vi_e; vi++) pMesh.mNormals[pMesh.mFaces[fi].mIndices[vi]] = tnorm;
  1022. }
  1023. }// if(pNormalPerVertex) else
  1024. }
  1025. void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::list<aiVector3D>& pNormals, const bool pNormalPerVertex) const
  1026. {
  1027. std::list<aiVector3D>::const_iterator norm_it = pNormals.begin();
  1028. if(pNormalPerVertex)
  1029. {
  1030. if(pNormals.size() != pMesh.mNumVertices) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and vertices count must be equal.");
  1031. // copy normals to mesh
  1032. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  1033. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mNormals[i] = *norm_it++;
  1034. }// if(pNormalPerVertex)
  1035. else
  1036. {
  1037. if(pNormals.size() != pMesh.mNumFaces) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and faces count must be equal.");
  1038. // copy normals to mesh
  1039. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  1040. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  1041. {
  1042. // apply color to all vertices of face
  1043. for(size_t vi = 0, vi_e = pMesh.mFaces[fi].mNumIndices; vi < vi_e; vi++) pMesh.mNormals[pMesh.mFaces[fi].mIndices[vi]] = *norm_it;
  1044. norm_it++;
  1045. }
  1046. }// if(pNormalPerVertex) else
  1047. }
  1048. void X3DImporter::MeshGeometry_AddTexCoord(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pTexCoordIdx,
  1049. const std::list<aiVector2D>& pTexCoords) const
  1050. {
  1051. std::vector<aiVector3D> texcoord_arr_copy;
  1052. std::vector<aiFace> faces;
  1053. unsigned int prim_type;
  1054. // copy list to array because we are need indexed access to normals.
  1055. texcoord_arr_copy.reserve(pTexCoords.size());
  1056. for(std::list<aiVector2D>::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++)
  1057. {
  1058. texcoord_arr_copy.push_back(aiVector3D((*it).x, (*it).y, 0));
  1059. }
  1060. if(pTexCoordIdx.size() > 0)
  1061. {
  1062. GeometryHelper_CoordIdxStr2FacesArr(pTexCoordIdx, faces, prim_type);
  1063. if ( faces.empty() )
  1064. {
  1065. throw DeadlyImportError( "Failed to add texture coordinates to mesh, faces list is empty." );
  1066. }
  1067. if ( faces.size() != pMesh.mNumFaces )
  1068. {
  1069. throw DeadlyImportError( "Texture coordinates faces count must be equal to mesh faces count." );
  1070. }
  1071. }
  1072. else
  1073. {
  1074. GeometryHelper_CoordIdxStr2FacesArr(pCoordIdx, faces, prim_type);
  1075. }
  1076. pMesh.mTextureCoords[0] = new aiVector3D[pMesh.mNumVertices];
  1077. pMesh.mNumUVComponents[0] = 2;
  1078. for(size_t fi = 0, fi_e = faces.size(); fi < fi_e; fi++)
  1079. {
  1080. if(pMesh.mFaces[fi].mNumIndices != faces.at(fi).mNumIndices)
  1081. throw DeadlyImportError("Number of indices in texture face and mesh face must be equal. Invalid face index: " + to_string(fi) + ".");
  1082. for(size_t ii = 0; ii < pMesh.mFaces[fi].mNumIndices; ii++)
  1083. {
  1084. size_t vert_idx = pMesh.mFaces[fi].mIndices[ii];
  1085. size_t tc_idx = faces.at(fi).mIndices[ii];
  1086. pMesh.mTextureCoords[0][vert_idx] = texcoord_arr_copy.at(tc_idx);
  1087. }
  1088. }// for(size_t fi = 0, fi_e = faces.size(); fi < fi_e; fi++)
  1089. }
  1090. void X3DImporter::MeshGeometry_AddTexCoord(aiMesh& pMesh, const std::list<aiVector2D>& pTexCoords) const
  1091. {
  1092. std::vector<aiVector3D> tc_arr_copy;
  1093. if ( pTexCoords.size() != pMesh.mNumVertices )
  1094. {
  1095. throw DeadlyImportError( "MeshGeometry_AddTexCoord. Texture coordinates and vertices count must be equal." );
  1096. }
  1097. // copy list to array because we are need convert aiVector2D to aiVector3D and also get indexed access as a bonus.
  1098. tc_arr_copy.reserve(pTexCoords.size());
  1099. for ( std::list<aiVector2D>::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++ )
  1100. {
  1101. tc_arr_copy.push_back( aiVector3D( ( *it ).x, ( *it ).y, 0 ) );
  1102. }
  1103. // copy texture coordinates to mesh
  1104. pMesh.mTextureCoords[0] = new aiVector3D[pMesh.mNumVertices];
  1105. pMesh.mNumUVComponents[0] = 2;
  1106. for ( size_t i = 0; i < pMesh.mNumVertices; i++ )
  1107. {
  1108. pMesh.mTextureCoords[ 0 ][ i ] = tc_arr_copy[ i ];
  1109. }
  1110. }
  1111. aiMesh* X3DImporter::GeometryHelper_MakeMesh(const std::vector<int32_t>& pCoordIdx, const std::list<aiVector3D>& pVertices) const
  1112. {
  1113. std::vector<aiFace> faces;
  1114. unsigned int prim_type = 0;
  1115. // create faces array from input string with vertices indices.
  1116. GeometryHelper_CoordIdxStr2FacesArr(pCoordIdx, faces, prim_type);
  1117. if ( !faces.size() )
  1118. {
  1119. throw DeadlyImportError( "Failed to create mesh, faces list is empty." );
  1120. }
  1121. //
  1122. // Create new mesh and copy geometry data.
  1123. //
  1124. aiMesh *tmesh = new aiMesh;
  1125. size_t ts = faces.size();
  1126. // faces
  1127. tmesh->mFaces = new aiFace[ts];
  1128. tmesh->mNumFaces = static_cast<unsigned int>(ts);
  1129. for(size_t i = 0; i < ts; i++) tmesh->mFaces[i] = faces.at(i);
  1130. // vertices
  1131. std::list<aiVector3D>::const_iterator vit = pVertices.begin();
  1132. ts = pVertices.size();
  1133. tmesh->mVertices = new aiVector3D[ts];
  1134. tmesh->mNumVertices = static_cast<unsigned int>(ts);
  1135. for ( size_t i = 0; i < ts; i++ )
  1136. {
  1137. tmesh->mVertices[ i ] = *vit++;
  1138. }
  1139. // set primitives type and return result.
  1140. tmesh->mPrimitiveTypes = prim_type;
  1141. return tmesh;
  1142. }
  1143. /*********************************************************************************************************************************************/
  1144. /************************************************************ Functions: parse set ***********************************************************/
  1145. /*********************************************************************************************************************************************/
  1146. void X3DImporter::ParseHelper_Group_Begin(const bool pStatic)
  1147. {
  1148. CX3DImporter_NodeElement_Group* new_group = new CX3DImporter_NodeElement_Group(NodeElement_Cur, pStatic);// create new node with current node as parent.
  1149. // if we are adding not the root element then add new element to current element child list.
  1150. if ( NodeElement_Cur != nullptr )
  1151. {
  1152. NodeElement_Cur->Child.push_back( new_group );
  1153. }
  1154. NodeElement_List.push_back(new_group);// it's a new element - add it to list.
  1155. NodeElement_Cur = new_group;// switch current element to new one.
  1156. }
  1157. void X3DImporter::ParseHelper_Node_Enter(CX3DImporter_NodeElement* pNode)
  1158. {
  1159. NodeElement_Cur->Child.push_back(pNode);// add new element to current element child list.
  1160. NodeElement_Cur = pNode;// switch current element to new one.
  1161. }
  1162. void X3DImporter::ParseHelper_Node_Exit()
  1163. {
  1164. // check if we can walk up.
  1165. if ( NodeElement_Cur != nullptr )
  1166. {
  1167. NodeElement_Cur = NodeElement_Cur->Parent;
  1168. }
  1169. }
  1170. void X3DImporter::ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
  1171. {
  1172. pOutString.clear();
  1173. const size_t instr_len = strlen(pInStr);
  1174. if ( 0 == instr_len )
  1175. {
  1176. return;
  1177. }
  1178. pOutString.reserve(instr_len * 3 / 2);
  1179. // check and correct floats in format ".x". Must be "x.y".
  1180. if ( pInStr[ 0 ] == '.' )
  1181. {
  1182. pOutString.push_back( '0' );
  1183. }
  1184. pOutString.push_back(pInStr[0]);
  1185. for(size_t ci = 1; ci < instr_len; ci++)
  1186. {
  1187. if((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t')))
  1188. {
  1189. pOutString.push_back('0');
  1190. pOutString.push_back('.');
  1191. }
  1192. else
  1193. {
  1194. pOutString.push_back(pInStr[ci]);
  1195. }
  1196. }
  1197. }
  1198. extern FIVocabulary X3D_vocabulary_3_2;
  1199. extern FIVocabulary X3D_vocabulary_3_3;
  1200. void X3DImporter::ParseFile(const std::string& pFile, IOSystem* pIOHandler)
  1201. {
  1202. std::unique_ptr<FIReader> OldReader = std::move(mReader);// store current XMLreader.
  1203. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  1204. // Check whether we can read from the file
  1205. if ( file.get() == nullptr )
  1206. {
  1207. throw DeadlyImportError( "Failed to open X3D file " + pFile + "." );
  1208. }
  1209. mReader = FIReader::create(file.get());
  1210. if ( !mReader )
  1211. {
  1212. throw DeadlyImportError( "Failed to create XML reader for file" + pFile + "." );
  1213. }
  1214. mReader->registerVocabulary("urn:web3d:x3d:fi-vocabulary-3.2", &X3D_vocabulary_3_2);
  1215. mReader->registerVocabulary("urn:web3d:x3d:fi-vocabulary-3.3", &X3D_vocabulary_3_3);
  1216. // start reading
  1217. ParseNode_Root();
  1218. // restore old XMLreader
  1219. mReader = std::move(OldReader);
  1220. }
  1221. void X3DImporter::ParseNode_Root()
  1222. {
  1223. // search for root tag <X3D>
  1224. if ( !XML_SearchNode( "X3D" ) )
  1225. {
  1226. throw DeadlyImportError( "Root node \"X3D\" not found." );
  1227. }
  1228. ParseHelper_Group_Begin();// create root node element.
  1229. // parse other contents
  1230. while(mReader->read())
  1231. {
  1232. if ( mReader->getNodeType() != irr::io::EXN_ELEMENT )
  1233. {
  1234. continue;
  1235. }
  1236. if(XML_CheckNode_NameEqual("head"))
  1237. ParseNode_Head();
  1238. else if(XML_CheckNode_NameEqual("Scene"))
  1239. ParseNode_Scene();
  1240. else
  1241. XML_CheckNode_SkipUnsupported("Root");
  1242. }
  1243. // exit from root node element.
  1244. ParseHelper_Node_Exit();
  1245. }
  1246. void X3DImporter::ParseNode_Head()
  1247. {
  1248. bool close_found = false;// flag: true if close tag of node are found.
  1249. while(mReader->read())
  1250. {
  1251. if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1252. {
  1253. if(XML_CheckNode_NameEqual("meta"))
  1254. {
  1255. XML_CheckNode_MustBeEmpty();
  1256. // adding metadata from <head> as MetaString from <Scene>
  1257. bool added( false );
  1258. CX3DImporter_NodeElement_MetaString* ms = new CX3DImporter_NodeElement_MetaString(NodeElement_Cur);
  1259. ms->Name = mReader->getAttributeValueSafe("name");
  1260. // name must not be empty
  1261. if(!ms->Name.empty())
  1262. {
  1263. ms->Value.push_back(mReader->getAttributeValueSafe("content"));
  1264. NodeElement_List.push_back(ms);
  1265. if ( NodeElement_Cur != nullptr )
  1266. {
  1267. NodeElement_Cur->Child.push_back( ms );
  1268. added = true;
  1269. }
  1270. }
  1271. // if an error has occurred, release instance
  1272. if ( !added ) {
  1273. delete ms;
  1274. }
  1275. }// if(XML_CheckNode_NameEqual("meta"))
  1276. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1277. else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1278. {
  1279. if(XML_CheckNode_NameEqual("head"))
  1280. {
  1281. close_found = true;
  1282. break;
  1283. }
  1284. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT) else
  1285. }// while(mReader->read())
  1286. if ( !close_found )
  1287. {
  1288. Throw_CloseNotFound( "head" );
  1289. }
  1290. }
  1291. void X3DImporter::ParseNode_Scene()
  1292. {
  1293. auto GroupCounter_Increase = [](size_t& pCounter, const char* pGroupName) -> void
  1294. {
  1295. pCounter++;
  1296. if(pCounter == 0) throw DeadlyImportError("Group counter overflow. Too much groups with type: " + std::string(pGroupName) + ".");
  1297. };
  1298. auto GroupCounter_Decrease = [&](size_t& pCounter, const char* pGroupName) -> void
  1299. {
  1300. if(pCounter == 0) Throw_TagCountIncorrect(pGroupName);
  1301. pCounter--;
  1302. };
  1303. static const char* GroupName_Group = "Group";
  1304. static const char* GroupName_StaticGroup = "StaticGroup";
  1305. static const char* GroupName_Transform = "Transform";
  1306. static const char* GroupName_Switch = "Switch";
  1307. bool close_found = false;
  1308. size_t counter_group = 0;
  1309. size_t counter_transform = 0;
  1310. size_t counter_switch = 0;
  1311. // while create static node? Because objects name used deeper in "USE" attribute can be equal to some meta in <head> node.
  1312. ParseHelper_Group_Begin(true);
  1313. while(mReader->read())
  1314. {
  1315. if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1316. {
  1317. if(XML_CheckNode_NameEqual("Shape"))
  1318. {
  1319. ParseNode_Shape_Shape();
  1320. }
  1321. else if(XML_CheckNode_NameEqual(GroupName_Group))
  1322. {
  1323. GroupCounter_Increase(counter_group, GroupName_Group);
  1324. ParseNode_Grouping_Group();
  1325. // if node is empty then decrease group counter at this place.
  1326. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_group, GroupName_Group);
  1327. }
  1328. else if(XML_CheckNode_NameEqual(GroupName_StaticGroup))
  1329. {
  1330. GroupCounter_Increase(counter_group, GroupName_StaticGroup);
  1331. ParseNode_Grouping_StaticGroup();
  1332. // if node is empty then decrease group counter at this place.
  1333. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_group, GroupName_StaticGroup);
  1334. }
  1335. else if(XML_CheckNode_NameEqual(GroupName_Transform))
  1336. {
  1337. GroupCounter_Increase(counter_transform, GroupName_Transform);
  1338. ParseNode_Grouping_Transform();
  1339. // if node is empty then decrease group counter at this place.
  1340. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_transform, GroupName_Transform);
  1341. }
  1342. else if(XML_CheckNode_NameEqual(GroupName_Switch))
  1343. {
  1344. GroupCounter_Increase(counter_switch, GroupName_Switch);
  1345. ParseNode_Grouping_Switch();
  1346. // if node is empty then decrease group counter at this place.
  1347. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_switch, GroupName_Switch);
  1348. }
  1349. else if(XML_CheckNode_NameEqual("DirectionalLight"))
  1350. {
  1351. ParseNode_Lighting_DirectionalLight();
  1352. }
  1353. else if(XML_CheckNode_NameEqual("PointLight"))
  1354. {
  1355. ParseNode_Lighting_PointLight();
  1356. }
  1357. else if(XML_CheckNode_NameEqual("SpotLight"))
  1358. {
  1359. ParseNode_Lighting_SpotLight();
  1360. }
  1361. else if(XML_CheckNode_NameEqual("Inline"))
  1362. {
  1363. ParseNode_Networking_Inline();
  1364. }
  1365. else if(!ParseHelper_CheckRead_X3DMetadataObject())
  1366. {
  1367. XML_CheckNode_SkipUnsupported("Scene");
  1368. }
  1369. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1370. else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1371. {
  1372. if(XML_CheckNode_NameEqual("Scene"))
  1373. {
  1374. close_found = true;
  1375. break;
  1376. }
  1377. else if(XML_CheckNode_NameEqual(GroupName_Group))
  1378. {
  1379. GroupCounter_Decrease(counter_group, GroupName_Group);
  1380. ParseNode_Grouping_GroupEnd();
  1381. }
  1382. else if(XML_CheckNode_NameEqual(GroupName_StaticGroup))
  1383. {
  1384. GroupCounter_Decrease(counter_group, GroupName_StaticGroup);
  1385. ParseNode_Grouping_StaticGroupEnd();
  1386. }
  1387. else if(XML_CheckNode_NameEqual(GroupName_Transform))
  1388. {
  1389. GroupCounter_Decrease(counter_transform, GroupName_Transform);
  1390. ParseNode_Grouping_TransformEnd();
  1391. }
  1392. else if(XML_CheckNode_NameEqual(GroupName_Switch))
  1393. {
  1394. GroupCounter_Decrease(counter_switch, GroupName_Switch);
  1395. ParseNode_Grouping_SwitchEnd();
  1396. }
  1397. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT) else
  1398. }// while(mReader->read())
  1399. ParseHelper_Node_Exit();
  1400. if(counter_group) Throw_TagCountIncorrect("Group");
  1401. if(counter_transform) Throw_TagCountIncorrect("Transform");
  1402. if(counter_switch) Throw_TagCountIncorrect("Switch");
  1403. if(!close_found) Throw_CloseNotFound("Scene");
  1404. }
  1405. /*********************************************************************************************************************************************/
  1406. /******************************************************** Functions: BaseImporter set ********************************************************/
  1407. /*********************************************************************************************************************************************/
  1408. bool X3DImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const
  1409. {
  1410. const std::string extension = GetExtension(pFile);
  1411. if((extension == "x3d") || (extension == "x3db")) return true;
  1412. if(!extension.length() || pCheckSig)
  1413. {
  1414. const char* tokens[] = { "DOCTYPE X3D PUBLIC", "http://www.web3d.org/specifications/x3d" };
  1415. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 2);
  1416. }
  1417. return false;
  1418. }
  1419. void X3DImporter::GetExtensionList(std::set<std::string>& pExtensionList)
  1420. {
  1421. pExtensionList.insert("x3d");
  1422. pExtensionList.insert("x3db");
  1423. }
  1424. const aiImporterDesc* X3DImporter::GetInfo () const
  1425. {
  1426. return &Description;
  1427. }
  1428. void X3DImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  1429. {
  1430. mpIOHandler = pIOHandler;
  1431. Clear();// delete old graph.
  1432. std::string::size_type slashPos = pFile.find_last_of("\\/");
  1433. pIOHandler->PushDirectory(slashPos == std::string::npos ? std::string() : pFile.substr(0, slashPos + 1));
  1434. ParseFile(pFile, pIOHandler);
  1435. pIOHandler->PopDirectory();
  1436. //
  1437. // Assimp use static arrays of objects for fast speed of rendering. That's good, but need some additional operations/
  1438. // We know that geometry objects(meshes) are stored in <Shape>, also in <Shape>-><Appearance> materials(in Assimp logical view)
  1439. // are stored. So at first we need to count how meshes and materials are stored in scene graph.
  1440. //
  1441. // at first creating root node for aiScene.
  1442. pScene->mRootNode = new aiNode;
  1443. pScene->mRootNode->mParent = nullptr;
  1444. pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
  1445. //search for root node element
  1446. NodeElement_Cur = NodeElement_List.front();
  1447. while(NodeElement_Cur->Parent != nullptr) NodeElement_Cur = NodeElement_Cur->Parent;
  1448. {// fill aiScene with objects.
  1449. std::list<aiMesh*> mesh_list;
  1450. std::list<aiMaterial*> mat_list;
  1451. std::list<aiLight*> light_list;
  1452. // create nodes tree
  1453. Postprocess_BuildNode(*NodeElement_Cur, *pScene->mRootNode, mesh_list, mat_list, light_list);
  1454. // copy needed data to scene
  1455. if(mesh_list.size() > 0)
  1456. {
  1457. std::list<aiMesh*>::const_iterator it = mesh_list.begin();
  1458. pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
  1459. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  1460. for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *it++;
  1461. }
  1462. if(mat_list.size() > 0)
  1463. {
  1464. std::list<aiMaterial*>::const_iterator it = mat_list.begin();
  1465. pScene->mNumMaterials = static_cast<unsigned int>(mat_list.size());
  1466. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  1467. for(size_t i = 0; i < pScene->mNumMaterials; i++) pScene->mMaterials[i] = *it++;
  1468. }
  1469. if(light_list.size() > 0)
  1470. {
  1471. std::list<aiLight*>::const_iterator it = light_list.begin();
  1472. pScene->mNumLights = static_cast<unsigned int>(light_list.size());
  1473. pScene->mLights = new aiLight*[pScene->mNumLights];
  1474. for(size_t i = 0; i < pScene->mNumLights; i++) pScene->mLights[i] = *it++;
  1475. }
  1476. }// END: fill aiScene with objects.
  1477. ///TODO: IME optimize tree
  1478. }
  1479. }// namespace Assimp
  1480. #endif // !ASSIMP_BUILD_NO_X3D_IMPORTER