simObject.cpp 100 KB

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