simObject.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790
  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. AssertWarn( mNameSpace == NULL, "SimObject::linkNamespaces -- Namespace linkage already in place" );
  1106. if( mNameSpace )
  1107. return;
  1108. // Get the namespace for the C++ class.
  1109. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1110. // Parent namespace defaults to namespace of C++ class.
  1111. Namespace* parentNamespace = cppNamespace;
  1112. // Perform superclass linking, if requested.
  1113. if( mSuperClassName && mSuperClassName[ 0 ] )
  1114. {
  1115. // Look up the superclass namespace.
  1116. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1117. // If packages are active and adding to the superclass namespace, then we will
  1118. // have multiple packages in a parent chain that all have the same name.
  1119. // Con::lookupNamespace returns the bottom-most package in the chain to us so
  1120. // in order to properly link namespace here without conflicting with the package
  1121. // mechanism, we need to properly link child namespaces to the bottom-most namespace
  1122. // while linking parent namespaces to the topmost namespace. To find the latter
  1123. // one, we walk up the hierarchy here.
  1124. Namespace* superClassNamespacePackageRoot = superClassNamespace->getPackageRoot();
  1125. // Link the superclass namespace to the C++ class namespace.
  1126. if( superClassNamespacePackageRoot->getParent() == NULL )
  1127. {
  1128. // The superclass namespace isn't linked yet so we just
  1129. // link it to the C++ class namespace and make that our parent.
  1130. // No increasing parent reference counts is needed in this case.
  1131. bool ok = superClassNamespacePackageRoot->classLinkTo( cppNamespace );
  1132. AssertFatal( ok, "SimObject::linkNamespaces - failed to link new namespace to c++ class name" );
  1133. parentNamespace = superClassNamespace;
  1134. }
  1135. else
  1136. {
  1137. // In debug builds, make sure the namespace hierarchy that's been
  1138. // put into place actually makes sense and leads back to the C++
  1139. // class namespace.
  1140. #ifdef TORQUE_DEBUG
  1141. bool foundClassNameNS = false;
  1142. for( Namespace* linkWalk = superClassNamespacePackageRoot->getParent(); linkWalk != NULL;
  1143. linkWalk = linkWalk->getParent() )
  1144. {
  1145. if( linkWalk == cppNamespace )
  1146. {
  1147. foundClassNameNS = true;
  1148. break;
  1149. }
  1150. }
  1151. if( !foundClassNameNS )
  1152. {
  1153. // C++ class namespace not in parent link chain. Warn about it.
  1154. Con::errorf(
  1155. "SimObject::linkNamespaces - cannot link object to superclass %s because c++ class %s is not in the parent namespace chain. Linking object to c++ class.",
  1156. mSuperClassName,
  1157. getClassName()
  1158. );
  1159. // Clear out superclass name so we don't come across it during
  1160. // unlinking.
  1161. mSuperClassName = NULL;
  1162. }
  1163. else
  1164. #endif
  1165. {
  1166. // Super link is ok.
  1167. parentNamespace = superClassNamespace;
  1168. // Now increase the reference count of all namespaces in the parent hierarchy
  1169. // (up to the C++ class).
  1170. for( Namespace* linkWalk = parentNamespace;
  1171. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL;
  1172. linkWalk = linkWalk->getParent() )
  1173. {
  1174. // Skip namespaces coming from packages.
  1175. if( linkWalk->getPackage() != NULL )
  1176. continue;
  1177. linkWalk->incRefCountToParent();
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // If class name is set, link it in as the new parent
  1183. // which itself inherits from the current parent.
  1184. if( mClassName && mClassName[ 0 ] )
  1185. {
  1186. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1187. if( classNamespace && classNamespace->classLinkTo( parentNamespace ) )
  1188. {
  1189. parentNamespace = classNamespace;
  1190. }
  1191. else
  1192. {
  1193. // Clear out class name so we don't perform a bogus unlink
  1194. // in unlinkNamespaces().
  1195. mClassName = NULL;
  1196. }
  1197. }
  1198. // Finally, if we have an object name, link its namespace
  1199. // as the child to the current parent namespace and let it
  1200. // become the final namespace of this object.
  1201. StringTableEntry objectName = getName();
  1202. if( objectName && objectName[ 0 ] )
  1203. {
  1204. Namespace* objectNamespace = Con::lookupNamespace( objectName );
  1205. if( objectNamespace && objectNamespace->classLinkTo( parentNamespace ) )
  1206. {
  1207. parentNamespace = objectNamespace;
  1208. }
  1209. }
  1210. // Store our namespace.
  1211. mNameSpace = parentNamespace;
  1212. }
  1213. //-----------------------------------------------------------------------------
  1214. void SimObject::unlinkNamespaces()
  1215. {
  1216. if( !mNameSpace )
  1217. return;
  1218. Namespace* cppNamespace = getClassRep()->getNameSpace();
  1219. Namespace* parentNamespace = cppNamespace;
  1220. // Handle superclass.
  1221. if( mSuperClassName && mSuperClassName[ 0 ] )
  1222. {
  1223. // Get the superclass namespace.
  1224. Namespace* superClassNamespace = Con::lookupNamespace( mSuperClassName );
  1225. // Make it the parent namespace.
  1226. parentNamespace = superClassNamespace;
  1227. // Decrease parent refcounts on the superclass hierarchy.
  1228. for( Namespace* linkWalk = superClassNamespace;
  1229. linkWalk != NULL && linkWalk != cppNamespace && linkWalk->getParent() != NULL; )
  1230. {
  1231. // Store the parent link since it may disappear once we
  1232. // decrease the reference count.
  1233. Namespace* parent = linkWalk->getParent();
  1234. // Decrease the refcount.
  1235. if( linkWalk->getPackage() == NULL ) // Skip namespaces coming from packages.
  1236. linkWalk->decRefCountToParent();
  1237. // Walk up.
  1238. linkWalk = parent;
  1239. }
  1240. }
  1241. // Handle class.
  1242. if( mClassName && mClassName[ 0 ] )
  1243. {
  1244. Namespace* classNamespace = Con::lookupNamespace( mClassName );
  1245. if( classNamespace )
  1246. {
  1247. classNamespace->decRefCountToParent();
  1248. parentNamespace = classNamespace;
  1249. }
  1250. }
  1251. // Handle object name.
  1252. if (mNameSpace && mNameSpace->mClassRep == NULL)
  1253. mNameSpace->decRefCountToParent();
  1254. mNameSpace = NULL;
  1255. }
  1256. //-----------------------------------------------------------------------------
  1257. void SimObject::setClassNamespace( const char *classNamespace )
  1258. {
  1259. StringTableEntry oldClassNamespace = mClassName;
  1260. StringTableEntry newClassNamespace = StringTable->insert( classNamespace );
  1261. if( oldClassNamespace == newClassNamespace )
  1262. return;
  1263. if( isProperlyAdded() )
  1264. unlinkNamespaces();
  1265. mClassName = newClassNamespace;
  1266. if( isProperlyAdded() )
  1267. {
  1268. linkNamespaces();
  1269. // Restore old namespace setup if linkage failed.
  1270. if( mClassName != newClassNamespace )
  1271. {
  1272. mClassName = oldClassNamespace;
  1273. linkNamespaces();
  1274. }
  1275. }
  1276. }
  1277. //-----------------------------------------------------------------------------
  1278. void SimObject::setSuperClassNamespace( const char *superClassNamespace )
  1279. {
  1280. StringTableEntry oldSuperClassNamespace = mSuperClassName;
  1281. StringTableEntry newSuperClassNamespace = StringTable->insert( superClassNamespace );
  1282. if( oldSuperClassNamespace == newSuperClassNamespace )
  1283. return;
  1284. if( isProperlyAdded() )
  1285. unlinkNamespaces();
  1286. mSuperClassName = newSuperClassNamespace;
  1287. if( isProperlyAdded() )
  1288. {
  1289. linkNamespaces();
  1290. // Restore old setup if linkage failed.
  1291. if( mSuperClassName != newSuperClassNamespace )
  1292. {
  1293. mSuperClassName = oldSuperClassNamespace;
  1294. linkNamespaces();
  1295. }
  1296. }
  1297. }
  1298. //=============================================================================
  1299. // Misc.
  1300. //=============================================================================
  1301. // MARK: ---- Misc ----
  1302. //-----------------------------------------------------------------------------
  1303. void SimObject::setInternalName( const char* newname )
  1304. {
  1305. if( newname )
  1306. mInternalName = StringTable->insert( newname );
  1307. else
  1308. mInternalName = StringTable->EmptyString();
  1309. }
  1310. //-----------------------------------------------------------------------------
  1311. void SimObject::setOriginalName( const char* originalName )
  1312. {
  1313. if( originalName )
  1314. mOriginalName = StringTable->insert( originalName );
  1315. else
  1316. mOriginalName = StringTable->EmptyString();
  1317. }
  1318. //-----------------------------------------------------------------------------
  1319. const char *SimObject::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  1320. {
  1321. return mNameSpace->tabComplete(prevText, baseLen, fForward);
  1322. }
  1323. //-----------------------------------------------------------------------------
  1324. void SimObject::setSelected( bool sel )
  1325. {
  1326. if( mFlags.test( Selected ) == sel )
  1327. return; // No change.
  1328. if( sel )
  1329. {
  1330. mFlags.set( Selected );
  1331. _onSelected();
  1332. }
  1333. else
  1334. {
  1335. mFlags.clear( Selected );
  1336. _onUnselected();
  1337. }
  1338. }
  1339. //-----------------------------------------------------------------------------
  1340. bool SimObject::isSelectedRecursive() const
  1341. {
  1342. const SimObject *walk = this;
  1343. while ( walk )
  1344. {
  1345. if ( walk->isSelected() )
  1346. return true;
  1347. walk = walk->getGroup();
  1348. }
  1349. return false;
  1350. }
  1351. //-----------------------------------------------------------------------------
  1352. void SimObject::setLocked( bool b )
  1353. {
  1354. if( b )
  1355. mFlags.set( Locked );
  1356. else
  1357. mFlags.clear( Locked );
  1358. }
  1359. //-----------------------------------------------------------------------------
  1360. void SimObject::setHidden( bool b )
  1361. {
  1362. if( b )
  1363. mFlags.set( Hidden );
  1364. else
  1365. mFlags.clear( Hidden );
  1366. }
  1367. //-----------------------------------------------------------------------------
  1368. void SimObject::setCopySource( SimObject* object )
  1369. {
  1370. if( mCopySource )
  1371. mCopySource->unregisterReference( &mCopySource );
  1372. mCopySource = object;
  1373. if( mCopySource )
  1374. mCopySource->registerReference( &mCopySource );
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. bool SimObject::_setCanSave( void* object, const char* index, const char* data )
  1378. {
  1379. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1380. obj->setCanSave( dAtob( data ) );
  1381. return false;
  1382. }
  1383. //-----------------------------------------------------------------------------
  1384. const char* SimObject::_getCanSave( void* object, const char* data )
  1385. {
  1386. SimObject* obj = reinterpret_cast< SimObject* >( object );
  1387. if( obj->getCanSave() )
  1388. return "1";
  1389. else
  1390. return "0";
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. // Copy SimObject to another SimObject (Originally designed for T2D).
  1394. void SimObject::copyTo( SimObject* object )
  1395. {
  1396. object->mClassName = mClassName;
  1397. object->mSuperClassName = mSuperClassName;
  1398. linkNamespaces();
  1399. }
  1400. //-----------------------------------------------------------------------------
  1401. bool SimObject::setProtectedParent( void *obj, const char *index, const char *data )
  1402. {
  1403. SimGroup *parent = NULL;
  1404. SimObject *object = static_cast<SimObject*>(obj);
  1405. if(Sim::findObject(data, parent))
  1406. parent->addObject(object);
  1407. // always return false, because we've set mGroup when we called addObject
  1408. return false;
  1409. }
  1410. //-----------------------------------------------------------------------------
  1411. bool SimObject::setProtectedName(void *obj, const char *index, const char *data)
  1412. {
  1413. SimObject *object = static_cast<SimObject*>(obj);
  1414. if ( object->isProperlyAdded() )
  1415. object->assignName( data );
  1416. // always return false because we assign the name here
  1417. return false;
  1418. }
  1419. //-----------------------------------------------------------------------------
  1420. void SimObject::inspectPreApply()
  1421. {
  1422. }
  1423. //-----------------------------------------------------------------------------
  1424. void SimObject::inspectPostApply()
  1425. {
  1426. }
  1427. //-----------------------------------------------------------------------------
  1428. String SimObject::_getLogMessage(const char* fmt, va_list args) const
  1429. {
  1430. String objClass = "UnknownClass";
  1431. if(getClassRep())
  1432. objClass = getClassRep()->getClassName();
  1433. String objName = getName();
  1434. if(objName.isEmpty())
  1435. objName = "Unnamed";
  1436. String formattedMessage = String::VToString(fmt, args);
  1437. return String::ToString("%s - %s(%i) - %s",
  1438. objClass.c_str(), objName.c_str(), getId(), formattedMessage.c_str());
  1439. }
  1440. //=============================================================================
  1441. // API.
  1442. //=============================================================================
  1443. // MARK: ---- API ----
  1444. //-----------------------------------------------------------------------------
  1445. DefineEngineMethod( SimObject, dumpGroupHierarchy, void, (),,
  1446. "Dump the hierarchy of this object up to RootGroup to the console." )
  1447. {
  1448. object->dumpGroupHierarchy();
  1449. }
  1450. //-----------------------------------------------------------------------------
  1451. DefineConsoleMethod( SimObject, isMethod, bool, ( const char* methodName ),,
  1452. "Test whether the given method is defined on this object.\n"
  1453. "@param The name of the method.\n"
  1454. "@return True if the object implements the given method." )
  1455. {
  1456. return object->isMethod( methodName );
  1457. }
  1458. //-----------------------------------------------------------------------------
  1459. DefineEngineMethod( SimObject, isChildOfGroup, bool, ( SimGroup* group ),,
  1460. "Test whether the object belongs directly or indirectly to the given group.\n"
  1461. "@param group The SimGroup object.\n"
  1462. "@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." )
  1463. {
  1464. return object->isChildOfGroup( group );
  1465. }
  1466. //-----------------------------------------------------------------------------
  1467. DefineConsoleMethod( SimObject, getClassNamespace, const char*, (),,
  1468. "Get the name of the class namespace assigned to this object.\n"
  1469. "@return The name of the 'class' namespace." )
  1470. {
  1471. return object->getClassNamespace();
  1472. }
  1473. //-----------------------------------------------------------------------------
  1474. DefineConsoleMethod( SimObject, getSuperClassNamespace, const char*, (),,
  1475. "Get the name of the superclass namespace assigned to this object.\n"
  1476. "@return The name of the 'superClass' namespace." )
  1477. {
  1478. return object->getSuperClassNamespace();
  1479. }
  1480. //-----------------------------------------------------------------------------
  1481. DefineConsoleMethod( SimObject, setClassNamespace, void, ( const char* name ),,
  1482. "Assign a class namespace to this object.\n"
  1483. "@param name The name of the 'class' namespace for this object." )
  1484. {
  1485. object->setClassNamespace( name );
  1486. }
  1487. //-----------------------------------------------------------------------------
  1488. DefineConsoleMethod( SimObject, setSuperClassNamespace, void, ( const char* name ),,
  1489. "Assign a superclass namespace to this object.\n"
  1490. "@param name The name of the 'superClass' namespace for this object." )
  1491. {
  1492. object->setSuperClassNamespace( name );
  1493. }
  1494. //-----------------------------------------------------------------------------
  1495. DefineEngineMethod( SimObject, isSelected, bool, (),,
  1496. "Get whether the object has been marked as selected. (in editor)\n"
  1497. "@return True if the object is currently selected." )
  1498. {
  1499. return object->isSelected();
  1500. }
  1501. //-----------------------------------------------------------------------------
  1502. DefineEngineMethod( SimObject, setIsSelected, void, ( bool state ), ( true ),
  1503. "Set whether the object has been marked as selected. (in editor)\n"
  1504. "@param state True if object is to be marked selected; false if not." )
  1505. {
  1506. object->setSelected( state );
  1507. }
  1508. //-----------------------------------------------------------------------------
  1509. DefineConsoleMethod( SimObject, isExpanded, bool, (),,
  1510. "Get whether the object has been marked as expanded. (in editor)\n"
  1511. "@return True if the object is marked expanded." )
  1512. {
  1513. return object->isExpanded();
  1514. }
  1515. //-----------------------------------------------------------------------------
  1516. DefineConsoleMethod( SimObject, setIsExpanded, void, ( bool state ), ( true ),
  1517. "Set whether the object has been marked as expanded. (in editor)\n"
  1518. "@param state True if the object is to be marked expanded; false if not." )
  1519. {
  1520. object->setExpanded( state );
  1521. }
  1522. //-----------------------------------------------------------------------------
  1523. DefineConsoleMethod( SimObject, getFilename, const char*, (),,
  1524. "Returns the filename the object is attached to.\n"
  1525. "@return The name of the file the object is associated with; usually the file the object was loaded from." )
  1526. {
  1527. return object->getFilename();
  1528. }
  1529. //-----------------------------------------------------------------------------
  1530. DefineConsoleMethod( SimObject, setFilename, void, ( const char* fileName ),,
  1531. "Sets the object's file name and path\n"
  1532. "@param fileName The name of the file to associate this object with." )
  1533. {
  1534. return object->setFilename( fileName );
  1535. }
  1536. //-----------------------------------------------------------------------------
  1537. DefineConsoleMethod( SimObject, getDeclarationLine, S32, (),,
  1538. "Get the line number at which the object is defined in its file.\n\n"
  1539. "@return The line number of the object's definition in script.\n"
  1540. "@see getFilename()")
  1541. {
  1542. return object->getDeclarationLine();
  1543. }
  1544. //-----------------------------------------------------------------------------
  1545. #ifdef TORQUE_DEBUG
  1546. static const char* sEnumCallbackFunction;
  1547. static void sEnumCallback( EngineObject* object )
  1548. {
  1549. SimObject* simObject = dynamic_cast< SimObject* >( object );
  1550. if( !simObject )
  1551. return;
  1552. Con::evaluatef( "%s( %i );", sEnumCallbackFunction, simObject->getId() );
  1553. }
  1554. DefineEngineFunction( debugEnumInstances, void, ( const char* className, const char* functionName ),,
  1555. "Call the given function for each instance of the given class.\n"
  1556. "@param className Name of the class for which to enumerate instances.\n"
  1557. "@param functionName Name of function to call and pass each instance of the given class.\n"
  1558. "@note This function is only available in debug builds and primarily meant as an aid in debugging."
  1559. "@ingroup Console")
  1560. {
  1561. sEnumCallbackFunction = functionName;
  1562. ConsoleObject::debugEnumInstances( className, sEnumCallback );
  1563. }
  1564. #endif
  1565. //-----------------------------------------------------------------------------
  1566. DefineConsoleMethod( SimObject, assignFieldsFrom, void, ( SimObject* fromObject ),,
  1567. "Copy fields from another object onto this one. The objects must "
  1568. "be of same type. Everything from the object will overwrite what's "
  1569. "in this object; extra fields in this object will remain. This "
  1570. "includes dynamic fields.\n"
  1571. "@param fromObject The object from which to copy fields." )
  1572. {
  1573. if( fromObject )
  1574. object->assignFieldsFrom( fromObject );
  1575. }
  1576. //-----------------------------------------------------------------------------
  1577. DefineEngineMethod( SimObject, assignPersistentId, void, (),,
  1578. "Assign a persistent ID to the object if it does not already have one." )
  1579. {
  1580. object->getOrCreatePersistentId();
  1581. }
  1582. //-----------------------------------------------------------------------------
  1583. DefineConsoleMethod( SimObject, getCanSave, bool, (),,
  1584. "Get whether the object will be included in saves.\n"
  1585. "@return True if the object will be saved; false otherwise." )
  1586. {
  1587. return object->getCanSave();
  1588. }
  1589. //-----------------------------------------------------------------------------
  1590. DefineConsoleMethod( SimObject, setCanSave, void, ( bool value ), ( true ),
  1591. "Set whether the object will be included in saves.\n"
  1592. "@param value If true, the object will be included in saves; if false, it will be excluded." )
  1593. {
  1594. object->setCanSave( value );
  1595. }
  1596. //-----------------------------------------------------------------------------
  1597. DefineEngineMethod( SimObject, isEditorOnly, bool, (),,
  1598. "Return true if the object is only used by the editor.\n"
  1599. "@return True if this object exists only for the sake of editing." )
  1600. {
  1601. return object->isEditorOnly();
  1602. }
  1603. //-----------------------------------------------------------------------------
  1604. DefineEngineMethod( SimObject, setEditorOnly, void, ( bool value ), ( true ),
  1605. "Set/clear the editor-only flag on this object.\n"
  1606. "@param value If true, the object is marked as existing only for the editor." )
  1607. {
  1608. object->setEditorOnly( value );
  1609. }
  1610. //-----------------------------------------------------------------------------
  1611. DefineEngineMethod( SimObject, isNameChangeAllowed, bool, (),,
  1612. "Get whether this object may be renamed.\n"
  1613. "@return True if this object can be renamed; false otherwise." )
  1614. {
  1615. return object->isNameChangeAllowed();
  1616. }
  1617. //-----------------------------------------------------------------------------
  1618. DefineEngineMethod( SimObject, setNameChangeAllowed, void, ( bool value ), ( true ),
  1619. "Set whether this object can be renamed from its first name.\n"
  1620. "@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." )
  1621. {
  1622. object->setNameChangeAllowed( value );
  1623. }
  1624. //-----------------------------------------------------------------------------
  1625. DefineEngineMethod( SimObject, clone, SimObject*, (),,
  1626. "Create a copy of this object.\n"
  1627. "@return An exact duplicate of this object." )
  1628. {
  1629. return object->clone();
  1630. }
  1631. //-----------------------------------------------------------------------------
  1632. DefineEngineMethod( SimObject, deepClone, SimObject*, (),,
  1633. "Create a copy of this object and all its subobjects.\n"
  1634. "@return An exact duplicate of this object and all objects it references." )
  1635. {
  1636. return object->deepClone();
  1637. }
  1638. //-----------------------------------------------------------------------------
  1639. DefineEngineMethod( SimObject, setLocked, void, ( bool value ), ( true ),
  1640. "Lock/unlock the object in the editor.\n"
  1641. "@param value If true, the object will be locked; if false, the object will be unlocked." )
  1642. {
  1643. object->setLocked( value );
  1644. }
  1645. //-----------------------------------------------------------------------------
  1646. DefineEngineMethod( SimObject, setHidden, void, ( bool value ), ( true ),
  1647. "Hide/unhide the object.\n"
  1648. "@param value If true, the object will be hidden; if false, the object will be unhidden." )
  1649. {
  1650. object->setHidden( value );
  1651. }
  1652. //-----------------------------------------------------------------------------
  1653. DefineConsoleMethod( SimObject, dumpMethods, ArrayObject*, (),,
  1654. "List the methods defined on this object.\n\n"
  1655. "Each description is a newline-separated vector with the following elements:\n"
  1656. "- Minimum number of arguments.\n"
  1657. "- Maximum number of arguments.\n"
  1658. "- Prototype string.\n"
  1659. "- Full script file path (if script method).\n"
  1660. "- Line number of method definition in script (if script method).\n\n"
  1661. "- Documentation string (not including prototype). This takes up the remainder of the vector.\n"
  1662. "@return An ArrayObject populated with (name,description) pairs of all methods defined on the object." )
  1663. {
  1664. Namespace *ns = object->getNamespace();
  1665. if( !ns )
  1666. return 0;
  1667. ArrayObject* dictionary = new ArrayObject();
  1668. dictionary->registerObject();
  1669. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  1670. ns->getEntryList(&vec);
  1671. for(Vector< Namespace::Entry* >::iterator j = vec.begin(); j != vec.end(); j++)
  1672. {
  1673. Namespace::Entry* e = *j;
  1674. if( e->mType < 0 )
  1675. continue;
  1676. StringBuilder str;
  1677. str.append( String::ToString( e->mMinArgs ) );
  1678. str.append( '\n' );
  1679. str.append( String::ToString( e->mMaxArgs ) );
  1680. str.append( '\n' );
  1681. str.append( e->getPrototypeString() );
  1682. str.append( '\n' );
  1683. if( e->mCode && e->mCode->fullPath )
  1684. str.append( e->mCode->fullPath );
  1685. str.append( '\n' );
  1686. if( e->mCode )
  1687. str.append( String::ToString( e->mFunctionLineNumber ) );
  1688. str.append( '\n' );
  1689. String docs = e->getDocString();
  1690. if( !docs.isEmpty() )
  1691. str.append( docs );
  1692. dictionary->push_back( e->mFunctionName, str.end() );
  1693. }
  1694. return dictionary;
  1695. }
  1696. //-----------------------------------------------------------------------------
  1697. namespace {
  1698. S32 QSORT_CALLBACK compareFields( const void* a,const void* b )
  1699. {
  1700. const AbstractClassRep::Field* fa = *((const AbstractClassRep::Field**)a);
  1701. const AbstractClassRep::Field* fb = *((const AbstractClassRep::Field**)b);
  1702. return dStricmp(fa->pFieldname, fb->pFieldname);
  1703. }
  1704. struct DocString
  1705. {
  1706. char mPadding[ 8 ];
  1707. String mPrototype;
  1708. String mDescription;
  1709. const char* mReturnType;
  1710. DocString( Namespace::Entry* entry )
  1711. : mPrototype( entry->getArgumentsString() ),
  1712. mDescription( entry->getBriefDescription() )
  1713. {
  1714. mReturnType = " ";
  1715. mPadding[ 0 ] = 0;
  1716. if( entry->mType == -4 )
  1717. {
  1718. //TODO: need to have script callbacks set up proper return type info
  1719. }
  1720. else
  1721. {
  1722. switch( entry->mType )
  1723. {
  1724. case Namespace::Entry::StringCallbackType:
  1725. mReturnType = "string";
  1726. mPadding[ 0 ] = ' ';
  1727. mPadding[ 1 ] = ' ';
  1728. mPadding[ 2 ] = 0;
  1729. break;
  1730. case Namespace::Entry::IntCallbackType:
  1731. mReturnType = "int";
  1732. mPadding[ 0 ] = ' ';
  1733. mPadding[ 1 ] = ' ';
  1734. mPadding[ 2 ] = ' ';
  1735. mPadding[ 3 ] = ' ';
  1736. mPadding[ 4 ] = ' ';
  1737. mPadding[ 5 ] = 0;
  1738. break;
  1739. case Namespace::Entry::FloatCallbackType:
  1740. mReturnType = "float";
  1741. mPadding[ 0 ] = ' ';
  1742. mPadding[ 1 ] = ' ';
  1743. mPadding[ 2 ] = ' ';
  1744. mPadding[ 3 ] = 0;
  1745. break;
  1746. case Namespace::Entry::VoidCallbackType:
  1747. mReturnType = "void";
  1748. mPadding[ 0 ] = ' ';
  1749. mPadding[ 1 ] = ' ';
  1750. mPadding[ 2 ] = ' ';
  1751. mPadding[ 3 ] = ' ';
  1752. mPadding[ 4 ] = 0;
  1753. break;
  1754. case Namespace::Entry::BoolCallbackType:
  1755. mReturnType = "bool";
  1756. mPadding[ 0 ] = ' ';
  1757. mPadding[ 1 ] = ' ';
  1758. mPadding[ 2 ] = ' ';
  1759. mPadding[ 3 ] = ' ';
  1760. mPadding[ 4 ] = 0;
  1761. break;
  1762. }
  1763. }
  1764. }
  1765. };
  1766. }
  1767. DefineEngineMethod( SimObject, dump, void, ( bool detailed ), ( false ),
  1768. "Dump a description of all fields and methods defined on this object to the console.\n"
  1769. "@param detailed Whether to print detailed information about members." )
  1770. {
  1771. Con::printf( "Class: %s", object->getClassName() );
  1772. const AbstractClassRep::FieldList &list = object->getFieldList();
  1773. char expandedBuffer[4096];
  1774. Con::printf( "Static Fields:" );
  1775. Vector<const AbstractClassRep::Field *> flist(__FILE__, __LINE__);
  1776. for(U32 i = 0; i < list.size(); i++)
  1777. flist.push_back(&list[i]);
  1778. dQsort(flist.address(),flist.size(),sizeof(AbstractClassRep::Field *),compareFields);
  1779. for(Vector<const AbstractClassRep::Field *>::iterator itr = flist.begin(); itr != flist.end(); itr++)
  1780. {
  1781. const AbstractClassRep::Field* f = *itr;
  1782. // The special field types can be skipped.
  1783. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  1784. continue;
  1785. for(U32 j = 0; S32(j) < f->elementCount; j++)
  1786. {
  1787. // [neo, 07/05/2007 - #3000]
  1788. // Some objects use dummy vars and projected fields so make sure we call the get functions
  1789. //const char *val = Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag);
  1790. 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));
  1791. ConsoleBaseType* conType = ConsoleBaseType::getType( f->type );
  1792. const char* conTypeName = "<unknown>";
  1793. if( conType )
  1794. conTypeName = conType->getTypeClassName();
  1795. if( !val /*|| !*val*/ )
  1796. continue;
  1797. if( f->elementCount == 1 )
  1798. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s = \"", conTypeName, f->pFieldname );
  1799. else
  1800. dSprintf( expandedBuffer, sizeof( expandedBuffer ), " %s %s[ %d ] = \"", conTypeName, f->pFieldname, j );
  1801. expandEscape( expandedBuffer + dStrlen(expandedBuffer), val);
  1802. Con::printf( "%s\"", expandedBuffer );
  1803. if( detailed && f->pFieldDocs && f->pFieldDocs[ 0 ] )
  1804. Con::printf( " %s", f->pFieldDocs );
  1805. }
  1806. }
  1807. Con::printf( "Dynamic Fields:" );
  1808. if(object->getFieldDictionary())
  1809. object->getFieldDictionary()->printFields(object);
  1810. Con::printf( "Methods:" );
  1811. Namespace *ns = object->getNamespace();
  1812. VectorPtr<Namespace::Entry *> vec(__FILE__, __LINE__);
  1813. if(ns)
  1814. ns->getEntryList(&vec);
  1815. bool sawCBs = false;
  1816. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  1817. {
  1818. Namespace::Entry *e = *j;
  1819. if(e->mType == Namespace::Entry::ScriptCallbackType)
  1820. sawCBs = true;
  1821. if(e->mType < 0)
  1822. continue;
  1823. DocString doc( e );
  1824. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->mFunctionName, doc.mPrototype.c_str() );
  1825. if( detailed && !doc.mDescription.isEmpty() )
  1826. Con::printf( " %s", doc.mDescription.c_str() );
  1827. }
  1828. if( sawCBs )
  1829. {
  1830. Con::printf( "Callbacks:" );
  1831. for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
  1832. {
  1833. Namespace::Entry *e = *j;
  1834. if(e->mType != Namespace::Entry::ScriptCallbackType)
  1835. continue;
  1836. DocString doc( e );
  1837. Con::printf( " %s%s%s%s", doc.mReturnType, doc.mPadding, e->cb.mCallbackName, doc.mPrototype.c_str() );
  1838. if( detailed && !doc.mDescription.isEmpty() )
  1839. Con::printf( " %s", doc.mDescription.c_str() );
  1840. }
  1841. }
  1842. }
  1843. //-----------------------------------------------------------------------------
  1844. DefineConsoleMethod( SimObject, save, bool, ( const char* fileName, bool selectedOnly, const char* preAppendString ), ( false, "" ),
  1845. "Save out the object to the given file.\n"
  1846. "@param fileName The name of the file to save to."
  1847. "@param selectedOnly If true, only objects marked as selected will be saved out.\n"
  1848. "@param preAppendString Text which will be preprended directly to the object serialization.\n"
  1849. "@param True on success, false on failure." )
  1850. {
  1851. return object->save( fileName, selectedOnly, preAppendString );
  1852. }
  1853. //-----------------------------------------------------------------------------
  1854. DefineEngineMethod( SimObject, setName, void, ( const char* newName ),,
  1855. "Set the global name of the object.\n"
  1856. "@param newName The new global name to assign to the object.\n"
  1857. "@note If name changing is disallowed on the object, the method will fail with a console error." )
  1858. {
  1859. object->assignName( newName );
  1860. }
  1861. //-----------------------------------------------------------------------------
  1862. DefineEngineMethod( SimObject, getName, const char*, (),,
  1863. "Get the global name of the object.\n"
  1864. "@return The global name assigned to the object." )
  1865. {
  1866. const char *ret = object->getName();
  1867. return ret ? ret : "";
  1868. }
  1869. //-----------------------------------------------------------------------------
  1870. DefineConsoleMethod( SimObject, getClassName, const char*, (),,
  1871. "Get the name of the C++ class which the object is an instance of.\n"
  1872. "@return The name of the C++ class of the object." )
  1873. {
  1874. const char *ret = object->getClassName();
  1875. return ret ? ret : "";
  1876. }
  1877. //-----------------------------------------------------------------------------
  1878. DefineConsoleMethod( SimObject, isField, bool, ( const char* fieldName ),,
  1879. "Test whether the given field is defined on this object.\n"
  1880. "@param fieldName The name of the field.\n"
  1881. "@return True if the object implements the given field." )
  1882. {
  1883. return object->isField( fieldName );
  1884. }
  1885. //-----------------------------------------------------------------------------
  1886. DefineConsoleMethod( SimObject, getFieldValue, const char*, ( const char* fieldName, S32 index ), ( -1 ),
  1887. "Return the value of the given field on this object.\n"
  1888. "@param fieldName The name of the field. If it includes a field index, the index is parsed out.\n"
  1889. "@param index Optional parameter to specify the index of an array field separately.\n"
  1890. "@return The value of the given field or \"\" if undefined." )
  1891. {
  1892. char fieldNameBuffer[ 1024 ];
  1893. char arrayIndexBuffer[ 64 ];
  1894. // Parse out index if the field is given in the form of 'name[index]'.
  1895. const char* arrayIndex = NULL;
  1896. const U32 nameLen = dStrlen( fieldName );
  1897. if( fieldName[ nameLen - 1 ] == ']' )
  1898. {
  1899. const char* leftBracket = dStrchr( fieldName, '[' );
  1900. const char* rightBracket = &fieldName[ nameLen - 1 ];
  1901. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  1902. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  1903. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  1904. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  1905. fieldNameBuffer[ fieldNameLen ] = '\0';
  1906. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  1907. fieldName = fieldNameBuffer;
  1908. arrayIndex = arrayIndexBuffer;
  1909. }
  1910. fieldName = StringTable->insert( fieldName );
  1911. if( index != -1 )
  1912. {
  1913. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  1914. arrayIndex = arrayIndexBuffer;
  1915. }
  1916. return object->getDataField( fieldName, arrayIndex );
  1917. }
  1918. //-----------------------------------------------------------------------------
  1919. DefineConsoleMethod( SimObject, setFieldValue, bool, ( const char* fieldName, const char* value, S32 index ), ( -1 ),
  1920. "Set the value of the given field on this object.\n"
  1921. "@param fieldName The name of the field to assign to. If it includes an array index, the index will be parsed out.\n"
  1922. "@param value The new value to assign to the field.\n"
  1923. "@param index Optional argument to specify an index for an array field.\n"
  1924. "@return True." )
  1925. {
  1926. char fieldNameBuffer[ 1024 ];
  1927. char arrayIndexBuffer[ 64 ];
  1928. // Parse out index if the field is given in the form of 'name[index]'.
  1929. const char* arrayIndex = NULL;
  1930. const U32 nameLen = dStrlen( fieldName );
  1931. if( fieldName[ nameLen - 1 ] == ']' )
  1932. {
  1933. const char* leftBracket = dStrchr( fieldName, '[' );
  1934. const char* rightBracket = &fieldName[ nameLen - 1 ];
  1935. const U32 fieldNameLen = getMin( U32( leftBracket - fieldName ), sizeof( fieldNameBuffer ) - 1 );
  1936. const U32 arrayIndexLen = getMin( U32( rightBracket - leftBracket - 1 ), sizeof( arrayIndexBuffer ) - 1 );
  1937. dMemcpy( fieldNameBuffer, fieldName, fieldNameLen );
  1938. dMemcpy( arrayIndexBuffer, leftBracket + 1, arrayIndexLen );
  1939. fieldNameBuffer[ fieldNameLen ] = '\0';
  1940. arrayIndexBuffer[ arrayIndexLen ] = '\0';
  1941. fieldName = fieldNameBuffer;
  1942. arrayIndex = arrayIndexBuffer;
  1943. }
  1944. fieldName = StringTable->insert( fieldName );
  1945. if( index != -1 )
  1946. {
  1947. dSprintf( arrayIndexBuffer, sizeof( arrayIndexBuffer ), "%i", index );
  1948. arrayIndex = arrayIndexBuffer;
  1949. }
  1950. object->setDataField( fieldName, arrayIndex, value );
  1951. return true;
  1952. }
  1953. //-----------------------------------------------------------------------------
  1954. DefineConsoleMethod( SimObject, getFieldType, const char*, ( const char* fieldName ),,
  1955. "Get the console type code of the given field.\n"
  1956. "@return The numeric type code for the underlying console type of the given field." )
  1957. {
  1958. U32 typeID = object->getDataFieldType( StringTable->insert( fieldName ), NULL );
  1959. ConsoleBaseType* type = ConsoleBaseType::getType( typeID );
  1960. if( type )
  1961. return type->getTypeName();
  1962. return "";
  1963. }
  1964. //-----------------------------------------------------------------------------
  1965. DefineConsoleMethod( SimObject, setFieldType, void, ( const char* fieldName, const char* type ),,
  1966. "Set the console type code for the given field.\n"
  1967. "@param fieldName The name of the dynamic field to change to type for.\n"
  1968. "@param type The name of the console type.\n"
  1969. "@note This only works for dynamic fields. Types of static fields cannot be changed." )
  1970. {
  1971. object->setDataFieldType( type, StringTable->insert( fieldName ), NULL );
  1972. }
  1973. //-----------------------------------------------------------------------------
  1974. ConsoleMethod( SimObject, call, const char*, 3, 0, "( string method, string args... ) Dynamically call a method on an object.\n"
  1975. "@param method Name of method to call.\n"
  1976. "@param args Zero or more arguments for the method.\n"
  1977. "@return The result of the method call." )
  1978. {
  1979. argv[1] = argv[2];
  1980. return Con::execute( object, argc - 1, argv + 1 );
  1981. }
  1982. //-----------------------------------------------------------------------------
  1983. DefineEngineMethod( SimObject, setInternalName, void, ( const char* newInternalName ),,
  1984. "Set the internal name of the object.\n"
  1985. "@param newInternalName The new internal name for the object." )
  1986. {
  1987. object->setInternalName( newInternalName );
  1988. }
  1989. //-----------------------------------------------------------------------------
  1990. DefineEngineMethod( SimObject, getInternalName, const char*, (),,
  1991. "Get the internal name of the object.\n"
  1992. "@return The internal name of the object." )
  1993. {
  1994. return object->getInternalName();
  1995. }
  1996. //-----------------------------------------------------------------------------
  1997. DefineConsoleMethod( SimObject, dumpClassHierarchy, void, (),,
  1998. "Dump the native C++ class hierarchy of this object's C++ class to the console." )
  1999. {
  2000. object->dumpClassHierarchy();
  2001. }
  2002. //-----------------------------------------------------------------------------
  2003. DefineConsoleMethod( SimObject, isMemberOfClass, bool, ( const char* className ),,
  2004. "Test whether this object is a member of the specified class.\n"
  2005. "@param className Name of a native C++ class.\n"
  2006. "@return True if this object is an instance of the given C++ class or any of its super classes." )
  2007. {
  2008. AbstractClassRep* pRep = object->getClassRep();
  2009. while(pRep)
  2010. {
  2011. if( !dStricmp(pRep->getClassName(), className ) )
  2012. {
  2013. //matches
  2014. return true;
  2015. }
  2016. pRep = pRep->getParentClass();
  2017. }
  2018. return false;
  2019. }
  2020. //-----------------------------------------------------------------------------
  2021. DefineConsoleMethod( SimObject, isInNamespaceHierarchy, bool, ( const char* name ),,
  2022. "Test whether the namespace of this object is a direct or indirect child to the given namespace.\n"
  2023. "@param name The name of a namespace.\n"
  2024. "@return True if the given namespace name is within the namespace hierarchy of this object." )
  2025. {
  2026. Namespace* nspace = object->getNamespace();
  2027. while( nspace && dStricmp( nspace->mName, name ) != 0 )
  2028. nspace = nspace->mParent;
  2029. return ( nspace != NULL );
  2030. }
  2031. //-----------------------------------------------------------------------------
  2032. DefineEngineMethod( SimObject, getId, S32, (),,
  2033. "Get the underlying unique numeric ID of the object.\n"
  2034. "@note Object IDs are unique only during single engine runs.\n"
  2035. "@return The unique numeric ID of the object." )
  2036. {
  2037. return object->getId();
  2038. }
  2039. //-----------------------------------------------------------------------------
  2040. DefineEngineMethod( SimObject, getGroup, SimGroup*, (),,
  2041. "Get the group that this object is contained in.\n"
  2042. "@note If not assigned to particular SimGroup, an object belongs to RootGroup.\n"
  2043. "@return The SimGroup object to which the object belongs." )
  2044. {
  2045. return object->getGroup();
  2046. }
  2047. //-----------------------------------------------------------------------------
  2048. DefineConsoleMethod( SimObject, delete, void, (),,
  2049. "Delete and remove the object." )
  2050. {
  2051. object->deleteObject();
  2052. }
  2053. //-----------------------------------------------------------------------------
  2054. ConsoleMethod( SimObject,schedule, S32, 4, 0, "( float time, string method, string args... ) Delay an invocation of a method.\n"
  2055. "@param time The number of milliseconds after which to invoke the method. This is a soft limit.\n"
  2056. "@param method The method to call.\n"
  2057. "@param args The arguments with which to call the method.\n"
  2058. "@return The numeric ID of the created schedule. Can be used to cancel the call.\n" )
  2059. {
  2060. U32 timeDelta = U32(dAtof(argv[2]));
  2061. argv[2] = argv[3];
  2062. argv[3] = argv[1];
  2063. SimConsoleEvent *evt = new SimConsoleEvent(argc - 2, argv + 2, true);
  2064. S32 ret = Sim::postEvent(object, evt, Sim::getCurrentTime() + timeDelta);
  2065. // #ifdef DEBUG
  2066. // Con::printf("obj %s schedule(%s) = %d", argv[3], argv[2], ret);
  2067. // Con::executef( "backtrace");
  2068. // #endif
  2069. return ret;
  2070. }
  2071. //-----------------------------------------------------------------------------
  2072. DefineConsoleMethod( SimObject, getDynamicFieldCount, S32, (),,
  2073. "Get the number of dynamic fields defined on the object.\n"
  2074. "@return The number of dynamic fields defined on the object." )
  2075. {
  2076. S32 count = 0;
  2077. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2078. for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
  2079. count++;
  2080. return count;
  2081. }
  2082. //-----------------------------------------------------------------------------
  2083. DefineConsoleMethod( SimObject, getDynamicField, const char*, ( S32 index ),,
  2084. "Get a value of a dynamic field by index.\n"
  2085. "@param index The index of the dynamic field.\n"
  2086. "@return The value of the dynamic field at the given index or \"\"." )
  2087. {
  2088. SimFieldDictionary* fieldDictionary = object->getFieldDictionary();
  2089. SimFieldDictionaryIterator itr(fieldDictionary);
  2090. for (S32 i = 0; i < index; i++)
  2091. {
  2092. if (!(*itr))
  2093. {
  2094. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2095. return NULL;
  2096. }
  2097. ++itr;
  2098. }
  2099. static const U32 bufSize = 256;
  2100. char* buffer = Con::getReturnBuffer(bufSize);
  2101. if (*itr)
  2102. {
  2103. SimFieldDictionary::Entry* entry = *itr;
  2104. dSprintf(buffer, bufSize, "%s\t%s", entry->slotName, entry->value);
  2105. return buffer;
  2106. }
  2107. Con::warnf("Invalid dynamic field index passed to SimObject::getDynamicField!");
  2108. return NULL;
  2109. }
  2110. //-----------------------------------------------------------------------------
  2111. DefineConsoleMethod( SimObject, getFieldCount, S32, (),,
  2112. "Get the number of static fields on the object.\n"
  2113. "@return The number of static fields defined on the object." )
  2114. {
  2115. const AbstractClassRep::FieldList &list = object->getFieldList();
  2116. const AbstractClassRep::Field* f;
  2117. U32 numDummyEntries = 0;
  2118. for(S32 i = 0; i < list.size(); i++)
  2119. {
  2120. f = &list[i];
  2121. // The special field types do not need to be counted.
  2122. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2123. numDummyEntries++;
  2124. }
  2125. return list.size() - numDummyEntries;
  2126. }
  2127. //-----------------------------------------------------------------------------
  2128. DefineConsoleMethod( SimObject, getField, const char*, ( S32 index ),,
  2129. "Retrieve the value of a static field by index.\n"
  2130. "@param index The index of the static field.\n"
  2131. "@return The value of the static field with the given index or \"\"." )
  2132. {
  2133. const AbstractClassRep::FieldList &list = object->getFieldList();
  2134. if( ( index < 0 ) || ( index >= list.size() ) )
  2135. return "";
  2136. const AbstractClassRep::Field* f;
  2137. S32 currentField = 0;
  2138. for ( U32 i = 0; i < list.size() && currentField <= index; i++ )
  2139. {
  2140. f = &list[i];
  2141. // The special field types can be skipped.
  2142. if ( f->type >= AbstractClassRep::ARCFirstCustomField )
  2143. continue;
  2144. if(currentField == index)
  2145. return f->pFieldname;
  2146. currentField++;
  2147. }
  2148. // if we found nada, return nada.
  2149. return "";
  2150. }
  2151. //-----------------------------------------------------------------------------
  2152. #ifdef TORQUE_DEBUG
  2153. DefineEngineMethod( SimObject, getDebugInfo, ArrayObject*, (),,
  2154. "Return some behind-the-scenes information on the object.\n"
  2155. "@return An ArrayObject filled with internal information about the object." )
  2156. {
  2157. ArrayObject* array = new ArrayObject();
  2158. array->registerObject();
  2159. array->push_back( "C++|Address", String::ToString( "0x%x", object ) );
  2160. array->push_back( "C++|Size", String::ToString( object->getClassRep()->getSizeof() ) );
  2161. array->push_back( "Object|Description", object->describeSelf() );
  2162. array->push_back( "Object|FileName", object->getFilename() );
  2163. array->push_back( "Object|DeclarationLine", String::ToString( object->getDeclarationLine() ) );
  2164. array->push_back( "Object|CopySource", object->getCopySource() ?
  2165. String::ToString( "%i:%s (%s)", object->getCopySource()->getId(), object->getCopySource()->getClassName(), object->getCopySource()->getName() ) : "" );
  2166. array->push_back( "Flag|EditorOnly", object->isEditorOnly() ? "true" : "false" );
  2167. array->push_back( "Flag|NameChangeAllowed", object->isNameChangeAllowed() ? "true" : "false" );
  2168. array->push_back( "Flag|AutoDelete", object->isAutoDeleted() ? "true" : "false" );
  2169. array->push_back( "Flag|Selected", object->isSelected() ? "true" : "false" );
  2170. array->push_back( "Flag|Expanded", object->isExpanded() ? "true" : "false" );
  2171. array->push_back( "Flag|ModStaticFields", object->canModStaticFields() ? "true" : "false" );
  2172. array->push_back( "Flag|ModDynamicFields", object->canModDynamicFields() ? "true" : "false" );
  2173. array->push_back( "Flag|CanSave", object->getCanSave() ? "true" : "false" );
  2174. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  2175. Memory::Info memInfo;
  2176. Memory::getMemoryInfo( object, memInfo );
  2177. array->push_back( "Memory|AllocNumber", String::ToString( memInfo.mAllocNumber ) );
  2178. array->push_back( "Memory|AllocSize", String::ToString( memInfo.mAllocSize ) );
  2179. array->push_back( "Memory|AllocFile", memInfo.mFileName );
  2180. array->push_back( "Memory|AllocLine", String::ToString( memInfo.mLineNumber ) );
  2181. array->push_back( "Memory|IsGlobal", memInfo.mIsGlobal ? "true" : "false" );
  2182. array->push_back( "Memory|IsStatic", memInfo.mIsStatic ? "true" : "false" );
  2183. #endif
  2184. return array;
  2185. }
  2186. #endif