simObject.cpp 105 KB

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