taml.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "taml.h"
  23. #ifndef _TAML_XMLWRITER_H_
  24. #include "persistence/taml/xml/tamlXmlWriter.h"
  25. #endif
  26. #ifndef _TAML_XMLREADER_H_
  27. #include "persistence/taml/xml/tamlXmlReader.h"
  28. #endif
  29. #ifndef _TAML_XMLPARSER_H_
  30. #include "persistence/taml/xml/tamlXmlParser.h"
  31. #endif
  32. #ifndef _TAML_BINARYWRITER_H_
  33. #include "persistence/taml/binary/tamlBinaryWriter.h"
  34. #endif
  35. #ifndef _TAML_BINARYREADER_H_
  36. #include "persistence/taml/binary/tamlBinaryReader.h"
  37. #endif
  38. /*#ifndef _TAML_JSONWRITER_H_
  39. #include "taml/json/tamlJSONWriter.h"
  40. #endif
  41. #ifndef _TAML_JSONREADER_H_
  42. #include "taml/json/tamlJSONReader.h"
  43. #endif
  44. #ifndef _TAML_JSONPARSER_H_
  45. #include "taml/json/tamlJSONParser.h"
  46. #endif*/
  47. #ifndef _FRAMEALLOCATOR_H_
  48. #include "core/frameAllocator.h"
  49. #endif
  50. #ifndef _SIMBASE_H_
  51. #include "console/simBase.h"
  52. #endif
  53. #ifndef _MATHTYPES_H_
  54. #include "math/mathTypes.h"
  55. #endif
  56. #ifndef _MPOINT2_H_
  57. #include "math/mPoint2.h"
  58. #endif
  59. #ifndef _ASSET_BASE_H_
  60. #include "assets/assetBase.h"
  61. #endif
  62. // Script bindings.
  63. #include "taml_ScriptBinding.h"
  64. // Debug Profiling.
  65. #include "platform/profiler.h"
  66. //-----------------------------------------------------------------------------
  67. IMPLEMENT_CONOBJECT(Taml);
  68. //-----------------------------------------------------------------------------
  69. StringTableEntry tamlRefIdName = StringTable->insert("TamlId");
  70. StringTableEntry tamlRefToIdName = StringTable->insert("TamlRefId");
  71. StringTableEntry tamlNamedObjectName = StringTable->insert("Name");
  72. //-----------------------------------------------------------------------------
  73. typedef Taml::TamlFormatMode _TamlFormatMode;
  74. ImplementEnumType(_TamlFormatMode,
  75. "")
  76. {
  77. Taml::XmlFormat, "xml"
  78. },
  79. { Taml::BinaryFormat, "binary" }//,
  80. //{ Taml::JSONFormat, "json" }
  81. EndImplementEnumType;
  82. //-----------------------------------------------------------------------------
  83. Taml::TamlFormatMode Taml::getFormatModeEnum(const char* label)
  84. {
  85. // Search for Mnemonic.
  86. for (U32 i = 0; i < (sizeof(__TamlFormatMode::_sEnums) / sizeof(EnumTable::Value)); i++)
  87. {
  88. if (dStricmp(__TamlFormatMode::_sEnumTable[i].getName(), label) == 0)
  89. return (TamlFormatMode)__TamlFormatMode::_sEnumTable[i].getInt();
  90. }
  91. // Warn.
  92. Con::warnf("Taml::getFormatModeEnum() - Invalid format of '%s'.", label);
  93. return Taml::InvalidFormat;
  94. }
  95. //-----------------------------------------------------------------------------
  96. const char* Taml::getFormatModeDescription(const Taml::TamlFormatMode formatMode)
  97. {
  98. // Search for Mnemonic.
  99. for (U32 i = 0; i < (sizeof(__TamlFormatMode::_sEnums) / sizeof(EnumTable::Value)); i++)
  100. {
  101. if (__TamlFormatMode::_sEnumTable[i].getInt() == (S32)formatMode)
  102. return __TamlFormatMode::_sEnumTable[i].getName();
  103. }
  104. // Warn.
  105. Con::warnf("Taml::getFormatModeDescription() - Invalid format mode.");
  106. return StringTable->EmptyString();
  107. }
  108. //-----------------------------------------------------------------------------
  109. // The string-table-entries are set to string literals below because Taml is used in a static scope and the string-table cannot currently be used like that.
  110. Taml::Taml() :
  111. mMasterNodeId(0),
  112. mFormatMode(XmlFormat),
  113. mJSONStrict(true),
  114. mBinaryCompression(true),
  115. mWriteDefaults(false),
  116. mAutoFormatXmlExtension("taml"),
  117. mAutoFormat(true),
  118. mProgenitorUpdate(true),
  119. mAutoFormatBinaryExtension("baml"),
  120. mAutoFormatJSONExtension("json")
  121. {
  122. // Reset the file-path buffer.
  123. mFilePathBuffer[0] = 0;
  124. }
  125. //-----------------------------------------------------------------------------
  126. void Taml::initPersistFields()
  127. {
  128. // Call parent.
  129. Parent::initPersistFields();
  130. addField("Format", TYPEID<_TamlFormatMode>(), Offset(mFormatMode, Taml), "The read/write format that should be used.");
  131. addField("JSONStrict", TypeBool, Offset(mBinaryCompression, Taml), "Whether to write JSON that is strictly compatible with RFC4627 or not.\n");
  132. addField("BinaryCompression", TypeBool, Offset(mBinaryCompression, Taml), "Whether ZIP compression is used on binary formatting or not.\n");
  133. addField("WriteDefaults", TypeBool, Offset(mWriteDefaults, Taml), "Whether to write static fields that are at their default or not.\n");
  134. addField("ProgenitorUpdate", TypeBool, Offset(mProgenitorUpdate, Taml), "Whether to update each type instances file-progenitor or not.\n");
  135. addField("AutoFormat", TypeBool, Offset(mAutoFormat, Taml), "Whether the format type is automatically determined by the filename extension or not.\n");
  136. addField("AutoFormatXmlExtension", TypeString, Offset(mAutoFormatXmlExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the XML format.\n");
  137. addField("AutoFormatBinaryExtension", TypeString, Offset(mAutoFormatBinaryExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the BINARY format.\n");
  138. addField("AutoFormatJSONExtension", TypeString, Offset(mAutoFormatJSONExtension, Taml), "When using auto-format, this is the extension (end of filename) used to detect the JSON format.\n");
  139. }
  140. //-----------------------------------------------------------------------------
  141. bool Taml::onAdd()
  142. {
  143. // Call parent.
  144. if (!Parent::onAdd())
  145. return false;
  146. // Set JSON strict mode.
  147. mJSONStrict = Con::getBoolVariable(TAML_JSON_STRICT_VARIBLE, true);
  148. // Reset the compilation.
  149. resetCompilation();
  150. return true;
  151. }
  152. //-----------------------------------------------------------------------------
  153. void Taml::onRemove()
  154. {
  155. // Reset the compilation.
  156. resetCompilation();
  157. // Call parent.
  158. Parent::onRemove();
  159. }
  160. //-----------------------------------------------------------------------------
  161. bool Taml::write(SimObject* pSimObject, const char* pFilename)
  162. {
  163. // Debug Profiling.
  164. PROFILE_SCOPE(Taml_Write);
  165. // Sanity!
  166. AssertFatal(pSimObject != NULL, "Cannot write a NULL object.");
  167. AssertFatal(pFilename != NULL, "Cannot write to a NULL filename.");
  168. // Expand the file-name into the file-path buffer.
  169. Con::expandToolScriptFilename(mFilePathBuffer, sizeof(mFilePathBuffer), pFilename);
  170. FileStream stream;
  171. // File opened?
  172. if (!stream.open(mFilePathBuffer, Torque::FS::File::Write))
  173. {
  174. // No, so warn.
  175. Con::warnf("Taml::writeFile() - Could not open filename '%s' for write.", mFilePathBuffer);
  176. return false;
  177. }
  178. // Get the file auto-format mode.
  179. const TamlFormatMode formatMode = getFileAutoFormatMode(mFilePathBuffer);
  180. // Reset the compilation.
  181. resetCompilation();
  182. // Write object.
  183. const bool status = write(stream, pSimObject, formatMode);
  184. // Close file.
  185. stream.close();
  186. // Reset the compilation.
  187. resetCompilation();
  188. return status;
  189. }
  190. //-----------------------------------------------------------------------------
  191. SimObject* Taml::read(const char* pFilename)
  192. {
  193. // Debug Profiling.
  194. PROFILE_SCOPE(Taml_Read);
  195. // Sanity!
  196. AssertFatal(pFilename != NULL, "Cannot read from a NULL filename.");
  197. // Expand the file-name into the file-path buffer.
  198. Con::expandScriptFilename(mFilePathBuffer, sizeof(mFilePathBuffer), pFilename);
  199. FileStream stream;
  200. // File opened?
  201. if (!stream.open(mFilePathBuffer, Torque::FS::File::Read))
  202. {
  203. // No, so warn.
  204. Con::warnf("Taml::read() - Could not open filename '%s' for read.", mFilePathBuffer);
  205. return NULL;
  206. }
  207. // Get the file auto-format mode.
  208. const TamlFormatMode formatMode = getFileAutoFormatMode(mFilePathBuffer);
  209. // Reset the compilation.
  210. resetCompilation();
  211. // Write object.
  212. SimObject* pSimObject = read(stream, formatMode);
  213. // Close file.
  214. stream.close();
  215. // Reset the compilation.
  216. resetCompilation();
  217. // Did we generate an object?
  218. if (pSimObject == NULL)
  219. {
  220. // No, so warn.
  221. Con::warnf("Taml::read() - Failed to load an object from the file '%s'.", mFilePathBuffer);
  222. }
  223. else
  224. {
  225. pSimObject->onPostAdd();
  226. }
  227. return pSimObject;
  228. }
  229. //-----------------------------------------------------------------------------
  230. bool Taml::write(FileStream& stream, SimObject* pSimObject, const TamlFormatMode formatMode)
  231. {
  232. // Sanity!
  233. AssertFatal(pSimObject != NULL, "Cannot write a NULL object.");
  234. // Compile nodes.
  235. TamlWriteNode* pRootNode = compileObject(pSimObject);
  236. // Format appropriately.
  237. switch (formatMode)
  238. {
  239. /// Xml.
  240. case XmlFormat:
  241. {
  242. // Create writer.
  243. TamlXmlWriter writer(this);
  244. // Write.
  245. return writer.write(stream, pRootNode);
  246. }
  247. /// Binary.
  248. case BinaryFormat:
  249. {
  250. // Create writer.
  251. TamlBinaryWriter writer(this);
  252. // Write.
  253. return writer.write(stream, pRootNode, mBinaryCompression);
  254. }
  255. /// JSON.
  256. case JSONFormat:
  257. {
  258. // Create writer.
  259. //TamlJSONWriter writer( this );
  260. // Write.
  261. //return writer.write( stream, pRootNode );
  262. return false;
  263. }
  264. /// Invalid.
  265. case InvalidFormat:
  266. {
  267. // Warn.
  268. Con::warnf("Taml::write() - Cannot write, invalid format.");
  269. return false;
  270. }
  271. }
  272. // Warn.
  273. Con::warnf("Taml::write() - Unknown format.");
  274. return false;
  275. }
  276. //-----------------------------------------------------------------------------
  277. SimObject* Taml::read(FileStream& stream, const TamlFormatMode formatMode)
  278. {
  279. // Format appropriately.
  280. switch (formatMode)
  281. {
  282. /// Xml.
  283. case XmlFormat:
  284. {
  285. // Create reader.
  286. TamlXmlReader reader(this);
  287. // Read.
  288. return reader.read(stream);
  289. }
  290. /// Binary.
  291. case BinaryFormat:
  292. {
  293. // Create reader.
  294. TamlBinaryReader reader(this);
  295. // Read.
  296. return reader.read(stream);
  297. }
  298. /// JSON.
  299. case JSONFormat:
  300. {
  301. // Create reader.
  302. //TamlJSONReader reader( this );
  303. // Read.
  304. //return reader.read( stream );
  305. return NULL;
  306. }
  307. /// Invalid.
  308. case InvalidFormat:
  309. {
  310. // Warn.
  311. Con::warnf("Taml::read() - Cannot read, invalid format.");
  312. return NULL;
  313. }
  314. }
  315. // Warn.
  316. Con::warnf("Taml::read() - Unknown format.");
  317. return NULL;
  318. }
  319. //-----------------------------------------------------------------------------
  320. bool Taml::parse(const char* pFilename, TamlVisitor& visitor)
  321. {
  322. // Debug Profiling.
  323. PROFILE_SCOPE(Taml_Parse);
  324. // Sanity!
  325. AssertFatal(pFilename != NULL, "Taml::parse() - Cannot parse a NULL filename.");
  326. // Fetch format mode.
  327. const TamlFormatMode formatMode = getFileAutoFormatMode(pFilename);
  328. // Handle format mode appropriately.
  329. switch (formatMode)
  330. {
  331. case XmlFormat:
  332. {
  333. // Parse with the visitor.
  334. TamlXmlParser parser;
  335. // Are property changes needed but not supported?
  336. if (visitor.wantsPropertyChanges() && !parser.canChangeProperty())
  337. {
  338. // Yes, so warn.
  339. Con::warnf("Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a specified visitor requires property changes which are not supported by the parser.", getFormatModeDescription(formatMode), pFilename);
  340. return false;
  341. }
  342. return parser.accept(pFilename, visitor);
  343. }
  344. case JSONFormat:
  345. {
  346. // Parse with the visitor.
  347. /*TamlJSONParser parser;
  348. // Are property changes needed but not supported?
  349. if ( visitor.wantsPropertyChanges() && !parser.canChangeProperty() )
  350. {
  351. // Yes, so warn.
  352. Con::warnf( "Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a specified visitor requires property changes which are not supported by the parser.", getFormatModeDescription(formatMode), pFilename );
  353. return false;
  354. }
  355. return parser.accept( pFilename, visitor ); */
  356. return false;
  357. }
  358. case BinaryFormat:
  359. default:
  360. break;
  361. }
  362. // Warn.
  363. Con::warnf("Taml::parse() - Cannot parse '%s' file-type for filename '%s' as a required parser is not available.", getFormatModeDescription(formatMode), pFilename);
  364. return false;
  365. }
  366. //-----------------------------------------------------------------------------
  367. void Taml::resetCompilation(void)
  368. {
  369. // Debug Profiling.
  370. PROFILE_SCOPE(Taml_ResetCompilation);
  371. // Clear compiled nodes.
  372. for (typeNodeVector::iterator itr = mCompiledNodes.begin(); itr != mCompiledNodes.end(); ++itr)
  373. {
  374. // Fetch node.
  375. TamlWriteNode* pNode = (*itr);
  376. // Reset node.
  377. pNode->resetNode();
  378. // Delete node.
  379. delete pNode;
  380. }
  381. mCompiledNodes.clear();
  382. // Clear compiled objects.
  383. mCompiledObjects.clear();
  384. // Reset master node Id.
  385. mMasterNodeId = 0;
  386. }
  387. //-----------------------------------------------------------------------------
  388. Taml::TamlFormatMode Taml::getFileAutoFormatMode(const char* pFilename)
  389. {
  390. // Sanity!
  391. AssertFatal(pFilename != NULL, "Taml::getFileAutoFormatMode() - Cannot auto-format using a NULL filename.");
  392. // Is auto-format active?
  393. if (mAutoFormat)
  394. {
  395. // Yes, so fetch the extension lengths.
  396. const U32 xmlExtensionLength = dStrlen(mAutoFormatXmlExtension);
  397. const U32 binaryExtensionLength = dStrlen(mAutoFormatBinaryExtension);
  398. const U32 jsonExtensionLength = dStrlen(mAutoFormatJSONExtension);
  399. // Fetch filename length.
  400. const U32 filenameLength = dStrlen(pFilename);
  401. // Fetch end of filename,
  402. const char* pEndOfFilename = pFilename + filenameLength;
  403. // Check for the XML format.
  404. if (xmlExtensionLength <= filenameLength && dStricmp(pEndOfFilename - xmlExtensionLength, mAutoFormatXmlExtension) == 0)
  405. return Taml::XmlFormat;
  406. // Check for the Binary format.
  407. if (binaryExtensionLength <= filenameLength && dStricmp(pEndOfFilename - xmlExtensionLength, mAutoFormatBinaryExtension) == 0)
  408. return Taml::BinaryFormat;
  409. // Check for the XML format.
  410. if (jsonExtensionLength <= filenameLength && dStricmp(pEndOfFilename - jsonExtensionLength, mAutoFormatJSONExtension) == 0)
  411. return Taml::JSONFormat;
  412. }
  413. // Use the explicitly specified format mode.
  414. return mFormatMode;
  415. }
  416. //-----------------------------------------------------------------------------
  417. TamlWriteNode* Taml::compileObject(SimObject* pSimObject, const bool forceId)
  418. {
  419. // Debug Profiling.
  420. PROFILE_SCOPE(Taml_CompileObject);
  421. // Sanity!
  422. AssertFatal(pSimObject != NULL, "Taml::compileObject() - Cannot compile a NULL object.");
  423. // Fetch object Id.
  424. const SimObjectId objectId = pSimObject->getId();
  425. // Find a previously compiled node.
  426. typeCompiledHash::Iterator compiledItr = mCompiledObjects.find(objectId);
  427. // Have we already compiled this?
  428. if (compiledItr != mCompiledObjects.end())
  429. {
  430. // Yes, so sanity!
  431. AssertFatal(mCompiledNodes.size() != 0, "Taml::compileObject() - Found a compiled node at the root.");
  432. // Yes, so fetch node.
  433. TamlWriteNode* compiledNode = compiledItr->value;
  434. // Is a reference Id already present?
  435. if (compiledNode->mRefId == 0)
  436. {
  437. // No, so allocate one.
  438. compiledNode->mRefId = ++mMasterNodeId;
  439. }
  440. // Create write node.
  441. TamlWriteNode* pNewNode = new TamlWriteNode();
  442. pNewNode->set(pSimObject);
  443. // Set reference node.
  444. pNewNode->mRefToNode = compiledNode;
  445. // Push new node.
  446. mCompiledNodes.push_back(pNewNode);
  447. return pNewNode;
  448. }
  449. // No, so create write node.
  450. TamlWriteNode* pNewNode = new TamlWriteNode();
  451. pNewNode->set(pSimObject);
  452. // Is an Id being forced for this object?
  453. if (forceId)
  454. {
  455. // Yes, so allocate one.
  456. pNewNode->mRefId = ++mMasterNodeId;
  457. }
  458. // Push new node.
  459. mCompiledNodes.push_back(pNewNode);
  460. // Insert compiled object.
  461. mCompiledObjects.insertUnique(objectId, pNewNode);
  462. // Are there any Taml callbacks?
  463. if (pNewNode->mpTamlCallbacks != NULL)
  464. {
  465. // Yes, so call it.
  466. tamlPreWrite(pNewNode->mpTamlCallbacks);
  467. }
  468. // Compile static and dynamic fields.
  469. compileStaticFields(pNewNode);
  470. compileDynamicFields(pNewNode);
  471. // Compile children.
  472. compileChildren(pNewNode);
  473. // Compile custom state.
  474. compileCustomState(pNewNode);
  475. // Are there any Taml callbacks?
  476. if (pNewNode->mpTamlCallbacks != NULL)
  477. {
  478. // Yes, so call it.
  479. tamlPostWrite(pNewNode->mpTamlCallbacks);
  480. }
  481. return pNewNode;
  482. }
  483. //-----------------------------------------------------------------------------
  484. void Taml::compileStaticFields(TamlWriteNode* pTamlWriteNode)
  485. {
  486. // Debug Profiling.
  487. PROFILE_SCOPE(Taml_CompileStaticFields);
  488. // Sanity!
  489. AssertFatal(pTamlWriteNode != NULL, "Cannot compile static fields on a NULL node.");
  490. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile static fields on a node with no object.");
  491. // Fetch object.
  492. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  493. // Fetch field list.
  494. const AbstractClassRep::FieldList& fieldList = pSimObject->getFieldList();
  495. // Fetch field count.
  496. const U32 fieldCount = fieldList.size();
  497. ConsoleObject* defaultConObject;
  498. SimObject* defaultObject;
  499. if (!getWriteDefaults())
  500. {
  501. // Create a default object of the same type
  502. defaultConObject = ConsoleObject::create(pSimObject->getClassName());
  503. defaultObject = dynamic_cast<SimObject*>(defaultConObject);
  504. // ***Really*** shouldn't happen
  505. if (!defaultObject)
  506. return;
  507. }
  508. // Iterate fields.
  509. U8 arrayDepth = 0;
  510. TamlCustomNode* currentArrayNode = NULL;
  511. for (U32 index = 0; index < fieldCount; ++index)
  512. {
  513. // Fetch field.
  514. const AbstractClassRep::Field* pField = &fieldList[index];
  515. // Ignore if field not appropriate.
  516. if (pField->type == AbstractClassRep::DeprecatedFieldType ||
  517. pField->type == AbstractClassRep::StartGroupFieldType ||
  518. pField->type == AbstractClassRep::EndGroupFieldType)
  519. continue;
  520. if (pField->type == AbstractClassRep::StartArrayFieldType)
  521. {
  522. TamlCustomNodes& pCustomNodes = pTamlWriteNode->mCustomNodes;
  523. currentArrayNode = pCustomNodes.addNode(pField->pGroupname);
  524. for (U16 idx = 0; idx < pField->elementCount; idx++)
  525. currentArrayNode->addNode(pField->pFieldname);
  526. arrayDepth++;
  527. continue;
  528. }
  529. if (pField->type == AbstractClassRep::EndArrayFieldType)
  530. {
  531. arrayDepth--;
  532. continue;
  533. }
  534. if (arrayDepth == 0 && pField->elementCount > 1)
  535. {
  536. TamlCustomNodes& pCustomNodes = pTamlWriteNode->mCustomNodes;
  537. char* niceFieldName = const_cast<char *>(pField->pFieldname);
  538. niceFieldName[0] = dToupper(niceFieldName[0]);
  539. String str_niceFieldName = String(niceFieldName);
  540. currentArrayNode = pCustomNodes.addNode(str_niceFieldName + "s");
  541. for (U16 idx = 0; idx < pField->elementCount; idx++)
  542. currentArrayNode->addNode(str_niceFieldName);
  543. }
  544. // Fetch fieldname.
  545. StringTableEntry fieldName = StringTable->insert(pField->pFieldname);
  546. // Fetch element count.
  547. const U32 elementCount = pField->elementCount;
  548. // Skip if the field should not be written.
  549. // For now, we only deal with non-array fields.
  550. if (elementCount == 1 &&
  551. pField->setDataFn != NULL &&
  552. (!getWriteDefaults() && pField->writeDataFn(pSimObject, fieldName) == false))
  553. continue;
  554. // Iterate elements.
  555. for (U32 elementIndex = 0; elementIndex < elementCount; ++elementIndex)
  556. {
  557. char indexBuffer[8];
  558. dSprintf(indexBuffer, 8, "%d", elementIndex);
  559. // Fetch object field value.
  560. const char* pFieldValue = pSimObject->getPrefixedDataField(fieldName, indexBuffer);
  561. if (!pFieldValue)
  562. pFieldValue = StringTable->EmptyString();
  563. U32 nBufferSize = dStrlen(pFieldValue) + 1;
  564. FrameTemp<char> valueCopy(nBufferSize);
  565. dStrcpy((char *)valueCopy, pFieldValue, nBufferSize);
  566. // Skip if field should not be written.
  567. if (!pSimObject->writeField(fieldName, valueCopy))
  568. continue;
  569. if (!getWriteDefaults())
  570. {
  571. //If the field hasn't been changed from the default value, then don't bother writing it out
  572. const char* fieldData = defaultObject->getDataField(fieldName, indexBuffer);
  573. if (fieldData != '\0' && dStricmp(fieldData, pFieldValue) == 0)
  574. continue;
  575. }
  576. // Reassign field value.
  577. pFieldValue = valueCopy;
  578. if (pField->type == TypeBool)
  579. pFieldValue = dAtob(pFieldValue) ? "true" : "false";
  580. // Detect and collapse relative path information
  581. char fnBuf[1024];
  582. if ((S32)pField->type == TypeFilename)
  583. {
  584. Con::collapseScriptFilename(fnBuf, 1024, pFieldValue);
  585. pFieldValue = fnBuf;
  586. }
  587. // Save field/value.
  588. if (arrayDepth > 0 || pField->elementCount > 1)
  589. currentArrayNode->getChildren()[elementIndex]->addField(fieldName, pFieldValue);
  590. else
  591. {
  592. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(fieldName, pFieldValue);
  593. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  594. }
  595. }
  596. }
  597. if (!getWriteDefaults())
  598. {
  599. // Cleanup our created default object
  600. delete defaultConObject;
  601. }
  602. }
  603. //-----------------------------------------------------------------------------
  604. static S32 QSORT_CALLBACK compareFieldEntries(const void* a, const void* b)
  605. {
  606. // Debug Profiling.
  607. PROFILE_SCOPE(Taml_CompareFieldEntries);
  608. SimFieldDictionary::Entry *fa = *((SimFieldDictionary::Entry **)a);
  609. SimFieldDictionary::Entry *fb = *((SimFieldDictionary::Entry **)b);
  610. return dStricmp(fa->slotName, fb->slotName);
  611. }
  612. //-----------------------------------------------------------------------------
  613. void Taml::compileDynamicFields(TamlWriteNode* pTamlWriteNode)
  614. {
  615. // Debug Profiling.
  616. PROFILE_SCOPE(Taml_CompileDynamicFields);
  617. // Sanity!
  618. AssertFatal(pTamlWriteNode != NULL, "Cannot compile dynamic fields on a NULL node.");
  619. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile dynamic fields on a node with no object.");
  620. // Fetch object.
  621. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  622. // Fetch field dictionary.
  623. SimFieldDictionary* pFieldDictionary = pSimObject->getFieldDictionary();
  624. // Ignore if not writing dynamic fields.
  625. if (!pFieldDictionary || !pSimObject->getCanSaveDynamicFields())
  626. return;
  627. // Fetch field list.
  628. const AbstractClassRep::FieldList& fieldList = pSimObject->getFieldList();
  629. // Fetch field count.
  630. const U32 fieldCount = fieldList.size();
  631. Vector<SimFieldDictionary::Entry*> dynamicFieldList(__FILE__, __LINE__);
  632. // Ensure the dynamic field doesn't conflict with static field.
  633. for (U32 hashIndex = 0; hashIndex < SimFieldDictionary::HashTableSize; ++hashIndex)
  634. {
  635. for (SimFieldDictionary::Entry* pEntry = pFieldDictionary->mHashTable[hashIndex]; pEntry; pEntry = pEntry->next)
  636. {
  637. // Iterate static fields.
  638. U32 fieldIndex;
  639. for (fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
  640. {
  641. if (fieldList[fieldIndex].pFieldname == pEntry->slotName)
  642. break;
  643. }
  644. // Skip if found.
  645. if (fieldIndex != (U32)fieldList.size())
  646. continue;
  647. // Skip if not writing field.
  648. if (!pSimObject->writeField(pEntry->slotName, pEntry->value))
  649. continue;
  650. dynamicFieldList.push_back(pEntry);
  651. }
  652. }
  653. // Sort Entries to prevent version control conflicts
  654. if (dynamicFieldList.size() > 1)
  655. dQsort(dynamicFieldList.address(), dynamicFieldList.size(), sizeof(SimFieldDictionary::Entry*), compareFieldEntries);
  656. // Save the fields.
  657. for (Vector<SimFieldDictionary::Entry*>::iterator entryItr = dynamicFieldList.begin(); entryItr != dynamicFieldList.end(); ++entryItr)
  658. {
  659. // Fetch entry.
  660. SimFieldDictionary::Entry* pEntry = *entryItr;
  661. // Save field/value.
  662. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(pEntry->slotName, pEntry->value);
  663. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  664. }
  665. }
  666. //-----------------------------------------------------------------------------
  667. void Taml::compileChildren(TamlWriteNode* pTamlWriteNode)
  668. {
  669. // Debug Profiling.
  670. PROFILE_SCOPE(Taml_CompileChildren);
  671. // Sanity!
  672. AssertFatal(pTamlWriteNode != NULL, "Cannot compile children on a NULL node.");
  673. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile children on a node with no object.");
  674. // Fetch object.
  675. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  676. // Fetch the Taml children.
  677. TamlChildren* pChildren = dynamic_cast<TamlChildren*>(pSimObject);
  678. // Finish if object does not contain Taml children.
  679. if (pChildren == NULL || pChildren->getTamlChildCount() == 0)
  680. return;
  681. // Create children vector.
  682. pTamlWriteNode->mChildren = new typeNodeVector();
  683. // Fetch the child count.
  684. const U32 childCount = pChildren->getTamlChildCount();
  685. // Iterate children.
  686. for (U32 childIndex = 0; childIndex < childCount; childIndex++)
  687. {
  688. // Compile object.
  689. TamlWriteNode* pChildTamlWriteNode = compileObject(pChildren->getTamlChild(childIndex));
  690. // Save node.
  691. pTamlWriteNode->mChildren->push_back(pChildTamlWriteNode);
  692. }
  693. }
  694. //-----------------------------------------------------------------------------
  695. void Taml::compileCustomState(TamlWriteNode* pTamlWriteNode)
  696. {
  697. // Debug Profiling.
  698. PROFILE_SCOPE(Taml_CompileCustomProperties);
  699. // Sanity!
  700. AssertFatal(pTamlWriteNode != NULL, "Cannot compile custom state on a NULL node.");
  701. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile custom state on a node with no object.");
  702. // Fetch the custom node on the write node.
  703. TamlCustomNodes& customNodes = pTamlWriteNode->mCustomNodes;
  704. // Are there any Taml callbacks?
  705. if (pTamlWriteNode->mpTamlCallbacks != NULL)
  706. {
  707. // Yes, so call it.
  708. tamlCustomWrite(pTamlWriteNode->mpTamlCallbacks, customNodes);
  709. }
  710. // Fetch custom nodes.
  711. const TamlCustomNodeVector& nodes = customNodes.getNodes();
  712. // Finish if no custom nodes to process.
  713. if (nodes.size() == 0)
  714. return;
  715. // Iterate custom properties.
  716. for (TamlCustomNodeVector::const_iterator customNodesItr = nodes.begin(); customNodesItr != nodes.end(); ++customNodesItr)
  717. {
  718. // Fetch the custom node.
  719. TamlCustomNode* pCustomNode = *customNodesItr;
  720. // Compile custom node state.
  721. compileCustomNodeState(pCustomNode);
  722. }
  723. }
  724. //-----------------------------------------------------------------------------
  725. void Taml::compileCustomNodeState(TamlCustomNode* pCustomNode)
  726. {
  727. // Sanity!
  728. AssertFatal(pCustomNode != NULL, "Taml: Cannot compile NULL custom node state.");
  729. // Fetch children.
  730. const TamlCustomNodeVector& children = pCustomNode->getChildren();
  731. // Fetch proxy object.
  732. SimObject* pProxyObject = pCustomNode->getProxyObject<SimObject>(false);
  733. // Do we have a proxy object?
  734. if (pProxyObject != NULL)
  735. {
  736. // Yes, so sanity!
  737. AssertFatal(children.size() == 0, "Taml: Cannot compile a proxy object on a custom node that has children.");
  738. // Yes, so compile it.
  739. // NOTE: We force an Id for custom compiled objects so we guarantee an Id. The reason for this is fairly
  740. // weak in that the XML parser currently has no way of distinguishing between a compiled object node
  741. // and a custom node. If the node has an Id or an Id-Ref then it's obviously an object and should be parsed as such.
  742. pCustomNode->setWriteNode(compileObject(pProxyObject, true));
  743. return;
  744. }
  745. // Finish if no children.
  746. if (children.size() == 0)
  747. return;
  748. // Iterate children.
  749. for (TamlCustomNodeVector::const_iterator childItr = children.begin(); childItr != children.end(); ++childItr)
  750. {
  751. // Fetch shape node.
  752. TamlCustomNode* pChildNode = *childItr;
  753. // Compile the child.
  754. compileCustomNodeState(pChildNode);
  755. }
  756. }
  757. //-----------------------------------------------------------------------------
  758. SimObject* Taml::createType(StringTableEntry typeName, const Taml* pTaml, const char* pProgenitorSuffix)
  759. {
  760. // Debug Profiling.
  761. PROFILE_SCOPE(Taml_CreateType);
  762. typedef HashTable<StringTableEntry, AbstractClassRep*> typeClassHash;
  763. static typeClassHash mClassMap;
  764. // Sanity!
  765. AssertFatal(typeName != NULL, "Taml: Type cannot be NULL");
  766. // Find type.
  767. typeClassHash::Iterator typeItr = mClassMap.find(typeName);
  768. // Found type?
  769. if (typeItr == mClassMap.end())
  770. {
  771. // No, so find type.
  772. AbstractClassRep* pClassRep = AbstractClassRep::getClassList();
  773. while (pClassRep)
  774. {
  775. // Is this the type?
  776. if (dStricmp(pClassRep->getClassName(), typeName) == 0)
  777. {
  778. // Yes, so insert it.
  779. typeItr = mClassMap.insertUnique(typeName, pClassRep);
  780. break;
  781. }
  782. // Next type.
  783. pClassRep = pClassRep->getNextClass();
  784. }
  785. // Did we find the type?
  786. if (typeItr == mClassMap.end())
  787. {
  788. // No, so warn and fail.
  789. Con::warnf("Taml: Failed to create type '%s' as such a registered type could not be found.", typeName);
  790. return NULL;
  791. }
  792. }
  793. // Create the object.
  794. ConsoleObject* pConsoleObject = typeItr->value->create();
  795. // NOTE: It is important that we don't register the object here as many objects rely on the fact that
  796. // fields are set prior to the object being registered. Registering here will invalid those assumptions.
  797. // Fetch the SimObject.
  798. SimObject* pSimObject = dynamic_cast<SimObject*>(pConsoleObject);
  799. // Was it a SimObject?
  800. if (pSimObject == NULL)
  801. {
  802. // No, so warn.
  803. Con::warnf("Taml: Failed to create type '%s' as it is not a SimObject.", typeName);
  804. // Destroy object and fail.
  805. delete pConsoleObject;
  806. return NULL;
  807. }
  808. // Are we updating the file-progenitor?
  809. if (pTaml->getProgenitorUpdate())
  810. {
  811. // Yes, so do we have a progenitor suffix?
  812. if (pProgenitorSuffix == NULL)
  813. {
  814. // No, so just set it to the progenitor file.
  815. pSimObject->setProgenitorFile(pTaml->getFilePathBuffer());
  816. }
  817. else
  818. {
  819. // Yes, so format the progenitor buffer.
  820. char progenitorBuffer[2048];
  821. dSprintf(progenitorBuffer, sizeof(progenitorBuffer), "%s,%s", pTaml->getFilePathBuffer(), pProgenitorSuffix);
  822. // Set the progenitor file.
  823. pSimObject->setProgenitorFile(progenitorBuffer);
  824. }
  825. }
  826. return pSimObject;
  827. }
  828. //-----------------------------------------------------------------------------
  829. bool Taml::generateTamlSchema()
  830. {
  831. // Fetch any TAML Schema file reference.
  832. const char* pTamlSchemaFile = Con::getVariable(TAML_SCHEMA_VARIABLE);
  833. // Do we have a schema file reference?
  834. if (pTamlSchemaFile == NULL || *pTamlSchemaFile == 0)
  835. {
  836. // No, so warn.
  837. Con::warnf("Taml::generateTamlSchema() - Cannot write a TAML schema as no schema variable is set ('%s').", TAML_SCHEMA_VARIABLE);
  838. return false;
  839. }
  840. // Expand the file-name into the file-path buffer.
  841. char filePathBuffer[1024];
  842. Con::expandToolScriptFilename(filePathBuffer, sizeof(filePathBuffer), pTamlSchemaFile);
  843. FileStream stream;
  844. // File opened?
  845. /*if ( !stream.open( filePathBuffer, Torque::FS::File::Write ) )
  846. {
  847. // No, so warn.
  848. Con::warnf("Taml::GenerateTamlSchema() - Could not open filename '%s' for write.", filePathBuffer );
  849. return false;
  850. }*/
  851. // Create document.
  852. tinyxml2::XMLDocument schemaDocument;
  853. // Add declaration.
  854. tinyxml2::XMLDeclaration* schemaDeclaration = schemaDocument.NewDeclaration("xml version=\"1.0\" encoding=\"iso-8859-1\" standalone =\"no\"");
  855. schemaDocument.InsertEndChild(schemaDeclaration);
  856. // Add schema element.
  857. tinyxml2::XMLElement* pSchemaElement = schemaDocument.NewElement("xs:schema");
  858. pSchemaElement->SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
  859. schemaDocument.LinkEndChild(pSchemaElement);
  860. // Fetch class-rep root.
  861. AbstractClassRep* pRootType = AbstractClassRep::getClassList();
  862. // Fetch SimObject class rep.
  863. AbstractClassRep* pSimObjectType = AbstractClassRep::findClassRep("SimObject");
  864. // Sanity!
  865. AssertFatal(pSimObjectType != NULL, "Taml::GenerateTamlSchema() - Could not find SimObject class rep.");
  866. // Reset scratch state.
  867. char buffer[1024];
  868. HashTable<AbstractClassRep*, StringTableEntry> childGroups;
  869. // *************************************************************
  870. // Generate console type elements.
  871. // *************************************************************
  872. // Vector2.
  873. tinyxml2::XMLComment* pVector2Comment = schemaDocument.NewComment("Vector2 Console Type");
  874. pSchemaElement->LinkEndChild(pVector2Comment);
  875. tinyxml2::XMLElement* pVector2TypeElement = schemaDocument.NewElement("xs:simpleType");
  876. pVector2TypeElement->SetAttribute("name", "Vector2_ConsoleType");
  877. pSchemaElement->LinkEndChild(pVector2TypeElement);
  878. tinyxml2::XMLElement* pVector2ElementA = schemaDocument.NewElement("xs:restriction");
  879. pVector2ElementA->SetAttribute("base", "xs:string");
  880. pVector2TypeElement->LinkEndChild(pVector2ElementA);
  881. tinyxml2::XMLElement* pVector2ElementB = schemaDocument.NewElement("xs:pattern");
  882. pVector2ElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  883. pVector2ElementA->LinkEndChild(pVector2ElementB);
  884. // Point2F.
  885. tinyxml2::XMLComment* pPoint2FComment = schemaDocument.NewComment("Point2F Console Type");
  886. pSchemaElement->LinkEndChild(pPoint2FComment);
  887. tinyxml2::XMLElement* pPoint2FTypeElement = schemaDocument.NewElement("xs:simpleType");
  888. pPoint2FTypeElement->SetAttribute("name", "Point2F_ConsoleType");
  889. pSchemaElement->LinkEndChild(pPoint2FTypeElement);
  890. tinyxml2::XMLElement* pPoint2FElementA = schemaDocument.NewElement("xs:restriction");
  891. pPoint2FElementA->SetAttribute("base", "xs:string");
  892. pPoint2FTypeElement->LinkEndChild(pPoint2FElementA);
  893. tinyxml2::XMLElement* pPoint2FElementB = schemaDocument.NewElement("xs:pattern");
  894. pPoint2FElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  895. pPoint2FElementA->LinkEndChild(pPoint2FElementB);
  896. // Point2I.
  897. tinyxml2::XMLComment* pPoint2IComment = schemaDocument.NewComment("Point2I Console Type");
  898. pSchemaElement->LinkEndChild(pPoint2IComment);
  899. tinyxml2::XMLElement* pPoint2ITypeElement = schemaDocument.NewElement("xs:simpleType");
  900. pPoint2ITypeElement->SetAttribute("name", "Point2I_ConsoleType");
  901. pSchemaElement->LinkEndChild(pPoint2ITypeElement);
  902. tinyxml2::XMLElement* pPoint2IElementA = schemaDocument.NewElement("xs:restriction");
  903. pPoint2IElementA->SetAttribute("base", "xs:string");
  904. pPoint2ITypeElement->LinkEndChild(pPoint2IElementA);
  905. tinyxml2::XMLElement* pPoint2IElementB = schemaDocument.NewElement("xs:pattern");
  906. pPoint2IElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]*");
  907. pPoint2IElementA->LinkEndChild(pPoint2IElementB);
  908. // b2AABB.
  909. tinyxml2::XMLComment* pb2AABBComment = schemaDocument.NewComment("b2AABB Console Type");
  910. pSchemaElement->LinkEndChild(pb2AABBComment);
  911. tinyxml2::XMLElement* pb2AABBTypeElement = schemaDocument.NewElement("xs:simpleType");
  912. pb2AABBTypeElement->SetAttribute("name", "b2AABB_ConsoleType");
  913. pSchemaElement->LinkEndChild(pb2AABBTypeElement);
  914. tinyxml2::XMLElement* pb2AABBElementA = schemaDocument.NewElement("xs:restriction");
  915. pb2AABBElementA->SetAttribute("base", "xs:string");
  916. pb2AABBTypeElement->LinkEndChild(pb2AABBElementA);
  917. tinyxml2::XMLElement* pb2AABBElementB = schemaDocument.NewElement("xs:pattern");
  918. pb2AABBElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  919. pb2AABBElementA->LinkEndChild(pb2AABBElementB);
  920. // RectI.
  921. tinyxml2::XMLComment* pRectIComment = schemaDocument.NewComment("RectI Console Type");
  922. pSchemaElement->LinkEndChild(pRectIComment);
  923. tinyxml2::XMLElement* pRectITypeElement = schemaDocument.NewElement("xs:simpleType");
  924. pRectITypeElement->SetAttribute("name", "RectI_ConsoleType");
  925. pSchemaElement->LinkEndChild(pRectITypeElement);
  926. tinyxml2::XMLElement* pRectIElementA = schemaDocument.NewElement("xs:restriction");
  927. pRectIElementA->SetAttribute("base", "xs:string");
  928. pRectITypeElement->LinkEndChild(pRectIElementA);
  929. tinyxml2::XMLElement* pRectIElementB = schemaDocument.NewElement("xs:pattern");
  930. pRectIElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  931. pRectIElementA->LinkEndChild(pRectIElementB);
  932. // RectF.
  933. tinyxml2::XMLComment* pRectFComment = schemaDocument.NewComment("RectF Console Type");
  934. pSchemaElement->LinkEndChild(pRectFComment);
  935. tinyxml2::XMLElement* pRectFTypeElement = schemaDocument.NewElement("xs:simpleType");
  936. pRectFTypeElement->SetAttribute("name", "RectF_ConsoleType");
  937. pSchemaElement->LinkEndChild(pRectFTypeElement);
  938. tinyxml2::XMLElement* pRectFElementA = schemaDocument.NewElement("xs:restriction");
  939. pRectFElementA->SetAttribute("base", "xs:string");
  940. pRectFTypeElement->LinkEndChild(pRectFElementA);
  941. tinyxml2::XMLElement* pRectFElementB = schemaDocument.NewElement("xs:pattern");
  942. pRectFElementB->SetAttribute("value", "(\\b[-]?(b[0-9]+)?\\.)?[0-9]+\\b");
  943. pRectFElementA->LinkEndChild(pRectFElementB);
  944. // AssetId.
  945. tinyxml2::XMLComment* pAssetIdComment = schemaDocument.NewComment("AssetId Console Type");
  946. pSchemaElement->LinkEndChild(pAssetIdComment);
  947. tinyxml2::XMLElement* pAssetIdTypeElement = schemaDocument.NewElement("xs:simpleType");
  948. pAssetIdTypeElement->SetAttribute("name", "AssetId_ConsoleType");
  949. pSchemaElement->LinkEndChild(pAssetIdTypeElement);
  950. tinyxml2::XMLElement* pAssetIdElementA = schemaDocument.NewElement("xs:restriction");
  951. pAssetIdElementA->SetAttribute("base", "xs:string");
  952. pAssetIdTypeElement->LinkEndChild(pAssetIdElementA);
  953. tinyxml2::XMLElement* pAssetIdElementB = schemaDocument.NewElement("xs:pattern");
  954. dSprintf(buffer, sizeof(buffer), "(%s)?\\b[a-zA-Z0-9]+\\b%s\\b[a-zA-Z0-9]+\\b", ASSET_ID_FIELD_PREFIX, ASSET_SCOPE_TOKEN);
  955. pAssetIdElementB->SetAttribute("value", buffer);
  956. pAssetIdElementA->LinkEndChild(pAssetIdElementB);
  957. // Color Enums.
  958. tinyxml2::XMLComment* pColorEnumsComment = schemaDocument.NewComment("Color Enums");
  959. pSchemaElement->LinkEndChild(pColorEnumsComment);
  960. tinyxml2::XMLElement* pColorEnumsTypeElement = schemaDocument.NewElement("xs:simpleType");
  961. pColorEnumsTypeElement->SetAttribute("name", "Color_Enums");
  962. pSchemaElement->LinkEndChild(pColorEnumsTypeElement);
  963. tinyxml2::XMLElement* pColorEnumsRestrictionElement = schemaDocument.NewElement("xs:restriction");
  964. pColorEnumsRestrictionElement->SetAttribute("base", "xs:string");
  965. pColorEnumsTypeElement->LinkEndChild(pColorEnumsRestrictionElement);
  966. const S32 ColorEnumsCount = StockColor::getCount();
  967. for (S32 index = 0; index < ColorEnumsCount; ++index)
  968. {
  969. // Add enumeration element.
  970. tinyxml2::XMLElement* pColorEnumsAttributeEnumerationElement = schemaDocument.NewElement("xs:enumeration");
  971. pColorEnumsAttributeEnumerationElement->SetAttribute("value", StockColor::getColorItem(index)->getColorName());
  972. pColorEnumsRestrictionElement->LinkEndChild(pColorEnumsAttributeEnumerationElement);
  973. }
  974. // LinearColorF.
  975. tinyxml2::XMLComment* pColorFValuesComment = schemaDocument.NewComment("LinearColorF Values");
  976. pSchemaElement->LinkEndChild(pColorFValuesComment);
  977. tinyxml2::XMLElement* pColorFValuesTypeElement = schemaDocument.NewElement("xs:simpleType");
  978. pColorFValuesTypeElement->SetAttribute("name", "ColorF_Values");
  979. pSchemaElement->LinkEndChild(pColorFValuesTypeElement);
  980. tinyxml2::XMLElement* pColorFValuesElementA = schemaDocument.NewElement("xs:restriction");
  981. pColorFValuesElementA->SetAttribute("base", "xs:string");
  982. pColorFValuesTypeElement->LinkEndChild(pColorFValuesElementA);
  983. tinyxml2::XMLElement* pColorFValuesElementB = schemaDocument.NewElement("xs:pattern");
  984. pColorFValuesElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  985. pColorFValuesElementA->LinkEndChild(pColorFValuesElementB);
  986. tinyxml2::XMLComment* pColorFComment = schemaDocument.NewComment("LinearColorF Console Type");
  987. pSchemaElement->LinkEndChild(pColorFComment);
  988. tinyxml2::XMLElement* pColorFTypeElement = schemaDocument.NewElement("xs:simpleType");
  989. pColorFTypeElement->SetAttribute("name", "ColorF_ConsoleType");
  990. pSchemaElement->LinkEndChild(pColorFTypeElement);
  991. tinyxml2::XMLElement* pColorFUnionElement = schemaDocument.NewElement("xs:union");
  992. pColorFUnionElement->SetAttribute("memberTypes", "ColorF_Values Color_Enums");
  993. pColorFTypeElement->LinkEndChild(pColorFUnionElement);
  994. // ColorI.
  995. tinyxml2::XMLComment* pColorIValuesComment = schemaDocument.NewComment("ColorI Values");
  996. pSchemaElement->LinkEndChild(pColorIValuesComment);
  997. tinyxml2::XMLElement* pColorIValuesTypeElement = schemaDocument.NewElement("xs:simpleType");
  998. pColorIValuesTypeElement->SetAttribute("name", "ColorI_Values");
  999. pSchemaElement->LinkEndChild(pColorIValuesTypeElement);
  1000. tinyxml2::XMLElement* pColorIValuesElementA = schemaDocument.NewElement("xs:restriction");
  1001. pColorIValuesElementA->SetAttribute("base", "xs:string");
  1002. pColorIValuesTypeElement->LinkEndChild(pColorIValuesElementA);
  1003. tinyxml2::XMLElement* pColorIValuesElementB = schemaDocument.NewElement("xs:pattern");
  1004. pColorIValuesElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  1005. pColorIValuesElementA->LinkEndChild(pColorIValuesElementB);
  1006. tinyxml2::XMLComment* pColorIComment = schemaDocument.NewComment("ColorI Console Type");
  1007. pSchemaElement->LinkEndChild(pColorIComment);
  1008. tinyxml2::XMLElement* pColorITypeElement = schemaDocument.NewElement("xs:simpleType");
  1009. pColorITypeElement->SetAttribute("name", "ColorI_ConsoleType");
  1010. pSchemaElement->LinkEndChild(pColorITypeElement);
  1011. tinyxml2::XMLElement* pColorIUnionElement = schemaDocument.NewElement("xs:union");
  1012. pColorIUnionElement->SetAttribute("memberTypes", "ColorI_Values Color_Enums");
  1013. pColorITypeElement->LinkEndChild(pColorIUnionElement);
  1014. // *************************************************************
  1015. // Generate engine type elements.
  1016. // *************************************************************
  1017. // Generate the engine type elements.
  1018. tinyxml2::XMLComment* tComment = schemaDocument.NewComment("Type Elements");
  1019. pSchemaElement->LinkEndChild(tComment);
  1020. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  1021. {
  1022. // Add type.
  1023. tinyxml2::XMLElement* pTypeElement = schemaDocument.NewElement("xs:element");
  1024. pTypeElement->SetAttribute("name", pType->getClassName());
  1025. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1026. pTypeElement->SetAttribute("type", buffer);
  1027. pSchemaElement->LinkEndChild(pTypeElement);
  1028. }
  1029. // *************************************************************
  1030. // Generate the engine complex types.
  1031. // *************************************************************
  1032. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  1033. {
  1034. // Add complex type comment.
  1035. dSprintf(buffer, sizeof(buffer), " %s Type ", pType->getClassName());
  1036. tinyxml2::XMLComment* ctComment = schemaDocument.NewComment(buffer);
  1037. pSchemaElement->LinkEndChild(ctComment);
  1038. // Add complex type.
  1039. tinyxml2::XMLElement* pComplexTypeElement = schemaDocument.NewElement("xs:complexType");
  1040. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1041. pComplexTypeElement->SetAttribute("name", buffer);
  1042. pSchemaElement->LinkEndChild(pComplexTypeElement);
  1043. // Add sequence.
  1044. tinyxml2::XMLElement* pSequenceElement = schemaDocument.NewElement("xs:sequence");
  1045. pComplexTypeElement->LinkEndChild(pSequenceElement);
  1046. // Fetch container child class.
  1047. AbstractClassRep* pContainerChildClass = pType->getContainerChildClass(true);
  1048. // Is the type allowed children?
  1049. if (pContainerChildClass != NULL)
  1050. {
  1051. // Yes, so add choice element.
  1052. tinyxml2::XMLElement* pChoiceElement = schemaDocument.NewElement("xs:choice");
  1053. pChoiceElement->SetAttribute("minOccurs", 0);
  1054. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1055. pSequenceElement->LinkEndChild(pChoiceElement);
  1056. // Find child group.
  1057. HashTable<AbstractClassRep*, StringTableEntry>::Iterator childGroupItr = childGroups.find(pContainerChildClass);
  1058. // Does the group exist?
  1059. if (childGroupItr == childGroups.end())
  1060. {
  1061. // No, so format group name.
  1062. dSprintf(buffer, sizeof(buffer), "%s_ChildrenTypes", pContainerChildClass->getClassName());
  1063. // Insert into child group hash.
  1064. childGroupItr = childGroups.insertUnique(pContainerChildClass, StringTable->insert(buffer));
  1065. // Add the group.
  1066. tinyxml2::XMLElement* pChildrenGroupElement = schemaDocument.NewElement("xs:group");
  1067. pChildrenGroupElement->SetAttribute("name", buffer);
  1068. pSchemaElement->LinkEndChild(pChildrenGroupElement);
  1069. // Add choice element.
  1070. tinyxml2::XMLElement* pChildreGroupChoiceElement = schemaDocument.NewElement("xs:choice");
  1071. pChildrenGroupElement->LinkEndChild(pChildreGroupChoiceElement);
  1072. // Add choice members.
  1073. for (AbstractClassRep* pChoiceType = pRootType; pChoiceType != NULL; pChoiceType = pChoiceType->getNextClass())
  1074. {
  1075. // Skip if not derived from the container child class.
  1076. if (!pChoiceType->isClass(pContainerChildClass))
  1077. continue;
  1078. // Add choice member.
  1079. tinyxml2::XMLElement* pChildrenMemberElement = schemaDocument.NewElement("xs:element");
  1080. pChildrenMemberElement->SetAttribute("name", pChoiceType->getClassName());
  1081. dSprintf(buffer, sizeof(buffer), "%s_Type", pChoiceType->getClassName());
  1082. pChildrenMemberElement->SetAttribute("type", buffer);
  1083. pChildreGroupChoiceElement->LinkEndChild(pChildrenMemberElement);
  1084. }
  1085. }
  1086. // Reference the child group.
  1087. tinyxml2::XMLElement* pChoiceGroupReferenceElement = schemaDocument.NewElement("xs:group");
  1088. pChoiceGroupReferenceElement->SetAttribute("ref", childGroupItr->value);
  1089. pChoiceGroupReferenceElement->SetAttribute("minOccurs", 0);
  1090. pChoiceElement->LinkEndChild(pChoiceGroupReferenceElement);
  1091. }
  1092. // Generate the custom Taml schema.
  1093. for (AbstractClassRep* pCustomSchemaType = pType; pCustomSchemaType != NULL; pCustomSchemaType = pCustomSchemaType->getParentClass())
  1094. {
  1095. // Fetch the types custom TAML schema function.
  1096. AbstractClassRep::WriteCustomTamlSchema customSchemaFn = pCustomSchemaType->getCustomTamlSchema();
  1097. // Skip if no function avilable.
  1098. if (customSchemaFn == NULL)
  1099. continue;
  1100. // Call schema generation function.
  1101. customSchemaFn(pType, pSequenceElement);
  1102. }
  1103. // Generate field attribute group.
  1104. tinyxml2::XMLElement* pFieldAttributeGroupElement = schemaDocument.NewElement("xs:attributeGroup");
  1105. dSprintf(buffer, sizeof(buffer), "%s_Fields", pType->getClassName());
  1106. pFieldAttributeGroupElement->SetAttribute("name", buffer);
  1107. pSchemaElement->LinkEndChild(pFieldAttributeGroupElement);
  1108. // Fetch field list.
  1109. const AbstractClassRep::FieldList& fields = pType->mFieldList;
  1110. // Fetcj field count.
  1111. const S32 fieldCount = fields.size();
  1112. // Iterate static fields (in reverse as most types are organized from the root-fields up).
  1113. for (S32 index = fieldCount - 1; index > 0; --index)
  1114. {
  1115. // Fetch field.
  1116. const AbstractClassRep::Field& field = fields[index];
  1117. // Skip if not a data field.
  1118. if (field.type == AbstractClassRep::DeprecatedFieldType ||
  1119. field.type == AbstractClassRep::StartGroupFieldType ||
  1120. field.type == AbstractClassRep::EndGroupFieldType)
  1121. continue;
  1122. // Skip if the field root is not this type.
  1123. if (pType->findFieldRoot(field.pFieldname) != pType)
  1124. continue;
  1125. // Add attribute element.
  1126. tinyxml2::XMLElement* pAttributeElement = schemaDocument.NewElement("xs:attribute");
  1127. pAttributeElement->SetAttribute("name", field.pFieldname);
  1128. // Handle the console type appropriately.
  1129. const S32 fieldType = (S32)field.type;
  1130. /*
  1131. // Is the field an enumeration?
  1132. if ( fieldType == TypeEnum )
  1133. {
  1134. // Yes, so add attribute type.
  1135. tinyxml2::XMLElement* pAttributeSimpleTypeElement = schemaDocument.NewElement( "xs:simpleType" );
  1136. pAttributeElement->LinkEndChild( pAttributeSimpleTypeElement );
  1137. // Add restriction element.
  1138. tinyxml2::XMLElement* pAttributeRestrictionElement = schemaDocument.NewElement( "xs:restriction" );
  1139. pAttributeRestrictionElement->SetAttribute( "base", "xs:string" );
  1140. pAttributeSimpleTypeElement->LinkEndChild( pAttributeRestrictionElement );
  1141. // Yes, so fetch enumeration count.
  1142. const S32 enumCount = field.table->size;
  1143. // Iterate enumeration.
  1144. for( S32 index = 0; index < enumCount; ++index )
  1145. {
  1146. // Add enumeration element.
  1147. tinyxml2::XMLElement* pAttributeEnumerationElement = schemaDocument.NewElement( "xs:enumeration" );
  1148. pAttributeEnumerationElement->SetAttribute( "value", field.table->table[index].label );
  1149. pAttributeRestrictionElement->LinkEndChild( pAttributeEnumerationElement );
  1150. }
  1151. }
  1152. else
  1153. {*/
  1154. // No, so assume it's a string type initially.
  1155. const char* pFieldTypeDescription = "xs:string";
  1156. // Handle known types.
  1157. if (fieldType == TypeF32)
  1158. {
  1159. pFieldTypeDescription = "xs:float";
  1160. }
  1161. else if (fieldType == TypeS8 || fieldType == TypeS32)
  1162. {
  1163. pFieldTypeDescription = "xs:int";
  1164. }
  1165. else if (fieldType == TypeBool || fieldType == TypeFlag)
  1166. {
  1167. pFieldTypeDescription = "xs:boolean";
  1168. }
  1169. else if (fieldType == TypePoint2F)
  1170. {
  1171. pFieldTypeDescription = "Point2F_ConsoleType";
  1172. }
  1173. else if (fieldType == TypePoint2I)
  1174. {
  1175. pFieldTypeDescription = "Point2I_ConsoleType";
  1176. }
  1177. else if (fieldType == TypeRectI)
  1178. {
  1179. pFieldTypeDescription = "RectI_ConsoleType";
  1180. }
  1181. else if (fieldType == TypeRectF)
  1182. {
  1183. pFieldTypeDescription = "RectF_ConsoleType";
  1184. }
  1185. else if (fieldType == TypeColorF)
  1186. {
  1187. pFieldTypeDescription = "ColorF_ConsoleType";
  1188. }
  1189. else if (fieldType == TypeColorI)
  1190. {
  1191. pFieldTypeDescription = "ColorI_ConsoleType";
  1192. }
  1193. else if (fieldType == TypeAssetId/* ||
  1194. fieldType == TypeImageAssetPtr ||
  1195. fieldType == TypeAnimationAssetPtr ||
  1196. fieldType == TypeAudioAssetPtr*/)
  1197. {
  1198. pFieldTypeDescription = "AssetId_ConsoleType";
  1199. }
  1200. // Set attribute type.
  1201. pAttributeElement->SetAttribute("type", pFieldTypeDescription);
  1202. //}
  1203. pAttributeElement->SetAttribute("use", "optional");
  1204. pFieldAttributeGroupElement->LinkEndChild(pAttributeElement);
  1205. }
  1206. // Is this the SimObject Type?
  1207. if (pType == pSimObjectType)
  1208. {
  1209. // Yes, so add reserved Taml field attributes here...
  1210. // Add Taml "Name" attribute element.
  1211. tinyxml2::XMLElement* pNameAttributeElement = schemaDocument.NewElement("xs:attribute");
  1212. pNameAttributeElement->SetAttribute("name", tamlNamedObjectName);
  1213. pNameAttributeElement->SetAttribute("type", "xs:normalizedString");
  1214. pFieldAttributeGroupElement->LinkEndChild(pNameAttributeElement);
  1215. // Add Taml "TamlId" attribute element.
  1216. tinyxml2::XMLElement* pTamlIdAttributeElement = schemaDocument.NewElement("xs:attribute");
  1217. pTamlIdAttributeElement->SetAttribute("name", tamlRefIdName);
  1218. pTamlIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1219. pFieldAttributeGroupElement->LinkEndChild(pTamlIdAttributeElement);
  1220. // Add Taml "TamlRefId" attribute element.
  1221. tinyxml2::XMLElement* pTamlRefIdAttributeElement = schemaDocument.NewElement("xs:attribute");
  1222. pTamlRefIdAttributeElement->SetAttribute("name", tamlRefToIdName);
  1223. pTamlRefIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1224. pFieldAttributeGroupElement->LinkEndChild(pTamlRefIdAttributeElement);
  1225. }
  1226. // Add attribute group types.
  1227. for (AbstractClassRep* pAttributeGroupsType = pType; pAttributeGroupsType != NULL; pAttributeGroupsType = pAttributeGroupsType->getParentClass())
  1228. {
  1229. tinyxml2::XMLElement* pFieldAttributeGroupRefElement = schemaDocument.NewElement("xs:attributeGroup");
  1230. dSprintf(buffer, sizeof(buffer), "%s_Fields", pAttributeGroupsType->getClassName());
  1231. pFieldAttributeGroupRefElement->SetAttribute("ref", buffer);
  1232. pComplexTypeElement->LinkEndChild(pFieldAttributeGroupRefElement);
  1233. }
  1234. // Add "any" attribute element (dynamic fields).
  1235. tinyxml2::XMLElement* pAnyAttributeElement = schemaDocument.NewElement("xs:anyAttribute");
  1236. pAnyAttributeElement->SetAttribute("processContents", "skip");
  1237. pComplexTypeElement->LinkEndChild(pAnyAttributeElement);
  1238. }
  1239. // Write the schema document.
  1240. schemaDocument.SaveFile(filePathBuffer);
  1241. // Close file.
  1242. stream.close();
  1243. return true;
  1244. }
  1245. //-----------------------------------------------------------------------------
  1246. void Taml::WriteUnrestrictedCustomTamlSchema(const char* pCustomNodeName, const AbstractClassRep* pClassRep, tinyxml2::XMLElement* pParentElement)
  1247. {
  1248. // Sanity!
  1249. AssertFatal(pCustomNodeName != NULL, "Taml::WriteDefaultCustomTamlSchema() - Node name cannot be NULL.");
  1250. AssertFatal(pClassRep != NULL, "Taml::WriteDefaultCustomTamlSchema() - ClassRep cannot be NULL.");
  1251. AssertFatal(pParentElement != NULL, "Taml::WriteDefaultCustomTamlSchema() - Parent Element cannot be NULL.");
  1252. tinyxml2::XMLDocument* doc = pParentElement->GetDocument();
  1253. char buffer[1024];
  1254. // Add custom type element.
  1255. tinyxml2::XMLElement* pCustomElement = doc->NewElement("xs:element");
  1256. dSprintf(buffer, sizeof(buffer), "%s.%s", pClassRep->getClassName(), pCustomNodeName);
  1257. pCustomElement->SetAttribute("name", buffer);
  1258. pCustomElement->SetAttribute("minOccurs", 0);
  1259. pCustomElement->SetAttribute("maxOccurs", 1);
  1260. pParentElement->LinkEndChild(pCustomElement);
  1261. // Add complex type element.
  1262. tinyxml2::XMLElement* pComplexTypeElement = doc->NewElement("xs:complexType");
  1263. pCustomElement->LinkEndChild(pComplexTypeElement);
  1264. // Add choice element.
  1265. tinyxml2::XMLElement* pChoiceElement = doc->NewElement("xs:choice");
  1266. pChoiceElement->SetAttribute("minOccurs", 0);
  1267. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1268. pComplexTypeElement->LinkEndChild(pChoiceElement);
  1269. // Add sequence element.
  1270. tinyxml2::XMLElement* pSequenceElement = doc->NewElement("xs:sequence");
  1271. pChoiceElement->LinkEndChild(pSequenceElement);
  1272. // Add "any" element.
  1273. tinyxml2::XMLElement* pAnyElement = doc->NewElement("xs:any");
  1274. pAnyElement->SetAttribute("processContents", "skip");
  1275. pSequenceElement->LinkEndChild(pAnyElement);
  1276. }