persistenceManager.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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 "persistenceManager.h"
  23. #include "console/simSet.h"
  24. #include "console/consoleTypes.h"
  25. #include "core/stream/fileStream.h"
  26. #include "gui/core/guiTypes.h"
  27. #include "materials/customMaterialDefinition.h"
  28. #include "ts/tsShapeConstruct.h"
  29. #include "sim/netStringTable.h"
  30. IMPLEMENT_CONOBJECT(PersistenceManager);
  31. ConsoleDocClass( PersistenceManager,
  32. "@brief this class manages updating SimObjects in the file they were "
  33. "created in non-destructively (mostly aimed at datablocks and materials).\n\n"
  34. "Basic scripting interface:\n\n"
  35. " - Creation: new PersistenceManager(FooManager);\n"
  36. " - Flag objects as dirty: FooManager.setDirty(<object name or id>);\n"
  37. " - Remove objects from dirty list: FooManager.removeDirty(<object name or id>);\n"
  38. " - List all currently dirty objects: FooManager.listDirty();\n"
  39. " - Check to see if an object is dirty: FooManager.isDirty(<object name or id>);\n"
  40. " - Save dirty objects to their files: FooManager.saveDirty();\n\n"
  41. "@note Dirty objects don't update their files until saveDirty() is "
  42. "called so you can change their properties after you flag them as dirty\n\n"
  43. "@note Currently only used by editors, not intended for actual game development\n\n"
  44. "@ingroup Console\n"
  45. "@ingroup Editors\n"
  46. "@internal");
  47. PersistenceManager::PersistenceManager()
  48. {
  49. mCurrentObject = NULL;
  50. mCurrentFile = NULL;
  51. VECTOR_SET_ASSOCIATION(mLineBuffer);
  52. mLineBuffer.reserve(2048);
  53. }
  54. PersistenceManager::~PersistenceManager()
  55. {
  56. mDirtyObjects.clear();
  57. }
  58. bool PersistenceManager::onAdd()
  59. {
  60. if (!Parent::onAdd())
  61. return false;
  62. return true;
  63. }
  64. void PersistenceManager::onRemove()
  65. {
  66. Parent::onRemove();
  67. }
  68. void PersistenceManager::clearLineBuffer()
  69. {
  70. for (U32 i = 0; i < mLineBuffer.size(); i++)
  71. {
  72. dFree( mLineBuffer[ i ] );
  73. mLineBuffer[ i ] = NULL;
  74. }
  75. mLineBuffer.clear();
  76. }
  77. void PersistenceManager::deleteObject(ParsedObject* object)
  78. {
  79. if (object)
  80. {
  81. // Clear up used property memory
  82. for (U32 j = 0; j < object->properties.size(); j++)
  83. {
  84. ParsedProperty& prop = object->properties[j];
  85. if (prop.value)
  86. {
  87. dFree( prop.value );
  88. prop.value = NULL;
  89. }
  90. }
  91. object->properties.clear();
  92. // Delete the parsed object
  93. SAFE_DELETE(object);
  94. }
  95. }
  96. void PersistenceManager::clearObjects()
  97. {
  98. // Clean up the object buffer
  99. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  100. deleteObject(mObjectBuffer[i]);
  101. mObjectBuffer.clear();
  102. // We shouldn't have anything in the object stack
  103. // but let's clean it up just in case
  104. // Clean up the object buffer
  105. for (U32 i = 0; i < mObjectStack.size(); i++)
  106. deleteObject(mObjectStack[i]);
  107. mObjectStack.clear();
  108. // Finally make sure there isn't a current object
  109. deleteObject(mCurrentObject);
  110. }
  111. void PersistenceManager::clearFileData()
  112. {
  113. // Clear the active file name
  114. if (mCurrentFile)
  115. {
  116. dFree( mCurrentFile );
  117. mCurrentFile = NULL;
  118. }
  119. // Clear the file objects
  120. clearObjects();
  121. // Clear the line buffer
  122. clearLineBuffer();
  123. // Clear the tokenizer data
  124. mParser.clear();
  125. }
  126. void PersistenceManager::clearAll()
  127. {
  128. // Clear the file data in case it hasn't cleared yet
  129. clearFileData();
  130. // Clear the dirty object list
  131. mDirtyObjects.clear();
  132. // Clear the remove field list
  133. mRemoveFields.clear();
  134. }
  135. bool PersistenceManager::readFile(const char* fileName)
  136. {
  137. // Clear our previous file buffers just in
  138. // case saveDirtyFile() didn't catch it
  139. clearFileData();
  140. // Handle an object writing out to a new file
  141. if ( !Torque::FS::IsFile( fileName ) )
  142. {
  143. // Set our current file
  144. mCurrentFile = dStrdup(fileName);
  145. return true;
  146. }
  147. // Try to open the file
  148. FileStream stream;
  149. stream.open( fileName, Torque::FS::File::Read );
  150. if ( stream.getStatus() != Stream::Ok )
  151. {
  152. Con::errorf("PersistenceManager::readFile() - Failed to open %s", fileName);
  153. return false;
  154. }
  155. // The file is good so read it in
  156. mCurrentFile = dStrdup(fileName);
  157. while(stream.getStatus() != Stream::EOS)
  158. {
  159. U8* buffer = ( U8* ) dMalloc( 2048 );
  160. dMemset(buffer, 0, 2048);
  161. stream.readLine(buffer, 2048);
  162. mLineBuffer.push_back((const char*)buffer);
  163. }
  164. // Because of the way that writeLine() works we need to
  165. // make sure we don't have an empty last line or else
  166. // we will get an extra line break
  167. if (mLineBuffer.size() > 0)
  168. {
  169. if (mLineBuffer.last() && mLineBuffer.last()[0] == 0)
  170. {
  171. dFree(mLineBuffer.last());
  172. mLineBuffer.pop_back();
  173. }
  174. }
  175. stream.close();
  176. //Con::printf("Successfully opened and read %s", mCurrentFile);
  177. return true;
  178. }
  179. void PersistenceManager::killObject()
  180. {
  181. // Don't save this object
  182. SAFE_DELETE(mCurrentObject);
  183. // If there is an object in the stack restore it
  184. if (mObjectStack.size() > 0)
  185. {
  186. mCurrentObject = mObjectStack.last();
  187. mObjectStack.pop_back();
  188. }
  189. }
  190. void PersistenceManager::saveObject()
  191. {
  192. // Now that we have all of the data attempt to
  193. // find the corresponding SimObject
  194. mCurrentObject->simObject = Sim::findObject(mCurrentFile, mCurrentObject->endLine + 1);
  195. // Save this object
  196. mObjectBuffer.push_back(mCurrentObject);
  197. mCurrentObject = NULL;
  198. // If there is an object in the stack restore it
  199. if (mObjectStack.size() > 0)
  200. {
  201. mCurrentObject = mObjectStack.last();
  202. mObjectStack.pop_back();
  203. }
  204. }
  205. void PersistenceManager::parseObject()
  206. {
  207. // We *should* already be in position but just in case...
  208. if (!mParser.tokenICmp("new") &&
  209. !mParser.tokenICmp("singleton") &&
  210. !mParser.tokenICmp("datablock"))
  211. {
  212. Con::errorf("PersistenceManager::parseObject() - handed a position that doesn't point to an object \
  213. creation keyword (new, singleton, datablock)");
  214. return;
  215. }
  216. // If there is an object already being parsed then
  217. // push it into the stack to finish later
  218. if (mCurrentObject)
  219. mObjectStack.push_back(mCurrentObject);
  220. mCurrentObject = new ParsedObject;
  221. //// If this object declaration is being assigned to a variable then
  222. //// consider that the "start" of the declaration (otherwise we could
  223. //// get a script compile error if we delete the object declaration)
  224. mParser.regressToken(true);
  225. if (mParser.tokenICmp("="))
  226. {
  227. // Ok, we are at an '='...back up to the beginning of that variable
  228. mParser.regressToken(true);
  229. // Get the startLine and startPosition
  230. mCurrentObject->startLine = mParser.getCurrentLine();
  231. mCurrentObject->startPosition = mParser.getTokenLineOffset();
  232. // Advance back to the object declaration
  233. mParser.advanceToken(true);
  234. mParser.advanceToken(true);
  235. }
  236. else
  237. {
  238. // Advance back to the object declaration
  239. mParser.advanceToken(true);
  240. // Get the startLine and startPosition
  241. mCurrentObject->startLine = mParser.getCurrentLine();
  242. mCurrentObject->startPosition = mParser.getTokenLineOffset();
  243. }
  244. if (mObjectStack.size() > 0)
  245. mCurrentObject->parentObject = mObjectStack.last();
  246. // The next token should be the className
  247. mCurrentObject->className = StringTable->insert(mParser.getNextToken());
  248. // Advance to '('
  249. mParser.advanceToken(true);
  250. if (!mParser.tokenICmp("("))
  251. {
  252. Con::errorf("PersistenceManager::parseObject() - badly formed object \
  253. declaration on line %d - was expecting a '(' character", mParser.getCurrentLine()+1);
  254. // Remove this object without saving it
  255. killObject();
  256. return;
  257. }
  258. // The next token should either be the object name or ')'
  259. mParser.advanceToken(true);
  260. if (mParser.tokenICmp(")"))
  261. {
  262. mCurrentObject->name = StringTable->insert("");
  263. mCurrentObject->nameLine = mParser.getCurrentLine();
  264. mCurrentObject->namePosition = mParser.getTokenLineOffset();
  265. }
  266. else
  267. {
  268. mCurrentObject->name = StringTable->insert(mParser.getToken());
  269. mCurrentObject->nameLine = mParser.getCurrentLine();
  270. mCurrentObject->namePosition = mParser.getTokenLineOffset();
  271. // Advance to either ')' or ':'
  272. mParser.advanceToken(true);
  273. if (mParser.tokenICmp(":"))
  274. {
  275. // Advance past the object we are copying from
  276. mParser.advanceToken(true);
  277. // Advance to ')'
  278. mParser.advanceToken(true);
  279. }
  280. if (!mParser.tokenICmp(")"))
  281. {
  282. Con::errorf("PersistenceManager::parseObject() - badly formed object \
  283. declaration on line %d - was expecting a ')' character", mParser.getCurrentLine()+1);
  284. // Remove this object without saving it
  285. killObject();
  286. return;
  287. }
  288. }
  289. // The next token should either be a ';' or a '{'
  290. mParser.advanceToken(true);
  291. if (mParser.tokenICmp(";"))
  292. {
  293. // Save the end line number
  294. mCurrentObject->endLine = mParser.getCurrentLine();
  295. // Save the end position
  296. mCurrentObject->endPosition = mParser.getTokenLineOffset();
  297. // Flag this object as not having braces
  298. mCurrentObject->hasBraces = false;
  299. saveObject(); // Object has no fields
  300. return;
  301. }
  302. else if (!mParser.tokenICmp("{"))
  303. {
  304. Con::errorf("PersistenceManager::parseObject() - badly formed object \
  305. declaration on line %d - was expecting a '{' character", mParser.getCurrentLine()+1);
  306. // Remove this object without saving it
  307. killObject();
  308. return;
  309. }
  310. while (mParser.advanceToken(true))
  311. {
  312. // Check for a subobject
  313. if (mParser.tokenICmp("new") ||
  314. mParser.tokenICmp("singleton") ||
  315. mParser.tokenICmp("datablock"))
  316. {
  317. parseObject();
  318. }
  319. // Check to see if we have a property
  320. if (mParser.tokenICmp("="))
  321. {
  322. // Ok, we are at an '='...back up to find out
  323. // what variable is getting assigned
  324. mParser.regressToken(true);
  325. const char* variable = mParser.getToken();
  326. if (variable && dStrlen(variable) > 0)
  327. {
  328. // See if it is a global or a local variable
  329. if (variable[0] == '%' || variable[0] == '$')
  330. {
  331. // We ignore this variable and go
  332. // back to our previous place
  333. mParser.advanceToken(true);
  334. }
  335. // Could also potentially be a <object>.<variable>
  336. // assignment which we don't care about either
  337. else if (dStrchr(variable, '.'))
  338. {
  339. // We ignore this variable and go
  340. // back to our previous place
  341. mParser.advanceToken(true);
  342. }
  343. // If we made it to here assume it is a variable
  344. // for the current object
  345. else
  346. {
  347. // Create our new property
  348. mCurrentObject->properties.increment();
  349. ParsedProperty& prop = mCurrentObject->properties.last();
  350. // Check to see if this is an array variable
  351. if (dStrlen(variable) > 3 && variable[dStrlen(variable) - 1] == ']')
  352. {
  353. // The last character is a ']' which *should* mean
  354. // there is also a corresponding '['
  355. const char* arrayPosStart = dStrrchr(variable, '[');
  356. if (!arrayPosStart)
  357. {
  358. Con::errorf("PersistenceManager::parseObject() - error parsing array position - \
  359. was expecting a '[' character");
  360. }
  361. else
  362. {
  363. // Parse the array position for the variable name
  364. S32 arrayPos = -1;
  365. dSscanf(arrayPosStart, "[%d]", &arrayPos);
  366. // If we got a valid array position then set it
  367. if (arrayPos > -1)
  368. prop.arrayPos = arrayPos;
  369. // Trim off the [<pos>] from the variable name
  370. char* variableName = dStrdup(variable);
  371. variableName[arrayPosStart - variable] = 0;
  372. // Set the variable name to our new shortened name
  373. variable = StringTable->insert(variableName, true);
  374. // Cleanup our variableName buffer
  375. dFree( variableName );
  376. }
  377. }
  378. // Set back the variable name
  379. prop.name = StringTable->insert(variable, true);
  380. // Store the start position for this variable
  381. prop.startLine = mParser.getCurrentLine();
  382. prop.startPosition = mParser.getTokenLineOffset();
  383. // Advance back to the '='
  384. mParser.advanceToken(true);
  385. // Sanity check
  386. if (!mParser.tokenICmp("="))
  387. Con::errorf("PersistenceManager::parseObject() - somehow we aren't \
  388. pointing at the expected '=' character");
  389. else
  390. {
  391. // The next token should be the value
  392. // being assigned to the variable
  393. mParser.advanceToken(true);
  394. // Store the line number for this value
  395. prop.valueLine = mParser.getCurrentLine();
  396. // Store the values beginning position
  397. prop.valuePosition = mParser.getTokenLineOffset();
  398. // Read tokens up to the semicolon.
  399. // Quoted tokens skip the leading and trailing quote characters. eg.
  400. // "this" becomes: this
  401. // "this" TAB "that" becomes: this" TAB "that
  402. // "this" TAB "that" TAB "other" becomes: this" TAB "that" TAB "other
  403. String value;
  404. bool wasQuoted = false;
  405. while (!mParser.endOfFile() && !mParser.tokenICmp(";"))
  406. {
  407. // Join tokens together (skipped first time through when string is empty)
  408. if (value.length() > 0)
  409. {
  410. if (wasQuoted)
  411. value += "\" "; // quoted followed by non-quoted
  412. else if (mParser.tokenIsQuoted())
  413. value += " \""; // non-quoted followed by quoted
  414. else
  415. value += " "; // non-quoted followed by non-quoted
  416. }
  417. value += mParser.getToken();
  418. wasQuoted = mParser.tokenIsQuoted();
  419. mParser.advanceToken(true);
  420. }
  421. // TODO: make sure this doesn't leak
  422. prop.value = dStrdup(value.c_str());
  423. if (!mParser.tokenICmp(";"))
  424. Con::errorf("PersistenceManager::parseObject() - badly formed variable "
  425. "assignment on line %d - was expecting a ';' character", mParser.getCurrentLine()+1);
  426. // Store the end position for this variable
  427. prop.endLine = mParser.getCurrentLine();
  428. prop.endPosition = mParser.getTokenLineOffset();
  429. if (wasQuoted)
  430. prop.endPosition -= 1;
  431. }
  432. }
  433. }
  434. }
  435. // Check for the end of the object declaration
  436. if (mParser.tokenICmp("}"))
  437. {
  438. // See if the next token is a ';'
  439. mParser.advanceToken(true);
  440. if (mParser.tokenICmp(";"))
  441. {
  442. // Save the end line number
  443. mCurrentObject->endLine = mParser.getCurrentLine();
  444. // Save the end position
  445. mCurrentObject->endPosition = mParser.getTokenLineOffset();
  446. saveObject();
  447. break;
  448. }
  449. }
  450. }
  451. }
  452. bool PersistenceManager::parseFile(const char* fileName)
  453. {
  454. // Read the file into the line buffer
  455. if (!readFile(fileName))
  456. return false;
  457. // Load it into our Tokenizer parser
  458. if (!mParser.openFile(fileName))
  459. {
  460. // Handle an object writing out to a new file
  461. if ( !Torque::FS::IsFile( fileName ) )
  462. return true;
  463. return false;
  464. }
  465. // Set our reserved "single" tokens
  466. mParser.setSingleTokens("(){};=:");
  467. // Search object declarations
  468. while (mParser.advanceToken(true))
  469. {
  470. if (mParser.tokenICmp("new") ||
  471. mParser.tokenICmp("singleton") ||
  472. mParser.tokenICmp("datablock"))
  473. {
  474. parseObject();
  475. }
  476. }
  477. // If we had an object that didn't end properly
  478. // then we could have objects on the stack
  479. while (mCurrentObject)
  480. saveObject();
  481. //Con::errorf("Parsed Results:");
  482. //for (U32 i = 0; i < mObjectBuffer.size(); i++)
  483. //{
  484. // ParsedObject* parsedObject = mObjectBuffer[i];
  485. // Con::warnf(" mObjectBuffer[%d]:", i);
  486. // Con::warnf(" name = %s", parsedObject->name);
  487. // Con::warnf(" className = %s", parsedObject->className);
  488. // Con::warnf(" startLine = %d", parsedObject->startLine + 1);
  489. // Con::warnf(" endLine = %d", parsedObject->endLine + 1);
  490. // //if (mObjectBuffer[i]->properties.size() > 0)
  491. // //{
  492. // // Con::warnf(" properties:");
  493. // // for (U32 j = 0; j < mObjectBuffer[i]->properties.size(); j++)
  494. // // Con::warnf(" %s = %s;", mObjectBuffer[i]->properties[j].name,
  495. // // mObjectBuffer[i]->properties[j].value);
  496. // //}
  497. // if (!parsedObject->simObject.isNull())
  498. // {
  499. // SimObject* simObject = parsedObject->simObject;
  500. // Con::warnf(" SimObject(%s) %d:", simObject->getName(), simObject->getId());
  501. // Con::warnf(" declaration line = %d", simObject->getDeclarationLine());
  502. // }
  503. //}
  504. return true;
  505. }
  506. S32 PersistenceManager::getPropertyIndex(ParsedObject* parsedObject, const char* fieldName, U32 arrayPos)
  507. {
  508. S32 propertyIndex = -1;
  509. if (!parsedObject)
  510. return propertyIndex;
  511. for (U32 i = 0; i < parsedObject->properties.size(); i++)
  512. {
  513. if (dStricmp(fieldName, parsedObject->properties[i].name) == 0 &&
  514. parsedObject->properties[i].arrayPos == arrayPos)
  515. {
  516. propertyIndex = i;
  517. break;
  518. }
  519. }
  520. return propertyIndex;
  521. }
  522. char* PersistenceManager::getObjectIndent(ParsedObject* object)
  523. {
  524. char* indent = Con::getReturnBuffer(2048);
  525. indent[0] = 0;
  526. if (!object)
  527. return indent;
  528. if (object->startLine < 0 || object->startLine >= mLineBuffer.size())
  529. return indent;
  530. const char* line = mLineBuffer[object->startLine];
  531. if (line)
  532. {
  533. const char* nonSpace = line;
  534. U32 strLen = dStrlen(line);
  535. for (U32 i = 0; i < strLen; i++)
  536. {
  537. if (*nonSpace != ' ')
  538. break;
  539. nonSpace++;
  540. }
  541. dStrncpy(indent, line, nonSpace - line);
  542. indent[nonSpace - line] = 0;
  543. }
  544. return indent;
  545. }
  546. void PersistenceManager::updatePositions(U32 lineNumber, U32 startPos, S32 diff)
  547. {
  548. if (diff == 0)
  549. return;
  550. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  551. {
  552. ParsedObject* object = mObjectBuffer[i];
  553. if (object->nameLine == lineNumber && object->namePosition > startPos)
  554. object->namePosition += diff;
  555. if (object->endLine == lineNumber && object->endPosition > startPos)
  556. object->endPosition += diff;
  557. if (lineNumber >= object->startLine && lineNumber <= object->endLine)
  558. {
  559. for (U32 j = 0; j < object->properties.size(); j++)
  560. {
  561. ParsedProperty& prop = object->properties[j];
  562. S32 propStartPos = prop.startPosition;
  563. S32 endPos = prop.endPosition;
  564. S32 valuePos = prop.valuePosition;
  565. if (lineNumber == prop.startLine && propStartPos > startPos)
  566. {
  567. propStartPos += diff;
  568. if (propStartPos < 0)
  569. propStartPos = 0;
  570. prop.startPosition = valuePos;
  571. }
  572. if (lineNumber == prop.endLine && endPos > startPos)
  573. {
  574. endPos += diff;
  575. if (endPos < 0)
  576. endPos = 0;
  577. prop.endPosition = endPos;
  578. }
  579. if (lineNumber == prop.valueLine && valuePos > startPos)
  580. {
  581. valuePos += diff;
  582. if (valuePos < 0)
  583. valuePos = 0;
  584. prop.valuePosition = valuePos;
  585. }
  586. }
  587. }
  588. }
  589. }
  590. void PersistenceManager::updateLineOffsets(U32 startLine, S32 diff, ParsedObject* skipObject)
  591. {
  592. if (diff == 0)
  593. return;
  594. if (startLine >= mLineBuffer.size())
  595. return;
  596. if (startLine + diff >= mLineBuffer.size())
  597. return;
  598. // Make sure we don't double offset a SimObject's
  599. // declaration line
  600. SimObjectList updated;
  601. if (skipObject && !skipObject->simObject.isNull())
  602. updated.push_back_unique(skipObject->simObject);
  603. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  604. {
  605. ParsedObject* object = mObjectBuffer[i];
  606. // See if this is the skipObject
  607. if (skipObject && skipObject == object)
  608. continue;
  609. // We can safely ignore objects that
  610. // came earlier in the file
  611. if (object->endLine < startLine)
  612. continue;
  613. if (object->startLine >= startLine)
  614. object->startLine += diff;
  615. if (object->nameLine >= startLine)
  616. object->nameLine += diff;
  617. for (U32 j = 0; j < object->properties.size(); j++)
  618. {
  619. if (object->properties[j].startLine >= startLine)
  620. object->properties[j].startLine += diff;
  621. if (object->properties[j].endLine >= startLine)
  622. object->properties[j].endLine += diff;
  623. if (object->properties[j].valueLine >= startLine)
  624. object->properties[j].valueLine += diff;
  625. }
  626. if (object->endLine >= startLine)
  627. object->endLine += diff;
  628. if (!object->simObject.isNull() &&
  629. object->simObject->getDeclarationLine() > startLine)
  630. {
  631. // Check for already updated SimObject's
  632. U32 currSize = updated.size();
  633. updated.push_back_unique(object->simObject);
  634. if (updated.size() == currSize)
  635. continue;
  636. S32 newDeclLine = object->simObject->getDeclarationLine() + diff;
  637. if (newDeclLine < 0)
  638. newDeclLine = 0;
  639. object->simObject->setDeclarationLine(newDeclLine);
  640. }
  641. }
  642. }
  643. PersistenceManager::ParsedObject* PersistenceManager::findParentObject(SimObject* object, ParsedObject* parentObject)
  644. {
  645. ParsedObject* ret = NULL;
  646. if (!object)
  647. return ret;
  648. // First test for the SimGroup it belongs to
  649. ret = findParsedObject(object->getGroup(), parentObject);
  650. if (ret)
  651. return ret;
  652. // TODO: Test all of the SimSet's that this object belongs to
  653. return ret;
  654. }
  655. PersistenceManager::ParsedObject* PersistenceManager::findParsedObject(SimObject* object, ParsedObject* parentObject)
  656. {
  657. if (!object)
  658. return NULL;
  659. // See if our object belongs to a parent
  660. if (!parentObject)
  661. parentObject = findParentObject(object, parentObject);
  662. // First let's compare the object to the SimObject's that
  663. // we matched to our ParsedObject's when we loaded them
  664. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  665. {
  666. ParsedObject* testObj = mObjectBuffer[i];
  667. if (testObj->simObject == object)
  668. {
  669. // Deal with children objects
  670. if (testObj->parentObject != parentObject)
  671. continue;
  672. return testObj;
  673. }
  674. }
  675. // Didn't find it in our ParsedObject's SimObject's
  676. // so see if we can find one that corresponds to the
  677. // same name and className
  678. const char *originalName = object->getOriginalName();
  679. // Find the corresponding ParsedObject
  680. if (originalName && originalName[0])
  681. {
  682. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  683. {
  684. ParsedObject* testObj = mObjectBuffer[i];
  685. if (testObj->name == originalName)
  686. {
  687. // Deal with children objects
  688. if (testObj->parentObject != parentObject)
  689. continue;
  690. return testObj;
  691. }
  692. }
  693. }
  694. //Check internal names
  695. if (object->getInternalName())
  696. {
  697. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  698. {
  699. ParsedObject* testObj = mObjectBuffer[i];
  700. for (U32 j = 0; j < testObj->properties.size(); j++)
  701. {
  702. const ParsedProperty &prop = testObj->properties[j];
  703. if ( dStrcmp( prop.name, "internalName" ) == 0 &&
  704. dStrcmp( prop.value, object->getInternalName() ) == 0 )
  705. return testObj;
  706. else if ( dStrcmp(prop.name, "internalName") == 0)
  707. break;
  708. }
  709. }
  710. }
  711. return NULL;
  712. }
  713. void PersistenceManager::updateToken( const U32 lineNumber, const U32 linePosition, const U32 oldValueLen, const char* newValue, bool addQuotes )
  714. {
  715. // Make sure we have a valid lineNumber
  716. if (lineNumber < 0 || linePosition < 0 ||
  717. lineNumber >= mLineBuffer.size())
  718. return;
  719. // Grab the line that the value is on
  720. const char* line = mLineBuffer[lineNumber];
  721. U32 newValueLen = ( newValue ) ? dStrlen(newValue) : 0;
  722. // Make sure we have a valid linePosition
  723. if (linePosition >= dStrlen(line) ||
  724. linePosition + oldValueLen > dStrlen(line))
  725. return;
  726. // Get all of the characters up to the value position
  727. U32 preStringLen = linePosition;
  728. bool needQuotes = false;
  729. if( addQuotes && line[ linePosition - 1 ] != '"' )
  730. {
  731. preStringLen ++;
  732. needQuotes = true;
  733. }
  734. char* preString = ( char* ) dMalloc( preStringLen + 1 );
  735. dMemcpy( preString, line, linePosition );
  736. if( needQuotes )
  737. {
  738. preString[ linePosition ] = '"';
  739. preString[ linePosition + 1 ] = 0;
  740. }
  741. else
  742. preString[ linePosition ] = 0;
  743. // Get all of the characters that occur after the value
  744. const char* postStringSrc = line + linePosition + oldValueLen;
  745. U32 postStringLen = dStrlen( postStringSrc );
  746. if( needQuotes )
  747. postStringLen ++;
  748. char* postString = ( char* ) dMalloc( postStringLen + 1 );
  749. if( needQuotes )
  750. postString[ 0 ] = '"';
  751. dStrcpy( &postString[ needQuotes ? 1 : 0 ], postStringSrc );
  752. postString[ postStringLen ] = 0;
  753. // Calculate the length of our new line
  754. U32 newLineLen = 0;
  755. newLineLen += preStringLen;
  756. newLineLen += newValueLen;
  757. newLineLen += postStringLen;
  758. // Create a buffer for our new line and
  759. // null terminate it
  760. char* newLine = ( char* ) dMalloc( newLineLen + 1 );
  761. newLine[0] = 0;
  762. // Build the new line with the
  763. // preString + newValue + postString
  764. dStrcat(newLine, preString);
  765. if ( newValue )
  766. dStrcat(newLine, newValue);
  767. dStrcat(newLine, postString);
  768. // Clear our existing line
  769. if (mLineBuffer[lineNumber])
  770. {
  771. dFree( mLineBuffer[ lineNumber ] );
  772. mLineBuffer[ lineNumber ] = NULL;
  773. }
  774. // Set the new line
  775. mLineBuffer[lineNumber] = newLine;
  776. // Figure out the size difference of the old value
  777. // and new value in case we need to update any else
  778. // on the line after it
  779. S32 diff = newValueLen - oldValueLen;
  780. // Update anything that is on the line after this that needs
  781. // to change its offsets to reflect the new line
  782. updatePositions(lineNumber, linePosition, diff);
  783. // Clean up our buffers
  784. dFree( preString );
  785. dFree( postString );
  786. }
  787. const char* PersistenceManager::getFieldValue(SimObject* object, const char* fieldName, U32 arrayPos)
  788. {
  789. // Our return string
  790. char* ret = NULL;
  791. // Buffer to hold the string equivalent of the arrayPos
  792. char arrayPosStr[8];
  793. dSprintf(arrayPosStr, 8, "%d", arrayPos);
  794. // Get the object's value
  795. const char *value = object->getDataField(fieldName, arrayPosStr );
  796. if (value)
  797. ret = dStrdup(value);
  798. return ret;
  799. }
  800. const char* PersistenceManager::createNewProperty(const char* name, const char* value, bool isArray, U32 arrayPos)
  801. {
  802. if (!name || !value)
  803. return NULL;
  804. AssertFatal( value[0] != StringTagPrefixByte, "Got tagged string!" );
  805. char* newProp = ( char* ) dMalloc( 2048 );
  806. dMemset(newProp, 0, 2048);
  807. if (value)
  808. {
  809. if (isArray)
  810. dSprintf(newProp, 2048, "%s[%d] = \"%s\";", name, arrayPos, value);
  811. else
  812. dSprintf(newProp, 2048, "%s = \"%s\";", name, value);
  813. }
  814. else
  815. {
  816. if (isArray)
  817. dSprintf(newProp, 2048, "%s[%d] = \"\";", name, arrayPos);
  818. else
  819. dSprintf(newProp, 2048, "%s = \"\";", name);
  820. }
  821. return newProp;
  822. }
  823. bool PersistenceManager::isEmptyLine(const char* line)
  824. {
  825. // Simple test first
  826. if (!line || dStrlen(line) == 0)
  827. return true;
  828. U32 len = dStrlen(line);
  829. for (U32 i = 0; i < len; i++)
  830. {
  831. const char& c = line[i];
  832. // Skip "empty" characters
  833. if (c == ' ' ||
  834. c == '\t' ||
  835. c == '\r' ||
  836. c == '\n')
  837. {
  838. continue;
  839. }
  840. // If we have made it to the an end of the line
  841. // comment then consider this an empty line
  842. if (c == '/')
  843. {
  844. if (i < len - 1)
  845. {
  846. if (line[i + 1] == '/')
  847. return true;
  848. }
  849. }
  850. // If it isn't an "empty" character or a comment then
  851. // we have a valid character on the line and it isn't empty
  852. return false;
  853. }
  854. return true;
  855. }
  856. void PersistenceManager::removeLine(U32 lineNumber)
  857. {
  858. if (lineNumber >= mLineBuffer.size())
  859. return;
  860. if (mLineBuffer[lineNumber])
  861. {
  862. dFree( mLineBuffer[ lineNumber ] );
  863. mLineBuffer[ lineNumber ] = NULL;
  864. }
  865. mLineBuffer.erase(lineNumber);
  866. updateLineOffsets(lineNumber, -1);
  867. }
  868. void PersistenceManager::removeTextBlock(U32 startLine, U32 endLine, U32 startPos, U32 endPos, bool removeEmptyLines)
  869. {
  870. // Make sure we have valid lines
  871. if (startLine >= mLineBuffer.size() || endLine >= mLineBuffer.size())
  872. return;
  873. // We assume that the startLine is before the endLine
  874. if (startLine > endLine)
  875. return;
  876. // Grab the lines (they may be the same)
  877. const char* startLineText = mLineBuffer[startLine];
  878. const char* endLineText = mLineBuffer[endLine];
  879. // Make sure we have a valid startPos
  880. if (startPos >= dStrlen(startLineText))
  881. return;
  882. // Make sure we have a valid endPos
  883. if (endPos > dStrlen(endLineText))
  884. return;
  885. if (startLine == endLine)
  886. {
  887. // Now let updateToken do the heavy lifting on removing it
  888. updateToken(startLine, startPos, endPos - startPos, "");
  889. // Handle removing an empty lines if desired
  890. if (removeEmptyLines)
  891. {
  892. const char* line = mLineBuffer[startLine];
  893. if (isEmptyLine(line))
  894. removeLine(startLine);
  895. }
  896. }
  897. else
  898. {
  899. // Start with clearing the startLine from startPos to the end
  900. updateToken(startLine, startPos, dStrlen(startLineText + startPos), "");
  901. // Then clear the endLine from beginning to endPos
  902. updateToken(endLine, 0, endPos, "");
  903. // Handle removing an empty endLine if desired
  904. if (removeEmptyLines)
  905. {
  906. const char* line = mLineBuffer[endLine];
  907. if (isEmptyLine(line))
  908. removeLine(endLine);
  909. }
  910. // Handle removing any lines between the startLine and endLine
  911. for (U32 i = startLine + 1; i < endLine; i++)
  912. removeLine(startLine + 1);
  913. // Handle removing an empty startLine if desired
  914. if (removeEmptyLines)
  915. {
  916. const char* line = mLineBuffer[startLine];
  917. if (isEmptyLine(line))
  918. removeLine(startLine);
  919. }
  920. }
  921. }
  922. void PersistenceManager::removeParsedObject(ParsedObject* parsedObject)
  923. {
  924. if (!parsedObject)
  925. return;
  926. if (parsedObject->startLine < 0 || parsedObject->startLine >= mLineBuffer.size())
  927. return;
  928. if (parsedObject->endLine < 0 || parsedObject->startLine >= mLineBuffer.size())
  929. return;
  930. removeTextBlock(parsedObject->startLine, parsedObject->endLine,
  931. parsedObject->startPosition, parsedObject->endPosition+1, true); // +1 to remove trailing semicolon as well
  932. parsedObject->parentObject = NULL;
  933. parsedObject->simObject = NULL;
  934. }
  935. void PersistenceManager::removeField(const ParsedProperty& prop)
  936. {
  937. if (prop.startLine < 0 || prop.startLine >= mLineBuffer.size())
  938. return;
  939. if (prop.endLine < 0 || prop.endLine >= mLineBuffer.size())
  940. return;
  941. S32 endPosition = prop.endPosition+1; // +1 to remove trailing semicolon as well
  942. if ((endPosition < dStrlen(mLineBuffer[prop.endLine])) &&
  943. (mLineBuffer[prop.endLine][endPosition] == ';')) // adjust end position for quoted values (otherwise a trailing semicolon will remain)
  944. endPosition++;
  945. removeTextBlock(prop.startLine, prop.endLine, prop.startPosition, endPosition, true);
  946. }
  947. U32 PersistenceManager::writeProperties(const Vector<const char*>& properties, const U32 insertLine, const char* objectIndent)
  948. {
  949. U32 currInsertLine = insertLine;
  950. for (U32 i = 0; i < properties.size(); i++)
  951. {
  952. const char* prop = properties[i];
  953. if (!prop || dStrlen(prop) == 0)
  954. continue;
  955. U32 len = dStrlen(objectIndent) + dStrlen(prop) + 4;
  956. char* newLine = ( char* ) dMalloc( len );
  957. dSprintf(newLine, len, "%s %s", objectIndent, prop);
  958. mLineBuffer.insert(currInsertLine, newLine);
  959. currInsertLine++;
  960. }
  961. return currInsertLine - insertLine;
  962. }
  963. PersistenceManager::ParsedObject* PersistenceManager::writeNewObject(SimObject* object, const Vector<const char*>& properties, const U32 insertLine, ParsedObject* parentObject)
  964. {
  965. ParsedObject* parsedObject = new ParsedObject;
  966. parsedObject->name = object->getName();
  967. parsedObject->className = object->getClassName();
  968. parsedObject->simObject = object;
  969. U32 currInsertLine = insertLine;
  970. // If the parentObject isn't set see if
  971. // we can find it in the file
  972. if (!parentObject)
  973. parentObject = findParentObject(object);
  974. parsedObject->parentObject = parentObject;
  975. char* indent = getObjectIndent(parentObject);
  976. if (parentObject)
  977. dStrcat(indent, " \0");
  978. // Write out the beginning of the object declaration
  979. const char* dclToken = "new";
  980. if (dynamic_cast<Material*>(object) ||
  981. dynamic_cast<CustomMaterial*>(object) ||
  982. dynamic_cast<GuiControlProfile*>(object) ||
  983. dynamic_cast<TSShapeConstructor*>(object))
  984. dclToken = "singleton";
  985. else if( dynamic_cast< SimDataBlock* >( object ) )
  986. {
  987. SimDataBlock* db = static_cast<SimDataBlock*>(object);
  988. if( db->isClientOnly() )
  989. {
  990. if( db->getName() && db->getName()[ 0 ] )
  991. dclToken = "singleton";
  992. }
  993. else
  994. dclToken = "datablock";
  995. }
  996. char newLine[ 4096 ];
  997. dMemset(newLine, 0, sizeof( newLine));
  998. // New line before an object declaration
  999. dSprintf(newLine, sizeof( newLine ), "");
  1000. mLineBuffer.insert(currInsertLine, dStrdup(newLine));
  1001. currInsertLine++;
  1002. dMemset(newLine, 0, sizeof( newLine ));
  1003. parsedObject->startLine = currInsertLine;
  1004. parsedObject->nameLine = currInsertLine;
  1005. parsedObject->namePosition = dStrlen(indent) + dStrlen(dclToken) + dStrlen(object->getClassName()) + 2;
  1006. // Objects that had no name were getting saved out as: Object((null))
  1007. if ( object->getName() != NULL )
  1008. {
  1009. if( object->getCopySource() )
  1010. dSprintf(newLine, sizeof( newLine ), "%s%s %s(%s : %s)", indent, dclToken, object->getClassName(), object->getName(),
  1011. object->getCopySource() ? object->getCopySource()->getName() : "" );
  1012. else
  1013. dSprintf(newLine, sizeof( newLine ), "%s%s %s(%s)", indent, dclToken, object->getClassName(), object->getName());
  1014. }
  1015. else
  1016. dSprintf(newLine, sizeof( newLine ), "%s%s %s()", indent, dclToken, object->getClassName() );
  1017. mLineBuffer.insert(currInsertLine, dStrdup(newLine));
  1018. currInsertLine++;
  1019. dMemset(newLine, 0, sizeof( newLine ));
  1020. dSprintf(newLine, sizeof( newLine ), "%s{", indent);
  1021. mLineBuffer.insert(currInsertLine, dStrdup(newLine));
  1022. currInsertLine++;
  1023. dMemset(newLine, 0, sizeof( newLine ));
  1024. currInsertLine += writeProperties(properties, currInsertLine, indent);
  1025. parsedObject->endLine = currInsertLine;
  1026. parsedObject->updated = true;
  1027. dSprintf(newLine, sizeof( newLine ), "%s};", indent);
  1028. mLineBuffer.insert(currInsertLine, dStrdup(newLine));
  1029. currInsertLine++;
  1030. updateLineOffsets(insertLine, currInsertLine - insertLine, parsedObject);
  1031. mObjectBuffer.push_back(parsedObject);
  1032. // Update the SimObject to reflect its saved name and declaration line.
  1033. // These values should always reflect what is in the file, even if the object
  1034. // has not actually been re-created from an execution of that file yet.
  1035. object->setOriginalName( object->getName() );
  1036. object->setDeclarationLine( currInsertLine );
  1037. if (mCurrentFile)
  1038. object->setFilename(mCurrentFile);
  1039. return parsedObject;
  1040. }
  1041. void PersistenceManager::updateObject(SimObject* object, ParsedObject* parentObject)
  1042. {
  1043. // Create a default object of the same type
  1044. ConsoleObject *defaultConObject = ConsoleObject::create(object->getClassName());
  1045. SimObject* defaultObject = dynamic_cast<SimObject*>(defaultConObject);
  1046. // ***Really*** shouldn't happen
  1047. if (!defaultObject)
  1048. return;
  1049. Vector<const char*> newLines;
  1050. ParsedObject* parsedObject = findParsedObject(object, parentObject);
  1051. // If we don't already have an association between the ParsedObject
  1052. // and the SimObject then go ahead and create it
  1053. if (parsedObject && parsedObject->simObject.isNull())
  1054. parsedObject->simObject = object;
  1055. // Kill all fields on the remove list.
  1056. for( U32 i = 0; i < mRemoveFields.size(); ++ i )
  1057. {
  1058. RemoveField& field = mRemoveFields[ i ];
  1059. if( field.object != object )
  1060. continue;
  1061. S32 propertyIndex = getPropertyIndex( parsedObject, field.fieldName, field.arrayPos );
  1062. if( propertyIndex != -1 )
  1063. removeField( parsedObject->properties[ propertyIndex ] );
  1064. }
  1065. // Get our field list
  1066. const AbstractClassRep::FieldList &list = object->getFieldList();
  1067. for(U32 i = 0; i < list.size(); i++)
  1068. {
  1069. const AbstractClassRep::Field* f = &list[i];
  1070. // Skip the special field types.
  1071. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  1072. continue;
  1073. for(U32 j = 0; S32(j) < f->elementCount; j++)
  1074. {
  1075. const char* value = getFieldValue(object, f->pFieldname, j);
  1076. // Make sure we got a value
  1077. if (!value)
  1078. continue;
  1079. // Let's see if this field is already in the file
  1080. S32 propertyIndex = getPropertyIndex(parsedObject, f->pFieldname, j);
  1081. if (propertyIndex > -1)
  1082. {
  1083. ParsedProperty& prop = parsedObject->properties[propertyIndex];
  1084. // If this field is on the remove list then remove it and continue
  1085. if (findRemoveField(object, f->pFieldname, j) || !object->writeField(f->pFieldname, value))
  1086. {
  1087. removeField( parsedObject->properties[ propertyIndex ] );
  1088. dFree( value );
  1089. continue;
  1090. }
  1091. // Run the parsed value through the console system conditioners so
  1092. // that it will better match the data we got back from the object.
  1093. const char* evalue = Con::getFormattedData(f->type, prop.value, f->table, f->flag);
  1094. // If our data doesn't match then we get to update it.
  1095. //
  1096. // As for copy-sources, we just assume here that if a property setting
  1097. // is there in the file, the user does not want it inherited from the copy-source
  1098. // even in the case the actual values are identical.
  1099. if( dStricmp(value, evalue) != 0 )
  1100. {
  1101. if( value[ 0 ] == '\0' &&
  1102. dStricmp( getFieldValue( defaultObject, f->pFieldname, j ), value ) == 0 &&
  1103. ( !object->getCopySource() || dStricmp( getFieldValue( object->getCopySource(), f->pFieldname, j ), value ) == 0 ) )
  1104. {
  1105. removeField( prop );
  1106. }
  1107. else
  1108. {
  1109. // TODO: This should be wrapped in a helper method... probably.
  1110. // Detect and collapse relative path information
  1111. if (f->type == TypeFilename ||
  1112. f->type == TypeStringFilename ||
  1113. f->type == TypeImageFilename ||
  1114. f->type == TypePrefabFilename ||
  1115. f->type == TypeShapeFilename)
  1116. {
  1117. char fnBuf[1024];
  1118. Con::collapseScriptFilename(fnBuf, 1024, value);
  1119. updateToken(prop.valueLine, prop.valuePosition, prop.endPosition - prop.valuePosition, fnBuf, true);
  1120. }
  1121. else
  1122. updateToken(prop.valueLine, prop.valuePosition, prop.endPosition - prop.valuePosition, value, true);
  1123. }
  1124. }
  1125. }
  1126. else
  1127. {
  1128. // No need to process a removed field that doesn't exist in the file
  1129. if (findRemoveField(object, f->pFieldname, j) || !object->writeField(f->pFieldname, value))
  1130. {
  1131. dFree( value );
  1132. continue;
  1133. }
  1134. bool mustUpdate = false;
  1135. // If we didn't find the property in the ParsedObject
  1136. // then we need to compare against the default value
  1137. // for this property and save it out if it is different
  1138. const char* defaultValue = getFieldValue(defaultObject, f->pFieldname, j);
  1139. if( !defaultValue || dStricmp( value, defaultValue ) != 0 )
  1140. {
  1141. // Value differs. Check whether it also differs from the
  1142. // value in the copy source if there is one.
  1143. if( object->getCopySource() )
  1144. {
  1145. const char* copySourceValue = getFieldValue( object->getCopySource(), f->pFieldname, j );
  1146. if( !copySourceValue || dStricmp( copySourceValue, value ) != 0 )
  1147. mustUpdate = true;
  1148. if( copySourceValue )
  1149. dFree( copySourceValue );
  1150. }
  1151. else
  1152. mustUpdate = true;
  1153. }
  1154. else
  1155. {
  1156. // Value does not differ. If it differs from the copy source's value,
  1157. // though, we still want to write it out as otherwise we'll see the
  1158. // copy source's value override us.
  1159. if( object->getCopySource() )
  1160. {
  1161. const char* copySourceValue = getFieldValue( object->getCopySource(), f->pFieldname, j );
  1162. if( copySourceValue && dStricmp( copySourceValue, value ) != 0 )
  1163. mustUpdate = true;
  1164. if( copySourceValue )
  1165. dFree( copySourceValue );
  1166. }
  1167. }
  1168. // The default value for most string type fields is
  1169. // NULL so we can't just continue here or we'd never ever
  1170. // write them out...
  1171. //
  1172. //if (!defaultValue)
  1173. // continue;
  1174. // If the object's value is different from the default
  1175. // value then add it to the ParsedObject's newLines
  1176. if ( mustUpdate )
  1177. {
  1178. // TODO: This should be wrapped in a helper method... probably.
  1179. // Detect and collapse relative path information
  1180. if (f->type == TypeFilename ||
  1181. f->type == TypeStringFilename ||
  1182. f->type == TypeImageFilename ||
  1183. f->type == TypePrefabFilename ||
  1184. f->type == TypeShapeFilename)
  1185. {
  1186. char fnBuf[1024];
  1187. Con::collapseScriptFilename(fnBuf, 1024, value);
  1188. newLines.push_back(createNewProperty(f->pFieldname, fnBuf, f->elementCount > 1, j));
  1189. }
  1190. else
  1191. newLines.push_back(createNewProperty(f->pFieldname, value, f->elementCount > 1, j));
  1192. }
  1193. if (defaultValue)
  1194. dFree( defaultValue );
  1195. }
  1196. dFree( value );
  1197. }
  1198. }
  1199. // Handle dynamic fields
  1200. SimFieldDictionary* fieldDict = object->getFieldDictionary();
  1201. for(SimFieldDictionaryIterator itr(fieldDict); *itr; ++itr)
  1202. {
  1203. SimFieldDictionary::Entry * entry = (*itr);
  1204. if( !entry->value )
  1205. continue;
  1206. // Let's see if this field is already in the file
  1207. S32 propertyIndex = getPropertyIndex(parsedObject, entry->slotName);
  1208. if (propertyIndex > -1)
  1209. {
  1210. ParsedProperty& prop = parsedObject->properties[propertyIndex];
  1211. // If this field is on the remove list then remove it and continue
  1212. if (findRemoveField(object, entry->slotName) || !object->writeField(entry->slotName, entry->value))
  1213. {
  1214. removeField( parsedObject->properties[ propertyIndex ] );
  1215. continue;
  1216. }
  1217. if( object->getCopySource() )
  1218. {
  1219. const char* copySourceFieldValue = object->getCopySource()->getDataField( entry->slotName, NULL );
  1220. if( dStrcmp( copySourceFieldValue, entry->value ) == 0 )
  1221. {
  1222. removeField( prop );
  1223. continue;
  1224. }
  1225. }
  1226. const char* evalue = prop.value;
  1227. const char *entryVal = entry->value;
  1228. if ( entryVal[0] == StringTagPrefixByte )
  1229. entryVal = gNetStringTable->lookupString( dAtoi( entryVal+1 ) );
  1230. else
  1231. {
  1232. // Run the parsed value through the console system conditioners so
  1233. // that it will better match the data we got back from the object.
  1234. evalue = Con::getFormattedData(TypeString, evalue);
  1235. }
  1236. // If our data doesn't match then we get to update it
  1237. if (dStricmp(entryVal, evalue) != 0)
  1238. updateToken(prop.valueLine, prop.valuePosition, prop.endPosition - prop.valuePosition, entryVal);
  1239. }
  1240. else
  1241. {
  1242. // No need to process a removed field that doesn't exist in the file
  1243. if (findRemoveField(object, entry->slotName) || !object->writeField(entry->slotName, entry->value))
  1244. continue;
  1245. if( object->getCopySource() )
  1246. {
  1247. const char* copySourceFieldValue = object->getCopySource()->getDataField( entry->slotName, NULL );
  1248. if( dStrcmp( copySourceFieldValue, entry->value ) == 0 )
  1249. continue;
  1250. }
  1251. newLines.push_back(createNewProperty(entry->slotName, entry->value));
  1252. }
  1253. }
  1254. // If we have a parsedObject and the name changed
  1255. // then update the parsedObject to the new name.
  1256. // NOTE: an object 'can' have a NULL name which crashes in dStricmp.
  1257. if (parsedObject && parsedObject->name != StringTable->insert(object->getName(), true) )
  1258. {
  1259. StringTableEntry objectName = StringTable->insert(object->getName(), true);
  1260. if (parsedObject->name != objectName)
  1261. {
  1262. // Update the name in the file
  1263. updateToken(parsedObject->nameLine, parsedObject->namePosition, dStrlen(parsedObject->name), object->getName());
  1264. // Updated the parsedObject's name
  1265. parsedObject->name = objectName;
  1266. // Updated the object's "original" name to the one that is now in the file
  1267. object->setOriginalName(objectName);
  1268. }
  1269. }
  1270. if (parsedObject && newLines.size() > 0)
  1271. {
  1272. U32 lastPropLine = parsedObject->endLine;
  1273. if (parsedObject->properties.size() > 0)
  1274. lastPropLine = parsedObject->properties.last().valueLine + 1;
  1275. U32 currInsertLine = lastPropLine;
  1276. const char* indent = getObjectIndent(parsedObject);
  1277. // This should handle adding the opening { to an object
  1278. // that formerly did not have {};
  1279. if (!parsedObject->hasBraces)
  1280. {
  1281. updateToken(parsedObject->endLine, parsedObject->endPosition, 1, "\r\n{");
  1282. currInsertLine++;
  1283. }
  1284. currInsertLine += writeProperties(newLines, currInsertLine, indent);
  1285. // This should handle adding the opening } to an object
  1286. // that formerly did not have {};
  1287. if (!parsedObject->hasBraces)
  1288. {
  1289. U32 len = dStrlen(indent) + 3;
  1290. char* newLine = ( char* ) dMalloc( len );
  1291. dSprintf(newLine, len, "%s};", indent);
  1292. mLineBuffer.insert(currInsertLine, newLine);
  1293. currInsertLine++;
  1294. }
  1295. // Update the line offsets to account for the new lines
  1296. updateLineOffsets(lastPropLine, currInsertLine - lastPropLine);
  1297. }
  1298. else if (!parsedObject)
  1299. {
  1300. U32 insertLine = mLineBuffer.size();
  1301. if (!parentObject)
  1302. parentObject = findParentObject(object, parentObject);
  1303. if (parentObject && parentObject->endLine > -1)
  1304. insertLine = parentObject->endLine;
  1305. parsedObject = writeNewObject(object, newLines, insertLine, parentObject);
  1306. }
  1307. // Clean up the newLines memory
  1308. for (U32 i = 0; i < newLines.size(); i++)
  1309. {
  1310. if (newLines[i])
  1311. {
  1312. dFree(newLines[i]);
  1313. newLines[ i ] = NULL;
  1314. }
  1315. }
  1316. newLines.clear();
  1317. SimSet* set = dynamic_cast<SimSet*>(object);
  1318. if (set)
  1319. {
  1320. for(SimSet::iterator i = set->begin(); i != set->end(); i++)
  1321. {
  1322. SimObject* subObject = (SimObject*)(*i);
  1323. updateObject(subObject, parsedObject);
  1324. }
  1325. }
  1326. // Loop through the children of this parsedObject
  1327. // If they haven't been updated then assume that they
  1328. // don't exist in the file anymore
  1329. if (parsedObject)
  1330. {
  1331. for (S32 i = 0; i < mObjectBuffer.size(); i++)
  1332. {
  1333. ParsedObject* removeObj = mObjectBuffer[i];
  1334. if (removeObj->parentObject == parsedObject && !removeObj->updated)
  1335. {
  1336. removeParsedObject(removeObj);
  1337. mObjectBuffer.erase(i);
  1338. i--;
  1339. deleteObject(removeObj);
  1340. }
  1341. }
  1342. }
  1343. // Flag this as an updated object
  1344. if (parsedObject)
  1345. parsedObject->updated = true;
  1346. // Cleanup our created default object
  1347. delete defaultConObject;
  1348. }
  1349. bool PersistenceManager::saveDirtyFile()
  1350. {
  1351. FileStream stream;
  1352. stream.open( mCurrentFile, Torque::FS::File::Write );
  1353. if ( stream.getStatus() != Stream::Ok )
  1354. {
  1355. clearFileData();
  1356. return false;
  1357. }
  1358. for (U32 i = 0; i < mLineBuffer.size(); i++)
  1359. stream.writeLine((const U8*)mLineBuffer[i]);
  1360. stream.close();
  1361. //Con::printf("Successfully opened and wrote %s", mCurrentFile);
  1362. //Con::errorf("Updated Results:");
  1363. //for (U32 i = 0; i < mObjectBuffer.size(); i++)
  1364. //{
  1365. // ParsedObject* parsedObject = mObjectBuffer[i];
  1366. // Con::warnf(" mObjectBuffer[%d]:", i);
  1367. // Con::warnf(" name = %s", parsedObject->name);
  1368. // Con::warnf(" className = %s", parsedObject->className);
  1369. // Con::warnf(" startLine = %d", parsedObject->startLine + 1);
  1370. // Con::warnf(" endLine = %d", parsedObject->endLine + 1);
  1371. // //if (mObjectBuffer[i]->properties.size() > 0)
  1372. // //{
  1373. // // Con::warnf(" properties:");
  1374. // // for (U32 j = 0; j < mObjectBuffer[i]->properties.size(); j++)
  1375. // // Con::warnf(" %s = %s;", mObjectBuffer[i]->properties[j].name,
  1376. // // mObjectBuffer[i]->properties[j].value);
  1377. // //}
  1378. // if (!parsedObject->simObject.isNull())
  1379. // {
  1380. // SimObject* simObject = parsedObject->simObject;
  1381. // Con::warnf(" SimObject(%s) %d:", simObject->getName(), simObject->getId());
  1382. // Con::warnf(" declaration line = %d", simObject->getDeclarationLine());
  1383. // }
  1384. //}
  1385. // Clear our file data
  1386. clearFileData();
  1387. return true;
  1388. }
  1389. S32 QSORT_CALLBACK PersistenceManager::compareFiles(const void* a,const void* b)
  1390. {
  1391. DirtyObject* objectA = (DirtyObject*)(a);
  1392. DirtyObject* objectB = (DirtyObject*)(b);
  1393. if (objectA->isNull())
  1394. return -1;
  1395. else if (objectB->isNull())
  1396. return 1;
  1397. if (objectA->fileName == objectB->fileName)
  1398. return objectA->getObject()->getDeclarationLine() - objectB->getObject()->getDeclarationLine();
  1399. return dStricmp(objectA->fileName, objectB->fileName);
  1400. }
  1401. bool PersistenceManager::setDirty(SimObject* inObject, const char* inFileName)
  1402. {
  1403. // Check if the object is already in the dirty list...
  1404. DirtyObject *pDirty = findDirtyObject( inObject );
  1405. // The filename we will save this object to (later)..
  1406. String saveFile;
  1407. // Expand the script filename if we were passed one.
  1408. if ( inFileName )
  1409. {
  1410. char buffer[4096];
  1411. Con::expandScriptFilename( buffer, 4096, inFileName );
  1412. saveFile = buffer;
  1413. }
  1414. // If no filename was passed in, and the object was already dirty,
  1415. // we have nothing to do.
  1416. if ( saveFile.isEmpty() && pDirty )
  1417. return true;
  1418. // Otherwise default to the simObject's filename.
  1419. if ( saveFile.isEmpty() )
  1420. saveFile = inObject->getFilename();
  1421. // Error if still no filename.
  1422. if ( saveFile.isEmpty() )
  1423. {
  1424. if (inObject->getName())
  1425. Con::errorf("PersistenceManager::setDirty() - SimObject %s has no file name associated with it - can not save", inObject->getName());
  1426. else
  1427. Con::errorf("PersistenceManager::setDirty() - SimObject %d has no file name associated with it - can not save", inObject->getId());
  1428. return false;
  1429. }
  1430. // Update the DirtyObject's fileName if we have it
  1431. // else create a new one.
  1432. if ( pDirty )
  1433. pDirty->fileName = StringTable->insert( saveFile );
  1434. else
  1435. {
  1436. // Add the newly dirty object.
  1437. mDirtyObjects.increment();
  1438. mDirtyObjects.last().setObject( inObject );
  1439. mDirtyObjects.last().fileName = StringTable->insert( saveFile );
  1440. }
  1441. return true;
  1442. }
  1443. void PersistenceManager::removeDirty(SimObject* object)
  1444. {
  1445. for (U32 i = 0; i < mDirtyObjects.size(); i++)
  1446. {
  1447. const DirtyObject& dirtyObject = mDirtyObjects[i];
  1448. if (dirtyObject.isNull())
  1449. continue;
  1450. if (dirtyObject.getObject() == object)
  1451. {
  1452. mDirtyObjects.erase(i);
  1453. break;
  1454. }
  1455. }
  1456. for (U32 i = 0; i < mRemoveFields.size(); i++)
  1457. {
  1458. const RemoveField& field = mRemoveFields[i];
  1459. if (field.object != object)
  1460. continue;
  1461. mRemoveFields.erase(i);
  1462. if (i > 0)
  1463. i--;
  1464. }
  1465. }
  1466. void PersistenceManager::addRemoveField(SimObject* object, const char* fieldName)
  1467. {
  1468. // Check to see if this is an array variable
  1469. U32 arrayPos = 0;
  1470. const char* name = fieldName;
  1471. if (dStrlen(fieldName) > 3 && fieldName[dStrlen(fieldName) - 1] == ']')
  1472. {
  1473. // The last character is a ']' which *should* mean
  1474. // there is also a corresponding '['
  1475. const char* arrayPosStart = dStrrchr(fieldName, '[');
  1476. if (!arrayPosStart)
  1477. {
  1478. Con::errorf("PersistenceManager::addRemoveField() - error parsing array position - \
  1479. was expecting a '[' character");
  1480. }
  1481. else
  1482. {
  1483. // Parse the array position for the variable name
  1484. dSscanf(arrayPosStart, "[%d]", &arrayPos);
  1485. // Trim off the [<pos>] from the variable name
  1486. char* variableName = dStrdup(fieldName);
  1487. variableName[arrayPosStart - fieldName] = 0;
  1488. // Set the variable name to our new shortened name
  1489. name = StringTable->insert(variableName, true);
  1490. // Cleanup our variableName buffer
  1491. dFree( variableName );
  1492. }
  1493. }
  1494. // Make sure this field isn't already on the list
  1495. if (!findRemoveField(object, name, arrayPos))
  1496. {
  1497. mRemoveFields.increment();
  1498. RemoveField& field = mRemoveFields.last();
  1499. field.object = object;
  1500. field.fieldName = StringTable->insert(name);
  1501. field.arrayPos = arrayPos;
  1502. }
  1503. }
  1504. bool PersistenceManager::isDirty(SimObject* object)
  1505. {
  1506. return ( findDirtyObject( object ) != NULL );
  1507. }
  1508. PersistenceManager::DirtyObject* PersistenceManager::findDirtyObject(SimObject* object)
  1509. {
  1510. for (U32 i = 0; i < mDirtyObjects.size(); i++)
  1511. {
  1512. const DirtyObject& dirtyObject = mDirtyObjects[i];
  1513. if (dirtyObject.isNull())
  1514. continue;
  1515. if (dirtyObject.getObject() == object)
  1516. return &mDirtyObjects[i];
  1517. }
  1518. return NULL;
  1519. }
  1520. bool PersistenceManager::findRemoveField(SimObject* object, const char* fieldName, U32 arrayPos)
  1521. {
  1522. for (U32 i = 0; i < mRemoveFields.size(); i++)
  1523. {
  1524. if (mRemoveFields[i].object == object &&
  1525. mRemoveFields[i].arrayPos == arrayPos &&
  1526. dStricmp(mRemoveFields[i].fieldName, fieldName) == 0)
  1527. {
  1528. return true;
  1529. }
  1530. }
  1531. return false;
  1532. }
  1533. bool PersistenceManager::saveDirty()
  1534. {
  1535. // Remove any null SimObject's first
  1536. for (S32 i = 0; i < mDirtyObjects.size(); i++)
  1537. {
  1538. const DirtyObject& dirtyObject = mDirtyObjects[i];
  1539. if (dirtyObject.isNull())
  1540. {
  1541. mDirtyObjects.erase(i);
  1542. i--;
  1543. }
  1544. }
  1545. // Sort by filename and declaration lines
  1546. dQsort(mDirtyObjects.address(), mDirtyObjects.size(), sizeof(DirtyList::value_type), compareFiles);
  1547. for (U32 i = 0; i < mDirtyObjects.size(); i++)
  1548. {
  1549. const DirtyObject& dirtyObject = mDirtyObjects[i];
  1550. if (dirtyObject.isNull())
  1551. continue;
  1552. SimObject* object = dirtyObject.getObject();
  1553. if (!mCurrentFile || dStricmp(mCurrentFile, dirtyObject.fileName) != 0)
  1554. {
  1555. // If mCurrentFile is set then that means we
  1556. // changed file names so save our previous one
  1557. if (mCurrentFile)
  1558. saveDirtyFile();
  1559. // Open our new file and parse it
  1560. bool success = parseFile(dirtyObject.fileName);
  1561. if (!success)
  1562. {
  1563. const char *name = object->getName();
  1564. if (name)
  1565. {
  1566. Con::errorf("PersistenceManager::saveDirty(): Unable to open %s to save %s %s (%d)",
  1567. dirtyObject.fileName, object->getClassName(), name, object->getId());
  1568. }
  1569. else
  1570. {
  1571. Con::errorf("PersistenceManager::saveDirty(): Unable to open %s to save %s (%d)",
  1572. dirtyObject.fileName, object->getClassName(), object->getId());
  1573. }
  1574. continue;
  1575. }
  1576. }
  1577. // Update this object's properties
  1578. //
  1579. // An empty script file (with 1 line) gets here with zero
  1580. // elements in the linebuffer, so this would prevent us from
  1581. // ever writing to it... Or is this test preventing bad things from
  1582. // happening if the file didn't exist at all?
  1583. //
  1584. if (mCurrentFile /*&& mLineBuffer.size() > 0*/)
  1585. updateObject(object);
  1586. }
  1587. // Save out our last file
  1588. if (mCurrentFile)
  1589. saveDirtyFile();
  1590. // Done writing out our dirty objects so reset everything
  1591. clearAll();
  1592. return true;
  1593. }
  1594. bool PersistenceManager::saveDirtyObject(SimObject* object)
  1595. {
  1596. // find our object passed in
  1597. for (U32 i = 0; i < mDirtyObjects.size(); i++)
  1598. {
  1599. const DirtyObject& dirtyObject = mDirtyObjects[i];
  1600. if (dirtyObject.isNull())
  1601. continue;
  1602. if (dirtyObject.getObject() == object)
  1603. {
  1604. // Open our new file and parse it
  1605. bool success = parseFile(dirtyObject.fileName);
  1606. if (!success)
  1607. {
  1608. const char *name = object->getName();
  1609. if (name)
  1610. {
  1611. Con::errorf("PersistenceManager::saveDirtyObject(): Unable to open %s to save %s %s (%d)",
  1612. dirtyObject.fileName, object->getClassName(), name, object->getId());
  1613. }
  1614. else
  1615. {
  1616. Con::errorf("PersistenceManager::saveDirtyObject(): Unable to open %s to save %s (%d)",
  1617. dirtyObject.fileName, object->getClassName(), object->getId());
  1618. }
  1619. return false;
  1620. }
  1621. // if the file exists then lets update and save
  1622. if(mCurrentFile)
  1623. {
  1624. updateObject(object);
  1625. saveDirtyFile();
  1626. }
  1627. break;
  1628. }
  1629. }
  1630. // remove this object from the dirty list
  1631. removeDirty(object);
  1632. return true;
  1633. }
  1634. void PersistenceManager::removeObjectFromFile(SimObject* object, const char* fileName)
  1635. {
  1636. if (mCurrentFile)
  1637. {
  1638. Con::errorf("PersistenceManager::removeObjectFromFile(): Can't remove an object from a \
  1639. file while another is currently opened");
  1640. return;
  1641. }
  1642. const char* file = object->getFilename();
  1643. if (fileName)
  1644. {
  1645. char buffer[1024];
  1646. Con::expandScriptFilename( buffer, 1024, fileName );
  1647. file = StringTable->insert(buffer);
  1648. }
  1649. bool success = false;
  1650. if ( file && file[ 0 ] )
  1651. success = parseFile(file);
  1652. if (!success)
  1653. {
  1654. const char *name = object->getName();
  1655. String errorNameStr;
  1656. if ( name )
  1657. errorNameStr = String::ToString( "%s %s (%d)", object->getClassName(), name, object->getId() );
  1658. else
  1659. errorNameStr = String::ToString( "%s (%d)", object->getClassName(), object->getId() );
  1660. if ( !file )
  1661. Con::errorf("PersistenceManager::removeObjectFromFile(): File was null trying to save %s", errorNameStr.c_str() );
  1662. else
  1663. Con::errorf("PersistenceManager::removeObjectFromFile(): Unable to open %s to save %s", file, errorNameStr.c_str() );
  1664. // Reset everything
  1665. clearAll();
  1666. return;
  1667. }
  1668. ParsedObject* parsedObject = findParsedObject(object);
  1669. if (!parsedObject)
  1670. {
  1671. const char *name = object->getName();
  1672. if (name)
  1673. {
  1674. Con::errorf("PersistenceManager::removeObjectFromFile(): Unable to find %s %s (%d) in %s",
  1675. object->getClassName(), name, object->getId(), file);
  1676. }
  1677. else
  1678. {
  1679. Con::errorf("PersistenceManager::removeObjectFromFile(): Unable to find %s (%d) in %s",
  1680. object->getClassName(), object->getId(), file);
  1681. }
  1682. // Reset everything
  1683. clearAll();
  1684. return;
  1685. }
  1686. removeParsedObject(parsedObject);
  1687. for (U32 i = 0; i < mObjectBuffer.size(); i++)
  1688. {
  1689. ParsedObject* removeObj = mObjectBuffer[i];
  1690. if (removeObj == parsedObject)
  1691. {
  1692. mObjectBuffer.erase(i);
  1693. break;
  1694. }
  1695. }
  1696. deleteObject(parsedObject);
  1697. // Save out the file
  1698. if (mCurrentFile)
  1699. saveDirtyFile();
  1700. // Reset everything
  1701. clearAll();
  1702. }
  1703. void PersistenceManager::deleteObjectsFromFile(const char* fileName)
  1704. {
  1705. if ( mCurrentFile )
  1706. {
  1707. Con::errorf( "PersistenceManager::deleteObjectsFromFile(): Cannot process while file while another is currently open." );
  1708. return;
  1709. }
  1710. // Expand Script File.
  1711. char buffer[1024];
  1712. Con::expandScriptFilename( buffer, 1024, fileName );
  1713. // Parse File.
  1714. if ( !parseFile( StringTable->insert(buffer) ) )
  1715. {
  1716. // Invalid.
  1717. return;
  1718. }
  1719. // Iterate over the objects.
  1720. for ( Vector<ParsedObject*>::iterator itr = mObjectBuffer.begin(); itr != mObjectBuffer.end(); itr++ )
  1721. {
  1722. SimObject *object;
  1723. if ( Sim::findObject( ( *itr )->name, object ) )
  1724. {
  1725. // Delete the Object.
  1726. object->deleteObject();
  1727. }
  1728. }
  1729. // Clear.
  1730. clearAll();
  1731. }
  1732. ConsoleMethod( PersistenceManager, deleteObjectsFromFile, void, 3, 3, "( fileName )"
  1733. "Delete all of the objects that are created from the given file." )
  1734. {
  1735. // Delete Objects.
  1736. object->deleteObjectsFromFile( argv[2] );
  1737. }
  1738. ConsoleMethod( PersistenceManager, setDirty, void, 3, 4, "(SimObject object, [filename])"
  1739. "Mark an existing SimObject as dirty (will be written out when saveDirty() is called).")
  1740. {
  1741. SimObject *dirtyObject = NULL;
  1742. if (argv[2][0])
  1743. {
  1744. if (!Sim::findObject(argv[2], dirtyObject))
  1745. {
  1746. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1747. return;
  1748. }
  1749. }
  1750. // Prevent ourselves from shooting us in the foot.
  1751. if( dirtyObject == Sim::getRootGroup() )
  1752. {
  1753. Con::errorf( "%s(): Cannot save RootGroup", argv[ 0 ] );
  1754. return;
  1755. }
  1756. if (dirtyObject)
  1757. {
  1758. if (argc == 4 && argv[3][0])
  1759. object->setDirty(dirtyObject, argv[3]);
  1760. else
  1761. object->setDirty(dirtyObject);
  1762. }
  1763. }
  1764. ConsoleMethod( PersistenceManager, removeDirty, void, 3, 3, "(SimObject object)"
  1765. "Remove a SimObject from the dirty list.")
  1766. {
  1767. SimObject *dirtyObject = NULL;
  1768. if (argv[2][0])
  1769. {
  1770. if (!Sim::findObject(argv[2], dirtyObject))
  1771. {
  1772. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1773. return;
  1774. }
  1775. }
  1776. if (dirtyObject)
  1777. object->removeDirty(dirtyObject);
  1778. }
  1779. ConsoleMethod( PersistenceManager, isDirty, bool, 3, 3, "(SimObject object)"
  1780. "Returns true if the SimObject is on the dirty list.")
  1781. {
  1782. SimObject *dirtyObject = NULL;
  1783. if (argv[2][0])
  1784. {
  1785. if (!Sim::findObject(argv[2], dirtyObject))
  1786. {
  1787. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1788. return false;
  1789. }
  1790. }
  1791. if (dirtyObject)
  1792. return object->isDirty(dirtyObject);
  1793. return false;
  1794. }
  1795. ConsoleMethod( PersistenceManager, hasDirty, bool, 2, 2, "()"
  1796. "Returns true if the manager has dirty objects to save." )
  1797. {
  1798. return object->hasDirty();
  1799. }
  1800. ConsoleMethod( PersistenceManager, getDirtyObjectCount, S32, 2, 2, "()"
  1801. "Returns the number of dirty objects." )
  1802. {
  1803. return object->getDirtyList().size();
  1804. }
  1805. ConsoleMethod( PersistenceManager, getDirtyObject, S32, 3, 3, "( index )"
  1806. "Returns the ith dirty object." )
  1807. {
  1808. const S32 index = dAtoi( argv[2] );
  1809. if ( index < 0 || index >= object->getDirtyList().size() )
  1810. {
  1811. Con::warnf( "PersistenceManager::getDirtyObject() - Index (%s) out of range.", argv[2] );
  1812. return 0;
  1813. }
  1814. // Fetch Object.
  1815. const PersistenceManager::DirtyObject& dirtyObject = object->getDirtyList()[index];
  1816. // Return Id.
  1817. return ( dirtyObject.getObject() ) ? dirtyObject.getObject()->getId() : 0;
  1818. }
  1819. ConsoleMethod( PersistenceManager, listDirty, void, 2, 2, "()"
  1820. "Prints the dirty list to the console.")
  1821. {
  1822. const PersistenceManager::DirtyList dirtyList = object->getDirtyList();
  1823. for(U32 i = 0; i < dirtyList.size(); i++)
  1824. {
  1825. const PersistenceManager::DirtyObject& dirtyObject = dirtyList[i];
  1826. if (dirtyObject.isNull())
  1827. continue;
  1828. SimObject *obj = dirtyObject.getObject();
  1829. bool isSet = dynamic_cast<SimSet *>(obj) != 0;
  1830. const char *name = obj->getName();
  1831. if (name)
  1832. {
  1833. Con::printf(" %d,\"%s\": %s %s %s", obj->getId(), name,
  1834. obj->getClassName(), dirtyObject.fileName, isSet ? "(g)":"");
  1835. }
  1836. else
  1837. {
  1838. Con::printf(" %d: %s %s, %s", obj->getId(), obj->getClassName(),
  1839. dirtyObject.fileName, isSet ? "(g)" : "");
  1840. }
  1841. }
  1842. }
  1843. ConsoleMethod( PersistenceManager, saveDirty, bool, 2, 2, "()"
  1844. "Saves all of the SimObject's on the dirty list to their respective files.")
  1845. {
  1846. return object->saveDirty();
  1847. }
  1848. ConsoleMethod( PersistenceManager, saveDirtyObject, bool, 3, 3, "(SimObject object)"
  1849. "Save a dirty SimObject to it's file.")
  1850. {
  1851. SimObject *dirtyObject = NULL;
  1852. if (argv[2][0])
  1853. {
  1854. if (!Sim::findObject(argv[2], dirtyObject))
  1855. {
  1856. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1857. return false;
  1858. }
  1859. }
  1860. if (dirtyObject)
  1861. return object->saveDirtyObject(dirtyObject);
  1862. return false;
  1863. }
  1864. ConsoleMethod( PersistenceManager, clearAll, void, 2, 2, "()"
  1865. "Clears all the tracked objects without saving them." )
  1866. {
  1867. object->clearAll();
  1868. }
  1869. ConsoleMethod( PersistenceManager, removeObjectFromFile, void, 3, 4, "(SimObject object, [filename])"
  1870. "Remove an existing SimObject from a file (can optionally specify a different file than \
  1871. the one it was created in.")
  1872. {
  1873. SimObject *dirtyObject = NULL;
  1874. if (argv[2][0])
  1875. {
  1876. if (!Sim::findObject(argv[2], dirtyObject))
  1877. {
  1878. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1879. return;
  1880. }
  1881. }
  1882. if (dirtyObject)
  1883. {
  1884. if (argc == 4 && argv[3][0])
  1885. object->removeObjectFromFile(dirtyObject, argv[3]);
  1886. else
  1887. object->removeObjectFromFile(dirtyObject);
  1888. }
  1889. }
  1890. ConsoleMethod( PersistenceManager, removeField, void, 4, 4, "(SimObject object, string fieldName)"
  1891. "Remove a specific field from an object declaration.")
  1892. {
  1893. SimObject *dirtyObject = NULL;
  1894. if (argv[2][0])
  1895. {
  1896. if (!Sim::findObject(argv[2], dirtyObject))
  1897. {
  1898. Con::printf("%s(): Invalid SimObject: %s", argv[0], argv[2]);
  1899. return;
  1900. }
  1901. }
  1902. if (dirtyObject)
  1903. {
  1904. if (argv[3][0])
  1905. object->addRemoveField(dirtyObject, argv[3]);
  1906. }
  1907. }