simObject.cpp 108 KB

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