simObject.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792
  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 "platform/platform.h"
  23. #include "platform/platformMemory.h"
  24. #include "console/simObject.h"
  25. #include "console/console.h"
  26. #include "console/consoleInternal.h"
  27. #include "console/engineAPI.h"
  28. #include "console/simFieldDictionary.h"
  29. #include "console/simPersistID.h"
  30. #include "console/typeValidators.h"
  31. #include "console/arrayObject.h"
  32. #include "console/codeBlock.h"
  33. #include "core/frameAllocator.h"
  34. #include "core/stream/fileStream.h"
  35. #include "core/fileObject.h"
  36. IMPLEMENT_CONOBJECT( SimObject );
  37. // See full description in the new CHM manual
  38. ConsoleDocClass( SimObject,
  39. "@brief Base class for almost all objects involved in the simulation.\n\n"
  40. "@ingroup Console\n"
  41. );
  42. bool SimObject::smForceId = false;
  43. SimObjectId SimObject::smForcedId = 0;
  44. namespace Sim
  45. {
  46. // Defined in simManager.cpp
  47. extern SimGroup *gRootGroup;
  48. extern SimManagerNameDictionary *gNameDictionary;
  49. extern SimIdDictionary *gIdDictionary;
  50. extern U32 gNextObjectId;
  51. }
  52. //-----------------------------------------------------------------------------
  53. SimObject::SimObject()
  54. {
  55. objectName = NULL;
  56. mOriginalName = NULL;
  57. mInternalName = NULL;
  58. nextNameObject = (SimObject*)-1;
  59. nextManagerNameObject = (SimObject*)-1;
  60. nextIdObject = NULL;
  61. mFilename = NULL;
  62. mDeclarationLine = -1;
  63. mId = 0;
  64. mIdString[ 0 ] = '\0';
  65. mGroup = 0;
  66. mNameSpace = NULL;
  67. mNotifyList = NULL;
  68. mFlags.set( ModStaticFields | ModDynamicFields );
  69. mFieldDictionary = NULL;
  70. mCanSaveFieldDictionary = true;
  71. mClassName = NULL;
  72. mSuperClassName = NULL;
  73. mCopySource = NULL;
  74. mPersistentId = NULL;
  75. }
  76. //-----------------------------------------------------------------------------
  77. SimObject::~SimObject()
  78. {
  79. if( mFieldDictionary )
  80. {
  81. delete mFieldDictionary;
  82. mFieldDictionary = NULL;
  83. }
  84. // Release persistent ID.
  85. if( mPersistentId )
  86. {
  87. mPersistentId->unresolve();
  88. mPersistentId->decRefCount();
  89. mPersistentId = NULL;
  90. }
  91. if( mCopySource )
  92. mCopySource->unregisterReference( &mCopySource );
  93. AssertFatal(nextNameObject == (SimObject*)-1,avar(
  94. "SimObject::~SimObject: Not removed from dictionary: name %s, id %i",
  95. objectName, mId));
  96. AssertFatal(nextManagerNameObject == (SimObject*)-1,avar(
  97. "SimObject::~SimObject: Not removed from manager dictionary: name %s, id %i",
  98. objectName,mId));
  99. AssertFatal(mFlags.test(Added) == 0, "SimObject::object "
  100. "missing call to SimObject::onRemove");
  101. }
  102. //-----------------------------------------------------------------------------
  103. bool SimObject::processArguments(S32 argc, ConsoleValueRef *argv)
  104. {
  105. return argc == 0;
  106. }
  107. //-----------------------------------------------------------------------------
  108. void SimObject::initPersistFields()
  109. {
  110. addGroup( "Ungrouped" );
  111. addProtectedField( "name", TypeName, Offset(objectName, SimObject), &setProtectedName, &defaultProtectedGetFn,
  112. "Optional global name of this object." );
  113. endGroup( "Ungrouped" );
  114. addGroup( "Object" );
  115. addField( "internalName", TypeString, Offset(mInternalName, SimObject),
  116. "Optional name that may be used to lookup this object within a SimSet.");
  117. addProtectedField( "parentGroup", TYPEID< SimObject >(), Offset(mGroup, SimObject), &setProtectedParent, &defaultProtectedGetFn,
  118. "Group hierarchy parent of the object." );
  119. addProtectedField( "class", TypeString, Offset(mClassName, SimObject), &setClass, &defaultProtectedGetFn,
  120. "Script class of object." );
  121. addProtectedField( "superClass", TypeString, Offset(mSuperClassName, SimObject), &setSuperClass, &defaultProtectedGetFn,
  122. "Script super-class of object." );
  123. // For legacy support
  124. addProtectedField( "className", TypeString, Offset(mClassName, SimObject), &setClass, &defaultProtectedGetFn,
  125. "Script class of object.", AbstractClassRep::FIELD_HideInInspectors );
  126. endGroup( "Object" );
  127. addGroup( "Editing" );
  128. addProtectedField( "hidden", TypeBool, NULL,
  129. &_setHidden, &_getHidden,
  130. "Whether the object is visible." );
  131. addProtectedField( "locked", TypeBool, NULL,
  132. &_setLocked, &_getLocked,
  133. "Whether the object can be edited." );
  134. endGroup( "Editing" );
  135. addGroup( "Persistence" );
  136. addProtectedField( "canSave", TypeBool, Offset( mFlags, SimObject ),
  137. &_setCanSave, &_getCanSave,
  138. "Whether the object can be saved out. If false, the object is purely transient in nature." );
  139. addField( "canSaveDynamicFields", TypeBool, Offset(mCanSaveFieldDictionary, SimObject),
  140. "True if dynamic fields (added at runtime) should be saved. Defaults to true." );
  141. addProtectedField( "persistentId", TypePID, Offset( mPersistentId, SimObject ),
  142. &_setPersistentID, &defaultProtectedGetFn,
  143. "The universally unique identifier for the object." );
  144. endGroup( "Persistence" );
  145. Parent::initPersistFields();
  146. }
  147. //-----------------------------------------------------------------------------
  148. String SimObject::describeSelf() const
  149. {
  150. String desc = Parent::describeSelf();
  151. if( mId != 0 )
  152. desc = avar( "%s|id: %i", desc.c_str(), mId );
  153. if( objectName )
  154. desc = avar( "%s|name: %s", desc.c_str(), objectName );
  155. if( mInternalName )
  156. desc = avar( "%s|internal: %s", desc.c_str(), mInternalName );
  157. if( mNameSpace )
  158. desc = avar( "%s|nspace: %s", desc.c_str(), mNameSpace->mName );
  159. if( mGroup )
  160. desc = avar( "%s|group: %s", desc.c_str(), mGroup->getName() );
  161. if( mCopySource )
  162. desc = avar( "%s|copy: %s", desc.c_str(), mCopySource->getName() );
  163. if( mPersistentId )
  164. desc = avar( "%s|pid: %s", desc.c_str(), mPersistentId->getUUID().toString().c_str() );
  165. return desc;
  166. }
  167. //=============================================================================
  168. // Persistence.
  169. //=============================================================================
  170. // MARK: ---- Persistence ----
  171. //-----------------------------------------------------------------------------
  172. bool SimObject::writeField(StringTableEntry fieldname, const char* value)
  173. {
  174. // Don't write empty fields.
  175. if (!value || !*value)
  176. return false;
  177. // Don't write owner field for components
  178. static StringTableEntry sOwner = StringTable->insert( "owner" );
  179. if( fieldname == sOwner )
  180. return false;
  181. // Don't write ParentGroup
  182. static StringTableEntry sParentGroup = StringTable->insert( "parentGroup" );
  183. if( fieldname == sParentGroup )
  184. return false;
  185. // Don't write name, is within the parenthesis already
  186. static StringTableEntry sName = StringTable->insert( "name" );
  187. if( fieldname == sName )
  188. return false;
  189. // Don't write className, it is read for legacy support but we
  190. // write it out as class.
  191. static StringTableEntry sClassName = StringTable->insert( "className" );
  192. if( fieldname == sClassName )
  193. return false;
  194. // Write persistent ID only if present.
  195. static StringTableEntry sPersistentId = StringTable->insert( "persistentId" );
  196. if( fieldname == sPersistentId && ( !value || !value[ 0 ] ) )
  197. return false;
  198. // Don't write hidden and locked flags if they are at their default value.
  199. static StringTableEntry sHidden = StringTable->insert( "hidden" );
  200. static StringTableEntry sLocked = StringTable->insert( "locked" );
  201. if( fieldname == sHidden && !dAtob( value ) )
  202. return false;
  203. if( fieldname == sLocked && !dAtob( value ) )
  204. return false;
  205. return true;
  206. }
  207. //-----------------------------------------------------------------------------
  208. void SimObject::writeFields(Stream &stream, U32 tabStop)
  209. {
  210. // Write static fields.
  211. const AbstractClassRep::FieldList &list = getFieldList();
  212. for(U32 i = 0; i < list.size(); i++)
  213. {
  214. const AbstractClassRep::Field* f = &list[i];
  215. // Skip the special field types.
  216. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  217. continue;
  218. for(U32 j = 0; S32(j) < f->elementCount; j++)
  219. {
  220. char array[8];
  221. dSprintf( array, 8, "%d", j );
  222. const char *val = getDataField(StringTable->insert( f->pFieldname ), array );
  223. // Make a copy for the field check.
  224. if (!val)
  225. continue;
  226. U32 nBufferSize = dStrlen( val ) + 1;
  227. FrameTemp<char> valCopy( nBufferSize );
  228. dStrcpy( (char *)valCopy, val );
  229. if (!writeField(f->pFieldname, valCopy))
  230. continue;
  231. val = valCopy;
  232. U32 expandedBufferSize = ( nBufferSize * 2 ) + dStrlen(f->pFieldname) + 32;
  233. FrameTemp<char> expandedBuffer( expandedBufferSize );
  234. if(f->elementCount == 1)
  235. dSprintf(expandedBuffer, expandedBufferSize, "%s = \"", f->pFieldname);
  236. else
  237. dSprintf(expandedBuffer, expandedBufferSize, "%s[%d] = \"", f->pFieldname, j);
  238. // detect and collapse relative path information
  239. char fnBuf[1024];
  240. if (f->type == TypeFilename ||
  241. f->type == TypeStringFilename ||
  242. f->type == TypeImageFilename ||
  243. f->type == TypePrefabFilename ||
  244. f->type == TypeShapeFilename)
  245. {
  246. Con::collapseScriptFilename(fnBuf, 1024, val);
  247. val = fnBuf;
  248. }
  249. expandEscape((char*)expandedBuffer + dStrlen(expandedBuffer), val);
  250. dStrcat(expandedBuffer, "\";\r\n");
  251. stream.writeTabs(tabStop);
  252. stream.write(dStrlen(expandedBuffer),expandedBuffer);
  253. }
  254. }
  255. // Write dynamic fields, if enabled.
  256. if(mFieldDictionary && mCanSaveFieldDictionary)
  257. mFieldDictionary->writeFields(this, stream, tabStop);
  258. }
  259. //-----------------------------------------------------------------------------
  260. void SimObject::write(Stream &stream, U32 tabStop, U32 flags)
  261. {
  262. if( !getCanSave() && !( flags & IgnoreCanSave ) )
  263. return;
  264. // Only output selected objects if they want that.
  265. if((flags & SelectedOnly) && !isSelected())
  266. return;
  267. stream.writeTabs(tabStop);
  268. char buffer[1024];
  269. dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() && !(flags & NoName) ? getName() : "");
  270. stream.write(dStrlen(buffer), buffer);
  271. writeFields(stream, tabStop + 1);
  272. stream.writeTabs(tabStop);
  273. stream.write(4, "};\r\n");
  274. }
  275. //-----------------------------------------------------------------------------
  276. bool SimObject::save(const char *pcFileName, bool bOnlySelected, const char *preappend)
  277. {
  278. static const char *beginMessage = "//--- OBJECT WRITE BEGIN ---";
  279. static const char *endMessage = "//--- OBJECT WRITE END ---";
  280. FileStream *stream;
  281. FileObject f;
  282. f.readMemory(pcFileName);
  283. // check for flags <selected, ...>
  284. U32 writeFlags = 0;
  285. if(bOnlySelected)
  286. writeFlags |= SimObject::SelectedOnly;
  287. if((stream = FileStream::createAndOpen( pcFileName, Torque::FS::File::Write )) == NULL)
  288. return false;
  289. char docRoot[256];
  290. char modRoot[256];
  291. dStrcpy(docRoot, pcFileName);
  292. char *p = dStrrchr(docRoot, '/');
  293. if (p) *++p = '\0';
  294. else docRoot[0] = '\0';
  295. dStrcpy(modRoot, pcFileName);
  296. p = dStrchr(modRoot, '/');
  297. if (p) *++p = '\0';
  298. else modRoot[0] = '\0';
  299. Con::setVariable("$DocRoot", docRoot);
  300. Con::setVariable("$ModRoot", modRoot);
  301. const char *buffer;
  302. while(!f.isEOF())
  303. {
  304. buffer = (const char *) f.readLine();
  305. if(!dStrcmp(buffer, beginMessage))
  306. break;
  307. stream->write(dStrlen(buffer), buffer);
  308. stream->write(2, "\r\n");
  309. }
  310. stream->write(dStrlen(beginMessage), beginMessage);
  311. stream->write(2, "\r\n");
  312. if ( preappend != NULL )
  313. stream->write(dStrlen(preappend),preappend);
  314. write(*stream, 0, writeFlags);
  315. stream->write(dStrlen(endMessage), endMessage);
  316. stream->write(2, "\r\n");
  317. while(!f.isEOF())
  318. {
  319. buffer = (const char *) f.readLine();
  320. if(!dStrcmp(buffer, endMessage))
  321. break;
  322. }
  323. while(!f.isEOF())
  324. {
  325. buffer = (const char *) f.readLine();
  326. stream->write(dStrlen(buffer), buffer);
  327. stream->write(2, "\r\n");
  328. }
  329. Con::setVariable("$DocRoot", NULL);
  330. Con::setVariable("$ModRoot", NULL);
  331. delete stream;
  332. return true;
  333. }
  334. //-----------------------------------------------------------------------------
  335. SimPersistID* SimObject::getOrCreatePersistentId()
  336. {
  337. if( !mPersistentId )
  338. {
  339. mPersistentId = SimPersistID::create( this );
  340. mPersistentId->incRefCount();
  341. }
  342. return mPersistentId;
  343. }
  344. //-----------------------------------------------------------------------------
  345. bool SimObject::_setPersistentID( void* object, const char* index, const char* data )
  346. {
  347. SimObject* simObject = reinterpret_cast< SimObject* >( object );
  348. // Make sure we don't already have a PID.
  349. if( simObject->getPersistentId() )
  350. {
  351. Con::errorf( "SimObject::_setPersistentID - cannot set a persistent ID on an object that already has a persistent ID assigned." );
  352. return false;
  353. }
  354. SimPersistID* pid;
  355. Con::setData( TypePID, &pid, 0, 1, &data );
  356. if ( !pid )
  357. return false;
  358. // Make sure it's not already bound to an object.
  359. if( pid->getObject() )
  360. {
  361. AssertWarn( pid->getObject() != simObject, "Sim::_setPersistentID - PID is bound to this object yet not assigned to it!" );
  362. SimObject* otherObj = pid->getObject();
  363. Con::errorf( "SimObject::_setPersistentID - UUID is already used by another object: '%s' -> %i:%s (%s)",
  364. data, otherObj->getId(), otherObj->getClassName(), otherObj->getName() );
  365. return false;
  366. }
  367. pid->resolve( simObject );
  368. pid->incRefCount();
  369. simObject->mPersistentId = pid;
  370. return false;
  371. }
  372. //-----------------------------------------------------------------------------
  373. void SimObject::setFilename( const char* file )
  374. {
  375. if( file )
  376. mFilename = StringTable->insert( file );
  377. else
  378. mFilename = StringTable->EmptyString();
  379. }
  380. //-----------------------------------------------------------------------------
  381. void SimObject::setDeclarationLine(U32 lineNumber)
  382. {
  383. mDeclarationLine = lineNumber;
  384. }
  385. //=============================================================================
  386. // Management.
  387. //=============================================================================
  388. // MARK: ---- Management ----
  389. //-----------------------------------------------------------------------------
  390. bool SimObject::registerObject()
  391. {
  392. AssertFatal( !mFlags.test( Added ), "reigsterObject - Object already registered!");
  393. mFlags.clear(Deleted | Removed);
  394. if(smForceId)
  395. {
  396. setId(smForcedId);
  397. smForceId = false;
  398. }
  399. if( !mId )
  400. {
  401. mId = Sim::gNextObjectId++;
  402. dSprintf( mIdString, sizeof( mIdString ), "%u", mId );
  403. }
  404. AssertFatal(Sim::gIdDictionary && Sim::gNameDictionary,
  405. "SimObject::registerObject - tried to register an object before Sim::init()!");
  406. Sim::gIdDictionary->insert(this);
  407. Sim::gNameDictionary->insert(this);
  408. // Notify object
  409. bool ret = onAdd();
  410. if(!ret)
  411. unregisterObject();
  412. AssertFatal(!ret || isProperlyAdded(), "Object did not call SimObject::onAdd()");
  413. return ret;
  414. }
  415. //-----------------------------------------------------------------------------
  416. void SimObject::unregisterObject()
  417. {
  418. mFlags.set(Removed);
  419. // Notify object first
  420. onRemove();
  421. // Clear out any pending notifications before
  422. // we call our own, just in case they delete
  423. // something that we have referenced.
  424. clearAllNotifications();
  425. // Notify all objects that are waiting for delete
  426. // messages
  427. if (getGroup())
  428. getGroup()->removeObject(this);
  429. processDeleteNotifies();
  430. // Do removals from the Sim.
  431. Sim::gNameDictionary->remove(this);
  432. Sim::gIdDictionary->remove(this);
  433. Sim::cancelPendingEvents(this);
  434. }
  435. //-----------------------------------------------------------------------------
  436. void SimObject::deleteObject()
  437. {
  438. Parent::destroySelf();
  439. }
  440. //-----------------------------------------------------------------------------
  441. void SimObject::_destroySelf()
  442. {
  443. AssertFatal( !isDeleted(), "SimObject::destroySelf - Object has already been deleted" );
  444. AssertFatal( !isRemoved(), "SimObject::destroySelf - Object in the process of being removed" );
  445. mFlags.set( Deleted );
  446. if( mFlags.test( Added ) )
  447. unregisterObject();
  448. Parent::_destroySelf();
  449. }
  450. //-----------------------------------------------------------------------------
  451. void SimObject::destroySelf()
  452. {
  453. // When using the legacy console interop, we don't delete objects
  454. // when their reference count drops to zero but rather defer their
  455. // deletion until deleteObject() is called.
  456. if( engineAPI::gUseConsoleInterop )
  457. return;
  458. Parent::destroySelf();
  459. }
  460. //-----------------------------------------------------------------------------
  461. class SimObjectDeleteEvent : public SimEvent
  462. {
  463. public:
  464. void process(SimObject *object)
  465. {
  466. object->deleteObject();
  467. }
  468. };
  469. void SimObject::safeDeleteObject()
  470. {
  471. Sim::postEvent( this, new SimObjectDeleteEvent, Sim::getCurrentTime() + 1 );
  472. }
  473. //-----------------------------------------------------------------------------
  474. void SimObject::setId(SimObjectId newId)
  475. {
  476. if(!mFlags.test(Added))
  477. mId = newId;
  478. else
  479. {
  480. // get this object out of the id dictionary if it's in it
  481. Sim::gIdDictionary->remove(this);
  482. // Free current Id.
  483. // Assign new one.
  484. mId = newId ? newId : Sim::gNextObjectId++;
  485. Sim::gIdDictionary->insert(this);
  486. }
  487. dSprintf( mIdString, sizeof( mIdString ), "%u", mId );
  488. }
  489. //-----------------------------------------------------------------------------
  490. void SimObject::assignName(const char *name)
  491. {
  492. if( objectName && !isNameChangeAllowed() )
  493. {
  494. Con::errorf( "SimObject::assignName - not allowed to change name of object '%s'", objectName );
  495. return;
  496. }
  497. // Added this assert 3/30/2007 because it is dumb to try to name
  498. // a SimObject the same thing as it's class name -patw
  499. //AssertFatal( dStricmp( getClassName(), name ), "Attempted to assign a name to a SimObject which matches it's type name." );
  500. if( dStricmp( getClassName(), name ) == 0 )
  501. Con::errorf( "SimObject::assignName - Assigning name '%s' to instance of object with type '%s'."
  502. " This can cause namespace linking issues.", getClassName(), name );
  503. StringTableEntry newName = NULL;
  504. if(name[0])
  505. newName = StringTable->insert(name);
  506. onNameChange( newName );
  507. if( mGroup )
  508. mGroup->mNameDictionary.remove( this );
  509. if( isProperlyAdded() )
  510. {
  511. unlinkNamespaces();
  512. Sim::gNameDictionary->remove( this );
  513. }
  514. objectName = newName;
  515. if( mGroup )
  516. mGroup->mNameDictionary.insert( this );
  517. if( isProperlyAdded() )
  518. {
  519. Sim::gNameDictionary->insert( this );
  520. linkNamespaces();
  521. }
  522. }
  523. //-----------------------------------------------------------------------------
  524. bool SimObject::registerObject(U32 id)
  525. {
  526. setId(id);
  527. return registerObject();
  528. }
  529. //-----------------------------------------------------------------------------
  530. bool SimObject::registerObject(const char *name)
  531. {
  532. assignName(name);
  533. return registerObject();
  534. }
  535. //-----------------------------------------------------------------------------
  536. bool SimObject::registerObject(const char *name, U32 id)
  537. {
  538. setId(id);
  539. assignName(name);
  540. return registerObject();
  541. }
  542. //=============================================================================
  543. // Introspection.
  544. //=============================================================================
  545. // MARK: ---- Introspection ----
  546. //-----------------------------------------------------------------------------
  547. bool SimObject::isMethod( const char* methodName )
  548. {
  549. if( !methodName || !methodName[0] )
  550. return false;
  551. StringTableEntry stname = StringTable->insert( methodName );
  552. if( getNamespace() )
  553. return ( getNamespace()->lookup( stname ) != NULL );
  554. return false;
  555. }
  556. //-----------------------------------------------------------------------------
  557. bool SimObject::isField( const char* fieldName, bool includeStatic, bool includeDynamic )
  558. {
  559. const char* strFieldName = StringTable->insert( fieldName );
  560. if( includeStatic && getClassRep()->findField( strFieldName ) )
  561. return true;
  562. if( includeDynamic && getFieldDictionary() && getFieldDictionary()->findDynamicField( strFieldName ) )
  563. return true;
  564. return false;
  565. }
  566. //-----------------------------------------------------------------------------
  567. void SimObject::assignDynamicFieldsFrom(SimObject* parent)
  568. {
  569. if(parent->mFieldDictionary)
  570. {
  571. if( mFieldDictionary == NULL )
  572. mFieldDictionary = new SimFieldDictionary;
  573. mFieldDictionary->assignFrom(parent->mFieldDictionary);
  574. }
  575. }
  576. //-----------------------------------------------------------------------------
  577. void SimObject::assignFieldsFrom(SimObject *parent)
  578. {
  579. // Only allow field assigns from objects of the same class or
  580. // a superclass.
  581. if( getClassRep()->isClass( parent->getClassRep() ) )
  582. {
  583. const AbstractClassRep::FieldList &list = parent->getFieldList();
  584. // copy out all the fields:
  585. for(U32 i = 0; i < list.size(); i++)
  586. {
  587. const AbstractClassRep::Field* f = &list[i];
  588. // Skip the special field types.
  589. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  590. continue;
  591. // Skip certain fields that we don't want to see copied so we don't
  592. // get error messages from their setters.
  593. static StringTableEntry sName = StringTable->insert( "name" );
  594. static StringTableEntry sPersistentId = StringTable->insert( "persistentId" );
  595. if( f->pFieldname == sName || f->pFieldname == sPersistentId )
  596. continue;
  597. S32 lastField = f->elementCount - 1;
  598. for(S32 j = 0; j <= lastField; j++)
  599. {
  600. const char* fieldVal = (*f->getDataFn)( parent, Con::getData(f->type, (void *) (((const char *)parent) + f->offset), j, f->table, f->flag));
  601. // Don't assign the field is the pointer is null or if
  602. // the field is not empty and writing it was disallowed.
  603. if ( !fieldVal || ( fieldVal[0] && !writeField( f->pFieldname, fieldVal ) ) )
  604. continue;
  605. // code copied from SimObject::setDataField().
  606. // TODO: paxorr: abstract this into a better setData / getData that considers prot fields.
  607. FrameTemp<char> buffer(2048);
  608. FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
  609. ConsoleBaseType *cbt = ConsoleBaseType::getType( f->type );
  610. const char* szBuffer = cbt->prepData( fieldVal, buffer, 2048 );
  611. dMemset( bufferSecure, 0, 2048 );
  612. dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
  613. if((*f->setDataFn)( this, NULL, bufferSecure ) )
  614. Con::setData(f->type, (void *) (((const char *)this) + f->offset), j, 1, &fieldVal, f->table);
  615. }
  616. }
  617. }
  618. else
  619. {
  620. Con::errorf( "SimObject::assignFieldsFrom() - cannot assigned fields from object of type '%s' to object of type '%s'",
  621. parent->getClassName(), getClassName()
  622. );
  623. }
  624. assignDynamicFieldsFrom(parent);
  625. }
  626. //-----------------------------------------------------------------------------
  627. void SimObject::setDataField(StringTableEntry slotName, const char *array, const char *value)
  628. {
  629. // first search the static fields if enabled
  630. if(mFlags.test(ModStaticFields))
  631. {
  632. const AbstractClassRep::Field *fld = findField(slotName);
  633. if(fld)
  634. {
  635. // Skip the special field types as they are not data.
  636. if ( fld->type >= AbstractClassRep::ARCFirstCustomField )
  637. return;
  638. S32 array1 = array ? dAtoi(array) : 0;
  639. if(array1 >= 0 && array1 < fld->elementCount && fld->elementCount >= 1)
  640. {
  641. // If the set data notify callback returns true, then go ahead and
  642. // set the data, otherwise, assume the set notify callback has either
  643. // already set the data, or has deemed that the data should not
  644. // be set at all.
  645. FrameTemp<char> buffer(2048);
  646. FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
  647. // so that if the prep functions or any other functions use the string stack, the data
  648. // is not corrupted.
  649. ConsoleBaseType *cbt = ConsoleBaseType::getType( fld->type );
  650. AssertFatal( cbt != NULL, "Could not resolve Type Id." );
  651. const char* szBuffer = cbt->prepData( value, buffer, 2048 );
  652. dMemset( bufferSecure, 0, 2048 );
  653. dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
  654. if( (*fld->setDataFn)( this, array, bufferSecure ) )
  655. Con::setData(fld->type, (void *) (((const char *)this) + fld->offset), array1, 1, &value, fld->table);
  656. if(fld->validator)
  657. fld->validator->validateType(this, (void *) (((const char *)this) + fld->offset));
  658. onStaticModified( slotName, value );
  659. return;
  660. }
  661. if(fld->validator)
  662. fld->validator->validateType(this, (void *) (((const char *)this) + fld->offset));
  663. onStaticModified( slotName, value );
  664. return;
  665. }
  666. }
  667. if(mFlags.test(ModDynamicFields))
  668. {
  669. if(!mFieldDictionary)
  670. mFieldDictionary = new SimFieldDictionary;
  671. if(!array)
  672. {
  673. mFieldDictionary->setFieldValue(slotName, value);
  674. onDynamicModified( slotName, value );
  675. }
  676. else
  677. {
  678. char buf[256];
  679. dStrcpy(buf, slotName);
  680. dStrcat(buf, array);
  681. StringTableEntry permanentSlotName = StringTable->insert(buf);
  682. mFieldDictionary->setFieldValue(permanentSlotName, value);
  683. onDynamicModified( permanentSlotName, value );
  684. }
  685. }
  686. }
  687. //-----------------------------------------------------------------------------
  688. const char *SimObject::getDataField(StringTableEntry slotName, const char *array)
  689. {
  690. if(mFlags.test(ModStaticFields))
  691. {
  692. S32 array1 = array ? dAtoi(array) : -1;
  693. const AbstractClassRep::Field *fld = findField(slotName);
  694. if(fld)
  695. {
  696. if(array1 == -1 && fld->elementCount == 1)
  697. return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), 0, fld->table, fld->flag) );
  698. if(array1 >= 0 && array1 < fld->elementCount)
  699. return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), array1, fld->table, fld->flag) );// + typeSizes[fld.type] * array1));
  700. return "";
  701. }
  702. }
  703. if(mFlags.test(ModDynamicFields))
  704. {
  705. if(!mFieldDictionary)
  706. return "";
  707. if(!array)
  708. {
  709. if (const char* val = mFieldDictionary->getFieldValue(slotName))
  710. return val;
  711. }
  712. else
  713. {
  714. static char buf[256];
  715. dStrcpy(buf, slotName);
  716. dStrcat(buf, array);
  717. if (const char* val = mFieldDictionary->getFieldValue(StringTable->insert(buf)))
  718. return val;
  719. }
  720. }
  721. return "";
  722. }
  723. //-----------------------------------------------------------------------------
  724. U32 SimObject::getDataFieldType( StringTableEntry slotName, const char* array )
  725. {
  726. const AbstractClassRep::Field* field = findField( slotName );
  727. if(field)
  728. return field->type;
  729. // Check dynamic fields
  730. if(!mFieldDictionary)
  731. return 0;
  732. if(array == NULL || *array == 0)
  733. return mFieldDictionary->getFieldType( slotName );
  734. else
  735. {
  736. static char buf[256];
  737. dStrcpy( buf, slotName );
  738. dStrcat( buf, array );
  739. return mFieldDictionary->getFieldType( StringTable->insert( buf ) );
  740. }
  741. }
  742. //-----------------------------------------------------------------------------
  743. void SimObject::setDataFieldType(const U32 fieldTypeId, StringTableEntry slotName, const char *array)
  744. {
  745. // This only works on dynamic fields, bail if we have no field dictionary
  746. if(!mFieldDictionary)
  747. return;
  748. if(array == NULL || *array == 0)
  749. {
  750. mFieldDictionary->setFieldType( slotName, fieldTypeId );
  751. onDynamicModified( slotName, mFieldDictionary->getFieldValue(slotName) );
  752. }
  753. else
  754. {
  755. static char buf[256];
  756. dStrcpy( buf, slotName );
  757. dStrcat( buf, array );
  758. mFieldDictionary->setFieldType( StringTable->insert( buf ), fieldTypeId );
  759. onDynamicModified( slotName, mFieldDictionary->getFieldValue(slotName) );
  760. }
  761. }
  762. //-----------------------------------------------------------------------------
  763. void SimObject::setDataFieldType(const char *typeName, StringTableEntry slotName, const char *array)
  764. {
  765. // This only works on dynamic fields, bail if we have no field dictionary
  766. if(!mFieldDictionary)
  767. return;
  768. if(array == NULL || *array == 0)
  769. mFieldDictionary->setFieldType( slotName, typeName );
  770. else
  771. {
  772. static char buf[256];
  773. dStrcpy( buf, slotName );
  774. dStrcat( buf, array );
  775. StringTableEntry permanentSlotName = StringTable->insert(buf);
  776. mFieldDictionary->setFieldType( permanentSlotName, typeName );
  777. onDynamicModified( permanentSlotName, mFieldDictionary->getFieldValue(permanentSlotName) );
  778. }
  779. }
  780. //-----------------------------------------------------------------------------
  781. void SimObject::dumpClassHierarchy()
  782. {
  783. AbstractClassRep* pRep = getClassRep();
  784. while(pRep)
  785. {
  786. Con::warnf("%s ->", pRep->getClassName());
  787. pRep = pRep->getParentClass();
  788. }
  789. }
  790. //-----------------------------------------------------------------------------
  791. SimObject* SimObject::clone()
  792. {
  793. if( !getClassRep() )
  794. return NULL;
  795. ConsoleObject* conObject = getClassRep()->create();
  796. if( !conObject )
  797. return NULL;
  798. SimObject* simObject = dynamic_cast< SimObject* >( conObject );
  799. if( !simObject )
  800. {
  801. delete conObject;
  802. return NULL;
  803. }
  804. simObject->assignFieldsFrom( this );
  805. String name = Sim::getUniqueName( getName() );
  806. if( !simObject->registerObject( name ) )
  807. {
  808. delete simObject;
  809. return NULL;
  810. }
  811. if( getGroup() )
  812. getGroup()->addObject( simObject );
  813. return simObject;
  814. }
  815. //-----------------------------------------------------------------------------
  816. SimObject* SimObject::deepClone()
  817. {
  818. return clone();
  819. }
  820. //=============================================================================
  821. // Grouping.
  822. //=============================================================================
  823. // MARK: ---- Grouping ----
  824. //-----------------------------------------------------------------------------
  825. SimObject* SimObject::findObject( const char* )
  826. {
  827. return NULL;
  828. }
  829. //-----------------------------------------------------------------------------
  830. bool SimObject::isChildOfGroup(SimGroup* pGroup)
  831. {
  832. if(!pGroup)
  833. return false;
  834. //if we *are* the group in question,
  835. //return true:
  836. if(pGroup == dynamic_cast<SimGroup*>(this))
  837. return true;
  838. SimGroup* temp = mGroup;
  839. while(temp)
  840. {
  841. if(temp == pGroup)
  842. return true;
  843. temp = temp->mGroup;
  844. }
  845. return false;
  846. }
  847. //-----------------------------------------------------------------------------
  848. bool SimObject::addToSet(SimObjectId spid)
  849. {
  850. if (mFlags.test(Added) == false)
  851. return false;
  852. SimObject* ptr = Sim::findObject(spid);
  853. if (ptr)
  854. {
  855. SimSet* sp = dynamic_cast<SimSet*>(ptr);
  856. AssertFatal(sp != 0,
  857. "SimObject::addToSet: "
  858. "ObjectId does not refer to a set object");
  859. sp->addObject(this);
  860. return true;
  861. }
  862. return false;
  863. }
  864. //-----------------------------------------------------------------------------
  865. bool SimObject::addToSet(const char *ObjectName)
  866. {
  867. if (mFlags.test(Added) == false)
  868. return false;
  869. SimObject* ptr = Sim::findObject(ObjectName);
  870. if (ptr)
  871. {
  872. SimSet* sp = dynamic_cast<SimSet*>(ptr);
  873. AssertFatal(sp != 0,
  874. "SimObject::addToSet: "
  875. "ObjectName does not refer to a set object");
  876. sp->addObject(this);
  877. return true;
  878. }
  879. return false;
  880. }
  881. //-----------------------------------------------------------------------------
  882. bool SimObject::removeFromSet(SimObjectId sid)
  883. {
  884. if (mFlags.test(Added) == false)
  885. return false;
  886. SimSet *set;
  887. if(Sim::findObject(sid, set))
  888. {
  889. set->removeObject(this);
  890. return true;
  891. }
  892. return false;
  893. }
  894. //-----------------------------------------------------------------------------
  895. bool SimObject::removeFromSet(const char *objectName)
  896. {
  897. if (mFlags.test(Added) == false)
  898. return false;
  899. SimSet *set;
  900. if(Sim::findObject(objectName, set))
  901. {
  902. set->removeObject(this);
  903. return true;
  904. }
  905. return false;
  906. }
  907. //-----------------------------------------------------------------------------
  908. void SimObject::dumpGroupHierarchy()
  909. {
  910. String className( getClassName() );
  911. String objectName( getName() );
  912. Con::warnf( "[%i] %s - %s ->", getId(), className.c_str(), objectName.c_str() );
  913. if ( mGroup )
  914. mGroup->dumpGroupHierarchy();
  915. }
  916. //=============================================================================
  917. // Events.
  918. //=============================================================================
  919. // MARK: ---- Events ----
  920. //-----------------------------------------------------------------------------
  921. bool SimObject::onAdd()
  922. {
  923. mFlags.set(Added);
  924. linkNamespaces();
  925. return true;
  926. }
  927. //-----------------------------------------------------------------------------
  928. void SimObject::onRemove()
  929. {
  930. mFlags.clear(Added);
  931. unlinkNamespaces();
  932. }
  933. //-----------------------------------------------------------------------------
  934. void SimObject::onGroupAdd()
  935. {
  936. }
  937. //-----------------------------------------------------------------------------
  938. void SimObject::onGroupRemove()
  939. {
  940. }
  941. //-----------------------------------------------------------------------------
  942. void SimObject::onDeleteNotify(SimObject*)
  943. {
  944. }
  945. //-----------------------------------------------------------------------------
  946. void SimObject::onNameChange(const char*)
  947. {
  948. }
  949. //-----------------------------------------------------------------------------
  950. void SimObject::onStaticModified(const char* slotName, const char* newValue)
  951. {
  952. }
  953. //-----------------------------------------------------------------------------
  954. void SimObject::onDynamicModified(const char* slotName, const char* newValue)
  955. {
  956. }
  957. //=============================================================================
  958. // Notifications.
  959. //=============================================================================
  960. // MARK: ---- Notifications ----
  961. static Chunker<SimObject::Notify> notifyChunker(128000);
  962. SimObject::Notify *SimObject::mNotifyFreeList = NULL;
  963. //-----------------------------------------------------------------------------
  964. SimObject::Notify *SimObject::allocNotify()
  965. {
  966. if(mNotifyFreeList)
  967. {
  968. SimObject::Notify *ret = mNotifyFreeList;
  969. mNotifyFreeList = ret->next;
  970. return ret;
  971. }
  972. return notifyChunker.alloc();
  973. }
  974. //-----------------------------------------------------------------------------
  975. void SimObject::freeNotify(SimObject::Notify* note)
  976. {
  977. AssertFatal(note->type != SimObject::Notify::Invalid, "Invalid notify");
  978. note->type = SimObject::Notify::Invalid;
  979. note->next = mNotifyFreeList;
  980. mNotifyFreeList = note;
  981. }
  982. //-----------------------------------------------------------------------------
  983. SimObject::Notify* SimObject::removeNotify(void *ptr, SimObject::Notify::Type type)
  984. {
  985. Notify **list = &mNotifyList;
  986. while(*list)
  987. {
  988. if((*list)->ptr == ptr && (*list)->type == type)
  989. {
  990. SimObject::Notify *ret = *list;
  991. *list = ret->next;
  992. return ret;
  993. }
  994. list = &((*list)->next);
  995. }
  996. return NULL;
  997. }
  998. //-----------------------------------------------------------------------------
  999. void SimObject::deleteNotify(SimObject* obj)
  1000. {
  1001. AssertFatal(!obj->isDeleted(),
  1002. "SimManager::deleteNotify: Object is being deleted");
  1003. Notify *note = allocNotify();
  1004. note->ptr = (void *) this;
  1005. note->next = obj->mNotifyList;
  1006. note->type = Notify::DeleteNotify;
  1007. obj->mNotifyList = note;
  1008. note = allocNotify();
  1009. note->ptr = (void *) obj;
  1010. note->next = mNotifyList;
  1011. note->type = Notify::ClearNotify;
  1012. mNotifyList = note;
  1013. //obj->deleteNotifyList.pushBack(this);
  1014. //clearNotifyList.pushBack(obj);
  1015. }
  1016. //-----------------------------------------------------------------------------
  1017. void SimObject::registerReference(SimObject **ptr)
  1018. {
  1019. Notify *note = allocNotify();
  1020. note->ptr = (void *) ptr;
  1021. note->next = mNotifyList;
  1022. note->type = Notify::ObjectRef;
  1023. mNotifyList = note;
  1024. }
  1025. //-----------------------------------------------------------------------------
  1026. void SimObject::unregisterReference(SimObject **ptr)
  1027. {
  1028. Notify *note = removeNotify((void *) ptr, Notify::ObjectRef);
  1029. if(note)
  1030. {
  1031. freeNotify(note);
  1032. if( mFlags.test( AutoDelete ) )
  1033. {
  1034. for( Notify* n = mNotifyList; n != NULL; n = n->next )
  1035. if( n->type == Notify::ObjectRef )
  1036. return;
  1037. deleteObject();
  1038. }
  1039. }
  1040. }
  1041. //-----------------------------------------------------------------------------
  1042. void SimObject::clearNotify(SimObject* obj)
  1043. {
  1044. Notify *note = obj->removeNotify((void *) this, Notify::DeleteNotify);
  1045. if(note)
  1046. freeNotify(note);
  1047. note = removeNotify((void *) obj, Notify::ClearNotify);
  1048. if(note)
  1049. freeNotify(note);
  1050. }
  1051. //-----------------------------------------------------------------------------
  1052. void SimObject::processDeleteNotifies()
  1053. {
  1054. // clear out any delete notifies and
  1055. // object refs.
  1056. while(mNotifyList)
  1057. {
  1058. Notify *note = mNotifyList;
  1059. mNotifyList = note->next;
  1060. AssertFatal(note->type != Notify::ClearNotify, "Clear notes should be all gone.");
  1061. if(note->type == Notify::DeleteNotify)
  1062. {
  1063. SimObject *obj = (SimObject *) note->ptr;
  1064. Notify *cnote = obj->removeNotify((void *)this, Notify::ClearNotify);
  1065. obj->onDeleteNotify(this);
  1066. freeNotify(cnote);
  1067. }
  1068. else
  1069. {
  1070. // it must be an object ref - a pointer refs this object
  1071. *((SimObject **) note->ptr) = NULL;
  1072. }
  1073. freeNotify(note);
  1074. }
  1075. }
  1076. //-----------------------------------------------------------------------------
  1077. void SimObject::clearAllNotifications()
  1078. {
  1079. for(Notify **cnote = &mNotifyList; *cnote; )
  1080. {
  1081. Notify *temp = *cnote;
  1082. if(temp->type == Notify::ClearNotify)
  1083. {
  1084. *cnote = temp->next;
  1085. Notify *note = ((SimObject *) temp->ptr)->removeNotify((void *) this, Notify::DeleteNotify);
  1086. freeNotify(temp);
  1087. if ( note )
  1088. freeNotify(note);
  1089. }
  1090. else
  1091. cnote = &(temp->next);
  1092. }
  1093. }
  1094. //=============================================================================
  1095. // Namespaces.
  1096. //=============================================================================
  1097. // MARK: ---- Namespaces ----
  1098. //-----------------------------------------------------------------------------
  1099. void SimObject::linkNamespaces()
  1100. {
  1101. // Don't link if we already have a namespace linkage in place.
  1102. // If you want to change namespace linking, first call unlinkNamespaces()
  1103. // while still having the class namespace fields matching the current
  1104. // setup.
  1105. if (mNameSpace)
  1106. {
  1107. Con::warnf("SimObject::linkNamespaces -- Namespace linkage already in place %s", mNameSpace->getName());
  1108. return;
  1109. }
  1110. // Get the namespace for the C++ class.
  1111. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1112. // Parent namespace defaults to namespace of C++ class.
  1113. Namespace* parentNamespace = cppNamespace;
  1114. // Perform superclass linking, if requested.
  1115. if( mSuperClassName && mSuperClassName[ 0 ] )
  1116. {
  1117. // Look up the superclass namespace.
  1118. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1119. // If packages are active and adding to the superclass namespace, then we will
  1120. // have multiple packages in a parent chain that all have the same name.
  1121. // Con::lookupNamespace returns the bottom-most package in the chain to us so
  1122. // in order to properly link namespace here without conflicting with the package
  1123. // mechanism, we need to properly link child namespaces to the bottom-most namespace
  1124. // while linking parent namespaces to the topmost namespace. To find the latter
  1125. // one, we walk up the hierarchy here.
  1126. Namespace* superClassNamespacePackageRoot = superClassNamespace->getPackageRoot();
  1127. // Link the superclass namespace to the C++ class namespace.
  1128. if( superClassNamespacePackageRoot->getParent() == NULL )
  1129. {
  1130. // The superclass namespace isn't linked yet so we just
  1131. // link it to the C++ class namespace and make that our parent.
  1132. // No increasing parent reference counts is needed in this case.
  1133. bool ok = superClassNamespacePackageRoot->classLinkTo( cppNamespace );
  1134. AssertFatal( ok, "SimObject::linkNamespaces - failed to link new namespace to c++ class name" );
  1135. parentNamespace = superClassNamespace;
  1136. }
  1137. else
  1138. {
  1139. // In debug builds, make sure the namespace hierarchy that's been
  1140. // put into place actually makes sense and leads back to the C++
  1141. // class namespace.
  1142. #ifdef TORQUE_DEBUG
  1143. bool foundClassNameNS = false;
  1144. for( Namespace* linkWalk = superClassNamespacePackageRoot->getParent(); linkWalk != NULL;
  1145. linkWalk = linkWalk->getParent() )
  1146. {
  1147. if( linkWalk == cppNamespace )
  1148. {
  1149. foundClassNameNS = true;
  1150. break;
  1151. }
  1152. }
  1153. if( !foundClassNameNS )
  1154. {
  1155. // C++ class namespace not in parent link chain. Warn about it.
  1156. Con::errorf(
  1157. "SimObject::linkNamespaces - cannot link object to superclass %s because c++ class %s is not in the parent namespace chain. Linking object to c++ class.",
  1158. mSuperClassName,
  1159. getClassName()
  1160. );
  1161. // Clear out superclass name so we don't come across it during
  1162. // unlinking.
  1163. mSuperClassName = NULL;
  1164. }
  1165. else
  1166. #endif
  1167. {
  1168. // Super link is ok.
  1169. parentNamespace = superClassNamespace;
  1170. // Now increase the reference count of all namespaces in the parent hierarchy
  1171. // (up to the C++ class).
  1172. for( Namespace* linkWalk = parentNamespace;
  1173. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL;
  1174. linkWalk = linkWalk->getParent() )
  1175. {
  1176. // Skip namespaces coming from packages.
  1177. if( linkWalk->getPackage() != NULL )
  1178. continue;
  1179. linkWalk->incRefCountToParent();
  1180. }
  1181. }
  1182. }
  1183. }
  1184. // If class name is set, link it in as the new parent
  1185. // which itself inherits from the current parent.
  1186. if( mClassName && mClassName[ 0 ] )
  1187. {
  1188. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1189. if( classNamespace && classNamespace->classLinkTo( parentNamespace ) )
  1190. {
  1191. parentNamespace = classNamespace;
  1192. }
  1193. else
  1194. {
  1195. // Clear out class name so we don't perform a bogus unlink
  1196. // in unlinkNamespaces().
  1197. mClassName = NULL;
  1198. }
  1199. }
  1200. // Finally, if we have an object name, link its namespace
  1201. // as the child to the current parent namespace and let it
  1202. // become the final namespace of this object.
  1203. StringTableEntry objectName = getName();
  1204. if( objectName && objectName[ 0 ] )
  1205. {
  1206. Namespace* objectNamespace = Con::lookupNamespace( objectName );
  1207. if( objectNamespace && objectNamespace->classLinkTo( parentNamespace ) )
  1208. {
  1209. parentNamespace = objectNamespace;
  1210. }
  1211. }
  1212. // Store our namespace.
  1213. mNameSpace = parentNamespace;
  1214. }
  1215. //-----------------------------------------------------------------------------
  1216. void SimObject::unlinkNamespaces()
  1217. {
  1218. if( !mNameSpace )
  1219. return;
  1220. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1221. Namespace* parentNamespace = cppNamespace;
  1222. // Handle superclass.
  1223. if( mSuperClassName && mSuperClassName[ 0 ] )
  1224. {
  1225. // Get the superclass namespace.
  1226. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1227. // Make it the parent namespace.
  1228. parentNamespace = superClassNamespace;
  1229. // Decrease parent refcounts on the superclass hierarchy.
  1230. for( Namespace* linkWalk = superClassNamespace;
  1231. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL; )
  1232. {
  1233. // Store the parent link since it may disappear once we
  1234. // decrease the reference count.
  1235. Namespace* parent = linkWalk->getParent();
  1236. // Decrease the refcount.
  1237. if( linkWalk->getPackage() == NULL ) // Skip namespaces coming from packages.
  1238. linkWalk->decRefCountToParent();
  1239. // Walk up.
  1240. linkWalk = parent;
  1241. }
  1242. }
  1243. // Handle class.
  1244. if( mClassName && mClassName[ 0 ] )
  1245. {
  1246. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1247. if( classNamespace )
  1248. {
  1249. classNamespace->decRefCountToParent();
  1250. parentNamespace = classNamespace;
  1251. }
  1252. }
  1253. // Handle object name.
  1254. StringTableEntry objectName = getName();
  1255. if( objectName && objectName[ 0 ] )
  1256. mNameSpace->decRefCountToParent();
  1257. mNameSpace = NULL;
  1258. }
  1259. //-----------------------------------------------------------------------------
  1260. void SimObject::setClassNamespace( const char *classNamespace )
  1261. {
  1262. StringTableEntry oldClassNamespace = mClassName;
  1263. StringTableEntry newClassNamespace = StringTable->insert( classNamespace );
  1264. if( oldClassNamespace == newClassNamespace )
  1265. return;
  1266. if( isProperlyAdded() )
  1267. unlinkNamespaces();
  1268. mClassName = newClassNamespace;
  1269. if( isProperlyAdded() )
  1270. {
  1271. linkNamespaces();
  1272. // Restore old namespace setup if linkage failed.
  1273. if( mClassName != newClassNamespace )
  1274. {
  1275. mClassName = oldClassNamespace;
  1276. linkNamespaces();
  1277. }
  1278. }
  1279. }
  1280. //-----------------------------------------------------------------------------
  1281. void SimObject::setSuperClassNamespace( const char *superClassNamespace )
  1282. {
  1283. StringTableEntry oldSuperClassNamespace = mSuperClassName;
  1284. StringTableEntry newSuperClassNamespace = StringTable->insert( superClassNamespace );
  1285. if( oldSuperClassNamespace == newSuperClassNamespace )
  1286. return;
  1287. if( isProperlyAdded() )
  1288. unlinkNamespaces();
  1289. mSuperClassName = newSuperClassNamespace;
  1290. if( isProperlyAdded() )
  1291. {
  1292. linkNamespaces();
  1293. // Restore old setup if linkage failed.
  1294. if( mSuperClassName != newSuperClassNamespace )
  1295. {
  1296. mSuperClassName = oldSuperClassNamespace;
  1297. linkNamespaces();
  1298. }
  1299. }
  1300. }
  1301. //=============================================================================
  1302. // Misc.
  1303. //=============================================================================
  1304. // MARK: ---- Misc ----
  1305. //-----------------------------------------------------------------------------
  1306. void SimObject::setInternalName( const char* newname )
  1307. {
  1308. if( newname )
  1309. mInternalName = StringTable->insert( newname );
  1310. else
  1311. mInternalName = StringTable->EmptyString();
  1312. }
  1313. //-----------------------------------------------------------------------------
  1314. void SimObject::setOriginalName( const char* originalName )
  1315. {
  1316. if( originalName )
  1317. mOriginalName = StringTable->insert( originalName );
  1318. else
  1319. mOriginalName = StringTable->EmptyString();
  1320. }
  1321. //-----------------------------------------------------------------------------
  1322. const char *SimObject::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  1323. {
  1324. return mNameSpace->tabComplete(prevText, baseLen, fForward);
  1325. }
  1326. //-----------------------------------------------------------------------------
  1327. void SimObject::setSelected( bool sel )
  1328. {
  1329. if( mFlags.test( Selected ) == sel )
  1330. return; // No change.
  1331. if( sel )
  1332. {
  1333. mFlags.set( Selected );
  1334. _onSelected();
  1335. }
  1336. else
  1337. {
  1338. mFlags.clear( Selected );
  1339. _onUnselected();
  1340. }
  1341. }
  1342. //-----------------------------------------------------------------------------
  1343. bool SimObject::isSelectedRecursive() const
  1344. {
  1345. const SimObject *walk = this;
  1346. while ( walk )
  1347. {
  1348. if ( walk->isSelected() )
  1349. return true;
  1350. walk = walk->getGroup();
  1351. }
  1352. return false;
  1353. }
  1354. //-----------------------------------------------------------------------------
  1355. void SimObject::setLocked( bool b )
  1356. {
  1357. if( b )
  1358. mFlags.set( Locked );
  1359. else
  1360. mFlags.clear( Locked );
  1361. }
  1362. //-----------------------------------------------------------------------------
  1363. void SimObject::setHidden( bool b )
  1364. {
  1365. if( b )
  1366. mFlags.set( Hidden );
  1367. else
  1368. mFlags.clear( Hidden );
  1369. }
  1370. //-----------------------------------------------------------------------------
  1371. void SimObject::setCopySource( SimObject* object )
  1372. {
  1373. if( mCopySource )
  1374. mCopySource->unregisterReference( &mCopySource );
  1375. mCopySource = object;
  1376. if( mCopySource )
  1377. mCopySource->registerReference( &mCopySource );
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. bool SimObject::_setCanSave( void* object, const char* index, const char* data )
  1381. {
  1382. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1383. obj->setCanSave( dAtob( data ) );
  1384. return false;
  1385. }
  1386. //-----------------------------------------------------------------------------
  1387. const char* SimObject::_getCanSave( void* object, const char* data )
  1388. {
  1389. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1390. if( obj->getCanSave() )
  1391. return "1";
  1392. else
  1393. return "0";
  1394. }
  1395. //---------------------------------------------------------------------------
  1396. // Copy SimObject to another SimObject (Originally designed for T2D).
  1397. void SimObject::copyTo( SimObject* object )
  1398. {
  1399. object->mClassName = mClassName;
  1400. object->mSuperClassName = mSuperClassName;
  1401. linkNamespaces();
  1402. }
  1403. //-----------------------------------------------------------------------------
  1404. bool SimObject::setProtectedParent( void *obj, const char *index, const char *data )
  1405. {
  1406. SimGroup *parent = NULL;
  1407. SimObject *object = static_cast<SimObject*>(obj);
  1408. if(Sim::findObject(data, parent))
  1409. parent->addObject(object);
  1410. // always return false, because we've set mGroup when we called addObject
  1411. return false;
  1412. }
  1413. //-----------------------------------------------------------------------------
  1414. bool SimObject::setProtectedName(void *obj, const char *index, const char *data)
  1415. {
  1416. SimObject *object = static_cast<SimObject*>(obj);
  1417. if ( object->isProperlyAdded() )
  1418. object->assignName( data );
  1419. // always return false because we assign the name here
  1420. return false;
  1421. }
  1422. //-----------------------------------------------------------------------------
  1423. void SimObject::inspectPreApply()
  1424. {
  1425. }
  1426. //-----------------------------------------------------------------------------
  1427. void SimObject::inspectPostApply()
  1428. {
  1429. }
  1430. //-----------------------------------------------------------------------------
  1431. String SimObject::_getLogMessage(const char* fmt, va_list args) const
  1432. {
  1433. String objClass = "UnknownClass";
  1434. if(getClassRep())
  1435. objClass = getClassRep()->getClassName();
  1436. String objName = getName();
  1437. if(objName.isEmpty())
  1438. objName = "Unnamed";
  1439. String formattedMessage = String::VToString(fmt, args);
  1440. return String::ToString("%s - %s(%i) - %s",
  1441. objClass.c_str(), objName.c_str(), getId(), formattedMessage.c_str());
  1442. }
  1443. //=============================================================================
  1444. // API.
  1445. //=============================================================================
  1446. // MARK: ---- API ----
  1447. //-----------------------------------------------------------------------------
  1448. DefineEngineMethod( SimObject, dumpGroupHierarchy, void, (),,
  1449. "Dump the hierarchy of this object up to RootGroup to the console." )
  1450. {
  1451. object->dumpGroupHierarchy();
  1452. }
  1453. //-----------------------------------------------------------------------------
  1454. DefineConsoleMethod( SimObject, isMethod, bool, ( const char* methodName ),,
  1455. "Test whether the given method is defined on this object.\n"
  1456. "@param The name of the method.\n"
  1457. "@return True if the object implements the given method." )
  1458. {
  1459. return object->isMethod( methodName );
  1460. }
  1461. //-----------------------------------------------------------------------------
  1462. DefineEngineMethod( SimObject, isChildOfGroup, bool, ( SimGroup* group ),,
  1463. "Test whether the object belongs directly or indirectly to the given group.\n"
  1464. "@param group The SimGroup object.\n"
  1465. "@return True if the object is a child of the given group or a child of a group that the given group is directly or indirectly a child to." )
  1466. {
  1467. return object->isChildOfGroup( group );
  1468. }
  1469. //-----------------------------------------------------------------------------
  1470. DefineConsoleMethod( SimObject, getClassNamespace, const char*, (),,
  1471. "Get the name of the class namespace assigned to this object.\n"
  1472. "@return The name of the 'class' namespace." )
  1473. {
  1474. return object->getClassNamespace();
  1475. }
  1476. //-----------------------------------------------------------------------------
  1477. DefineConsoleMethod( SimObject, getSuperClassNamespace, const char*, (),,
  1478. "Get the name of the superclass namespace assigned to this object.\n"
  1479. "@return The name of the 'superClass' namespace." )
  1480. {
  1481. return object->getSuperClassNamespace();
  1482. }
  1483. //-----------------------------------------------------------------------------
  1484. DefineConsoleMethod( SimObject, setClassNamespace, void, ( const char* name ),,
  1485. "Assign a class namespace to this object.\n"
  1486. "@param name The name of the 'class' namespace for this object." )
  1487. {
  1488. object->setClassNamespace( name );
  1489. }
  1490. //-----------------------------------------------------------------------------
  1491. DefineConsoleMethod( SimObject, setSuperClassNamespace, void, ( const char* name ),,
  1492. "Assign a superclass namespace to this object.\n"
  1493. "@param name The name of the 'superClass' namespace for this object." )
  1494. {
  1495. object->setSuperClassNamespace( name );
  1496. }
  1497. //-----------------------------------------------------------------------------
  1498. DefineEngineMethod( SimObject, isSelected, bool, (),,
  1499. "Get whether the object has been marked as selected. (in editor)\n"
  1500. "@return True if the object is currently selected." )
  1501. {
  1502. return object->isSelected();
  1503. }
  1504. //-----------------------------------------------------------------------------
  1505. DefineEngineMethod( SimObject, setIsSelected, void, ( bool state ), ( true ),
  1506. "Set whether the object has been marked as selected. (in editor)\n"
  1507. "@param state True if object is to be marked selected; false if not." )
  1508. {
  1509. object->setSelected( state );
  1510. }
  1511. //-----------------------------------------------------------------------------
  1512. DefineConsoleMethod( SimObject, isExpanded, bool, (),,
  1513. "Get whether the object has been marked as expanded. (in editor)\n"
  1514. "@return True if the object is marked expanded." )
  1515. {
  1516. return object->isExpanded();
  1517. }
  1518. //-----------------------------------------------------------------------------
  1519. DefineConsoleMethod( SimObject, setIsExpanded, void, ( bool state ), ( true ),
  1520. "Set whether the object has been marked as expanded. (in editor)\n"
  1521. "@param state True if the object is to be marked expanded; false if not." )
  1522. {
  1523. object->setExpanded( state );
  1524. }
  1525. //-----------------------------------------------------------------------------
  1526. DefineConsoleMethod( SimObject, getFilename, const char*, (),,
  1527. "Returns the filename the object is attached to.\n"
  1528. "@return The name of the file the object is associated with; usually the file the object was loaded from." )
  1529. {
  1530. return object->getFilename();
  1531. }
  1532. //-----------------------------------------------------------------------------
  1533. DefineConsoleMethod( SimObject, setFilename, void, ( const char* fileName ),,
  1534. "Sets the object's file name and path\n"
  1535. "@param fileName The name of the file to associate this object with." )
  1536. {
  1537. return object->setFilename( fileName );
  1538. }
  1539. //-----------------------------------------------------------------------------
  1540. DefineConsoleMethod( SimObject, getDeclarationLine, S32, (),,
  1541. "Get the line number at which the object is defined in its file.\n\n"
  1542. "@return The line number of the object's definition in script.\n"
  1543. "@see getFilename()")
  1544. {
  1545. return object->getDeclarationLine();
  1546. }
  1547. //-----------------------------------------------------------------------------
  1548. #ifdef TORQUE_DEBUG
  1549. static const char* sEnumCallbackFunction;
  1550. static void sEnumCallback( EngineObject* object )
  1551. {
  1552. SimObject* simObject = dynamic_cast< SimObject* >( object );
  1553. if( !simObject )
  1554. return;
  1555. Con::evaluatef( "%s( %i );", sEnumCallbackFunction, simObject->getId() );
  1556. }
  1557. DefineEngineFunction( debugEnumInstances, void, ( const char* className, const char* functionName ),,
  1558. "Call the given function for each instance of the given class.\n"
  1559. "@param className Name of the class for which to enumerate instances.\n"
  1560. "@param functionName Name of function to call and pass each instance of the given class.\n"
  1561. "@note This function is only available in debug builds and primarily meant as an aid in debugging."
  1562. "@ingroup Console")
  1563. {
  1564. sEnumCallbackFunction = functionName;
  1565. ConsoleObject::debugEnumInstances( className, sEnumCallback );
  1566. }
  1567. #endif
  1568. //-----------------------------------------------------------------------------
  1569. DefineConsoleMethod( SimObject, assignFieldsFrom, void, ( SimObject* fromObject ),,
  1570. "Copy fields from another object onto this one. The objects must "
  1571. "be of same type. Everything from the object will overwrite what's "
  1572. "in this object; extra fields in this object will remain. This "
  1573. "includes dynamic fields.\n"
  1574. "@param fromObject The object from which to copy fields." )
  1575. {
  1576. if( fromObject )
  1577. object->assignFieldsFrom( fromObject );
  1578. }
  1579. //-----------------------------------------------------------------------------
  1580. DefineEngineMethod( SimObject, assignPersistentId, void, (),,
  1581. "Assign a persistent ID to the object if it does not already have one." )
  1582. {
  1583. object->getOrCreatePersistentId();
  1584. }
  1585. //-----------------------------------------------------------------------------
  1586. DefineConsoleMethod( SimObject, getCanSave, bool, (),,
  1587. "Get whether the object will be included in saves.\n"
  1588. "@return True if the object will be saved; false otherwise." )
  1589. {
  1590. return object->getCanSave();
  1591. }
  1592. //-----------------------------------------------------------------------------
  1593. DefineConsoleMethod( SimObject, setCanSave, void, ( bool value ), ( true ),
  1594. "Set whether the object will be included in saves.\n"
  1595. "@param value If true, the object will be included in saves; if false, it will be excluded." )
  1596. {
  1597. object->setCanSave( value );
  1598. }
  1599. //-----------------------------------------------------------------------------
  1600. DefineEngineMethod( SimObject, isEditorOnly, bool, (),,
  1601. "Return true if the object is only used by the editor.\n"
  1602. "@return True if this object exists only for the sake of editing." )
  1603. {
  1604. return object->isEditorOnly();
  1605. }
  1606. //-----------------------------------------------------------------------------
  1607. DefineEngineMethod( SimObject, setEditorOnly, void, ( bool value ), ( true ),
  1608. "Set/clear the editor-only flag on this object.\n"
  1609. "@param value If true, the object is marked as existing only for the editor." )
  1610. {
  1611. object->setEditorOnly( value );
  1612. }
  1613. //-----------------------------------------------------------------------------
  1614. DefineEngineMethod( SimObject, isNameChangeAllowed, bool, (),,
  1615. "Get whether this object may be renamed.\n"
  1616. "@return True if this object can be renamed; false otherwise." )
  1617. {
  1618. return object->isNameChangeAllowed();
  1619. }
  1620. //-----------------------------------------------------------------------------
  1621. DefineEngineMethod( SimObject, setNameChangeAllowed, void, ( bool value ), ( true ),
  1622. "Set whether this object can be renamed from its first name.\n"
  1623. "@param value If true, renaming is allowed for this object; if false, trying to change the name of the object will generate a console error." )
  1624. {
  1625. object->setNameChangeAllowed( value );
  1626. }
  1627. //-----------------------------------------------------------------------------
  1628. DefineEngineMethod( SimObject, clone, SimObject*, (),,
  1629. "Create a copy of this object.\n"
  1630. "@return An exact duplicate of this object." )
  1631. {
  1632. return object->clone();
  1633. }
  1634. //-----------------------------------------------------------------------------
  1635. DefineEngineMethod( SimObject, deepClone, SimObject*, (),,
  1636. "Create a copy of this object and all its subobjects.\n"
  1637. "@return An exact duplicate of this object and all objects it references." )
  1638. {
  1639. return object->deepClone();
  1640. }
  1641. //-----------------------------------------------------------------------------
  1642. DefineEngineMethod( SimObject, setLocked, void, ( bool value ), ( true ),
  1643. "Lock/unlock the object in the editor.\n"
  1644. "@param value If true, the object will be locked; if false, the object will be unlocked." )
  1645. {
  1646. object->setLocked( value );
  1647. }
  1648. //-----------------------------------------------------------------------------
  1649. DefineEngineMethod( SimObject, setHidden, void, ( bool value ), ( true ),
  1650. "Hide/unhide the object.\n"
  1651. "@param value If true, the object will be hidden; if false, the object will be unhidden." )
  1652. {
  1653. object->setHidden( value );
  1654. }
  1655. //-----------------------------------------------------------------------------
  1656. DefineConsoleMethod( SimObject, dumpMethods, ArrayObject*, (),,
  1657. "List the methods defined on this object.\n\n"
  1658. "Each description is a newline-separated vector with the following elements:\n"
  1659. "- Minimum number of arguments.\n"
  1660. "- Maximum number of arguments.\n"
  1661. "- Prototype string.\n"
  1662. "- Full script file path (if script method).\n"
  1663. "- Line number of method definition in script (if script method).\n\n"
  1664. "- Documentation string (not including prototype). This takes up the remainder of the vector.\n"
  1665. "@return An ArrayObject populated with (name,description) pairs of all methods defined on the object." )
  1666. {
  1667. Namespace *ns = object->getNamespace();
  1668. if( !ns )
  1669. return 0;
  1670. ArrayObject* dictionary = new ArrayObject();
  1671. dictionary->registerObject();
  1672. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  1673. ns->getEntryList(&vec);
  1674. for(Vector< Namespace::Entry* >::iterator j = vec.begin(); j != vec.end(); j++)
  1675. {
  1676. Namespace::Entry* e = *j;
  1677. if( e->mType < 0 )
  1678. continue;
  1679. StringBuilder str;
  1680. str.append( String::ToString( e->mMinArgs ) );
  1681. str.append( '\n' );
  1682. str.append( String::ToString( e->mMaxArgs ) );
  1683. str.append( '\n' );
  1684. str.append( e->getPrototypeString() );
  1685. str.append( '\n' );
  1686. if( e->mCode && e->mCode->fullPath )
  1687. str.append( e->mCode->fullPath );
  1688. str.append( '\n' );
  1689. if( e->mCode )
  1690. str.append( String::ToString( e->mFunctionLineNumber ) );
  1691. str.append( '\n' );
  1692. String docs = e->getDocString();
  1693. if( !docs.isEmpty() )
  1694. str.append( docs );
  1695. dictionary->push_back( e->mFunctionName, str.end() );
  1696. }
  1697. return dictionary;
  1698. }
  1699. //-----------------------------------------------------------------------------
  1700. namespace {
  1701. S32 QSORT_CALLBACK compareFields( const void* a,const void* b )
  1702. {
  1703. const AbstractClassRep::Field* fa = *((const AbstractClassRep::Field**)a);
  1704. const AbstractClassRep::Field* fb = *((const AbstractClassRep::Field**)b);
  1705. return dStricmp(fa->pFieldname, fb->pFieldname);
  1706. }
  1707. struct DocString
  1708. {
  1709. char mPadding[ 8 ];
  1710. String mPrototype;
  1711. String mDescription;
  1712. const char* mReturnType;
  1713. DocString( Namespace::Entry* entry )
  1714. : mPrototype( entry->getArgumentsString() ),
  1715. mDescription( entry->getBriefDescription() )
  1716. {
  1717. mReturnType = " ";
  1718. mPadding[ 0 ] = 0;
  1719. if( entry->mType == -4 )
  1720. {
  1721. //TODO: need to have script callbacks set up proper return type info
  1722. }
  1723. else
  1724. {
  1725. switch( entry->mType )
  1726. {
  1727. case Namespace::Entry::StringCallbackType:
  1728. mReturnType = "string";
  1729. mPadding[ 0 ] = ' ';
  1730. mPadding[ 1 ] = ' ';
  1731. mPadding[ 2 ] = 0;
  1732. break;
  1733. case Namespace::Entry::IntCallbackType:
  1734. mReturnType = "int";
  1735. mPadding[ 0 ] = ' ';
  1736. mPadding[ 1 ] = ' ';
  1737. mPadding[ 2 ] = ' ';
  1738. mPadding[ 3 ] = ' ';
  1739. mPadding[ 4 ] = ' ';
  1740. mPadding[ 5 ] = 0;
  1741. break;
  1742. case Namespace::Entry::FloatCallbackType:
  1743. mReturnType = "float";
  1744. mPadding[ 0 ] = ' ';
  1745. mPadding[ 1 ] = ' ';
  1746. mPadding[ 2 ] = ' ';
  1747. mPadding[ 3 ] = 0;
  1748. break;
  1749. case Namespace::Entry::VoidCallbackType:
  1750. mReturnType = "void";
  1751. mPadding[ 0 ] = ' ';
  1752. mPadding[ 1 ] = ' ';
  1753. mPadding[ 2 ] = ' ';
  1754. mPadding[ 3 ] = ' ';
  1755. mPadding[ 4 ] = 0;
  1756. break;
  1757. case Namespace::Entry::BoolCallbackType:
  1758. mReturnType = "bool";
  1759. mPadding[ 0 ] = ' ';
  1760. mPadding[ 1 ] = ' ';
  1761. mPadding[ 2 ] = ' ';
  1762. mPadding[ 3 ] = ' ';
  1763. mPadding[ 4 ] = 0;
  1764. break;
  1765. }
  1766. }
  1767. }
  1768. };
  1769. }
  1770. DefineEngineMethod( SimObject, dump, void, ( bool detailed ), ( false ),
  1771. "Dump a description of all fields and methods defined on this object to the console.\n"
  1772. "@param detailed Whether to print detailed information about members." )
  1773. {
  1774. Con::printf( "Class: %s", object->getClassName() );
  1775. const AbstractClassRep::FieldList &list = object->getFieldList();
  1776. char expandedBuffer[4096];
  1777. Con::printf( "Static Fields:" );
  1778. Vector<const AbstractClassRep::Field *> flist(__FILE__, __LINE__);
  1779. for(U32 i = 0; i < list.size(); i++)
  1780. flist.push_back(&list[i]);
  1781. dQsort(flist.address(),flist.size(),sizeof(AbstractClassRep::Field *),compareFields);
  1782. for(Vector<const AbstractClassRep::Field *>::iterator itr = flist.begin(); itr != flist.end(); itr++)
  1783. {
  1784. const AbstractClassRep::Field* f = *itr;
  1785. // The special field types can be skipped.
  1786. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  1787. continue;
  1788. for(U32 j = 0; S32(j) < f->elementCount; j++)
  1789. {
  1790. // [neo, 07/05/2007 - #3000]
  1791. // Some objects use dummy vars and projected fields so make sure we call the get functions
  1792. //const char *val = Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag);
  1793. const char *val = (*f->getDataFn)( object, Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag) );// + typeSizes[fld.type] * array1));
  1794. ConsoleBaseType* conType = ConsoleBaseType::getType( f->type );
  1795. const char* conTypeName = "<unknown>";
  1796. if( conType )
  1797. conTypeName = conType->getTypeClassName();
  1798. if( !val /*|| !*val*/ )
  1799. continue;
  1800. if( f->elementCount == 1 )
  1801. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s = \"", conTypeName, f->pFieldname );
  1802. else
  1803. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s[ %d ] = \"", conTypeName, f->pFieldname, j );
  1804. expandEscape( expandedBuffer + dStrlen(expandedBuffer), val);
  1805. Con::printf( "%s\"", expandedBuffer );
  1806. if( detailed && f->pFieldDocs && f->pFieldDocs[ 0 ] )
  1807. Con::printf( " %s", f->pFieldDocs );
  1808. }
  1809. }
  1810. Con::printf( "Dynamic Fields:" );
  1811. if(object->getFieldDictionary())
  1812. object->getFieldDictionary()->printFields(object);
  1813. Con::printf( "Methods:" );
  1814. Namespace *ns = object->getNamespace();
  1815. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  1816. if(ns)
  1817. ns->getEntryList(&vec);
  1818. bool sawCBs = false;
  1819. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  1820. {
  1821. Namespace::Entry *e = *j;
  1822. if(e->mType == Namespace::Entry::ScriptCallbackType)
  1823. sawCBs = true;
  1824. if(e->mType < 0)
  1825. continue;
  1826. DocString doc( e );
  1827. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->mFunctionName, doc.mPrototype.c_str() );
  1828. if( detailed && !doc.mDescription.isEmpty() )
  1829. Con::printf( " %s", doc.mDescription.c_str() );
  1830. }
  1831. if( sawCBs )
  1832. {
  1833. Con::printf( "Callbacks:" );
  1834. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  1835. {
  1836. Namespace::Entry *e = *j;
  1837. if(e->mType != Namespace::Entry::ScriptCallbackType)
  1838. continue;
  1839. DocString doc( e );
  1840. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->cb.mCallbackName, doc.mPrototype.c_str() );
  1841. if( detailed && !doc.mDescription.isEmpty() )
  1842. Con::printf( " %s", doc.mDescription.c_str() );
  1843. }
  1844. }
  1845. }
  1846. //-----------------------------------------------------------------------------
  1847. DefineConsoleMethod( SimObject, save, bool, ( const char* fileName, bool selectedOnly, const char* preAppendString ), ( false, "" ),
  1848. "Save out the object to the given file.\n"
  1849. "@param fileName The name of the file to save to."
  1850. "@param selectedOnly If true, only objects marked as selected will be saved out.\n"
  1851. "@param preAppendString Text which will be preprended directly to the object serialization.\n"
  1852. "@param True on success, false on failure." )
  1853. {
  1854. return object->save( fileName, selectedOnly, preAppendString );
  1855. }
  1856. //-----------------------------------------------------------------------------
  1857. DefineEngineMethod( SimObject, setName, void, ( const char* newName ),,
  1858. "Set the global name of the object.\n"
  1859. "@param newName The new global name to assign to the object.\n"
  1860. "@note If name changing is disallowed on the object, the method will fail with a console error." )
  1861. {
  1862. object->assignName( newName );
  1863. }
  1864. //-----------------------------------------------------------------------------
  1865. DefineEngineMethod( SimObject, getName, const char*, (),,
  1866. "Get the global name of the object.\n"
  1867. "@return The global name assigned to the object." )
  1868. {
  1869. const char *ret = object->getName();
  1870. return ret ? ret : "";
  1871. }
  1872. //-----------------------------------------------------------------------------
  1873. DefineConsoleMethod( SimObject, getClassName, const char*, (),,
  1874. "Get the name of the C++ class which the object is an instance of.\n"
  1875. "@return The name of the C++ class of the object." )
  1876. {
  1877. const char *ret = object->getClassName();
  1878. return ret ? ret : "";
  1879. }
  1880. //-----------------------------------------------------------------------------
  1881. DefineConsoleMethod( SimObject, isField, bool, ( const char* fieldName ),,
  1882. "Test whether the given field is defined on this object.\n"
  1883. "@param fieldName The name of the field.\n"
  1884. "@return True if the object implements the given field." )
  1885. {
  1886. return object->isField( fieldName );
  1887. }
  1888. //-----------------------------------------------------------------------------
  1889. DefineConsoleMethod( SimObject, getFieldValue, const char*, ( const char* fieldName, S32 index ), ( -1 ),
  1890. "Return the value of the given field on this object.\n"
  1891. "@param fieldName The name of the field. If it includes a field index, the index is parsed out.\n"
  1892. "@param index Optional parameter to specify the index of an array field separately.\n"
  1893. "@return The value of the given field or \"\" if undefined." )
  1894. {
  1895. char fieldNameBuffer[ 1024 ];
  1896. char arrayIndexBuffer[ 64 ];
  1897. // Parse out index if the field is given in the form of 'name[index]'.
  1898. const char* arrayIndex = NULL;
  1899. const U32 nameLen = dStrlen( fieldName );
  1900. if( fieldName[ nameLen - 1 ] == ']' )
  1901. {
  1902. const char* leftBracket = dStrchr( fieldName, '[' );
  1903. const char* rightBracket = &fieldName[ nameLen - 1 ];
  1904. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  1905. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  1906. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  1907. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  1908. fieldNameBuffer[ fieldNameLen ] = '\0';
  1909. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  1910. fieldName = fieldNameBuffer;
  1911. arrayIndex = arrayIndexBuffer;
  1912. }
  1913. fieldName = StringTable->insert( fieldName );
  1914. if( index != -1 )
  1915. {
  1916. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  1917. arrayIndex = arrayIndexBuffer;
  1918. }
  1919. return object->getDataField( fieldName, arrayIndex );
  1920. }
  1921. //-----------------------------------------------------------------------------
  1922. DefineConsoleMethod( SimObject, setFieldValue, bool, ( const char* fieldName, const char* value, S32 index ), ( -1 ),
  1923. "Set the value of the given field on this object.\n"
  1924. "@param fieldName The name of the field to assign to. If it includes an array index, the index will be parsed out.\n"
  1925. "@param value The new value to assign to the field.\n"
  1926. "@param index Optional argument to specify an index for an array field.\n"
  1927. "@return True." )
  1928. {
  1929. char fieldNameBuffer[ 1024 ];
  1930. char arrayIndexBuffer[ 64 ];
  1931. // Parse out index if the field is given in the form of 'name[index]'.
  1932. const char* arrayIndex = NULL;
  1933. const U32 nameLen = dStrlen( fieldName );
  1934. if( fieldName[ nameLen - 1 ] == ']' )
  1935. {
  1936. const char* leftBracket = dStrchr( fieldName, '[' );
  1937. const char* rightBracket = &fieldName[ nameLen - 1 ];
  1938. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  1939. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  1940. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  1941. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  1942. fieldNameBuffer[ fieldNameLen ] = '\0';
  1943. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  1944. fieldName = fieldNameBuffer;
  1945. arrayIndex = arrayIndexBuffer;
  1946. }
  1947. fieldName = StringTable->insert( fieldName );
  1948. if( index != -1 )
  1949. {
  1950. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  1951. arrayIndex = arrayIndexBuffer;
  1952. }
  1953. object->setDataField( fieldName, arrayIndex, value );
  1954. return true;
  1955. }
  1956. //-----------------------------------------------------------------------------
  1957. DefineConsoleMethod( SimObject, getFieldType, const char*, ( const char* fieldName ),,
  1958. "Get the console type code of the given field.\n"
  1959. "@return The numeric type code for the underlying console type of the given field." )
  1960. {
  1961. U32 typeID = object->getDataFieldType( StringTable->insert( fieldName ), NULL );
  1962. ConsoleBaseType* type = ConsoleBaseType::getType( typeID );
  1963. if( type )
  1964. return type->getTypeName();
  1965. return "";
  1966. }
  1967. //-----------------------------------------------------------------------------
  1968. DefineConsoleMethod( SimObject, setFieldType, void, ( const char* fieldName, const char* type ),,
  1969. "Set the console type code for the given field.\n"
  1970. "@param fieldName The name of the dynamic field to change to type for.\n"
  1971. "@param type The name of the console type.\n"
  1972. "@note This only works for dynamic fields. Types of static fields cannot be changed." )
  1973. {
  1974. object->setDataFieldType( type, StringTable->insert( fieldName ), NULL );
  1975. }
  1976. //-----------------------------------------------------------------------------
  1977. ConsoleMethod( SimObject, call, const char*, 3, 0, "( string method, string args... ) Dynamically call a method on an object.\n"
  1978. "@param method Name of method to call.\n"
  1979. "@param args Zero or more arguments for the method.\n"
  1980. "@return The result of the method call." )
  1981. {
  1982. argv[1] = argv[2];
  1983. return Con::execute( object, argc - 1, argv + 1 );
  1984. }
  1985. //-----------------------------------------------------------------------------
  1986. DefineEngineMethod( SimObject, setInternalName, void, ( const char* newInternalName ),,
  1987. "Set the internal name of the object.\n"
  1988. "@param newInternalName The new internal name for the object." )
  1989. {
  1990. object->setInternalName( newInternalName );
  1991. }
  1992. //-----------------------------------------------------------------------------
  1993. DefineEngineMethod( SimObject, getInternalName, const char*, (),,
  1994. "Get the internal name of the object.\n"
  1995. "@return The internal name of the object." )
  1996. {
  1997. return object->getInternalName();
  1998. }
  1999. //-----------------------------------------------------------------------------
  2000. DefineConsoleMethod( SimObject, dumpClassHierarchy, void, (),,
  2001. "Dump the native C++ class hierarchy of this object's C++ class to the console." )
  2002. {
  2003. object->dumpClassHierarchy();
  2004. }
  2005. //-----------------------------------------------------------------------------
  2006. DefineConsoleMethod( SimObject, isMemberOfClass, bool, ( const char* className ),,
  2007. "Test whether this object is a member of the specified class.\n"
  2008. "@param className Name of a native C++ class.\n"
  2009. "@return True if this object is an instance of the given C++ class or any of its super classes." )
  2010. {
  2011. AbstractClassRep* pRep = object->getClassRep();
  2012. while(pRep)
  2013. {
  2014. if( !dStricmp(pRep->getClassName(), className ) )
  2015. {
  2016. //matches
  2017. return true;
  2018. }
  2019. pRep = pRep->getParentClass();
  2020. }
  2021. return false;
  2022. }
  2023. //-----------------------------------------------------------------------------
  2024. DefineConsoleMethod( SimObject, isInNamespaceHierarchy, bool, ( const char* name ),,
  2025. "Test whether the namespace of this object is a direct or indirect child to the given namespace.\n"
  2026. "@param name The name of a namespace.\n"
  2027. "@return True if the given namespace name is within the namespace hierarchy of this object." )
  2028. {
  2029. Namespace* nspace = object->getNamespace();
  2030. while( nspace && dStricmp( nspace->mName, name ) != 0 )
  2031. nspace = nspace->mParent;
  2032. return ( nspace != NULL );
  2033. }
  2034. //-----------------------------------------------------------------------------
  2035. DefineEngineMethod( SimObject, getId, S32, (),,
  2036. "Get the underlying unique numeric ID of the object.\n"
  2037. "@note Object IDs are unique only during single engine runs.\n"
  2038. "@return The unique numeric ID of the object." )
  2039. {
  2040. return object->getId();
  2041. }
  2042. //-----------------------------------------------------------------------------
  2043. DefineEngineMethod( SimObject, getGroup, SimGroup*, (),,
  2044. "Get the group that this object is contained in.\n"
  2045. "@note If not assigned to particular SimGroup, an object belongs to RootGroup.\n"
  2046. "@return The SimGroup object to which the object belongs." )
  2047. {
  2048. return object->getGroup();
  2049. }
  2050. //-----------------------------------------------------------------------------
  2051. DefineConsoleMethod( SimObject, delete, void, (),,
  2052. "Delete and remove the object." )
  2053. {
  2054. object->deleteObject();
  2055. }
  2056. //-----------------------------------------------------------------------------
  2057. ConsoleMethod( SimObject,schedule, S32, 4, 0, "( float time, string method, string args... ) Delay an invocation of a method.\n"
  2058. "@param time The number of milliseconds after which to invoke the method. This is a soft limit.\n"
  2059. "@param method The method to call.\n"
  2060. "@param args The arguments with which to call the method.\n"
  2061. "@return The numeric ID of the created schedule. Can be used to cancel the call.\n" )
  2062. {
  2063. U32 timeDelta = U32(dAtof(argv[2]));
  2064. argv[2] = argv[3];
  2065. argv[3] = argv[1];
  2066. SimConsoleEvent *evt = new SimConsoleEvent(argc - 2, argv + 2, true);
  2067. S32 ret = Sim::postEvent(object, evt, Sim::getCurrentTime() + timeDelta);
  2068. // #ifdef DEBUG
  2069. // Con::printf("obj %s schedule(%s) = %d", argv[3], argv[2], ret);
  2070. // Con::executef( "backtrace");
  2071. // #endif
  2072. return ret;
  2073. }
  2074. //-----------------------------------------------------------------------------
  2075. DefineConsoleMethod( SimObject, getDynamicFieldCount, S32, (),,
  2076. "Get the number of dynamic fields defined on the object.\n"
  2077. "@return The number of dynamic fields defined on the object." )
  2078. {
  2079. S32 count = 0;
  2080. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2081. for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
  2082. count++;
  2083. return count;
  2084. }
  2085. //-----------------------------------------------------------------------------
  2086. DefineConsoleMethod( SimObject, getDynamicField, const char*, ( S32 index ),,
  2087. "Get a value of a dynamic field by index.\n"
  2088. "@param index The index of the dynamic field.\n"
  2089. "@return The value of the dynamic field at the given index or \"\"." )
  2090. {
  2091. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2092. SimFieldDictionaryIterator itr(fieldDictionary);
  2093. for (S32 i = 0; i < index; i++)
  2094. {
  2095. if (!(*itr))
  2096. {
  2097. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2098. return NULL;
  2099. }
  2100. ++itr;
  2101. }
  2102. static const U32 bufSize = 256;
  2103. char* buffer = Con::getReturnBuffer(bufSize);
  2104. if (*itr)
  2105. {
  2106. SimFieldDictionary::Entry* entry = *itr;
  2107. dSprintf(buffer, bufSize, "%s\t%s", entry->slotName, entry->value);
  2108. return buffer;
  2109. }
  2110. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2111. return NULL;
  2112. }
  2113. //-----------------------------------------------------------------------------
  2114. DefineConsoleMethod( SimObject, getFieldCount, S32, (),,
  2115. "Get the number of static fields on the object.\n"
  2116. "@return The number of static fields defined on the object." )
  2117. {
  2118. const AbstractClassRep::FieldList &list = object->getFieldList();
  2119. const AbstractClassRep::Field* f;
  2120. U32 numDummyEntries = 0;
  2121. for(S32 i = 0; i < list.size(); i++)
  2122. {
  2123. f = &list[i];
  2124. // The special field types do not need to be counted.
  2125. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2126. numDummyEntries++;
  2127. }
  2128. return list.size() - numDummyEntries;
  2129. }
  2130. //-----------------------------------------------------------------------------
  2131. DefineConsoleMethod( SimObject, getField, const char*, ( S32 index ),,
  2132. "Retrieve the value of a static field by index.\n"
  2133. "@param index The index of the static field.\n"
  2134. "@return The value of the static field with the given index or \"\"." )
  2135. {
  2136. const AbstractClassRep::FieldList &list = object->getFieldList();
  2137. if( ( index < 0 ) || ( index >= list.size() ) )
  2138. return "";
  2139. const AbstractClassRep::Field* f;
  2140. S32 currentField = 0;
  2141. for ( U32 i = 0; i < list.size() && currentField <= index; i++ )
  2142. {
  2143. f = &list[i];
  2144. // The special field types can be skipped.
  2145. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2146. continue;
  2147. if(currentField == index)
  2148. return f->pFieldname;
  2149. currentField++;
  2150. }
  2151. // if we found nada, return nada.
  2152. return "";
  2153. }
  2154. //-----------------------------------------------------------------------------
  2155. #ifdef TORQUE_DEBUG
  2156. DefineEngineMethod( SimObject, getDebugInfo, ArrayObject*, (),,
  2157. "Return some behind-the-scenes information on the object.\n"
  2158. "@return An ArrayObject filled with internal information about the object." )
  2159. {
  2160. ArrayObject* array = new ArrayObject();
  2161. array->registerObject();
  2162. array->push_back( "C++|Address", String::ToString( "0x%x", object ) );
  2163. array->push_back( "C++|Size", String::ToString( object->getClassRep()->getSizeof() ) );
  2164. array->push_back( "Object|Description", object->describeSelf() );
  2165. array->push_back( "Object|FileName", object->getFilename() );
  2166. array->push_back( "Object|DeclarationLine", String::ToString( object->getDeclarationLine() ) );
  2167. array->push_back( "Object|CopySource", object->getCopySource() ?
  2168. String::ToString( "%i:%s (%s)", object->getCopySource()->getId(), object->getCopySource()->getClassName(), object->getCopySource()->getName() ) : "" );
  2169. array->push_back( "Flag|EditorOnly", object->isEditorOnly() ? "true" : "false" );
  2170. array->push_back( "Flag|NameChangeAllowed", object->isNameChangeAllowed() ? "true" : "false" );
  2171. array->push_back( "Flag|AutoDelete", object->isAutoDeleted() ? "true" : "false" );
  2172. array->push_back( "Flag|Selected", object->isSelected() ? "true" : "false" );
  2173. array->push_back( "Flag|Expanded", object->isExpanded() ? "true" : "false" );
  2174. array->push_back( "Flag|ModStaticFields", object->canModStaticFields() ? "true" : "false" );
  2175. array->push_back( "Flag|ModDynamicFields", object->canModDynamicFields() ? "true" : "false" );
  2176. array->push_back( "Flag|CanSave", object->getCanSave() ? "true" : "false" );
  2177. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  2178. Memory::Info memInfo;
  2179. Memory::getMemoryInfo( object, memInfo );
  2180. array->push_back( "Memory|AllocNumber", String::ToString( memInfo.mAllocNumber ) );
  2181. array->push_back( "Memory|AllocSize", String::ToString( memInfo.mAllocSize ) );
  2182. array->push_back( "Memory|AllocFile", memInfo.mFileName );
  2183. array->push_back( "Memory|AllocLine", String::ToString( memInfo.mLineNumber ) );
  2184. array->push_back( "Memory|IsGlobal", memInfo.mIsGlobal ? "true" : "false" );
  2185. array->push_back( "Memory|IsStatic", memInfo.mIsStatic ? "true" : "false" );
  2186. #endif
  2187. return array;
  2188. }
  2189. #endif