simObject.cpp 113 KB

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