simObject.cpp 100 KB

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