taml.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  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. if (dStricmp(defaultObject->getDataField(fieldName, indexBuffer), pFieldValue) == 0)
  573. continue;
  574. }
  575. // Reassign field value.
  576. pFieldValue = valueCopy;
  577. if (pField->type == TypeBool)
  578. pFieldValue = dAtob(pFieldValue) ? "true" : "false";
  579. // Detect and collapse relative path information
  580. char fnBuf[1024];
  581. if ((S32)pField->type == TypeFilename)
  582. {
  583. Con::collapseScriptFilename(fnBuf, 1024, pFieldValue);
  584. pFieldValue = fnBuf;
  585. }
  586. // Save field/value.
  587. if (arrayDepth > 0 || pField->elementCount > 1)
  588. currentArrayNode->getChildren()[elementIndex]->addField(fieldName, pFieldValue);
  589. else
  590. {
  591. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(fieldName, pFieldValue);
  592. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  593. }
  594. }
  595. }
  596. if (!getWriteDefaults())
  597. {
  598. // Cleanup our created default object
  599. delete defaultConObject;
  600. }
  601. }
  602. //-----------------------------------------------------------------------------
  603. static S32 QSORT_CALLBACK compareFieldEntries(const void* a, const void* b)
  604. {
  605. // Debug Profiling.
  606. PROFILE_SCOPE(Taml_CompareFieldEntries);
  607. SimFieldDictionary::Entry *fa = *((SimFieldDictionary::Entry **)a);
  608. SimFieldDictionary::Entry *fb = *((SimFieldDictionary::Entry **)b);
  609. return dStricmp(fa->slotName, fb->slotName);
  610. }
  611. //-----------------------------------------------------------------------------
  612. void Taml::compileDynamicFields(TamlWriteNode* pTamlWriteNode)
  613. {
  614. // Debug Profiling.
  615. PROFILE_SCOPE(Taml_CompileDynamicFields);
  616. // Sanity!
  617. AssertFatal(pTamlWriteNode != NULL, "Cannot compile dynamic fields on a NULL node.");
  618. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile dynamic fields on a node with no object.");
  619. // Fetch object.
  620. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  621. // Fetch field dictionary.
  622. SimFieldDictionary* pFieldDictionary = pSimObject->getFieldDictionary();
  623. // Ignore if not writing dynamic fields.
  624. if (!pFieldDictionary || !pSimObject->getCanSaveDynamicFields())
  625. return;
  626. // Fetch field list.
  627. const AbstractClassRep::FieldList& fieldList = pSimObject->getFieldList();
  628. // Fetch field count.
  629. const U32 fieldCount = fieldList.size();
  630. Vector<SimFieldDictionary::Entry*> dynamicFieldList(__FILE__, __LINE__);
  631. // Ensure the dynamic field doesn't conflict with static field.
  632. for (U32 hashIndex = 0; hashIndex < SimFieldDictionary::HashTableSize; ++hashIndex)
  633. {
  634. for (SimFieldDictionary::Entry* pEntry = pFieldDictionary->mHashTable[hashIndex]; pEntry; pEntry = pEntry->next)
  635. {
  636. // Iterate static fields.
  637. U32 fieldIndex;
  638. for (fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
  639. {
  640. if (fieldList[fieldIndex].pFieldname == pEntry->slotName)
  641. break;
  642. }
  643. // Skip if found.
  644. if (fieldIndex != (U32)fieldList.size())
  645. continue;
  646. // Skip if not writing field.
  647. if (!pSimObject->writeField(pEntry->slotName, pEntry->value))
  648. continue;
  649. dynamicFieldList.push_back(pEntry);
  650. }
  651. }
  652. // Sort Entries to prevent version control conflicts
  653. if (dynamicFieldList.size() > 1)
  654. dQsort(dynamicFieldList.address(), dynamicFieldList.size(), sizeof(SimFieldDictionary::Entry*), compareFieldEntries);
  655. // Save the fields.
  656. for (Vector<SimFieldDictionary::Entry*>::iterator entryItr = dynamicFieldList.begin(); entryItr != dynamicFieldList.end(); ++entryItr)
  657. {
  658. // Fetch entry.
  659. SimFieldDictionary::Entry* pEntry = *entryItr;
  660. // Save field/value.
  661. TamlWriteNode::FieldValuePair* pFieldValuePair = new TamlWriteNode::FieldValuePair(pEntry->slotName, pEntry->value);
  662. pTamlWriteNode->mFields.push_back(pFieldValuePair);
  663. }
  664. }
  665. //-----------------------------------------------------------------------------
  666. void Taml::compileChildren(TamlWriteNode* pTamlWriteNode)
  667. {
  668. // Debug Profiling.
  669. PROFILE_SCOPE(Taml_CompileChildren);
  670. // Sanity!
  671. AssertFatal(pTamlWriteNode != NULL, "Cannot compile children on a NULL node.");
  672. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile children on a node with no object.");
  673. // Fetch object.
  674. SimObject* pSimObject = pTamlWriteNode->mpSimObject;
  675. // Fetch the Taml children.
  676. TamlChildren* pChildren = dynamic_cast<TamlChildren*>(pSimObject);
  677. // Finish if object does not contain Taml children.
  678. if (pChildren == NULL || pChildren->getTamlChildCount() == 0)
  679. return;
  680. // Create children vector.
  681. pTamlWriteNode->mChildren = new typeNodeVector();
  682. // Fetch the child count.
  683. const U32 childCount = pChildren->getTamlChildCount();
  684. // Iterate children.
  685. for (U32 childIndex = 0; childIndex < childCount; childIndex++)
  686. {
  687. // Compile object.
  688. TamlWriteNode* pChildTamlWriteNode = compileObject(pChildren->getTamlChild(childIndex));
  689. // Save node.
  690. pTamlWriteNode->mChildren->push_back(pChildTamlWriteNode);
  691. }
  692. }
  693. //-----------------------------------------------------------------------------
  694. void Taml::compileCustomState(TamlWriteNode* pTamlWriteNode)
  695. {
  696. // Debug Profiling.
  697. PROFILE_SCOPE(Taml_CompileCustomProperties);
  698. // Sanity!
  699. AssertFatal(pTamlWriteNode != NULL, "Cannot compile custom state on a NULL node.");
  700. AssertFatal(pTamlWriteNode->mpSimObject != NULL, "Cannot compile custom state on a node with no object.");
  701. // Fetch the custom node on the write node.
  702. TamlCustomNodes& customNodes = pTamlWriteNode->mCustomNodes;
  703. // Are there any Taml callbacks?
  704. if (pTamlWriteNode->mpTamlCallbacks != NULL)
  705. {
  706. // Yes, so call it.
  707. tamlCustomWrite(pTamlWriteNode->mpTamlCallbacks, customNodes);
  708. }
  709. // Fetch custom nodes.
  710. const TamlCustomNodeVector& nodes = customNodes.getNodes();
  711. // Finish if no custom nodes to process.
  712. if (nodes.size() == 0)
  713. return;
  714. // Iterate custom properties.
  715. for (TamlCustomNodeVector::const_iterator customNodesItr = nodes.begin(); customNodesItr != nodes.end(); ++customNodesItr)
  716. {
  717. // Fetch the custom node.
  718. TamlCustomNode* pCustomNode = *customNodesItr;
  719. // Compile custom node state.
  720. compileCustomNodeState(pCustomNode);
  721. }
  722. }
  723. //-----------------------------------------------------------------------------
  724. void Taml::compileCustomNodeState(TamlCustomNode* pCustomNode)
  725. {
  726. // Sanity!
  727. AssertFatal(pCustomNode != NULL, "Taml: Cannot compile NULL custom node state.");
  728. // Fetch children.
  729. const TamlCustomNodeVector& children = pCustomNode->getChildren();
  730. // Fetch proxy object.
  731. SimObject* pProxyObject = pCustomNode->getProxyObject<SimObject>(false);
  732. // Do we have a proxy object?
  733. if (pProxyObject != NULL)
  734. {
  735. // Yes, so sanity!
  736. AssertFatal(children.size() == 0, "Taml: Cannot compile a proxy object on a custom node that has children.");
  737. // Yes, so compile it.
  738. // NOTE: We force an Id for custom compiled objects so we guarantee an Id. The reason for this is fairly
  739. // weak in that the XML parser currently has no way of distinguishing between a compiled object node
  740. // 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.
  741. pCustomNode->setWriteNode(compileObject(pProxyObject, true));
  742. return;
  743. }
  744. // Finish if no children.
  745. if (children.size() == 0)
  746. return;
  747. // Iterate children.
  748. for (TamlCustomNodeVector::const_iterator childItr = children.begin(); childItr != children.end(); ++childItr)
  749. {
  750. // Fetch shape node.
  751. TamlCustomNode* pChildNode = *childItr;
  752. // Compile the child.
  753. compileCustomNodeState(pChildNode);
  754. }
  755. }
  756. //-----------------------------------------------------------------------------
  757. SimObject* Taml::createType(StringTableEntry typeName, const Taml* pTaml, const char* pProgenitorSuffix)
  758. {
  759. // Debug Profiling.
  760. PROFILE_SCOPE(Taml_CreateType);
  761. typedef HashTable<StringTableEntry, AbstractClassRep*> typeClassHash;
  762. static typeClassHash mClassMap;
  763. // Sanity!
  764. AssertFatal(typeName != NULL, "Taml: Type cannot be NULL");
  765. // Find type.
  766. typeClassHash::Iterator typeItr = mClassMap.find(typeName);
  767. // Found type?
  768. if (typeItr == mClassMap.end())
  769. {
  770. // No, so find type.
  771. AbstractClassRep* pClassRep = AbstractClassRep::getClassList();
  772. while (pClassRep)
  773. {
  774. // Is this the type?
  775. if (dStricmp(pClassRep->getClassName(), typeName) == 0)
  776. {
  777. // Yes, so insert it.
  778. typeItr = mClassMap.insertUnique(typeName, pClassRep);
  779. break;
  780. }
  781. // Next type.
  782. pClassRep = pClassRep->getNextClass();
  783. }
  784. // Did we find the type?
  785. if (typeItr == mClassMap.end())
  786. {
  787. // No, so warn and fail.
  788. Con::warnf("Taml: Failed to create type '%s' as such a registered type could not be found.", typeName);
  789. return NULL;
  790. }
  791. }
  792. // Create the object.
  793. ConsoleObject* pConsoleObject = typeItr->value->create();
  794. // NOTE: It is important that we don't register the object here as many objects rely on the fact that
  795. // fields are set prior to the object being registered. Registering here will invalid those assumptions.
  796. // Fetch the SimObject.
  797. SimObject* pSimObject = dynamic_cast<SimObject*>(pConsoleObject);
  798. // Was it a SimObject?
  799. if (pSimObject == NULL)
  800. {
  801. // No, so warn.
  802. Con::warnf("Taml: Failed to create type '%s' as it is not a SimObject.", typeName);
  803. // Destroy object and fail.
  804. delete pConsoleObject;
  805. return NULL;
  806. }
  807. // Are we updating the file-progenitor?
  808. if (pTaml->getProgenitorUpdate())
  809. {
  810. // Yes, so do we have a progenitor suffix?
  811. if (pProgenitorSuffix == NULL)
  812. {
  813. // No, so just set it to the progenitor file.
  814. pSimObject->setProgenitorFile(pTaml->getFilePathBuffer());
  815. }
  816. else
  817. {
  818. // Yes, so format the progenitor buffer.
  819. char progenitorBuffer[2048];
  820. dSprintf(progenitorBuffer, sizeof(progenitorBuffer), "%s,%s", pTaml->getFilePathBuffer(), pProgenitorSuffix);
  821. // Set the progenitor file.
  822. pSimObject->setProgenitorFile(progenitorBuffer);
  823. }
  824. }
  825. return pSimObject;
  826. }
  827. //-----------------------------------------------------------------------------
  828. bool Taml::generateTamlSchema()
  829. {
  830. // Fetch any TAML Schema file reference.
  831. const char* pTamlSchemaFile = Con::getVariable(TAML_SCHEMA_VARIABLE);
  832. // Do we have a schema file reference?
  833. if (pTamlSchemaFile == NULL || *pTamlSchemaFile == 0)
  834. {
  835. // No, so warn.
  836. Con::warnf("Taml::generateTamlSchema() - Cannot write a TAML schema as no schema variable is set ('%s').", TAML_SCHEMA_VARIABLE);
  837. return false;
  838. }
  839. // Expand the file-name into the file-path buffer.
  840. char filePathBuffer[1024];
  841. Con::expandToolScriptFilename(filePathBuffer, sizeof(filePathBuffer), pTamlSchemaFile);
  842. FileStream stream;
  843. // File opened?
  844. /*if ( !stream.open( filePathBuffer, Torque::FS::File::Write ) )
  845. {
  846. // No, so warn.
  847. Con::warnf("Taml::GenerateTamlSchema() - Could not open filename '%s' for write.", filePathBuffer );
  848. return false;
  849. }*/
  850. // Create document.
  851. tinyxml2::XMLDocument schemaDocument;
  852. // Add declaration.
  853. tinyxml2::XMLDeclaration* schemaDeclaration = schemaDocument.NewDeclaration("xml version=\"1.0\" encoding=\"iso-8859-1\" standalone =\"no\"");
  854. schemaDocument.InsertEndChild(schemaDeclaration);
  855. // Add schema element.
  856. tinyxml2::XMLElement* pSchemaElement = schemaDocument.NewElement("xs:schema");
  857. pSchemaElement->SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
  858. schemaDocument.LinkEndChild(pSchemaElement);
  859. // Fetch class-rep root.
  860. AbstractClassRep* pRootType = AbstractClassRep::getClassList();
  861. // Fetch SimObject class rep.
  862. AbstractClassRep* pSimObjectType = AbstractClassRep::findClassRep("SimObject");
  863. // Sanity!
  864. AssertFatal(pSimObjectType != NULL, "Taml::GenerateTamlSchema() - Could not find SimObject class rep.");
  865. // Reset scratch state.
  866. char buffer[1024];
  867. HashTable<AbstractClassRep*, StringTableEntry> childGroups;
  868. // *************************************************************
  869. // Generate console type elements.
  870. // *************************************************************
  871. // Vector2.
  872. tinyxml2::XMLComment* pVector2Comment = schemaDocument.NewComment("Vector2 Console Type");
  873. pSchemaElement->LinkEndChild(pVector2Comment);
  874. tinyxml2::XMLElement* pVector2TypeElement = schemaDocument.NewElement("xs:simpleType");
  875. pVector2TypeElement->SetAttribute("name", "Vector2_ConsoleType");
  876. pSchemaElement->LinkEndChild(pVector2TypeElement);
  877. tinyxml2::XMLElement* pVector2ElementA = schemaDocument.NewElement("xs:restriction");
  878. pVector2ElementA->SetAttribute("base", "xs:string");
  879. pVector2TypeElement->LinkEndChild(pVector2ElementA);
  880. tinyxml2::XMLElement* pVector2ElementB = schemaDocument.NewElement("xs:pattern");
  881. pVector2ElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  882. pVector2ElementA->LinkEndChild(pVector2ElementB);
  883. // Point2F.
  884. tinyxml2::XMLComment* pPoint2FComment = schemaDocument.NewComment("Point2F Console Type");
  885. pSchemaElement->LinkEndChild(pPoint2FComment);
  886. tinyxml2::XMLElement* pPoint2FTypeElement = schemaDocument.NewElement("xs:simpleType");
  887. pPoint2FTypeElement->SetAttribute("name", "Point2F_ConsoleType");
  888. pSchemaElement->LinkEndChild(pPoint2FTypeElement);
  889. tinyxml2::XMLElement* pPoint2FElementA = schemaDocument.NewElement("xs:restriction");
  890. pPoint2FElementA->SetAttribute("base", "xs:string");
  891. pPoint2FTypeElement->LinkEndChild(pPoint2FElementA);
  892. tinyxml2::XMLElement* pPoint2FElementB = schemaDocument.NewElement("xs:pattern");
  893. pPoint2FElementB->SetAttribute("value", "([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b ([-]?(\\b[0-9]+)?\\.)?[0-9]+\\b");
  894. pPoint2FElementA->LinkEndChild(pPoint2FElementB);
  895. // Point2I.
  896. tinyxml2::XMLComment* pPoint2IComment = schemaDocument.NewComment("Point2I Console Type");
  897. pSchemaElement->LinkEndChild(pPoint2IComment);
  898. tinyxml2::XMLElement* pPoint2ITypeElement = schemaDocument.NewElement("xs:simpleType");
  899. pPoint2ITypeElement->SetAttribute("name", "Point2I_ConsoleType");
  900. pSchemaElement->LinkEndChild(pPoint2ITypeElement);
  901. tinyxml2::XMLElement* pPoint2IElementA = schemaDocument.NewElement("xs:restriction");
  902. pPoint2IElementA->SetAttribute("base", "xs:string");
  903. pPoint2ITypeElement->LinkEndChild(pPoint2IElementA);
  904. tinyxml2::XMLElement* pPoint2IElementB = schemaDocument.NewElement("xs:pattern");
  905. pPoint2IElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]*");
  906. pPoint2IElementA->LinkEndChild(pPoint2IElementB);
  907. // b2AABB.
  908. tinyxml2::XMLComment* pb2AABBComment = schemaDocument.NewComment("b2AABB Console Type");
  909. pSchemaElement->LinkEndChild(pb2AABBComment);
  910. tinyxml2::XMLElement* pb2AABBTypeElement = schemaDocument.NewElement("xs:simpleType");
  911. pb2AABBTypeElement->SetAttribute("name", "b2AABB_ConsoleType");
  912. pSchemaElement->LinkEndChild(pb2AABBTypeElement);
  913. tinyxml2::XMLElement* pb2AABBElementA = schemaDocument.NewElement("xs:restriction");
  914. pb2AABBElementA->SetAttribute("base", "xs:string");
  915. pb2AABBTypeElement->LinkEndChild(pb2AABBElementA);
  916. tinyxml2::XMLElement* pb2AABBElementB = schemaDocument.NewElement("xs:pattern");
  917. 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");
  918. pb2AABBElementA->LinkEndChild(pb2AABBElementB);
  919. // RectI.
  920. tinyxml2::XMLComment* pRectIComment = schemaDocument.NewComment("RectI Console Type");
  921. pSchemaElement->LinkEndChild(pRectIComment);
  922. tinyxml2::XMLElement* pRectITypeElement = schemaDocument.NewElement("xs:simpleType");
  923. pRectITypeElement->SetAttribute("name", "RectI_ConsoleType");
  924. pSchemaElement->LinkEndChild(pRectITypeElement);
  925. tinyxml2::XMLElement* pRectIElementA = schemaDocument.NewElement("xs:restriction");
  926. pRectIElementA->SetAttribute("base", "xs:string");
  927. pRectITypeElement->LinkEndChild(pRectIElementA);
  928. tinyxml2::XMLElement* pRectIElementB = schemaDocument.NewElement("xs:pattern");
  929. pRectIElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  930. pRectIElementA->LinkEndChild(pRectIElementB);
  931. // RectF.
  932. tinyxml2::XMLComment* pRectFComment = schemaDocument.NewComment("RectF Console Type");
  933. pSchemaElement->LinkEndChild(pRectFComment);
  934. tinyxml2::XMLElement* pRectFTypeElement = schemaDocument.NewElement("xs:simpleType");
  935. pRectFTypeElement->SetAttribute("name", "RectF_ConsoleType");
  936. pSchemaElement->LinkEndChild(pRectFTypeElement);
  937. tinyxml2::XMLElement* pRectFElementA = schemaDocument.NewElement("xs:restriction");
  938. pRectFElementA->SetAttribute("base", "xs:string");
  939. pRectFTypeElement->LinkEndChild(pRectFElementA);
  940. tinyxml2::XMLElement* pRectFElementB = schemaDocument.NewElement("xs:pattern");
  941. pRectFElementB->SetAttribute("value", "(\\b[-]?(b[0-9]+)?\\.)?[0-9]+\\b");
  942. pRectFElementA->LinkEndChild(pRectFElementB);
  943. // AssetId.
  944. tinyxml2::XMLComment* pAssetIdComment = schemaDocument.NewComment("AssetId Console Type");
  945. pSchemaElement->LinkEndChild(pAssetIdComment);
  946. tinyxml2::XMLElement* pAssetIdTypeElement = schemaDocument.NewElement("xs:simpleType");
  947. pAssetIdTypeElement->SetAttribute("name", "AssetId_ConsoleType");
  948. pSchemaElement->LinkEndChild(pAssetIdTypeElement);
  949. tinyxml2::XMLElement* pAssetIdElementA = schemaDocument.NewElement("xs:restriction");
  950. pAssetIdElementA->SetAttribute("base", "xs:string");
  951. pAssetIdTypeElement->LinkEndChild(pAssetIdElementA);
  952. tinyxml2::XMLElement* pAssetIdElementB = schemaDocument.NewElement("xs:pattern");
  953. 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);
  954. pAssetIdElementB->SetAttribute("value", buffer);
  955. pAssetIdElementA->LinkEndChild(pAssetIdElementB);
  956. // Color Enums.
  957. tinyxml2::XMLComment* pColorEnumsComment = schemaDocument.NewComment("Color Enums");
  958. pSchemaElement->LinkEndChild(pColorEnumsComment);
  959. tinyxml2::XMLElement* pColorEnumsTypeElement = schemaDocument.NewElement("xs:simpleType");
  960. pColorEnumsTypeElement->SetAttribute("name", "Color_Enums");
  961. pSchemaElement->LinkEndChild(pColorEnumsTypeElement);
  962. tinyxml2::XMLElement* pColorEnumsRestrictionElement = schemaDocument.NewElement("xs:restriction");
  963. pColorEnumsRestrictionElement->SetAttribute("base", "xs:string");
  964. pColorEnumsTypeElement->LinkEndChild(pColorEnumsRestrictionElement);
  965. const S32 ColorEnumsCount = StockColor::getCount();
  966. for (S32 index = 0; index < ColorEnumsCount; ++index)
  967. {
  968. // Add enumeration element.
  969. tinyxml2::XMLElement* pColorEnumsAttributeEnumerationElement = schemaDocument.NewElement("xs:enumeration");
  970. pColorEnumsAttributeEnumerationElement->SetAttribute("value", StockColor::getColorItem(index)->getColorName());
  971. pColorEnumsRestrictionElement->LinkEndChild(pColorEnumsAttributeEnumerationElement);
  972. }
  973. // LinearColorF.
  974. tinyxml2::XMLComment* pColorFValuesComment = schemaDocument.NewComment("LinearColorF Values");
  975. pSchemaElement->LinkEndChild(pColorFValuesComment);
  976. tinyxml2::XMLElement* pColorFValuesTypeElement = schemaDocument.NewElement("xs:simpleType");
  977. pColorFValuesTypeElement->SetAttribute("name", "ColorF_Values");
  978. pSchemaElement->LinkEndChild(pColorFValuesTypeElement);
  979. tinyxml2::XMLElement* pColorFValuesElementA = schemaDocument.NewElement("xs:restriction");
  980. pColorFValuesElementA->SetAttribute("base", "xs:string");
  981. pColorFValuesTypeElement->LinkEndChild(pColorFValuesElementA);
  982. tinyxml2::XMLElement* pColorFValuesElementB = schemaDocument.NewElement("xs:pattern");
  983. 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");
  984. pColorFValuesElementA->LinkEndChild(pColorFValuesElementB);
  985. tinyxml2::XMLComment* pColorFComment = schemaDocument.NewComment("LinearColorF Console Type");
  986. pSchemaElement->LinkEndChild(pColorFComment);
  987. tinyxml2::XMLElement* pColorFTypeElement = schemaDocument.NewElement("xs:simpleType");
  988. pColorFTypeElement->SetAttribute("name", "ColorF_ConsoleType");
  989. pSchemaElement->LinkEndChild(pColorFTypeElement);
  990. tinyxml2::XMLElement* pColorFUnionElement = schemaDocument.NewElement("xs:union");
  991. pColorFUnionElement->SetAttribute("memberTypes", "ColorF_Values Color_Enums");
  992. pColorFTypeElement->LinkEndChild(pColorFUnionElement);
  993. // ColorI.
  994. tinyxml2::XMLComment* pColorIValuesComment = schemaDocument.NewComment("ColorI Values");
  995. pSchemaElement->LinkEndChild(pColorIValuesComment);
  996. tinyxml2::XMLElement* pColorIValuesTypeElement = schemaDocument.NewElement("xs:simpleType");
  997. pColorIValuesTypeElement->SetAttribute("name", "ColorI_Values");
  998. pSchemaElement->LinkEndChild(pColorIValuesTypeElement);
  999. tinyxml2::XMLElement* pColorIValuesElementA = schemaDocument.NewElement("xs:restriction");
  1000. pColorIValuesElementA->SetAttribute("base", "xs:string");
  1001. pColorIValuesTypeElement->LinkEndChild(pColorIValuesElementA);
  1002. tinyxml2::XMLElement* pColorIValuesElementB = schemaDocument.NewElement("xs:pattern");
  1003. pColorIValuesElementB->SetAttribute("value", "[-]?[0-9]* [-]?[0-9]* [-]?[0-9]* [-]?[0-9]*");
  1004. pColorIValuesElementA->LinkEndChild(pColorIValuesElementB);
  1005. tinyxml2::XMLComment* pColorIComment = schemaDocument.NewComment("ColorI Console Type");
  1006. pSchemaElement->LinkEndChild(pColorIComment);
  1007. tinyxml2::XMLElement* pColorITypeElement = schemaDocument.NewElement("xs:simpleType");
  1008. pColorITypeElement->SetAttribute("name", "ColorI_ConsoleType");
  1009. pSchemaElement->LinkEndChild(pColorITypeElement);
  1010. tinyxml2::XMLElement* pColorIUnionElement = schemaDocument.NewElement("xs:union");
  1011. pColorIUnionElement->SetAttribute("memberTypes", "ColorI_Values Color_Enums");
  1012. pColorITypeElement->LinkEndChild(pColorIUnionElement);
  1013. // *************************************************************
  1014. // Generate engine type elements.
  1015. // *************************************************************
  1016. // Generate the engine type elements.
  1017. tinyxml2::XMLComment* tComment = schemaDocument.NewComment("Type Elements");
  1018. pSchemaElement->LinkEndChild(tComment);
  1019. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  1020. {
  1021. // Add type.
  1022. tinyxml2::XMLElement* pTypeElement = schemaDocument.NewElement("xs:element");
  1023. pTypeElement->SetAttribute("name", pType->getClassName());
  1024. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1025. pTypeElement->SetAttribute("type", buffer);
  1026. pSchemaElement->LinkEndChild(pTypeElement);
  1027. }
  1028. // *************************************************************
  1029. // Generate the engine complex types.
  1030. // *************************************************************
  1031. for (AbstractClassRep* pType = pRootType; pType != NULL; pType = pType->getNextClass())
  1032. {
  1033. // Add complex type comment.
  1034. dSprintf(buffer, sizeof(buffer), " %s Type ", pType->getClassName());
  1035. tinyxml2::XMLComment* ctComment = schemaDocument.NewComment(buffer);
  1036. pSchemaElement->LinkEndChild(ctComment);
  1037. // Add complex type.
  1038. tinyxml2::XMLElement* pComplexTypeElement = schemaDocument.NewElement("xs:complexType");
  1039. dSprintf(buffer, sizeof(buffer), "%s_Type", pType->getClassName());
  1040. pComplexTypeElement->SetAttribute("name", buffer);
  1041. pSchemaElement->LinkEndChild(pComplexTypeElement);
  1042. // Add sequence.
  1043. tinyxml2::XMLElement* pSequenceElement = schemaDocument.NewElement("xs:sequence");
  1044. pComplexTypeElement->LinkEndChild(pSequenceElement);
  1045. // Fetch container child class.
  1046. AbstractClassRep* pContainerChildClass = pType->getContainerChildClass(true);
  1047. // Is the type allowed children?
  1048. if (pContainerChildClass != NULL)
  1049. {
  1050. // Yes, so add choice element.
  1051. tinyxml2::XMLElement* pChoiceElement = schemaDocument.NewElement("xs:choice");
  1052. pChoiceElement->SetAttribute("minOccurs", 0);
  1053. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1054. pSequenceElement->LinkEndChild(pChoiceElement);
  1055. // Find child group.
  1056. HashTable<AbstractClassRep*, StringTableEntry>::Iterator childGroupItr = childGroups.find(pContainerChildClass);
  1057. // Does the group exist?
  1058. if (childGroupItr == childGroups.end())
  1059. {
  1060. // No, so format group name.
  1061. dSprintf(buffer, sizeof(buffer), "%s_ChildrenTypes", pContainerChildClass->getClassName());
  1062. // Insert into child group hash.
  1063. childGroupItr = childGroups.insertUnique(pContainerChildClass, StringTable->insert(buffer));
  1064. // Add the group.
  1065. tinyxml2::XMLElement* pChildrenGroupElement = schemaDocument.NewElement("xs:group");
  1066. pChildrenGroupElement->SetAttribute("name", buffer);
  1067. pSchemaElement->LinkEndChild(pChildrenGroupElement);
  1068. // Add choice element.
  1069. tinyxml2::XMLElement* pChildreGroupChoiceElement = schemaDocument.NewElement("xs:choice");
  1070. pChildrenGroupElement->LinkEndChild(pChildreGroupChoiceElement);
  1071. // Add choice members.
  1072. for (AbstractClassRep* pChoiceType = pRootType; pChoiceType != NULL; pChoiceType = pChoiceType->getNextClass())
  1073. {
  1074. // Skip if not derived from the container child class.
  1075. if (!pChoiceType->isClass(pContainerChildClass))
  1076. continue;
  1077. // Add choice member.
  1078. tinyxml2::XMLElement* pChildrenMemberElement = schemaDocument.NewElement("xs:element");
  1079. pChildrenMemberElement->SetAttribute("name", pChoiceType->getClassName());
  1080. dSprintf(buffer, sizeof(buffer), "%s_Type", pChoiceType->getClassName());
  1081. pChildrenMemberElement->SetAttribute("type", buffer);
  1082. pChildreGroupChoiceElement->LinkEndChild(pChildrenMemberElement);
  1083. }
  1084. }
  1085. // Reference the child group.
  1086. tinyxml2::XMLElement* pChoiceGroupReferenceElement = schemaDocument.NewElement("xs:group");
  1087. pChoiceGroupReferenceElement->SetAttribute("ref", childGroupItr->value);
  1088. pChoiceGroupReferenceElement->SetAttribute("minOccurs", 0);
  1089. pChoiceElement->LinkEndChild(pChoiceGroupReferenceElement);
  1090. }
  1091. // Generate the custom Taml schema.
  1092. for (AbstractClassRep* pCustomSchemaType = pType; pCustomSchemaType != NULL; pCustomSchemaType = pCustomSchemaType->getParentClass())
  1093. {
  1094. // Fetch the types custom TAML schema function.
  1095. AbstractClassRep::WriteCustomTamlSchema customSchemaFn = pCustomSchemaType->getCustomTamlSchema();
  1096. // Skip if no function avilable.
  1097. if (customSchemaFn == NULL)
  1098. continue;
  1099. // Call schema generation function.
  1100. customSchemaFn(pType, pSequenceElement);
  1101. }
  1102. // Generate field attribute group.
  1103. tinyxml2::XMLElement* pFieldAttributeGroupElement = schemaDocument.NewElement("xs:attributeGroup");
  1104. dSprintf(buffer, sizeof(buffer), "%s_Fields", pType->getClassName());
  1105. pFieldAttributeGroupElement->SetAttribute("name", buffer);
  1106. pSchemaElement->LinkEndChild(pFieldAttributeGroupElement);
  1107. // Fetch field list.
  1108. const AbstractClassRep::FieldList& fields = pType->mFieldList;
  1109. // Fetcj field count.
  1110. const S32 fieldCount = fields.size();
  1111. // Iterate static fields (in reverse as most types are organized from the root-fields up).
  1112. for (S32 index = fieldCount - 1; index > 0; --index)
  1113. {
  1114. // Fetch field.
  1115. const AbstractClassRep::Field& field = fields[index];
  1116. // Skip if not a data field.
  1117. if (field.type == AbstractClassRep::DeprecatedFieldType ||
  1118. field.type == AbstractClassRep::StartGroupFieldType ||
  1119. field.type == AbstractClassRep::EndGroupFieldType)
  1120. continue;
  1121. // Skip if the field root is not this type.
  1122. if (pType->findFieldRoot(field.pFieldname) != pType)
  1123. continue;
  1124. // Add attribute element.
  1125. tinyxml2::XMLElement* pAttributeElement = schemaDocument.NewElement("xs:attribute");
  1126. pAttributeElement->SetAttribute("name", field.pFieldname);
  1127. // Handle the console type appropriately.
  1128. const S32 fieldType = (S32)field.type;
  1129. /*
  1130. // Is the field an enumeration?
  1131. if ( fieldType == TypeEnum )
  1132. {
  1133. // Yes, so add attribute type.
  1134. tinyxml2::XMLElement* pAttributeSimpleTypeElement = schemaDocument.NewElement( "xs:simpleType" );
  1135. pAttributeElement->LinkEndChild( pAttributeSimpleTypeElement );
  1136. // Add restriction element.
  1137. tinyxml2::XMLElement* pAttributeRestrictionElement = schemaDocument.NewElement( "xs:restriction" );
  1138. pAttributeRestrictionElement->SetAttribute( "base", "xs:string" );
  1139. pAttributeSimpleTypeElement->LinkEndChild( pAttributeRestrictionElement );
  1140. // Yes, so fetch enumeration count.
  1141. const S32 enumCount = field.table->size;
  1142. // Iterate enumeration.
  1143. for( S32 index = 0; index < enumCount; ++index )
  1144. {
  1145. // Add enumeration element.
  1146. tinyxml2::XMLElement* pAttributeEnumerationElement = schemaDocument.NewElement( "xs:enumeration" );
  1147. pAttributeEnumerationElement->SetAttribute( "value", field.table->table[index].label );
  1148. pAttributeRestrictionElement->LinkEndChild( pAttributeEnumerationElement );
  1149. }
  1150. }
  1151. else
  1152. {*/
  1153. // No, so assume it's a string type initially.
  1154. const char* pFieldTypeDescription = "xs:string";
  1155. // Handle known types.
  1156. if (fieldType == TypeF32)
  1157. {
  1158. pFieldTypeDescription = "xs:float";
  1159. }
  1160. else if (fieldType == TypeS8 || fieldType == TypeS32)
  1161. {
  1162. pFieldTypeDescription = "xs:int";
  1163. }
  1164. else if (fieldType == TypeBool || fieldType == TypeFlag)
  1165. {
  1166. pFieldTypeDescription = "xs:boolean";
  1167. }
  1168. else if (fieldType == TypePoint2F)
  1169. {
  1170. pFieldTypeDescription = "Point2F_ConsoleType";
  1171. }
  1172. else if (fieldType == TypePoint2I)
  1173. {
  1174. pFieldTypeDescription = "Point2I_ConsoleType";
  1175. }
  1176. else if (fieldType == TypeRectI)
  1177. {
  1178. pFieldTypeDescription = "RectI_ConsoleType";
  1179. }
  1180. else if (fieldType == TypeRectF)
  1181. {
  1182. pFieldTypeDescription = "RectF_ConsoleType";
  1183. }
  1184. else if (fieldType == TypeColorF)
  1185. {
  1186. pFieldTypeDescription = "ColorF_ConsoleType";
  1187. }
  1188. else if (fieldType == TypeColorI)
  1189. {
  1190. pFieldTypeDescription = "ColorI_ConsoleType";
  1191. }
  1192. else if (fieldType == TypeAssetId/* ||
  1193. fieldType == TypeImageAssetPtr ||
  1194. fieldType == TypeAnimationAssetPtr ||
  1195. fieldType == TypeAudioAssetPtr*/)
  1196. {
  1197. pFieldTypeDescription = "AssetId_ConsoleType";
  1198. }
  1199. // Set attribute type.
  1200. pAttributeElement->SetAttribute("type", pFieldTypeDescription);
  1201. //}
  1202. pAttributeElement->SetAttribute("use", "optional");
  1203. pFieldAttributeGroupElement->LinkEndChild(pAttributeElement);
  1204. }
  1205. // Is this the SimObject Type?
  1206. if (pType == pSimObjectType)
  1207. {
  1208. // Yes, so add reserved Taml field attributes here...
  1209. // Add Taml "Name" attribute element.
  1210. tinyxml2::XMLElement* pNameAttributeElement = schemaDocument.NewElement("xs:attribute");
  1211. pNameAttributeElement->SetAttribute("name", tamlNamedObjectName);
  1212. pNameAttributeElement->SetAttribute("type", "xs:normalizedString");
  1213. pFieldAttributeGroupElement->LinkEndChild(pNameAttributeElement);
  1214. // Add Taml "TamlId" attribute element.
  1215. tinyxml2::XMLElement* pTamlIdAttributeElement = schemaDocument.NewElement("xs:attribute");
  1216. pTamlIdAttributeElement->SetAttribute("name", tamlRefIdName);
  1217. pTamlIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1218. pFieldAttributeGroupElement->LinkEndChild(pTamlIdAttributeElement);
  1219. // Add Taml "TamlRefId" attribute element.
  1220. tinyxml2::XMLElement* pTamlRefIdAttributeElement = schemaDocument.NewElement("xs:attribute");
  1221. pTamlRefIdAttributeElement->SetAttribute("name", tamlRefToIdName);
  1222. pTamlRefIdAttributeElement->SetAttribute("type", "xs:nonNegativeInteger");
  1223. pFieldAttributeGroupElement->LinkEndChild(pTamlRefIdAttributeElement);
  1224. }
  1225. // Add attribute group types.
  1226. for (AbstractClassRep* pAttributeGroupsType = pType; pAttributeGroupsType != NULL; pAttributeGroupsType = pAttributeGroupsType->getParentClass())
  1227. {
  1228. tinyxml2::XMLElement* pFieldAttributeGroupRefElement = schemaDocument.NewElement("xs:attributeGroup");
  1229. dSprintf(buffer, sizeof(buffer), "%s_Fields", pAttributeGroupsType->getClassName());
  1230. pFieldAttributeGroupRefElement->SetAttribute("ref", buffer);
  1231. pComplexTypeElement->LinkEndChild(pFieldAttributeGroupRefElement);
  1232. }
  1233. // Add "any" attribute element (dynamic fields).
  1234. tinyxml2::XMLElement* pAnyAttributeElement = schemaDocument.NewElement("xs:anyAttribute");
  1235. pAnyAttributeElement->SetAttribute("processContents", "skip");
  1236. pComplexTypeElement->LinkEndChild(pAnyAttributeElement);
  1237. }
  1238. // Write the schema document.
  1239. schemaDocument.SaveFile(filePathBuffer);
  1240. // Close file.
  1241. stream.close();
  1242. return true;
  1243. }
  1244. //-----------------------------------------------------------------------------
  1245. void Taml::WriteUnrestrictedCustomTamlSchema(const char* pCustomNodeName, const AbstractClassRep* pClassRep, tinyxml2::XMLElement* pParentElement)
  1246. {
  1247. // Sanity!
  1248. AssertFatal(pCustomNodeName != NULL, "Taml::WriteDefaultCustomTamlSchema() - Node name cannot be NULL.");
  1249. AssertFatal(pClassRep != NULL, "Taml::WriteDefaultCustomTamlSchema() - ClassRep cannot be NULL.");
  1250. AssertFatal(pParentElement != NULL, "Taml::WriteDefaultCustomTamlSchema() - Parent Element cannot be NULL.");
  1251. tinyxml2::XMLDocument* doc = pParentElement->GetDocument();
  1252. char buffer[1024];
  1253. // Add custom type element.
  1254. tinyxml2::XMLElement* pCustomElement = doc->NewElement("xs:element");
  1255. dSprintf(buffer, sizeof(buffer), "%s.%s", pClassRep->getClassName(), pCustomNodeName);
  1256. pCustomElement->SetAttribute("name", buffer);
  1257. pCustomElement->SetAttribute("minOccurs", 0);
  1258. pCustomElement->SetAttribute("maxOccurs", 1);
  1259. pParentElement->LinkEndChild(pCustomElement);
  1260. // Add complex type element.
  1261. tinyxml2::XMLElement* pComplexTypeElement = doc->NewElement("xs:complexType");
  1262. pCustomElement->LinkEndChild(pComplexTypeElement);
  1263. // Add choice element.
  1264. tinyxml2::XMLElement* pChoiceElement = doc->NewElement("xs:choice");
  1265. pChoiceElement->SetAttribute("minOccurs", 0);
  1266. pChoiceElement->SetAttribute("maxOccurs", "unbounded");
  1267. pComplexTypeElement->LinkEndChild(pChoiceElement);
  1268. // Add sequence element.
  1269. tinyxml2::XMLElement* pSequenceElement = doc->NewElement("xs:sequence");
  1270. pChoiceElement->LinkEndChild(pSequenceElement);
  1271. // Add "any" element.
  1272. tinyxml2::XMLElement* pAnyElement = doc->NewElement("xs:any");
  1273. pAnyElement->SetAttribute("processContents", "skip");
  1274. pSequenceElement->LinkEndChild(pAnyElement);
  1275. }