simObject.cpp 100 KB

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