simObject.cpp 105 KB

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