simObject.cpp 105 KB

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