taml.cpp 59 KB

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