simObject.cpp 100 KB

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