PythonUtil.py 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782
  1. """Undocumented Module"""
  2. __all__ = ['enumerate', 'unique', 'indent', 'nonRepeatingRandomList',
  3. 'writeFsmTree', 'StackTrace', 'traceFunctionCall', 'traceParentCall',
  4. 'printThisCall', 'tron', 'trace', 'troff', 'getClassLineage', 'pdir',
  5. '_pdir', '_is_variadic', '_has_keywordargs', '_varnames', '_getcode',
  6. 'Signature', 'doc', 'adjust', 'difference', 'intersection', 'union',
  7. 'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
  8. 'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
  9. 'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src',
  10. 'closestDestAngle2', 'closestDestAngle', 'binaryRepr', 'profileFunc',
  11. 'profiled', 'startProfile', 'printProfile', 'getSetterName',
  12. 'getSetter', 'Functor', 'Stack', 'Queue', 'ParamObj',
  13. 'POD', 'bound', 'lerp', 'average', 'addListsByValue',
  14. 'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
  15. 'stackEntryInfo', 'lineInfo', 'callerInfo', 'lineTag',
  16. 'findPythonModule', 'describeException', 'mostDerivedLast',
  17. 'clampScalar', 'weightedChoice', 'randFloat', 'normalDistrib',
  18. 'weightedRand', 'randUint31', 'randInt32', 'randUint32',
  19. 'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
  20. 'SingletonError', 'printListEnum', 'gcDebugOn', 'safeRepr',
  21. 'fastRepr', 'tagRepr', 'tagWithCaller', 'isDefaultValue', 'set_trace', 'pm',
  22. 'ScratchPad', 'Sync', 'RefCounter', 'itype', 'getNumberedTypedString',
  23. 'getNumberedTypedSortedString', 'getNumberedTypedSortedStringWithReferrers',
  24. 'getNumberedTypedSortedStringWithReferrersGen',
  25. 'printNumberedTyped', 'DelayedCall', 'DelayedFunctor',
  26. 'FrameDelayedCall', 'SubframeCall', 'ArgumentEater', 'ClassTree', 'getBase',
  27. 'superFlattenShip','HotkeyBreaker','logMethodCalls','GoldenRatio',
  28. 'GoldenRectangle', 'pivotScalar', 'rad90', 'rad180', 'rad270', 'rad360',
  29. 'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel', 'choice',
  30. 'printStack', 'printReverseStack', 'listToIndex2item', 'listToItem2index',
  31. 'pandaBreak','pandaTrace','formatTimeCompact','DestructiveScratchPad',
  32. 'deeptype','getProfileResultString','StdoutCapture','StdoutPassthrough',
  33. 'Averager',]
  34. import types
  35. import string
  36. import re
  37. import math
  38. import operator
  39. import inspect
  40. import os
  41. import sys
  42. import random
  43. import time
  44. import new
  45. import gc
  46. #if __debug__:
  47. import traceback
  48. import __builtin__
  49. import profile
  50. import pstats
  51. from StringIO import StringIO
  52. import marshal
  53. from direct.directutil import Verify
  54. # Don't import libpandaexpressModules, which doesn't get built until
  55. # genPyCode.
  56. import direct.extensions_native.extension_native_helpers
  57. from libpandaexpress import ConfigVariableBool
  58. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  59. import __builtin__
  60. if not hasattr(__builtin__, 'enumerate'):
  61. def enumerate(L):
  62. """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax:
  63. for i, item in enumerate(L):
  64. ...
  65. enumerate is a built-in feature in Python 2.3, which implements it
  66. using an iterator. For now, we can use this quick & dirty
  67. implementation that returns a list of tuples that is completely
  68. constructed every time enumerate() is called.
  69. """
  70. return zip(xrange(len(L)), L)
  71. __builtin__.enumerate = enumerate
  72. else:
  73. enumerate = __builtin__.enumerate
  74. """
  75. # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
  76. def Functor(function, *args, **kArgs):
  77. argsCopy = args[:]
  78. def functor(*cArgs, **ckArgs):
  79. kArgs.update(ckArgs)
  80. return function(*(argsCopy + cArgs), **kArgs)
  81. return functor
  82. """
  83. class Functor:
  84. def __init__(self, function, *args, **kargs):
  85. assert callable(function), "function should be a callable obj"
  86. self._function = function
  87. self._args = args
  88. self._kargs = kargs
  89. if hasattr(self._function, '__name__'):
  90. self.__name__ = self._function.__name__
  91. else:
  92. self.__name__ = str(itype(self._function))
  93. if hasattr(self._function, '__doc__'):
  94. self.__doc__ = self._function.__doc__
  95. else:
  96. self.__doc__ = self.__name__
  97. def destroy(self):
  98. del self._function
  99. del self._args
  100. del self._kargs
  101. del self.__name__
  102. del self.__doc__
  103. def _do__call__(self, *args, **kargs):
  104. _kargs = self._kargs.copy()
  105. _kargs.update(kargs)
  106. return self._function(*(self._args + args), **_kargs)
  107. # this method is used in place of __call__ if we are recording creation stacks
  108. def _exceptionLoggedCreationStack__call__(self, *args, **kargs):
  109. try:
  110. return self._do__call__(*args, **kargs)
  111. except Exception, e:
  112. print '-->Functor creation stack (%s): %s' % (
  113. self.__name__, self.getCreationStackTraceCompactStr())
  114. raise
  115. __call__ = _do__call__
  116. def __repr__(self):
  117. s = 'Functor(%s' % self._function.__name__
  118. for arg in self._args:
  119. try:
  120. argStr = repr(arg)
  121. except:
  122. argStr = 'bad repr: %s' % arg.__class__
  123. s += ', %s' % argStr
  124. for karg, value in self._kargs.items():
  125. s += ', %s=%s' % (karg, repr(value))
  126. s += ')'
  127. return s
  128. class Stack:
  129. def __init__(self):
  130. self.__list = []
  131. def push(self, item):
  132. self.__list.append(item)
  133. def top(self):
  134. # return the item on the top of the stack without popping it off
  135. return self.__list[-1]
  136. def pop(self):
  137. return self.__list.pop()
  138. def clear(self):
  139. self.__list = []
  140. def isEmpty(self):
  141. return len(self.__list) == 0
  142. def __len__(self):
  143. return len(self.__list)
  144. class Queue:
  145. # FIFO queue
  146. # interface is intentionally identical to Stack (LIFO)
  147. def __init__(self):
  148. self.__list = []
  149. def push(self, item):
  150. self.__list.append(item)
  151. def top(self):
  152. # return the next item at the front of the queue without popping it off
  153. return self.__list[0]
  154. def front(self):
  155. return self.__list[0]
  156. def back(self):
  157. return self.__list[-1]
  158. def pop(self):
  159. return self.__list.pop(0)
  160. def clear(self):
  161. self.__list = []
  162. def isEmpty(self):
  163. return len(self.__list) == 0
  164. def __len__(self):
  165. return len(self.__list)
  166. if __debug__:
  167. q = Queue()
  168. assert q.isEmpty()
  169. q.clear()
  170. assert q.isEmpty()
  171. q.push(10)
  172. assert not q.isEmpty()
  173. q.push(20)
  174. assert not q.isEmpty()
  175. assert len(q) == 2
  176. assert q.front() == 10
  177. assert q.back() == 20
  178. assert q.top() == 10
  179. assert q.top() == 10
  180. assert q.pop() == 10
  181. assert len(q) == 1
  182. assert not q.isEmpty()
  183. assert q.pop() == 20
  184. assert len(q) == 0
  185. assert q.isEmpty()
  186. def unique(L1, L2):
  187. """Return a list containing all items in 'L1' that are not in 'L2'"""
  188. L2 = dict([(k, None) for k in L2])
  189. return [item for item in L1 if item not in L2]
  190. def indent(stream, numIndents, str):
  191. """
  192. Write str to stream with numIndents in front of it
  193. """
  194. # To match emacs, instead of a tab character we will use 4 spaces
  195. stream.write(' ' * numIndents + str)
  196. def nonRepeatingRandomList(vals, max):
  197. random.seed(time.time())
  198. #first generate a set of random values
  199. valueList=range(max)
  200. finalVals=[]
  201. for i in range(vals):
  202. index=int(random.random()*len(valueList))
  203. finalVals.append(valueList[index])
  204. valueList.remove(valueList[index])
  205. return finalVals
  206. def writeFsmTree(instance, indent = 0):
  207. if hasattr(instance, 'parentFSM'):
  208. writeFsmTree(instance.parentFSM, indent-2)
  209. elif hasattr(instance, 'fsm'):
  210. name = ''
  211. if hasattr(instance.fsm, 'state'):
  212. name = instance.fsm.state.name
  213. print "%s: %s"%(instance.fsm.name, name)
  214. #if __debug__: #RAU accdg to Darren its's ok that StackTrace is not protected by __debug__
  215. # DCR: if somebody ends up using StackTrace in production, either
  216. # A) it will be OK because it hardly ever gets called, or
  217. # B) it will be easy to track it down (grep for StackTrace)
  218. class StackTrace:
  219. def __init__(self, label="", start=0, limit=None):
  220. """
  221. label is a string (or anything that be be a string)
  222. that is printed as part of the trace back.
  223. This is just to make it easier to tell what the
  224. stack trace is referring to.
  225. start is an integer number of stack frames back
  226. from the most recent. (This is automatically
  227. bumped up by one to skip the __init__ call
  228. to the StackTrace).
  229. limit is an integer number of stack frames
  230. to record (or None for unlimited).
  231. """
  232. self.label = label
  233. if limit is not None:
  234. self.trace = traceback.extract_stack(sys._getframe(1+start),
  235. limit=limit)
  236. else:
  237. self.trace = traceback.extract_stack(sys._getframe(1+start))
  238. def compact(self):
  239. r = ''
  240. comma = ','
  241. for filename, lineNum, funcName, text in self.trace:
  242. r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
  243. if len(r):
  244. r = r[:-len(comma)]
  245. return r
  246. def reverseCompact(self):
  247. r = ''
  248. comma = ','
  249. for filename, lineNum, funcName, text in self.trace:
  250. r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
  251. if len(r):
  252. r = r[:-len(comma)]
  253. return r
  254. def __str__(self):
  255. r = "Debug stack trace of %s (back %s frames):\n"%(
  256. self.label, len(self.trace),)
  257. for i in traceback.format_list(self.trace):
  258. r+=i
  259. r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
  260. return r
  261. def printStack():
  262. print StackTrace(start=1).compact()
  263. return True
  264. def printReverseStack():
  265. print StackTrace(start=1).reverseCompact()
  266. return True
  267. def printVerboseStack():
  268. print StackTrace(start=1)
  269. return True
  270. #-----------------------------------------------------------------------------
  271. def traceFunctionCall(frame):
  272. """
  273. return a string that shows the call frame with calling arguments.
  274. e.g.
  275. foo(x=234, y=135)
  276. """
  277. f = frame
  278. co = f.f_code
  279. dict = f.f_locals
  280. n = co.co_argcount
  281. if co.co_flags & 4: n = n+1
  282. if co.co_flags & 8: n = n+1
  283. r=''
  284. if dict.has_key('self'):
  285. r = '%s.'%(dict['self'].__class__.__name__,)
  286. r+="%s("%(f.f_code.co_name,)
  287. comma=0 # formatting, whether we should type a comma.
  288. for i in range(n):
  289. name = co.co_varnames[i]
  290. if name=='self':
  291. continue
  292. if comma:
  293. r+=', '
  294. else:
  295. # ok, we skipped the first one, the rest get commas:
  296. comma=1
  297. r+=name
  298. r+='='
  299. if dict.has_key(name):
  300. v=str(dict[name])
  301. if len(v)>2000:
  302. # r+="<too big for debug>"
  303. r += (str(dict[name])[:2000] + "...")
  304. else:
  305. r+=str(dict[name])
  306. else: r+="*** undefined ***"
  307. return r+')'
  308. def traceParentCall():
  309. return traceFunctionCall(sys._getframe(2))
  310. def printThisCall():
  311. print traceFunctionCall(sys._getframe(1))
  312. return 1 # to allow "assert printThisCall()"
  313. if __debug__:
  314. def lineage(obj, verbose=0, indent=0):
  315. """
  316. return instance or class name in as a multiline string.
  317. Usage: print lineage(foo)
  318. (Based on getClassLineage())
  319. """
  320. r=""
  321. if type(obj) == types.ListType:
  322. r+=(" "*indent)+"python list\n"
  323. elif type(obj) == types.DictionaryType:
  324. r+=(" "*indent)+"python dictionary\n"
  325. elif type(obj) == types.ModuleType:
  326. r+=(" "*indent)+str(obj)+"\n"
  327. elif type(obj) == types.InstanceType:
  328. r+=lineage(obj.__class__, verbose, indent)
  329. elif type(obj) == types.ClassType:
  330. r+=(" "*indent)
  331. if verbose:
  332. r+=obj.__module__+"."
  333. r+=obj.__name__+"\n"
  334. for c in obj.__bases__:
  335. r+=lineage(c, verbose, indent+2)
  336. return r
  337. def tron():
  338. sys.settrace(trace)
  339. def trace(frame, event, arg):
  340. if event == 'line':
  341. pass
  342. elif event == 'call':
  343. print traceFunctionCall(sys._getframe(1))
  344. elif event == 'return':
  345. print "returning"
  346. elif event == 'exception':
  347. print "exception"
  348. return trace
  349. def troff():
  350. sys.settrace(None)
  351. #-----------------------------------------------------------------------------
  352. def getClassLineage(obj):
  353. """
  354. print object inheritance list
  355. """
  356. if type(obj) == types.DictionaryType:
  357. # Just a dictionary, return dictionary
  358. return [obj]
  359. elif (type(obj) == types.InstanceType):
  360. # Instance, make a list with the instance and its class interitance
  361. return [obj] + getClassLineage(obj.__class__)
  362. elif ((type(obj) == types.ClassType) or
  363. (type(obj) == types.TypeType)):
  364. # Class or type, see what it derives from
  365. lineage = [obj]
  366. for c in obj.__bases__:
  367. lineage = lineage + getClassLineage(c)
  368. return lineage
  369. # New FFI objects are types that are not defined.
  370. # but they still act like classes
  371. elif hasattr(obj, '__class__'):
  372. # Instance, make a list with the instance and its class interitance
  373. return [obj] + getClassLineage(obj.__class__)
  374. else:
  375. # Not what I'm looking for
  376. return []
  377. def pdir(obj, str = None, width = None,
  378. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  379. # Remove redundant class entries
  380. uniqueLineage = []
  381. for l in getClassLineage(obj):
  382. if type(l) == types.ClassType:
  383. if l in uniqueLineage:
  384. break
  385. uniqueLineage.append(l)
  386. # Pretty print out directory info
  387. uniqueLineage.reverse()
  388. for obj in uniqueLineage:
  389. _pdir(obj, str, width, fTruncate, lineWidth, wantPrivate)
  390. print
  391. def _pdir(obj, str = None, width = None,
  392. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  393. """
  394. Print out a formatted list of members and methods of an instance or class
  395. """
  396. def printHeader(name):
  397. name = ' ' + name + ' '
  398. length = len(name)
  399. if length < 70:
  400. padBefore = int((70 - length)/2.0)
  401. padAfter = max(0, 70 - length - padBefore)
  402. header = '*' * padBefore + name + '*' * padAfter
  403. print header
  404. print
  405. def printInstanceHeader(i, printHeader = printHeader):
  406. printHeader(i.__class__.__name__ + ' INSTANCE INFO')
  407. def printClassHeader(c, printHeader = printHeader):
  408. printHeader(c.__name__ + ' CLASS INFO')
  409. def printDictionaryHeader(d, printHeader = printHeader):
  410. printHeader('DICTIONARY INFO')
  411. # Print Header
  412. if type(obj) == types.InstanceType:
  413. printInstanceHeader(obj)
  414. elif type(obj) == types.ClassType:
  415. printClassHeader(obj)
  416. elif type (obj) == types.DictionaryType:
  417. printDictionaryHeader(obj)
  418. # Get dict
  419. if type(obj) == types.DictionaryType:
  420. dict = obj
  421. # FFI objects are builtin types, they have no __dict__
  422. elif not hasattr(obj, '__dict__'):
  423. dict = {}
  424. else:
  425. dict = obj.__dict__
  426. # Adjust width
  427. if width:
  428. maxWidth = width
  429. else:
  430. maxWidth = 10
  431. keyWidth = 0
  432. aproposKeys = []
  433. privateKeys = []
  434. remainingKeys = []
  435. for key in dict.keys():
  436. if not width:
  437. keyWidth = len(key)
  438. if str:
  439. if re.search(str, key, re.I):
  440. aproposKeys.append(key)
  441. if (not width) and (keyWidth > maxWidth):
  442. maxWidth = keyWidth
  443. else:
  444. if key[:1] == '_':
  445. if wantPrivate:
  446. privateKeys.append(key)
  447. if (not width) and (keyWidth > maxWidth):
  448. maxWidth = keyWidth
  449. else:
  450. remainingKeys.append(key)
  451. if (not width) and (keyWidth > maxWidth):
  452. maxWidth = keyWidth
  453. # Sort appropriate keys
  454. if str:
  455. aproposKeys.sort()
  456. else:
  457. privateKeys.sort()
  458. remainingKeys.sort()
  459. # Print out results
  460. if wantPrivate:
  461. keys = aproposKeys + privateKeys + remainingKeys
  462. else:
  463. keys = aproposKeys + remainingKeys
  464. format = '%-' + `maxWidth` + 's'
  465. for key in keys:
  466. value = dict[key]
  467. if callable(value):
  468. strvalue = `Signature(value)`
  469. else:
  470. strvalue = `value`
  471. if fTruncate:
  472. # Cut off line (keeping at least 1 char)
  473. strvalue = strvalue[:max(1, lineWidth - maxWidth)]
  474. print (format % key)[:maxWidth] + '\t' + strvalue
  475. # Magic numbers: These are the bit masks in func_code.co_flags that
  476. # reveal whether or not the function has a *arg or **kw argument.
  477. _POS_LIST = 4
  478. _KEY_DICT = 8
  479. def _is_variadic(function):
  480. return function.func_code.co_flags & _POS_LIST
  481. def _has_keywordargs(function):
  482. return function.func_code.co_flags & _KEY_DICT
  483. def _varnames(function):
  484. return function.func_code.co_varnames
  485. def _getcode(f):
  486. """
  487. _getcode(f)
  488. This function returns the name and function object of a callable
  489. object.
  490. """
  491. def method_get(f):
  492. return f.__name__, f.im_func
  493. def function_get(f):
  494. return f.__name__, f
  495. def instance_get(f):
  496. if hasattr(f, '__call__'):
  497. method = f.__call__
  498. if (type(method) == types.MethodType):
  499. func = method.im_func
  500. else:
  501. func = method
  502. return ("%s%s" % (f.__class__.__name__, '__call__'), func)
  503. else:
  504. s = ("Instance %s of class %s does not have a __call__ method" %
  505. (f, f.__class__.__name__))
  506. raise TypeError, s
  507. def class_get(f):
  508. if hasattr(f, '__init__'):
  509. return f.__name__, f.__init__.im_func
  510. else:
  511. return f.__name__, lambda: None
  512. codedict = { types.UnboundMethodType: method_get,
  513. types.MethodType: method_get,
  514. types.FunctionType: function_get,
  515. types.InstanceType: instance_get,
  516. types.ClassType: class_get,
  517. }
  518. try:
  519. return codedict[type(f)](f)
  520. except KeyError:
  521. if callable(f): # eg, built-in functions and methods
  522. # raise ValueError, "type %s not supported yet." % type(f)
  523. return f.__name__, None
  524. else:
  525. raise TypeError, ("object %s of type %s is not callable." %
  526. (f, type(f)))
  527. class Signature:
  528. def __init__(self, func):
  529. self.type = type(func)
  530. self.name, self.func = _getcode(func)
  531. def ordinary_args(self):
  532. n = self.func.func_code.co_argcount
  533. return _varnames(self.func)[0:n]
  534. def special_args(self):
  535. n = self.func.func_code.co_argcount
  536. x = {}
  537. #
  538. if _is_variadic(self.func):
  539. x['positional'] = _varnames(self.func)[n]
  540. if _has_keywordargs(self.func):
  541. x['keyword'] = _varnames(self.func)[n+1]
  542. elif _has_keywordargs(self.func):
  543. x['keyword'] = _varnames(self.func)[n]
  544. else:
  545. pass
  546. return x
  547. def full_arglist(self):
  548. base = list(self.ordinary_args())
  549. x = self.special_args()
  550. if x.has_key('positional'):
  551. base.append(x['positional'])
  552. if x.has_key('keyword'):
  553. base.append(x['keyword'])
  554. return base
  555. def defaults(self):
  556. defargs = self.func.func_defaults
  557. args = self.ordinary_args()
  558. mapping = {}
  559. if defargs is not None:
  560. for i in range(-1, -(len(defargs)+1), -1):
  561. mapping[args[i]] = defargs[i]
  562. else:
  563. pass
  564. return mapping
  565. def __repr__(self):
  566. if self.func:
  567. defaults = self.defaults()
  568. specials = self.special_args()
  569. l = []
  570. for arg in self.ordinary_args():
  571. if defaults.has_key(arg):
  572. l.append(arg + '=' + str(defaults[arg]))
  573. else:
  574. l.append(arg)
  575. if specials.has_key('positional'):
  576. l.append('*' + specials['positional'])
  577. if specials.has_key('keyword'):
  578. l.append('**' + specials['keyword'])
  579. return "%s(%s)" % (self.name, string.join(l, ', '))
  580. else:
  581. return "%s(?)" % self.name
  582. def doc(obj):
  583. if (isinstance(obj, types.MethodType)) or \
  584. (isinstance(obj, types.FunctionType)):
  585. print obj.__doc__
  586. def adjust(command = None, dim = 1, parent = None, **kw):
  587. """
  588. adjust(command = None, parent = None, **kw)
  589. Popup and entry scale to adjust a parameter
  590. Accepts any Slider keyword argument. Typical arguments include:
  591. command: The one argument command to execute
  592. min: The min value of the slider
  593. max: The max value of the slider
  594. resolution: The resolution of the slider
  595. text: The label on the slider
  596. These values can be accessed and/or changed after the fact
  597. >>> vg = adjust()
  598. >>> vg['min']
  599. 0.0
  600. >>> vg['min'] = 10.0
  601. >>> vg['min']
  602. 10.0
  603. """
  604. # Make sure we enable Tk
  605. from direct.tkwidgets import Valuator
  606. # Set command if specified
  607. if command:
  608. kw['command'] = lambda x: apply(command, x)
  609. if parent is None:
  610. kw['title'] = command.__name__
  611. kw['dim'] = dim
  612. # Create toplevel if needed
  613. if not parent:
  614. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  615. else:
  616. vg = apply(Valuator.ValuatorGroup, (parent,), kw)
  617. vg.pack(expand = 1, fill = 'x')
  618. return vg
  619. def difference(a, b):
  620. """
  621. difference(list, list):
  622. """
  623. if not a: return b
  624. if not b: return a
  625. d = []
  626. for i in a:
  627. if (i not in b) and (i not in d):
  628. d.append(i)
  629. for i in b:
  630. if (i not in a) and (i not in d):
  631. d.append(i)
  632. return d
  633. def intersection(a, b):
  634. """
  635. intersection(list, list):
  636. """
  637. if not a: return []
  638. if not b: return []
  639. d = []
  640. for i in a:
  641. if (i in b) and (i not in d):
  642. d.append(i)
  643. for i in b:
  644. if (i in a) and (i not in d):
  645. d.append(i)
  646. return d
  647. def union(a, b):
  648. """
  649. union(list, list):
  650. """
  651. # Copy a
  652. c = a[:]
  653. for i in b:
  654. if (i not in c):
  655. c.append(i)
  656. return c
  657. def sameElements(a, b):
  658. if len(a) != len(b):
  659. return 0
  660. for elem in a:
  661. if elem not in b:
  662. return 0
  663. for elem in b:
  664. if elem not in a:
  665. return 0
  666. return 1
  667. def makeList(x):
  668. """returns x, converted to a list"""
  669. if type(x) is types.ListType:
  670. return x
  671. elif type(x) is types.TupleType:
  672. return list(x)
  673. else:
  674. return [x,]
  675. def makeTuple(x):
  676. """returns x, converted to a tuple"""
  677. if type(x) is types.ListType:
  678. return tuple(x)
  679. elif type(x) is types.TupleType:
  680. return x
  681. else:
  682. return (x,)
  683. def list2dict(L, value=None):
  684. """creates dict using elements of list, all assigned to same value"""
  685. return dict([(k, value) for k in L])
  686. def listToIndex2item(L):
  687. """converts list to dict of list index->list item"""
  688. d = {}
  689. for i, item in enumerate(L):
  690. d[i] = item
  691. return d
  692. assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
  693. def listToItem2index(L):
  694. """converts list to dict of list item->list index
  695. This is lossy if there are duplicate list items"""
  696. d = {}
  697. for i, item in enumerate(L):
  698. d[item] = i
  699. return d
  700. assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
  701. def invertDict(D, lossy=False):
  702. """creates a dictionary by 'inverting' D; keys are placed in the new
  703. dictionary under their corresponding value in the old dictionary.
  704. It is an error if D contains any duplicate values.
  705. >>> old = {'key1':1, 'key2':2}
  706. >>> invertDict(old)
  707. {1: 'key1', 2: 'key2'}
  708. """
  709. n = {}
  710. for key, value in D.items():
  711. if not lossy and value in n:
  712. raise 'duplicate key in invertDict: %s' % value
  713. n[value] = key
  714. return n
  715. def invertDictLossless(D):
  716. """similar to invertDict, but values of new dict are lists of keys from
  717. old dict. No information is lost.
  718. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  719. >>> invertDictLossless(old)
  720. {1: ['key1'], 2: ['key2', 'keyA']}
  721. """
  722. n = {}
  723. for key, value in D.items():
  724. n.setdefault(value, [])
  725. n[value].append(key)
  726. return n
  727. def uniqueElements(L):
  728. """are all elements of list unique?"""
  729. return len(L) == len(list2dict(L))
  730. def disjoint(L1, L2):
  731. """returns non-zero if L1 and L2 have no common elements"""
  732. used = dict([(k, None) for k in L1])
  733. for k in L2:
  734. if k in used:
  735. return 0
  736. return 1
  737. def contains(whole, sub):
  738. """
  739. Return 1 if whole contains sub, 0 otherwise
  740. """
  741. if (whole == sub):
  742. return 1
  743. for elem in sub:
  744. # The first item you find not in whole, return 0
  745. if elem not in whole:
  746. return 0
  747. # If you got here, whole must contain sub
  748. return 1
  749. def replace(list, old, new, all=0):
  750. """
  751. replace 'old' with 'new' in 'list'
  752. if all == 0, replace first occurrence
  753. otherwise replace all occurrences
  754. returns the number of items replaced
  755. """
  756. if old not in list:
  757. return 0
  758. if not all:
  759. i = list.index(old)
  760. list[i] = new
  761. return 1
  762. else:
  763. numReplaced = 0
  764. for i in xrange(len(list)):
  765. if list[i] == old:
  766. numReplaced += 1
  767. list[i] = new
  768. return numReplaced
  769. rad90 = math.pi / 2.
  770. rad180 = math.pi
  771. rad270 = 1.5 * math.pi
  772. rad360 = 2. * math.pi
  773. def reduceAngle(deg):
  774. """
  775. Reduces an angle (in degrees) to a value in [-180..180)
  776. """
  777. return (((deg + 180.) % 360.) - 180.)
  778. def fitSrcAngle2Dest(src, dest):
  779. """
  780. given a src and destination angle, returns an equivalent src angle
  781. that is within [-180..180) of dest
  782. examples:
  783. fitSrcAngle2Dest(30, 60) == 30
  784. fitSrcAngle2Dest(60, 30) == 60
  785. fitSrcAngle2Dest(0, 180) == 0
  786. fitSrcAngle2Dest(-1, 180) == 359
  787. fitSrcAngle2Dest(-180, 180) == 180
  788. """
  789. return dest + reduceAngle(src - dest)
  790. def fitDestAngle2Src(src, dest):
  791. """
  792. given a src and destination angle, returns an equivalent dest angle
  793. that is within [-180..180) of src
  794. examples:
  795. fitDestAngle2Src(30, 60) == 60
  796. fitDestAngle2Src(60, 30) == 30
  797. fitDestAngle2Src(0, 180) == -180
  798. fitDestAngle2Src(1, 180) == 180
  799. """
  800. return src + (reduceAngle(dest - src))
  801. def closestDestAngle2(src, dest):
  802. # The function above didn't seem to do what I wanted. So I hacked
  803. # this one together. I can't really say I understand it. It's more
  804. # from impirical observation... GRW
  805. diff = src - dest
  806. if diff > 180:
  807. # if the difference is greater that 180 it's shorter to go the other way
  808. return dest - 360
  809. elif diff < -180:
  810. # or perhaps the OTHER other way...
  811. return dest + 360
  812. else:
  813. # otherwise just go to the original destination
  814. return dest
  815. def closestDestAngle(src, dest):
  816. # The function above didn't seem to do what I wanted. So I hacked
  817. # this one together. I can't really say I understand it. It's more
  818. # from impirical observation... GRW
  819. diff = src - dest
  820. if diff > 180:
  821. # if the difference is greater that 180 it's shorter to go the other way
  822. return src - (diff - 360)
  823. elif diff < -180:
  824. # or perhaps the OTHER other way...
  825. return src - (360 + diff)
  826. else:
  827. # otherwise just go to the original destination
  828. return dest
  829. def binaryRepr(number, max_length = 32):
  830. # This will only work reliably for relatively small numbers.
  831. # Increase the value of max_length if you think you're going
  832. # to use long integers
  833. assert number < 2L << max_length
  834. shifts = map (operator.rshift, max_length * [number], \
  835. range (max_length - 1, -1, -1))
  836. digits = map (operator.mod, shifts, max_length * [2])
  837. if not digits.count (1): return 0
  838. digits = digits [digits.index (1):]
  839. return string.join (map (repr, digits), '')
  840. class StdoutCapture:
  841. # redirects stdout to a string
  842. def __init__(self):
  843. self._oldStdout = sys.stdout
  844. sys.stdout = self
  845. self._string = ''
  846. def destroy(self):
  847. sys.stdout = self._oldStdout
  848. del self._oldStdout
  849. def getString(self):
  850. return self._string
  851. # internal
  852. def write(self, string):
  853. self._string = ''.join([self._string, string])
  854. class StdoutPassthrough(StdoutCapture):
  855. # like StdoutCapture but also allows output to go through to the OS as normal
  856. # internal
  857. def write(self, string):
  858. self._string = ''.join([self._string, string])
  859. self._oldStdout.write(string)
  860. # constant profile defaults
  861. PyUtilProfileDefaultFilename = 'profiledata'
  862. PyUtilProfileDefaultLines = 80
  863. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  864. _ProfileResultStr = ''
  865. def getProfileResultString():
  866. # if you called profile with 'log' not set to True,
  867. # you can call this function to get the results as
  868. # a string
  869. global _ProfileResultStr
  870. return _ProfileResultStr
  871. def profileFunc(callback, name, terse, log=True):
  872. global _ProfileResultStr
  873. if 'globalProfileFunc' in __builtin__.__dict__:
  874. # rats. Python profiler is not re-entrant...
  875. base.notify.warning(
  876. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  877. #'\nStack Trace:\n%s'
  878. % (name, __builtin__.globalProfileFunc,
  879. #StackTrace()
  880. ))
  881. return
  882. __builtin__.globalProfileFunc = callback
  883. __builtin__.globalProfileResult = [None]
  884. prefix = '***** START PROFILE: %s *****' % name
  885. if log:
  886. print prefix
  887. startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
  888. suffix = '***** END PROFILE: %s *****' % name
  889. if log:
  890. print suffix
  891. else:
  892. _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
  893. result = globalProfileResult[0]
  894. del __builtin__.__dict__['globalProfileFunc']
  895. del __builtin__.__dict__['globalProfileResult']
  896. return result
  897. def profiled(category=None, terse=False):
  898. """ decorator for profiling functions
  899. turn categories on and off via "want-profile-categoryName 1"
  900. e.g.
  901. @profiled('particles')
  902. def loadParticles():
  903. ...
  904. want-profile-particles 1
  905. """
  906. assert type(category) in (types.StringType, types.NoneType), "must provide a category name for @profiled"
  907. # allow profiling in published versions
  908. """
  909. try:
  910. null = not __dev__
  911. except:
  912. null = not __debug__
  913. if null:
  914. # if we're not in __dev__, just return the function itself. This
  915. # results in zero runtime overhead, since decorators are evaluated
  916. # at module-load.
  917. def nullDecorator(f):
  918. return f
  919. return nullDecorator
  920. """
  921. def profileDecorator(f):
  922. def _profiled(*args, **kArgs):
  923. name = '(%s) %s from %s' % (category, f.func_name, f.__module__)
  924. # showbase might not be loaded yet, so don't use
  925. # base.config. Instead, query the ConfigVariableBool.
  926. if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
  927. return profileFunc(Functor(f, *args, **kArgs), name, terse)
  928. else:
  929. return f(*args, **kArgs)
  930. _profiled.__doc__ = f.__doc__
  931. return _profiled
  932. return profileDecorator
  933. # intercept profile-related file operations to avoid disk access
  934. movedOpenFuncs = []
  935. movedDumpFuncs = []
  936. movedLoadFuncs = []
  937. profileFilenames = set()
  938. profileFilenameList = Stack()
  939. profileFilename2file = {}
  940. profileFilename2marshalData = {}
  941. def _profileOpen(filename, *args, **kArgs):
  942. # this is a replacement for the file open() builtin function
  943. # for use during profiling, to intercept the file open
  944. # operation used by the Python profiler and profile stats
  945. # systems
  946. if filename in profileFilenames:
  947. # if this is a file related to profiling, create an
  948. # in-RAM file object
  949. if filename not in profileFilename2file:
  950. file = StringIO()
  951. file._profFilename = filename
  952. profileFilename2file[filename] = file
  953. else:
  954. file = profileFilename2file[filename]
  955. else:
  956. file = movedOpenFuncs[-1](filename, *args, **kArgs)
  957. return file
  958. def _profileMarshalDump(data, file):
  959. # marshal.dump doesn't work with StringIO objects
  960. # simulate it
  961. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  962. if file._profFilename in profileFilenames:
  963. profileFilename2marshalData[file._profFilename] = data
  964. return None
  965. return movedDumpFuncs[-1](data, file)
  966. def _profileMarshalLoad(file):
  967. # marshal.load doesn't work with StringIO objects
  968. # simulate it
  969. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  970. if file._profFilename in profileFilenames:
  971. return profileFilename2marshalData[file._profFilename]
  972. return movedLoadFuncs[-1](file)
  973. def _installProfileCustomFuncs(filename):
  974. assert filename not in profileFilenames
  975. profileFilenames.add(filename)
  976. profileFilenameList.push(filename)
  977. movedOpenFuncs.append(__builtin__.open)
  978. __builtin__.open = _profileOpen
  979. movedDumpFuncs.append(marshal.dump)
  980. marshal.dump = _profileMarshalDump
  981. movedLoadFuncs.append(marshal.load)
  982. marshal.load = _profileMarshalLoad
  983. def _removeProfileCustomFuncs(filename):
  984. assert profileFilenameList.top() == filename
  985. marshal.load = movedLoadFuncs.pop()
  986. marshal.dump = movedDumpFuncs.pop()
  987. __builtin__.open = movedOpenFuncs.pop()
  988. profileFilenames.remove(filename)
  989. profileFilenameList.pop()
  990. profileFilename2file.pop(filename, None)
  991. # don't let marshalled data pile up
  992. profileFilename2marshalData.pop(filename, None)
  993. # call this from the prompt, and break back out to the prompt
  994. # to stop profiling
  995. #
  996. # OR to do inline profiling, you must make a globally-visible
  997. # function to be profiled, i.e. to profile 'self.load()', do
  998. # something like this:
  999. #
  1000. # def func(self=self):
  1001. # self.load()
  1002. # import __builtin__
  1003. # __builtin__.func = func
  1004. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  1005. # del __builtin__.func
  1006. #
  1007. def _profileWithoutGarbageLeak(cmd, filename):
  1008. # this is necessary because the profile module creates a memory leak
  1009. Profile = profile.Profile
  1010. statement = cmd
  1011. sort = -1
  1012. retVal = None
  1013. #### COPIED FROM profile.run ####
  1014. prof = Profile()
  1015. try:
  1016. prof = prof.run(statement)
  1017. except SystemExit:
  1018. pass
  1019. if filename is not None:
  1020. prof.dump_stats(filename)
  1021. else:
  1022. #return prof.print_stats(sort) #DCR
  1023. retVal = prof.print_stats(sort) #DCR
  1024. #################################
  1025. # eliminate the garbage leak
  1026. del prof.dispatcher
  1027. return retVal
  1028. def startProfile(filename=PyUtilProfileDefaultFilename,
  1029. lines=PyUtilProfileDefaultLines,
  1030. sorts=PyUtilProfileDefaultSorts,
  1031. silent=0,
  1032. callInfo=1,
  1033. useDisk=False,
  1034. cmd='run()'):
  1035. # uniquify the filename to allow multiple processes to profile simultaneously
  1036. filename = '%s.%s%s' % (filename, randUint31(), randUint31())
  1037. if not useDisk:
  1038. # use a RAM file
  1039. _installProfileCustomFuncs(filename)
  1040. _profileWithoutGarbageLeak(cmd, filename)
  1041. if silent:
  1042. extractProfile(filename, lines, sorts, callInfo)
  1043. else:
  1044. printProfile(filename, lines, sorts, callInfo)
  1045. if not useDisk:
  1046. # discard the RAM file
  1047. _removeProfileCustomFuncs(filename)
  1048. else:
  1049. os.remove(filename)
  1050. # call these to see the results again, as a string or in the log
  1051. def printProfile(filename=PyUtilProfileDefaultFilename,
  1052. lines=PyUtilProfileDefaultLines,
  1053. sorts=PyUtilProfileDefaultSorts,
  1054. callInfo=1):
  1055. s = pstats.Stats(filename)
  1056. s.strip_dirs()
  1057. for sort in sorts:
  1058. s.sort_stats(sort)
  1059. s.print_stats(lines)
  1060. if callInfo:
  1061. s.print_callees(lines)
  1062. s.print_callers(lines)
  1063. # same args as printProfile
  1064. def extractProfile(*args, **kArgs):
  1065. global _ProfileResultStr
  1066. # capture print output
  1067. sc = StdoutCapture()
  1068. # print the profile output, redirected to the result string
  1069. printProfile(*args, **kArgs)
  1070. # make a copy of the print output
  1071. _ProfileResultStr = sc.getString()
  1072. # restore stdout to what it was before
  1073. sc.destroy()
  1074. def getSetterName(valueName, prefix='set'):
  1075. # getSetterName('color') -> 'setColor'
  1076. # getSetterName('color', 'get') -> 'getColor'
  1077. return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:])
  1078. def getSetter(targetObj, valueName, prefix='set'):
  1079. # getSetter(smiley, 'pos') -> smiley.setPos
  1080. return getattr(targetObj, getSetterName(valueName, prefix))
  1081. def mostDerivedLast(classList):
  1082. """pass in list of classes. sorts list in-place, with derived classes
  1083. appearing after their bases"""
  1084. def compare(a, b):
  1085. if issubclass(a, b):
  1086. result=1
  1087. elif issubclass(b, a):
  1088. result=-1
  1089. else:
  1090. result=0
  1091. #print a, b, result
  1092. return result
  1093. classList.sort(compare)
  1094. """
  1095. ParamObj/ParamSet
  1096. =================
  1097. These two classes support you in the definition of a formal set of
  1098. parameters for an object type. The parameters may be safely queried/set on
  1099. an object instance at any time, and the object will react to newly-set
  1100. values immediately.
  1101. ParamSet & ParamObj also provide a mechanism for atomically setting
  1102. multiple parameter values before allowing the object to react to any of the
  1103. new values--useful when two or more parameters are interdependent and there
  1104. is risk of setting an illegal combination in the process of applying a new
  1105. set of values.
  1106. To make use of these classes, derive your object from ParamObj. Then define
  1107. a 'ParamSet' subclass that derives from the parent class' 'ParamSet' class,
  1108. and define the object's parameters within its ParamSet class. (see examples
  1109. below)
  1110. The ParamObj base class provides 'get' and 'set' functions for each
  1111. parameter if they are not defined. These default implementations
  1112. respectively set the parameter value directly on the object, and expect the
  1113. value to be available in that location for retrieval.
  1114. Classes that derive from ParamObj can optionally declare a 'get' and 'set'
  1115. function for each parameter. The setter should simply store the value in a
  1116. location where the getter can find it; it should not do any further
  1117. processing based on the new parameter value. Further processing should be
  1118. implemented in an 'apply' function. The applier function is optional, and
  1119. there is no default implementation.
  1120. NOTE: the previous value of a parameter is available inside an apply
  1121. function as 'self.getPriorValue()'
  1122. The ParamSet class declaration lists the parameters and defines a default
  1123. value for each. ParamSet instances represent a complete set of parameter
  1124. values. A ParamSet instance created with no constructor arguments will
  1125. contain the default values for each parameter. The defaults may be
  1126. overriden by passing keyword arguments to the ParamSet's constructor. If a
  1127. ParamObj instance is passed to the constructor, the ParamSet will extract
  1128. the object's current parameter values.
  1129. ParamSet.applyTo(obj) sets all of its parameter values on 'obj'.
  1130. SETTERS AND APPLIERS
  1131. ====================
  1132. Under normal conditions, a call to a setter function, i.e.
  1133. cam.setFov(90)
  1134. will actually result in the following calls being made:
  1135. cam.setFov(90)
  1136. cam.applyFov()
  1137. Calls to several setter functions, i.e.
  1138. cam.setFov(90)
  1139. cam.setViewType('cutscene')
  1140. will result in this call sequence:
  1141. cam.setFov(90)
  1142. cam.applyFov()
  1143. cam.setViewType('cutscene')
  1144. cam.applyViewType()
  1145. Suppose that you desire the view type to already be set to 'cutscene' at
  1146. the time when applyFov() is called. You could reverse the order of the set
  1147. calls, but suppose that you also want the fov to be set properly at the
  1148. time when applyViewType() is called.
  1149. In this case, you can 'lock' the params, i.e.
  1150. cam.lockParams()
  1151. cam.setFov(90)
  1152. cam.setViewType('cutscene')
  1153. cam.unlockParams()
  1154. This will result in the following call sequence:
  1155. cam.setFov(90)
  1156. cam.setViewType('cutscene')
  1157. cam.applyFov()
  1158. cam.applyViewType()
  1159. NOTE: Currently the order of the apply calls following an unlock is not
  1160. guaranteed.
  1161. EXAMPLE CLASSES
  1162. ===============
  1163. Here is an example of a class that uses ParamSet/ParamObj to manage its
  1164. parameters:
  1165. class Camera(ParamObj):
  1166. class ParamSet(ParamObj.ParamSet):
  1167. Params = {
  1168. 'viewType': 'normal',
  1169. 'fov': 60,
  1170. }
  1171. ...
  1172. def getViewType(self):
  1173. return self.viewType
  1174. def setViewType(self, viewType):
  1175. self.viewType = viewType
  1176. def applyViewType(self):
  1177. if self.viewType == 'normal':
  1178. ...
  1179. def getFov(self):
  1180. return self.fov
  1181. def setFov(self, fov):
  1182. self.fov = fov
  1183. def applyFov(self):
  1184. base.camera.setFov(self.fov)
  1185. ...
  1186. EXAMPLE USAGE
  1187. =============
  1188. cam = Camera()
  1189. ...
  1190. # set up for the cutscene
  1191. savedSettings = cam.ParamSet(cam)
  1192. cam.setViewType('closeup')
  1193. cam.setFov(90)
  1194. ...
  1195. # cutscene is over, set the camera back
  1196. savedSettings.applyTo(cam)
  1197. del savedSettings
  1198. """
  1199. class ParamObj:
  1200. # abstract base for classes that want to support a formal parameter
  1201. # set whose values may be queried, changed, 'bulk' changed (defer reaction
  1202. # to changes until multiple changes have been performed), and
  1203. # extracted/stored/applied all at once (see documentation above)
  1204. # ParamSet subclass: container of parameter values. Derived class must
  1205. # derive a new ParamSet class if they wish to define new params. See
  1206. # documentation above.
  1207. class ParamSet:
  1208. Params = {
  1209. # base class does not define any parameters, but they would
  1210. # appear here as 'name': defaultValue,
  1211. #
  1212. # WARNING: default values of mutable types that do not copy by
  1213. # value (dicts, lists etc.) will be shared by all class instances
  1214. # if default value is callable, it will be called to get actual
  1215. # default value
  1216. #
  1217. # for example:
  1218. #
  1219. # class MapArea(ParamObj):
  1220. # class ParamSet(ParamObj.ParamSet):
  1221. # Params = {
  1222. # 'spawnIndices': Functor(list, [1,5,22]),
  1223. # }
  1224. #
  1225. }
  1226. def __init__(self, *args, **kwArgs):
  1227. self.__class__._compileDefaultParams()
  1228. if len(args) == 1 and len(kwArgs) == 0:
  1229. # extract our params from an existing ParamObj instance
  1230. obj = args[0]
  1231. self.paramVals = {}
  1232. for param in self.getParams():
  1233. self.paramVals[param] = getSetter(obj, param, 'get')()
  1234. else:
  1235. assert len(args) == 0
  1236. if __debug__:
  1237. for arg in kwArgs.keys():
  1238. assert arg in self.getParams()
  1239. self.paramVals = dict(kwArgs)
  1240. def getValue(self, param):
  1241. if param in self.paramVals:
  1242. return self.paramVals[param]
  1243. return self._Params[param]
  1244. def applyTo(self, obj):
  1245. # Apply our entire set of params to a ParamObj
  1246. obj.lockParams()
  1247. for param in self.getParams():
  1248. getSetter(obj, param)(self.getValue(param))
  1249. obj.unlockParams()
  1250. def extractFrom(self, obj):
  1251. # Extract our entire set of params from a ParamObj
  1252. obj.lockParams()
  1253. for param in self.getParams():
  1254. self.paramVals[param] = getSetter(obj, param, 'get')()
  1255. obj.unlockParams()
  1256. @classmethod
  1257. def getParams(cls):
  1258. # returns safely-mutable list of param names
  1259. cls._compileDefaultParams()
  1260. return cls._Params.keys()
  1261. @classmethod
  1262. def getDefaultValue(cls, param):
  1263. cls._compileDefaultParams()
  1264. dv = cls._Params[param]
  1265. if callable(dv):
  1266. dv = dv()
  1267. return dv
  1268. @classmethod
  1269. def _compileDefaultParams(cls):
  1270. if cls.__dict__.has_key('_Params'):
  1271. # we've already compiled the defaults for this class
  1272. return
  1273. bases = list(cls.__bases__)
  1274. # bring less-derived classes to the front
  1275. mostDerivedLast(bases)
  1276. cls._Params = {}
  1277. for c in (bases + [cls]):
  1278. # make sure this base has its dict of param defaults
  1279. c._compileDefaultParams()
  1280. if c.__dict__.has_key('Params'):
  1281. # apply this class' default param values to our dict
  1282. cls._Params.update(c.Params)
  1283. def __repr__(self):
  1284. argStr = ''
  1285. for param in self.getParams():
  1286. argStr += '%s=%s,' % (param,
  1287. repr(self.getValue(param)))
  1288. return '%s.%s(%s)' % (
  1289. self.__class__.__module__, self.__class__.__name__, argStr)
  1290. # END PARAMSET SUBCLASS
  1291. def __init__(self, *args, **kwArgs):
  1292. assert issubclass(self.ParamSet, ParamObj.ParamSet)
  1293. # If you pass in a ParamSet obj, its values will be applied to this
  1294. # object in the constructor.
  1295. params = None
  1296. if len(args) == 1 and len(kwArgs) == 0:
  1297. # if there's one argument, assume that it's a ParamSet
  1298. params = args[0]
  1299. elif len(kwArgs) > 0:
  1300. assert len(args) == 0
  1301. # if we've got keyword arguments, make a ParamSet out of them
  1302. params = self.ParamSet(**kwArgs)
  1303. self._paramLockRefCount = 0
  1304. # these hold the current value of parameters while they are being set to
  1305. # a new value, to support getPriorValue()
  1306. self._curParamStack = []
  1307. self._priorValuesStack = []
  1308. # insert stub funcs for param setters, to handle locked params
  1309. for param in self.ParamSet.getParams():
  1310. # set the default value on the object
  1311. setattr(self, param, self.ParamSet.getDefaultValue(param))
  1312. setterName = getSetterName(param)
  1313. getterName = getSetterName(param, 'get')
  1314. # is there a setter defined?
  1315. if not hasattr(self, setterName):
  1316. # no; provide the default
  1317. def defaultSetter(self, value, param=param):
  1318. #print '%s=%s for %s' % (param, value, id(self))
  1319. setattr(self, param, value)
  1320. self.__class__.__dict__[setterName] = defaultSetter
  1321. # is there a getter defined?
  1322. if not hasattr(self, getterName):
  1323. # no; provide the default. If there is no value set, return
  1324. # the default
  1325. def defaultGetter(self, param=param,
  1326. default=self.ParamSet.getDefaultValue(param)):
  1327. return getattr(self, param, default)
  1328. self.__class__.__dict__[getterName] = defaultGetter
  1329. # have we already installed a setter stub?
  1330. origSetterName = '%s_ORIG' % (setterName,)
  1331. if not hasattr(self, origSetterName):
  1332. # move the original setter aside
  1333. origSetterFunc = getattr(self.__class__, setterName)
  1334. setattr(self.__class__, origSetterName, origSetterFunc)
  1335. """
  1336. # if the setter is a direct member of this instance, move the setter
  1337. # aside
  1338. if setterName in self.__dict__:
  1339. self.__dict__[setterName + '_MOVED'] = self.__dict__[setterName]
  1340. setterFunc = self.__dict__[setterName]
  1341. """
  1342. # install a setter stub that will a) call the real setter and
  1343. # then the applier, or b) call the setter and queue the
  1344. # applier, depending on whether our params are locked
  1345. """
  1346. setattr(self, setterName, new.instancemethod(
  1347. Functor(setterStub, param, setterFunc), self, self.__class__))
  1348. """
  1349. def setterStub(self, value, param=param, origSetterName=origSetterName):
  1350. # should we apply the value now or should we wait?
  1351. # if this obj's params are locked, we track which values have
  1352. # been set, and on unlock, we'll call the applyers for those
  1353. # values
  1354. if self._paramLockRefCount > 0:
  1355. priorValues = self._priorValuesStack[-1]
  1356. if param not in priorValues:
  1357. try:
  1358. priorValue = getSetter(self, param, 'get')()
  1359. except:
  1360. priorValue = None
  1361. priorValues[param] = priorValue
  1362. self._paramsSet[param] = None
  1363. getattr(self, origSetterName)(value)
  1364. else:
  1365. # prepare for call to getPriorValue
  1366. try:
  1367. priorValue = getSetter(self, param, 'get')()
  1368. except:
  1369. priorValue = None
  1370. self._priorValuesStack.append({
  1371. param: priorValue,
  1372. })
  1373. getattr(self, origSetterName)(value)
  1374. # call the applier, if there is one
  1375. applier = getattr(self, getSetterName(param, 'apply'), None)
  1376. if applier is not None:
  1377. self._curParamStack.append(param)
  1378. applier()
  1379. self._curParamStack.pop()
  1380. self._priorValuesStack.pop()
  1381. if hasattr(self, 'handleParamChange'):
  1382. self.handleParamChange((param,))
  1383. setattr(self.__class__, setterName, setterStub)
  1384. if params is not None:
  1385. params.applyTo(self)
  1386. def destroy(self):
  1387. """
  1388. for param in self.ParamSet.getParams():
  1389. setterName = getSetterName(param)
  1390. self.__dict__[setterName].destroy()
  1391. del self.__dict__[setterName]
  1392. """
  1393. pass
  1394. def setDefaultParams(self):
  1395. # set all the default parameters on ourself
  1396. self.ParamSet().applyTo(self)
  1397. def getCurrentParams(self):
  1398. params = self.ParamSet()
  1399. params.extractFrom(self)
  1400. return params
  1401. def lockParams(self):
  1402. self._paramLockRefCount += 1
  1403. if self._paramLockRefCount == 1:
  1404. self._handleLockParams()
  1405. def unlockParams(self):
  1406. if self._paramLockRefCount > 0:
  1407. self._paramLockRefCount -= 1
  1408. if self._paramLockRefCount == 0:
  1409. self._handleUnlockParams()
  1410. def _handleLockParams(self):
  1411. # this will store the names of the parameters that are modified
  1412. self._paramsSet = {}
  1413. # this will store the values of modified params (from prior to
  1414. # the lock).
  1415. self._priorValuesStack.append({})
  1416. def _handleUnlockParams(self):
  1417. for param in self._paramsSet:
  1418. # call the applier, if there is one
  1419. applier = getattr(self, getSetterName(param, 'apply'), None)
  1420. if applier is not None:
  1421. self._curParamStack.append(param)
  1422. applier()
  1423. self._curParamStack.pop()
  1424. self._priorValuesStack.pop()
  1425. if hasattr(self, 'handleParamChange'):
  1426. self.handleParamChange(tuple(self._paramsSet.keys()))
  1427. del self._paramsSet
  1428. def paramsLocked(self):
  1429. return self._paramLockRefCount > 0
  1430. def getPriorValue(self):
  1431. # call this within an apply function to find out what the prior value
  1432. # of the param was
  1433. return self._priorValuesStack[-1][self._curParamStack[-1]]
  1434. def __repr__(self):
  1435. argStr = ''
  1436. for param in self.ParamSet.getParams():
  1437. try:
  1438. value = getSetter(self, param, 'get')()
  1439. except:
  1440. value = '<unknown>'
  1441. argStr += '%s=%s,' % (param, repr(value))
  1442. return '%s(%s)' % (self.__class__.__name__, argStr)
  1443. if __debug__:
  1444. class ParamObjTest(ParamObj):
  1445. class ParamSet(ParamObj.ParamSet):
  1446. Params = {
  1447. 'num': 0,
  1448. }
  1449. def applyNum(self):
  1450. self.priorValue = self.getPriorValue()
  1451. pto = ParamObjTest()
  1452. assert pto.getNum() == 0
  1453. pto.setNum(1)
  1454. assert pto.priorValue == 0
  1455. assert pto.getNum() == 1
  1456. pto.lockParams()
  1457. pto.setNum(2)
  1458. # make sure applyNum is not called until we call unlockParams
  1459. assert pto.priorValue == 0
  1460. assert pto.getNum() == 2
  1461. pto.unlockParams()
  1462. assert pto.priorValue == 1
  1463. assert pto.getNum() == 2
  1464. """
  1465. POD (Plain Ol' Data)
  1466. Like ParamObj/ParamSet, but without lock/unlock/getPriorValue and without
  1467. appliers. Similar to a C++ struct, but with auto-generated setters and
  1468. getters.
  1469. Use POD when you want the generated getters and setters of ParamObj, but
  1470. efficiency is a concern and you don't need the bells and whistles provided
  1471. by ParamObj.
  1472. POD.__init__ *MUST* be called. You should NOT define your own data getters
  1473. and setters. Data values may be read, set, and modified directly. You will
  1474. see no errors if you define your own getters/setters, but there is no
  1475. guarantee that they will be called--and they will certainly be bypassed by
  1476. POD internally.
  1477. EXAMPLE CLASSES
  1478. ===============
  1479. Here is an example of a class heirarchy that uses POD to manage its data:
  1480. class Enemy(POD):
  1481. DataSet = {
  1482. 'faction': 'navy',
  1483. }
  1484. class Sailor(Enemy):
  1485. DataSet = {
  1486. 'build': HUSKY,
  1487. 'weapon': Cutlass(scale=.9),
  1488. }
  1489. EXAMPLE USAGE
  1490. =============
  1491. s = Sailor(faction='undead', build=SKINNY)
  1492. # make two copies of s
  1493. s2 = s.makeCopy()
  1494. s3 = Sailor(s)
  1495. # example sets
  1496. s2.setWeapon(Musket())
  1497. s3.build = TALL
  1498. # example gets
  1499. faction2 = s2.getFaction()
  1500. faction3 = s3.faction
  1501. """
  1502. class POD:
  1503. DataSet = {
  1504. # base class does not define any data items, but they would
  1505. # appear here as 'name': defaultValue,
  1506. #
  1507. # WARNING: default values of mutable types that do not copy by
  1508. # value (dicts, lists etc.) will be shared by all class instances.
  1509. # if default value is callable, it will be called to get actual
  1510. # default value
  1511. #
  1512. # for example:
  1513. #
  1514. # class MapData(POD):
  1515. # DataSet = {
  1516. # 'spawnIndices': Functor(list, [1,5,22]),
  1517. # }
  1518. }
  1519. def __init__(self, **kwArgs):
  1520. self.__class__._compileDefaultDataSet()
  1521. if __debug__:
  1522. # make sure all of the keyword arguments passed in
  1523. # are present in our data set
  1524. for arg in kwArgs.keys():
  1525. assert arg in self.getDataNames(), (
  1526. "unknown argument for %s: '%s'" % (
  1527. self.__class__, arg))
  1528. # assign each of our data items directly to self
  1529. for name in self.getDataNames():
  1530. # if a value has been passed in for a data item, use
  1531. # that value, otherwise use the default value
  1532. if name in kwArgs:
  1533. getSetter(self, name)(kwArgs[name])
  1534. else:
  1535. getSetter(self, name)(self.getDefaultValue(name))
  1536. def setDefaultValues(self):
  1537. # set all the default data values on ourself
  1538. for name in self.getDataNames():
  1539. getSetter(self, name)(self.getDefaultValue(name))
  1540. # this functionality used to be in the constructor, triggered by a single
  1541. # positional argument; that was conflicting with POD subclasses that wanted
  1542. # to define different behavior for themselves when given a positional
  1543. # constructor argument
  1544. def copyFrom(self, other, strict=False):
  1545. # if 'strict' is true, other must have a value for all of our data items
  1546. # otherwise we'll use the defaults
  1547. for name in self.getDataNames():
  1548. if hasattr(other, getSetterName(name, 'get')):
  1549. setattr(self, name, getSetter(other, name, 'get')())
  1550. else:
  1551. if strict:
  1552. raise "object '%s' doesn't have value '%s'" % (other, name)
  1553. else:
  1554. setattr(self, name, self.getDefaultValue(name))
  1555. # support 'p = POD.POD().copyFrom(other)' syntax
  1556. return self
  1557. def makeCopy(self):
  1558. # returns a duplicate of this object
  1559. return self.__class__().copyFrom(self)
  1560. def applyTo(self, obj):
  1561. # Apply our entire set of data to another POD
  1562. for name in self.getDataNames():
  1563. getSetter(obj, name)(getSetter(self, name, 'get')())
  1564. def getValue(self, name):
  1565. return getSetter(self, name, 'get')()
  1566. @classmethod
  1567. def getDataNames(cls):
  1568. # returns safely-mutable list of datum names
  1569. cls._compileDefaultDataSet()
  1570. return cls._DataSet.keys()
  1571. @classmethod
  1572. def getDefaultValue(cls, name):
  1573. cls._compileDefaultDataSet()
  1574. dv = cls._DataSet[name]
  1575. # this allows us to create a new mutable object every time we ask
  1576. # for its default value, i.e. if the default value is dict, this
  1577. # method will return a new empty dictionary object every time. This
  1578. # will cause problems if the intent is to store a callable object
  1579. # as the default value itself; we need a way to specify that the
  1580. # callable *is* the default value and not a default-value creation
  1581. # function
  1582. if callable(dv):
  1583. dv = dv()
  1584. return dv
  1585. @classmethod
  1586. def _compileDefaultDataSet(cls):
  1587. if cls.__dict__.has_key('_DataSet'):
  1588. # we've already compiled the defaults for this class
  1589. return
  1590. # create setters & getters for this class
  1591. if cls.__dict__.has_key('DataSet'):
  1592. for name in cls.DataSet:
  1593. setterName = getSetterName(name)
  1594. if not hasattr(cls, setterName):
  1595. def defaultSetter(self, value, name=name):
  1596. setattr(self, name, value)
  1597. cls.__dict__[setterName] = defaultSetter
  1598. getterName = getSetterName(name, 'get')
  1599. if not hasattr(cls, getterName):
  1600. def defaultGetter(self, name=name):
  1601. return getattr(self, name)
  1602. cls.__dict__[getterName] = defaultGetter
  1603. # this dict will hold all of the aggregated default data values for
  1604. # this particular class, including values from its base classes
  1605. cls._DataSet = {}
  1606. bases = list(cls.__bases__)
  1607. # process in reverse of inheritance order, so that base classes listed first
  1608. # will take precedence over later base classes
  1609. bases.reverse()
  1610. for curBase in bases:
  1611. # skip multiple-inheritance base classes that do not derive from POD
  1612. if issubclass(curBase, POD):
  1613. # make sure this base has its dict of data defaults
  1614. curBase._compileDefaultDataSet()
  1615. # grab all inherited data default values
  1616. cls._DataSet.update(curBase._DataSet)
  1617. # pull in our own class' default values if any are specified
  1618. if 'DataSet' in cls.__dict__:
  1619. cls._DataSet.update(cls.DataSet)
  1620. def __repr__(self):
  1621. argStr = ''
  1622. for name in self.getDataNames():
  1623. argStr += '%s=%s,' % (name, repr(getSetter(self, name, 'get')()))
  1624. return '%s(%s)' % (self.__class__.__name__, argStr)
  1625. if __debug__:
  1626. class PODtest(POD):
  1627. DataSet = {
  1628. 'foo': dict,
  1629. }
  1630. p1 = PODtest()
  1631. p2 = PODtest()
  1632. assert hasattr(p1, 'foo')
  1633. # make sure the getter is working
  1634. assert p1.getFoo() is p1.foo
  1635. p1.getFoo()[1] = 2
  1636. assert p1.foo[1] == 2
  1637. # make sure that each instance gets its own copy of a mutable
  1638. # data item
  1639. assert p1.foo is not p2.foo
  1640. assert len(p1.foo) == 1
  1641. assert len(p2.foo) == 0
  1642. # make sure the setter is working
  1643. p2.setFoo({10:20})
  1644. assert p2.foo[10] == 20
  1645. # make sure modifications to mutable data items don't affect other
  1646. # instances
  1647. assert p1.foo[1] == 2
  1648. class DerivedPOD(PODtest):
  1649. DataSet = {
  1650. 'bar': list,
  1651. }
  1652. d1 = DerivedPOD()
  1653. # make sure that derived instances get their own copy of mutable
  1654. # data items
  1655. assert hasattr(d1, 'foo')
  1656. assert len(d1.foo) == 0
  1657. # make sure derived instances get their own items
  1658. assert hasattr(d1, 'bar')
  1659. assert len(d1.bar) == 0
  1660. def bound(value, bound1, bound2):
  1661. """
  1662. returns value if value is between bound1 and bound2
  1663. otherwise returns bound that is closer to value
  1664. """
  1665. if bound1 > bound2:
  1666. return min(max(value, bound2), bound1)
  1667. else:
  1668. return min(max(value, bound1), bound2)
  1669. def lerp(v0, v1, t):
  1670. """
  1671. returns a value lerped between v0 and v1, according to t
  1672. t == 0 maps to v0, t == 1 maps to v1
  1673. """
  1674. return v0 + ((v1 - v0) * t)
  1675. def getShortestRotation(start, end):
  1676. """
  1677. Given two heading values, return a tuple describing
  1678. the shortest interval from 'start' to 'end'. This tuple
  1679. can be used to lerp a camera between two rotations
  1680. while avoiding the 'spin' problem.
  1681. """
  1682. start, end = start % 360, end % 360
  1683. if abs(end - start) > 180:
  1684. if end < start:
  1685. end += 360
  1686. else:
  1687. start += 360
  1688. return (start, end)
  1689. def average(*args):
  1690. """ returns simple average of list of values """
  1691. val = 0.
  1692. for arg in args:
  1693. val += arg
  1694. return val / len(args)
  1695. class Averager:
  1696. def __init__(self, name):
  1697. self._name = name
  1698. self.reset()
  1699. def reset(self):
  1700. self._total = 0.
  1701. self._count = 0
  1702. def addValue(self, value):
  1703. self._total += value
  1704. self._count += 1
  1705. def getAverage(self):
  1706. return self._total / self._count
  1707. def getCount(self):
  1708. return self._count
  1709. def addListsByValue(a, b):
  1710. """
  1711. returns a new array containing the sums of the two array arguments
  1712. (c[0] = a[0 + b[0], etc.)
  1713. """
  1714. c = []
  1715. for x, y in zip(a, b):
  1716. c.append(x + y)
  1717. return c
  1718. def boolEqual(a, b):
  1719. """
  1720. returns true if a and b are both true or both false.
  1721. returns false otherwise
  1722. (a.k.a. xnor -- eXclusive Not OR).
  1723. """
  1724. return (a and b) or not (a or b)
  1725. def lineupPos(i, num, spacing):
  1726. """
  1727. use to line up a series of 'num' objects, in one dimension,
  1728. centered around zero
  1729. 'i' is the index of the object in the lineup
  1730. 'spacing' is the amount of space between objects in the lineup
  1731. """
  1732. assert num >= 1
  1733. assert i >= 0 and i < num
  1734. pos = float(i) * spacing
  1735. return pos - ((float(spacing) * (num-1))/2.)
  1736. def formatElapsedSeconds(seconds):
  1737. """
  1738. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  1739. representing the indicated elapsed time in seconds.
  1740. """
  1741. sign = ''
  1742. if seconds < 0:
  1743. seconds = -seconds
  1744. sign = '-'
  1745. # We use math.floor() instead of casting to an int, so we avoid
  1746. # problems with numbers that are too large to represent as
  1747. # type int.
  1748. seconds = math.floor(seconds)
  1749. hours = math.floor(seconds / (60 * 60))
  1750. if hours > 36:
  1751. days = math.floor((hours + 12) / 24)
  1752. return "%s%d days" % (sign, days)
  1753. seconds -= hours * (60 * 60)
  1754. minutes = (int)(seconds / 60)
  1755. seconds -= minutes * 60
  1756. if hours != 0:
  1757. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  1758. else:
  1759. return "%s%d:%02d" % (sign, minutes, seconds)
  1760. def solveQuadratic(a, b, c):
  1761. # quadratic equation: ax^2 + bx + c = 0
  1762. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  1763. # returns None, root, or [root1, root2]
  1764. # a cannot be zero.
  1765. if a == 0.:
  1766. return None
  1767. # calculate the determinant (b^2 - 4ac)
  1768. D = (b * b) - (4. * a * c)
  1769. if D < 0:
  1770. # there are no solutions (sqrt(negative number) is undefined)
  1771. return None
  1772. elif D == 0:
  1773. # only one root
  1774. return (-b) / (2. * a)
  1775. else:
  1776. # OK, there are two roots
  1777. sqrtD = math.sqrt(D)
  1778. twoA = 2. * a
  1779. root1 = ((-b) - sqrtD) / twoA
  1780. root2 = ((-b) + sqrtD) / twoA
  1781. return [root1, root2]
  1782. def stackEntryInfo(depth=0, baseFileName=1):
  1783. """
  1784. returns the sourcefilename, line number, and function name of
  1785. an entry in the stack.
  1786. 'depth' is how far back to go in the stack; 0 is the caller of this
  1787. function, 1 is the function that called the caller of this function, etc.
  1788. by default, strips off the path of the filename; override with baseFileName
  1789. returns (fileName, lineNum, funcName) --> (string, int, string)
  1790. returns (None, None, None) on error
  1791. """
  1792. try:
  1793. stack = None
  1794. frame = None
  1795. try:
  1796. stack = inspect.stack()
  1797. # add one to skip the frame associated with this function
  1798. frame = stack[depth+1]
  1799. filename = frame[1]
  1800. if baseFileName:
  1801. filename = os.path.basename(filename)
  1802. lineNum = frame[2]
  1803. funcName = frame[3]
  1804. result = (filename, lineNum, funcName)
  1805. finally:
  1806. del stack
  1807. del frame
  1808. except:
  1809. result = (None, None, None)
  1810. return result
  1811. def lineInfo(baseFileName=1):
  1812. """
  1813. returns the sourcefilename, line number, and function name of the
  1814. code that called this function
  1815. (answers the question: 'hey lineInfo, where am I in the codebase?')
  1816. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1817. """
  1818. return stackEntryInfo(1, baseFileName)
  1819. def callerInfo(baseFileName=1, howFarBack=0):
  1820. """
  1821. returns the sourcefilename, line number, and function name of the
  1822. caller of the function that called this function
  1823. (answers the question: 'hey callerInfo, who called me?')
  1824. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1825. """
  1826. return stackEntryInfo(2+howFarBack, baseFileName)
  1827. def lineTag(baseFileName=1, verbose=0, separator=':'):
  1828. """
  1829. returns a string containing the sourcefilename and line number
  1830. of the code that called this function
  1831. (equivalent to lineInfo, above, with different return type)
  1832. see stackEntryInfo, above, for info on 'baseFileName'
  1833. if 'verbose' is false, returns a compact string of the form
  1834. 'fileName:lineNum:funcName'
  1835. if 'verbose' is true, returns a longer string that matches the
  1836. format of Python stack trace dumps
  1837. returns empty string on error
  1838. """
  1839. fileName, lineNum, funcName = callerInfo(baseFileName)
  1840. if fileName is None:
  1841. return ''
  1842. if verbose:
  1843. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  1844. else:
  1845. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  1846. funcName)
  1847. def findPythonModule(module):
  1848. # Look along the python load path for the indicated filename.
  1849. # Returns the located pathname, or None if the filename is not
  1850. # found.
  1851. filename = module + '.py'
  1852. for dir in sys.path:
  1853. pathname = os.path.join(dir, filename)
  1854. if os.path.exists(pathname):
  1855. return pathname
  1856. return None
  1857. def describeException(backTrace = 4):
  1858. # When called in an exception handler, returns a string describing
  1859. # the current exception.
  1860. def byteOffsetToLineno(code, byte):
  1861. # Returns the source line number corresponding to the given byte
  1862. # offset into the indicated Python code module.
  1863. import array
  1864. lnotab = array.array('B', code.co_lnotab)
  1865. line = code.co_firstlineno
  1866. for i in range(0, len(lnotab), 2):
  1867. byte -= lnotab[i]
  1868. if byte <= 0:
  1869. return line
  1870. line += lnotab[i+1]
  1871. return line
  1872. infoArr = sys.exc_info()
  1873. exception = infoArr[0]
  1874. exceptionName = getattr(exception, '__name__', None)
  1875. extraInfo = infoArr[1]
  1876. trace = infoArr[2]
  1877. stack = []
  1878. while trace.tb_next:
  1879. # We need to call byteOffsetToLineno to determine the true
  1880. # line number at which the exception occurred, even though we
  1881. # have both trace.tb_lineno and frame.f_lineno, which return
  1882. # the correct line number only in non-optimized mode.
  1883. frame = trace.tb_frame
  1884. module = frame.f_globals.get('__name__', None)
  1885. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1886. stack.append("%s:%s, " % (module, lineno))
  1887. trace = trace.tb_next
  1888. frame = trace.tb_frame
  1889. module = frame.f_globals.get('__name__', None)
  1890. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1891. stack.append("%s:%s, " % (module, lineno))
  1892. description = ""
  1893. for i in range(len(stack) - 1, max(len(stack) - backTrace, 0) - 1, -1):
  1894. description += stack[i]
  1895. description += "%s: %s" % (exceptionName, extraInfo)
  1896. return description
  1897. def clampScalar(value, a, b):
  1898. # calling this ought to be faster than calling both min and max
  1899. if a < b:
  1900. if value < a:
  1901. return a
  1902. elif value > b:
  1903. return b
  1904. else:
  1905. return value
  1906. else:
  1907. if value < b:
  1908. return b
  1909. elif value > a:
  1910. return a
  1911. else:
  1912. return value
  1913. def pivotScalar(scalar, pivot):
  1914. # reflect scalar about pivot; see tests below
  1915. return pivot + (pivot - scalar)
  1916. if __debug__:
  1917. assert pivotScalar(1, 0) == -1
  1918. assert pivotScalar(-1, 0) == 1
  1919. assert pivotScalar(3, 5) == 7
  1920. assert pivotScalar(10, 1) == -8
  1921. def weightedChoice(choiceList, rng=random.random, sum=None):
  1922. """given a list of (weight, item) pairs, chooses an item based on the
  1923. weights. rng must return 0..1. if you happen to have the sum of the
  1924. weights, pass it in 'sum'."""
  1925. # TODO: add support for dicts
  1926. if sum is None:
  1927. sum = 0.
  1928. for weight, item in choiceList:
  1929. sum += weight
  1930. rand = rng()
  1931. accum = rand * sum
  1932. for weight, item in choiceList:
  1933. accum -= weight
  1934. if accum <= 0.:
  1935. return item
  1936. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1937. # Or you passed in a 'sum' that was was too large.
  1938. # Return the last item.
  1939. return item
  1940. def randFloat(a, b=0., rng=random.random):
  1941. """returns a random float in [a, b]
  1942. call with single argument to generate random float between arg and zero
  1943. """
  1944. return lerp(a, b, rng())
  1945. def normalDistrib(a, b, gauss=random.gauss):
  1946. """
  1947. NOTE: assumes a < b
  1948. Returns random number between a and b, using gaussian distribution, with
  1949. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1950. between a and b. Outlying results are clipped to a and b.
  1951. ------------------------------------------------------------------------
  1952. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1953. The 68-95-99.7% Rule
  1954. ====================
  1955. All normal density curves satisfy the following property which is often
  1956. referred to as the Empirical Rule:
  1957. 68% of the observations fall within 1 standard deviation of the mean.
  1958. 95% of the observations fall within 2 standard deviations of the mean.
  1959. 99.7% of the observations fall within 3 standard deviations of the mean.
  1960. Thus, for a normal distribution, almost all values lie within 3 standard
  1961. deviations of the mean.
  1962. ------------------------------------------------------------------------
  1963. In calculating our standard deviation, we divide (b-a) by 6, since the
  1964. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1965. """
  1966. return max(a, min(b, gauss((a+b)*.5, (b-a)/6.)))
  1967. def weightedRand(valDict, rng=random.random):
  1968. """
  1969. pass in a dictionary with a selection -> weight mapping. Eg.
  1970. {"Choice 1": 10,
  1971. "Choice 2": 30,
  1972. "bear": 100}
  1973. -Weights need not add up to any particular value.
  1974. -The actual selection will be returned.
  1975. """
  1976. selections = valDict.keys()
  1977. weights = valDict.values()
  1978. totalWeight = 0
  1979. for weight in weights:
  1980. totalWeight += weight
  1981. # get a random value between 0 and the total of the weights
  1982. randomWeight = rng() * totalWeight
  1983. # find the index that corresponds with this weight
  1984. for i in range(len(weights)):
  1985. totalWeight -= weights[i]
  1986. if totalWeight <= randomWeight:
  1987. return selections[i]
  1988. assert True, "Should never get here"
  1989. return selections[-1]
  1990. def randUint31(rng=random.random):
  1991. """returns a random integer in [0..2^31).
  1992. rng must return float in [0..1]"""
  1993. return int(rng() * 0x7FFFFFFF)
  1994. def randInt32(rng=random.random):
  1995. """returns a random integer in [-2147483648..2147483647].
  1996. rng must return float in [0..1]
  1997. """
  1998. i = int(rng() * 0x7FFFFFFF)
  1999. if rng() < .5:
  2000. i *= -1
  2001. return i
  2002. def randUint32(rng=random.random):
  2003. """returns a random integer in [0..2^32).
  2004. rng must return float in [0..1]"""
  2005. return long(rng() * 0xFFFFFFFFL)
  2006. class SerialNumGen:
  2007. """generates serial numbers"""
  2008. def __init__(self, start=None):
  2009. if start is None:
  2010. start = 0
  2011. self.__counter = start-1
  2012. def next(self):
  2013. self.__counter += 1
  2014. return self.__counter
  2015. _serialGen = SerialNumGen()
  2016. def serialNum():
  2017. global _serialGen
  2018. return _serialGen.next()
  2019. def uniqueName(name):
  2020. global _serialGen
  2021. return '%s-%s' % (name, _serialGen.next())
  2022. class EnumIter:
  2023. def __init__(self, enum):
  2024. self._values = enum._stringTable.keys()
  2025. self._index = 0
  2026. def __iter__(self):
  2027. return self
  2028. def next(self):
  2029. if self._index >= len(self._values):
  2030. raise StopIteration
  2031. self._index += 1
  2032. return self._values[self._index-1]
  2033. class Enum:
  2034. """Pass in list of strings or string of comma-separated strings.
  2035. Items are accessible as instance.item, and are assigned unique,
  2036. increasing integer values. Pass in integer for 'start' to override
  2037. starting value.
  2038. Example:
  2039. >>> colors = Enum('red, green, blue')
  2040. >>> colors.red
  2041. 0
  2042. >>> colors.green
  2043. 1
  2044. >>> colors.blue
  2045. 2
  2046. >>> colors.getString(colors.red)
  2047. 'red'
  2048. """
  2049. if __debug__:
  2050. # chars that cannot appear within an item string.
  2051. InvalidChars = string.whitespace
  2052. def _checkValidIdentifier(item):
  2053. invalidChars = string.whitespace+string.punctuation
  2054. invalidChars = invalidChars.replace('_','')
  2055. invalidFirstChars = invalidChars+string.digits
  2056. if item[0] in invalidFirstChars:
  2057. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  2058. item)
  2059. if not disjoint(item, invalidChars):
  2060. for char in item:
  2061. if char in invalidChars:
  2062. raise SyntaxError, (
  2063. "Enum\n'%s'\ncontains illegal char '%s'" %
  2064. (item, char))
  2065. return 1
  2066. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  2067. def __init__(self, items, start=0):
  2068. if type(items) == types.StringType:
  2069. items = items.split(',')
  2070. self._stringTable = {}
  2071. # make sure we don't overwrite an existing element of the class
  2072. assert self._checkExistingMembers(items)
  2073. assert uniqueElements(items)
  2074. i = start
  2075. for item in items:
  2076. # remove leading/trailing whitespace
  2077. item = string.strip(item)
  2078. # is there anything left?
  2079. if len(item) == 0:
  2080. continue
  2081. # make sure there are no invalid characters
  2082. assert Enum._checkValidIdentifier(item)
  2083. self.__dict__[item] = i
  2084. self._stringTable[i] = item
  2085. i += 1
  2086. def __iter__(self):
  2087. return EnumIter(self)
  2088. def getString(self, value):
  2089. return self._stringTable[value]
  2090. def __contains__(self, value):
  2091. return value in self._stringTable
  2092. def __len__(self):
  2093. return len(self._stringTable)
  2094. def copyTo(self, obj):
  2095. # copies all members onto obj
  2096. for name, value in self._stringTable:
  2097. setattr(obj, name, value)
  2098. if __debug__:
  2099. def _checkExistingMembers(self, items):
  2100. for item in items:
  2101. if hasattr(self, item):
  2102. return 0
  2103. return 1
  2104. ############################################################
  2105. # class: Singleton
  2106. # Purpose: This provides a base metaclass for all classes
  2107. # that require one and only one instance.
  2108. #
  2109. # Example: class mySingleton:
  2110. # __metaclass__ = PythonUtil.Singleton
  2111. # def __init__(self, ...):
  2112. # ...
  2113. #
  2114. # Note: This class is based on Python's New-Style Class
  2115. # design. An error will occur if a defined class
  2116. # attemps to inherit from a Classic-Style Class only,
  2117. # ie: class myClassX:
  2118. # def __init__(self, ...):
  2119. # ...
  2120. #
  2121. # class myNewClassX(myClassX):
  2122. # __metaclass__ = PythonUtil.Singleton
  2123. # def __init__(self, ...):
  2124. # myClassX.__init__(self, ...)
  2125. # ...
  2126. #
  2127. # This causes problems because myNewClassX is a
  2128. # New-Style class that inherits from only a
  2129. # Classic-Style base class. There are two ways
  2130. # simple ways to resolve this issue.
  2131. #
  2132. # First, if possible, make myClassX a
  2133. # New-Style class by inheriting from object
  2134. # object. IE: class myClassX(object):
  2135. #
  2136. # If for some reason that is not an option, make
  2137. # myNewClassX inherit from object and myClassX.
  2138. # IE: class myNewClassX(object, myClassX):
  2139. ############################################################
  2140. class Singleton(type):
  2141. def __init__(cls, name, bases, dic):
  2142. super(Singleton, cls).__init__(name, bases, dic)
  2143. cls.instance=None
  2144. def __call__(cls, *args, **kw):
  2145. if cls.instance is None:
  2146. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  2147. return cls.instance
  2148. class SingletonError(ValueError):
  2149. """ Used to indicate an inappropriate value for a Singleton."""
  2150. def printListEnumGen(l):
  2151. # log each individual item with a number in front of it
  2152. digits = 0
  2153. n = len(l)
  2154. while n > 0:
  2155. digits += 1
  2156. n /= 10
  2157. format = '%0' + '%s' % digits + 'i:%s'
  2158. for i in range(len(l)):
  2159. print format % (i, l[i])
  2160. yield None
  2161. def printListEnum(l):
  2162. for result in printListEnumGen(l):
  2163. pass
  2164. def gcDebugOn():
  2165. import gc
  2166. return (gc.get_debug() & gc.DEBUG_SAVEALL) == gc.DEBUG_SAVEALL
  2167. # base class for all Panda C++ objects
  2168. # libdtoolconfig doesn't seem to have this, grab it off of PandaNode
  2169. dtoolSuperBase = None
  2170. def _getDtoolSuperBase():
  2171. global dtoolSuperBase
  2172. from pandac.PandaModules import PandaNode
  2173. dtoolSuperBase = PandaNode('').__class__.__bases__[0].__bases__[0].__bases__[0]
  2174. safeReprNotify = None
  2175. def _getSafeReprNotify():
  2176. global safeReprNotify
  2177. from direct.directnotify.DirectNotifyGlobal import directNotify
  2178. safeReprNotify = directNotify.newCategory("safeRepr")
  2179. def safeRepr(obj):
  2180. global dtoolSuperBase
  2181. if dtoolSuperBase is None:
  2182. _getDtoolSuperBase()
  2183. global safeReprNotify
  2184. if safeReprNotify is None:
  2185. _getSafeReprNotify()
  2186. if isinstance(obj, dtoolSuperBase):
  2187. # repr of C++ object could crash, particularly if the object has been deleted
  2188. # log that we're calling repr
  2189. safeReprNotify.info('calling repr on instance of %s.%s' % (obj.__class__.__module__, obj.__class__.__name__))
  2190. sys.stdout.flush()
  2191. try:
  2192. return repr(obj)
  2193. except:
  2194. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  2195. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  2196. """ caps the length of iterable types, so very large objects will print faster.
  2197. also prevents infinite recursion """
  2198. try:
  2199. if _visitedIds is None:
  2200. _visitedIds = set()
  2201. if id(obj) in _visitedIds:
  2202. return '<ALREADY-VISITED %s>' % itype(obj)
  2203. if type(obj) in (types.TupleType, types.ListType):
  2204. s = ''
  2205. s += {types.TupleType: '(',
  2206. types.ListType: '[',}[type(obj)]
  2207. if maxLen is not None and len(obj) > maxLen:
  2208. o = obj[:maxLen]
  2209. ellips = '...'
  2210. else:
  2211. o = obj
  2212. ellips = ''
  2213. _visitedIds.add(id(obj))
  2214. for item in o:
  2215. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  2216. s += ', '
  2217. _visitedIds.remove(id(obj))
  2218. s += ellips
  2219. s += {types.TupleType: ')',
  2220. types.ListType: ']',}[type(obj)]
  2221. return s
  2222. elif type(obj) is types.DictType:
  2223. s = '{'
  2224. if maxLen is not None and len(obj) > maxLen:
  2225. o = obj.keys()[:maxLen]
  2226. ellips = '...'
  2227. else:
  2228. o = obj.keys()
  2229. ellips = ''
  2230. _visitedIds.add(id(obj))
  2231. for key in o:
  2232. value = obj[key]
  2233. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  2234. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  2235. _visitedIds.remove(id(obj))
  2236. s += ellips
  2237. s += '}'
  2238. return s
  2239. elif type(obj) is types.StringType:
  2240. if maxLen is not None:
  2241. maxLen *= strFactor
  2242. if maxLen is not None and len(obj) > maxLen:
  2243. return safeRepr(obj[:maxLen])
  2244. else:
  2245. return safeRepr(obj)
  2246. else:
  2247. r = safeRepr(obj)
  2248. maxLen *= strFactor
  2249. if len(r) > maxLen:
  2250. r = r[:maxLen]
  2251. return r
  2252. except:
  2253. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  2254. def tagRepr(obj, tag):
  2255. """adds a string onto the repr output of an instance"""
  2256. def reprWithTag(oldRepr, tag, self):
  2257. return oldRepr() + '::<TAG=' + tag + '>'
  2258. oldRepr = getattr(obj, '__repr__', None)
  2259. if oldRepr is None:
  2260. def stringer(s):
  2261. return s
  2262. oldRepr = Functor(stringer, repr(obj))
  2263. stringer = None
  2264. obj.__repr__ = new.instancemethod(Functor(reprWithTag, oldRepr, tag), obj, obj.__class__)
  2265. reprWithTag = None
  2266. return obj
  2267. def tagWithCaller(obj):
  2268. """add info about the caller of the caller"""
  2269. tagRepr(obj, str(callerInfo(howFarBack=1)))
  2270. def isDefaultValue(x):
  2271. return x == type(x)()
  2272. def notNone(A, B):
  2273. # returns A if not None, B otherwise
  2274. if A is None:
  2275. return B
  2276. return A
  2277. def appendStr(obj, st):
  2278. """adds a string onto the __str__ output of an instance"""
  2279. def appendedStr(oldStr, st, self):
  2280. return oldStr() + st
  2281. oldStr = getattr(obj, '__str__', None)
  2282. if oldStr is None:
  2283. def stringer(s):
  2284. return s
  2285. oldStr = Functor(stringer, str(obj))
  2286. stringer = None
  2287. obj.__str__ = new.instancemethod(Functor(appendedStr, oldStr, st), obj, obj.__class__)
  2288. appendedStr = None
  2289. return obj
  2290. # convenience shortcuts for __dev__ debugging
  2291. # we don't have the __dev__ flag at this point
  2292. try:
  2293. import pdb
  2294. set_trace = pdb.set_trace
  2295. # set_trace that can be asserted
  2296. def setTrace():
  2297. set_trace()
  2298. return True
  2299. pm = pdb.pm
  2300. except:
  2301. # we're in production, there is no pdb module. assign these to something so that the
  2302. # __builtin__ exports will work
  2303. # references in the code should either be if __dev__'d or asserted
  2304. set_trace = None
  2305. setTrace = None
  2306. pm = None
  2307. class ScratchPad:
  2308. """empty class to stick values onto"""
  2309. def __init__(self, **kArgs):
  2310. for key, value in kArgs.iteritems():
  2311. setattr(self, key, value)
  2312. self._keys = set(kArgs.keys())
  2313. def add(self, **kArgs):
  2314. for key, value in kArgs.iteritems():
  2315. setattr(self, key, value)
  2316. self._keys.update(kArgs.keys())
  2317. def destroy(self):
  2318. for key in self._keys:
  2319. delattr(self, key)
  2320. class DestructiveScratchPad(ScratchPad):
  2321. # automatically calls destroy() on elements passed to __init__
  2322. def add(self, **kArgs):
  2323. for key, value in kArgs.iteritems():
  2324. if hasattr(self, key):
  2325. getattr(self, key).destroy()
  2326. setattr(self, key, value)
  2327. self._keys.update(kArgs.keys())
  2328. def destroy(self):
  2329. for key in self._keys:
  2330. getattr(self, key).destroy()
  2331. ScratchPad.destroy(self)
  2332. class Sync:
  2333. _SeriesGen = SerialNumGen()
  2334. def __init__(self, name, other=None):
  2335. self._name = name
  2336. if other is None:
  2337. self._series = self._SeriesGen.next()
  2338. self._value = 0
  2339. else:
  2340. self._series = other._series
  2341. self._value = other._value
  2342. def invalidate(self):
  2343. self._value = None
  2344. def change(self):
  2345. self._value += 1
  2346. def sync(self, other):
  2347. if (self._series != other._series) or (self._value != other._value):
  2348. self._series = other._series
  2349. self._value = other._value
  2350. return True
  2351. else:
  2352. return False
  2353. def isSynced(self, other):
  2354. return ((self._series == other._series) and
  2355. (self._value == other._value))
  2356. def __repr__(self):
  2357. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  2358. self._name, self._series, self._value)
  2359. class RefCounter:
  2360. def __init__(self, byId=False):
  2361. self._byId = byId
  2362. self._refCounts = {}
  2363. def _getKey(self, item):
  2364. if self._byId:
  2365. key = id(item)
  2366. else:
  2367. key = item
  2368. def inc(self, item):
  2369. key = self._getKey(item)
  2370. self._refCounts.setdefault(key, 0)
  2371. self._refCounts[key] += 1
  2372. def dec(self, item):
  2373. """returns True if ref count has hit zero"""
  2374. key = self._getKey(item)
  2375. self._refCounts[key] -= 1
  2376. result = False
  2377. if self._refCounts[key] == 0:
  2378. result = True
  2379. del self._refCounts[key]
  2380. return result
  2381. def itype(obj):
  2382. # version of type that gives more complete information about instance types
  2383. global dtoolSuperBase
  2384. t = type(obj)
  2385. if t is types.InstanceType:
  2386. return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
  2387. str(obj.__class__))
  2388. else:
  2389. # C++ object instances appear to be types via type()
  2390. # check if this is a C++ object
  2391. if dtoolSuperBase is None:
  2392. _getDtoolSuperBase()
  2393. if isinstance(obj, dtoolSuperBase):
  2394. return '%s of %s>' % (repr(types.InstanceType)[:-1],
  2395. str(obj.__class__))
  2396. return t
  2397. def deeptype(obj, maxLen=100, _visitedIds=None):
  2398. if _visitedIds is None:
  2399. _visitedIds = set()
  2400. if id(obj) in _visitedIds:
  2401. return '<ALREADY-VISITED %s>' % itype(obj)
  2402. t = type(obj)
  2403. if t in (types.TupleType, types.ListType):
  2404. s = ''
  2405. s += {types.TupleType: '(',
  2406. types.ListType: '[',}[type(obj)]
  2407. if maxLen is not None and len(obj) > maxLen:
  2408. o = obj[:maxLen]
  2409. ellips = '...'
  2410. else:
  2411. o = obj
  2412. ellips = ''
  2413. _visitedIds.add(id(obj))
  2414. for item in o:
  2415. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  2416. s += ', '
  2417. _visitedIds.remove(id(obj))
  2418. s += ellips
  2419. s += {types.TupleType: ')',
  2420. types.ListType: ']',}[type(obj)]
  2421. return s
  2422. elif type(obj) is types.DictType:
  2423. s = '{'
  2424. if maxLen is not None and len(obj) > maxLen:
  2425. o = obj.keys()[:maxLen]
  2426. ellips = '...'
  2427. else:
  2428. o = obj.keys()
  2429. ellips = ''
  2430. _visitedIds.add(id(obj))
  2431. for key in o:
  2432. value = obj[key]
  2433. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  2434. deeptype(value, maxLen, _visitedIds=_visitedIds))
  2435. _visitedIds.remove(id(obj))
  2436. s += ellips
  2437. s += '}'
  2438. return s
  2439. else:
  2440. return str(itype(obj))
  2441. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  2442. """get a string that has each item of the list on its own line,
  2443. and each item is numbered on the left from zero"""
  2444. digits = 0
  2445. n = len(items)
  2446. while n > 0:
  2447. digits += 1
  2448. n /= 10
  2449. digits = digits
  2450. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  2451. first = True
  2452. s = ''
  2453. snip = '<SNIP>'
  2454. for i in xrange(len(items)):
  2455. if not first:
  2456. s += '\n'
  2457. first = False
  2458. objStr = fastRepr(items[i])
  2459. if len(objStr) > maxLen:
  2460. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2461. s += format % (i, itype(items[i]), objStr)
  2462. return s
  2463. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  2464. """get a string that has each item of the list on its own line,
  2465. the items are stringwise-sorted, and each item is numbered on
  2466. the left from zero"""
  2467. digits = 0
  2468. n = len(items)
  2469. while n > 0:
  2470. digits += 1
  2471. n /= 10
  2472. digits = digits
  2473. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  2474. snip = '<SNIP>'
  2475. strs = []
  2476. for item in items:
  2477. objStr = fastRepr(item)
  2478. if len(objStr) > maxLen:
  2479. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2480. strs.append(objStr)
  2481. first = True
  2482. s = ''
  2483. strs.sort()
  2484. for i in xrange(len(strs)):
  2485. if not first:
  2486. s += '\n'
  2487. first = False
  2488. objStr = strs[i]
  2489. s += format % (i, itype(items[i]), strs[i])
  2490. return s
  2491. def getNumberedTypedSortedStringWithReferrersGen(items, maxLen=10000, numPrefix=''):
  2492. """get a string that has each item of the list on its own line,
  2493. the items are stringwise-sorted, the object's referrers are shown,
  2494. and each item is numbered on the left from zero"""
  2495. digits = 0
  2496. n = len(items)
  2497. while n > 0:
  2498. digits += 1
  2499. n /= 10
  2500. digits = digits
  2501. format = numPrefix + '%0' + '%s' % digits + 'i:%s @ %s \t%s'
  2502. snip = '<SNIP>'
  2503. strs = []
  2504. for item in items:
  2505. strs.append(fastRepr(item))
  2506. strs.sort()
  2507. for i in xrange(len(strs)):
  2508. item = items[i]
  2509. objStr = strs[i]
  2510. objStr += ', \tREFERRERS=['
  2511. referrers = gc.get_referrers(item)
  2512. for ref in referrers:
  2513. objStr += '%s@%s, ' % (itype(ref), id(ref))
  2514. objStr += ']'
  2515. if len(objStr) > maxLen:
  2516. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2517. yield format % (i, itype(items[i]), id(items[i]), objStr)
  2518. def getNumberedTypedSortedStringWithReferrers(items, maxLen=10000, numPrefix=''):
  2519. """get a string that has each item of the list on its own line,
  2520. the items are stringwise-sorted, the object's referrers are shown,
  2521. and each item is numbered on the left from zero"""
  2522. s = ''
  2523. for line in getNumberedTypedSortedStringWithReferrersGen(items, maxLen, numPrefix):
  2524. s += '%s\n' % line
  2525. return s
  2526. def printNumberedTyped(items, maxLen=5000):
  2527. """print out each item of the list on its own line,
  2528. with each item numbered on the left from zero"""
  2529. digits = 0
  2530. n = len(items)
  2531. while n > 0:
  2532. digits += 1
  2533. n /= 10
  2534. digits = digits
  2535. format = '%0' + '%s' % digits + 'i:%s \t%s'
  2536. for i in xrange(len(items)):
  2537. objStr = fastRepr(items[i])
  2538. if len(objStr) > maxLen:
  2539. snip = '<SNIP>'
  2540. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2541. print format % (i, itype(items[i]), objStr)
  2542. def printNumberedTypesGen(items, maxLen=5000):
  2543. digits = 0
  2544. n = len(items)
  2545. while n > 0:
  2546. digits += 1
  2547. n /= 10
  2548. digits = digits
  2549. format = '%0' + '%s' % digits + 'i:%s'
  2550. for i in xrange(len(items)):
  2551. print format % (i, itype(items[i]))
  2552. yield None
  2553. def printNumberedTypes(items, maxLen=5000):
  2554. """print out the type of each item of the list on its own line,
  2555. with each item numbered on the left from zero"""
  2556. for result in printNumberedTypesGen(items, maxLen):
  2557. yield result
  2558. class DelayedCall:
  2559. """ calls a func after a specified delay """
  2560. def __init__(self, func, name=None, delay=None):
  2561. if name is None:
  2562. name = 'anonymous'
  2563. if delay is None:
  2564. delay = .01
  2565. self._func = func
  2566. self._taskName = 'DelayedCallback-%s' % name
  2567. self._delay = delay
  2568. self._finished = False
  2569. self._addDoLater()
  2570. def destroy(self):
  2571. self._finished = True
  2572. self._removeDoLater()
  2573. def finish(self):
  2574. if not self._finished:
  2575. self._doCallback()
  2576. self.destroy()
  2577. def _addDoLater(self):
  2578. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  2579. def _removeDoLater(self):
  2580. taskMgr.remove(self._taskName)
  2581. def _doCallback(self, task):
  2582. self._finished = True
  2583. func = self._func
  2584. del self._func
  2585. func()
  2586. class FrameDelayedCall:
  2587. """ calls a func after N frames """
  2588. def __init__(self, name, callback, frames=None, cancelFunc=None):
  2589. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  2590. # and callback is not called
  2591. if frames is None:
  2592. frames = 1
  2593. self._name = name
  2594. self._frames = frames
  2595. self._callback = callback
  2596. self._cancelFunc = cancelFunc
  2597. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  2598. self._finished = False
  2599. self._startTask()
  2600. def destroy(self):
  2601. self._finished = True
  2602. self._stopTask()
  2603. def finish(self):
  2604. if not self._finished:
  2605. self._finished = True
  2606. self._callback()
  2607. self.destroy()
  2608. def _startTask(self):
  2609. taskMgr.add(self._frameTask, self._taskName)
  2610. self._counter = 0
  2611. def _stopTask(self):
  2612. taskMgr.remove(self._taskName)
  2613. def _frameTask(self, task):
  2614. if self._cancelFunc and self._cancelFunc():
  2615. self.destroy()
  2616. return task.done
  2617. self._counter += 1
  2618. if self._counter >= self._frames:
  2619. self.finish()
  2620. return task.done
  2621. return task.cont
  2622. class DelayedFunctor:
  2623. """ Waits for this object to be called, then calls supplied functor after a delay.
  2624. Effectively inserts a time delay between the caller and the functor. """
  2625. def __init__(self, functor, name=None, delay=None):
  2626. self._functor = functor
  2627. self._name = name
  2628. # FunctionInterval requires __name__
  2629. self.__name__ = self._name
  2630. self._delay = delay
  2631. def _callFunctor(self):
  2632. cb = Functor(self._functor, *self._args, **self._kwArgs)
  2633. del self._functor
  2634. del self._name
  2635. del self._delay
  2636. del self._args
  2637. del self._kwArgs
  2638. del self._delayedCall
  2639. del self.__name__
  2640. cb()
  2641. def __call__(self, *args, **kwArgs):
  2642. self._args = args
  2643. self._kwArgs = kwArgs
  2644. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  2645. class SubframeCall:
  2646. """Calls a callback at a specific time during the frame using the
  2647. task system"""
  2648. def __init__(self, functor, taskPriority, name=None):
  2649. self._functor = functor
  2650. self._name = name
  2651. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  2652. taskMgr.add(self._doCallback,
  2653. self._taskName,
  2654. priority=taskPriority)
  2655. def _doCallback(self, task):
  2656. functor = self._functor
  2657. del self._functor
  2658. functor()
  2659. del self._name
  2660. self._taskName = None
  2661. return task.done
  2662. def cleanup(self):
  2663. if (self._taskName):
  2664. taskMgr.remove(self._taskName)
  2665. self._taskName = None
  2666. class ArgumentEater:
  2667. def __init__(self, numToEat, func):
  2668. self._numToEat = numToEat
  2669. self._func = func
  2670. def destroy(self):
  2671. del self._func
  2672. def __call__(self, *args, **kwArgs):
  2673. self._func(*args[self._numToEat:], **kwArgs)
  2674. class ClassTree:
  2675. def __init__(self, instanceOrClass):
  2676. if type(instanceOrClass) in (types.ClassType, types.TypeType):
  2677. cls = instanceOrClass
  2678. else:
  2679. cls = instanceOrClass.__class__
  2680. self._cls = cls
  2681. self._bases = []
  2682. for base in self._cls.__bases__:
  2683. if base not in (types.ObjectType, types.TypeType):
  2684. self._bases.append(ClassTree(base))
  2685. def getAllClasses(self):
  2686. # returns set of this class and all base classes
  2687. classes = set()
  2688. classes.add(self._cls)
  2689. for base in self._bases:
  2690. classes.update(base.getAllClasses())
  2691. return classes
  2692. def _getStr(self, indent=None, clsLeftAtIndent=None):
  2693. # indent is how far to the right to indent (i.e. how many levels
  2694. # deep in the hierarchy from the most-derived)
  2695. #
  2696. # clsLeftAtIndent is an array of # of classes left to be
  2697. # printed at each level of the hierarchy; most-derived is
  2698. # at index 0
  2699. if indent is None:
  2700. indent = 0
  2701. clsLeftAtIndent = [1]
  2702. s = ''
  2703. if (indent > 1):
  2704. for i in range(1, indent):
  2705. # if we have not printed all base classes at
  2706. # this indent level, keep printing the vertical
  2707. # column
  2708. if clsLeftAtIndent[i] > 0:
  2709. s += ' |'
  2710. else:
  2711. s += ' '
  2712. if (indent > 0):
  2713. s += ' +'
  2714. s += self._cls.__name__
  2715. clsLeftAtIndent[indent] -= 1
  2716. """
  2717. ### show the module to the right of the class name
  2718. moduleIndent = 48
  2719. if len(s) >= moduleIndent:
  2720. moduleIndent = (len(s) % 4) + 4
  2721. padding = moduleIndent - len(s)
  2722. s += padding * ' '
  2723. s += self._cls.__module__
  2724. ###
  2725. """
  2726. if len(self._bases):
  2727. newList = list(clsLeftAtIndent)
  2728. newList.append(len(self._bases))
  2729. bases = self._bases
  2730. # print classes with fewer bases first
  2731. bases.sort(lambda x,y: len(x._bases)-len(y._bases))
  2732. for base in bases:
  2733. s += '\n%s' % base._getStr(indent+1, newList)
  2734. return s
  2735. def __repr__(self):
  2736. return self._getStr()
  2737. def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigParam = []):
  2738. """
  2739. This is a decorator generating function. Use is similar to
  2740. a @decorator, except you must be sure to call it as a function.
  2741. It actually returns the decorator which is then used to transform
  2742. your decorated function. Confusing at first, I know.
  2743. Decoration occurs at function definition time.
  2744. If __dev__ is not defined, or resolves to False, this function
  2745. has no effect and no wrapping/transform occurs. So in production,
  2746. it's as if the report has been asserted out.
  2747. Parameters::
  2748. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  2749. This allows you to specify certain useful bits of info.
  2750. module: Prints the module that this report statement
  2751. can be found in.
  2752. args: Prints the arguments as they were passed to
  2753. this function.
  2754. timeStamp: Adds the current frame time to the output.
  2755. deltaStamp: Adds the current AI synched frame time to
  2756. the output
  2757. frameCount: Adds the current frame count to the output.
  2758. Usually cleaner than the timeStamp output.
  2759. avLocation: Adds the localAvatar's network location
  2760. to the output. Useful for interest debugging.
  2761. interests: Prints the current interest state after the
  2762. report.
  2763. stackTrace: Prints a stack trace after the report.
  2764. prefix: Optional string to prepend to output, just before the function.
  2765. Allows for easy grepping and is useful when merging AI/Client
  2766. reports into a single file.
  2767. notifyFunc: A notify function such as info, debug, warning, etc.
  2768. By default the report will be printed to stdout. This
  2769. will allow you send the report to a designated 'notify'
  2770. output.
  2771. dConfigParam: A list of Config.prc string variables.
  2772. By default the report will always print. If you
  2773. specify this param, it will only print if one of the
  2774. specified config strings resolve to True.
  2775. """
  2776. def decorator(f):
  2777. return f
  2778. try:
  2779. if not (__dev__ or config.GetBool('force-reports', 0)):
  2780. return decorator
  2781. # determine whether we should use the decorator
  2782. # based on the value of dConfigParam.
  2783. doPrint = False
  2784. if not dConfigParam:
  2785. doPrint = True
  2786. else:
  2787. if not isinstance(dConfigParam, (list,tuple)):
  2788. dConfigParamList = (dConfigParam,)
  2789. else:
  2790. dConfigParamList = dConfigParam
  2791. for param in dConfigParamList:
  2792. if(config.GetBool(param, 0)):
  2793. doPrint = True
  2794. break
  2795. if not doPrint:
  2796. return decorator
  2797. except NameError,e:
  2798. return decorator
  2799. from direct.distributed.ClockDelta import globalClockDelta
  2800. def decorator(f):
  2801. def wrap(*args,**kwargs):
  2802. if args:
  2803. rArgs = [args[0].__class__.__name__ + ', ']
  2804. else:
  2805. rArgs = []
  2806. if 'args' in types:
  2807. rArgs += [`x`+', ' for x in args[1:]] + \
  2808. [ x + ' = ' + '%s, ' % `y` for x,y in kwargs.items()]
  2809. if not rArgs:
  2810. rArgs = '()'
  2811. else:
  2812. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2813. outStr = '%s%s' % (f.func_name, rArgs)
  2814. if prefix:
  2815. outStr = '%s %s' % (prefix, outStr)
  2816. preStr = ''
  2817. if 'module' in types:
  2818. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  2819. if 'frameCount' in types:
  2820. outStr = '%8d : %s' % (globalClock.getFrameCount(), outStr)
  2821. if 'timeStamp' in types:
  2822. outStr = '%8.3f : %s' % (globalClock.getFrameTime(), outStr)
  2823. if 'deltaStamp' in types:
  2824. outStr = '%8.2f : %s' % (globalClock.getRealTime() - \
  2825. globalClockDelta.delta, outStr)
  2826. if 'avLocation' in types:
  2827. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  2828. if xform:
  2829. outStr = '%s : %s' % (outStr, xform(args[0]))
  2830. if notifyFunc:
  2831. notifyFunc(outStr)
  2832. else:
  2833. print outStr
  2834. if 'interests' in types:
  2835. base.cr.printInterestSets()
  2836. if 'stackTrace' in types:
  2837. print StackTrace()
  2838. return f(*args,**kwargs)
  2839. wrap.func_name = f.func_name
  2840. wrap.func_dict = f.func_dict
  2841. wrap.func_doc = f.func_doc
  2842. return wrap
  2843. return decorator
  2844. def getBase():
  2845. try:
  2846. return base
  2847. except:
  2848. return simbase
  2849. def superFlattenShip(ship):
  2850. #PHASE 1: remove characters
  2851. characterNodes=ship.findAllMatches("**/+Character")
  2852. for i in range(characterNodes.getNumPaths()):
  2853. character=characterNodes.getPath(i)
  2854. children=character.getChildrenAsList()
  2855. for child in children:
  2856. child.copyTo(character.getParent())
  2857. character.reparentTo(hidden)
  2858. #PHASE 2: remove textures
  2859. tex=ship.findAllTextures().getTexture(0)
  2860. ship.setTexture(tex,1000)
  2861. #PHASE 3: stop rocking task
  2862. taskMgr.remove("shipRocking-%d"%(ship.getDoId()))
  2863. #PHASE 4: kill lamp effects
  2864. from pirates.shipparts.DistributedShipDecor import DistributedShipDecor
  2865. for DO in base.cr.doId2do.values():
  2866. if(type(DO) == DistributedShipDecor):
  2867. if (hasattr(DO.prop, 'lanternGlowEffect')):
  2868. DO.prop.lanternGlowEffect.destroy()
  2869. #PHASE 5: flatten strong!
  2870. return ship.flattenStrong()
  2871. exceptionLoggedNotify = None
  2872. def exceptionLogged(append=True):
  2873. """decorator that outputs the function name and all arguments
  2874. if an exception passes back through the stack frame
  2875. if append is true, string is appended to the __str__ output of
  2876. the exception. if append is false, string is printed to the log
  2877. directly. If the output will take up many lines, it's recommended
  2878. to set append to False so that the exception stack is not hidden
  2879. by the output of this decorator.
  2880. """
  2881. try:
  2882. null = not __dev__
  2883. except:
  2884. null = not __debug__
  2885. if null:
  2886. # if we're not in __dev__, just return the function itself. This
  2887. # results in zero runtime overhead, since decorators are evaluated
  2888. # at module-load.
  2889. def nullDecorator(f):
  2890. return f
  2891. return nullDecorator
  2892. def _decoratorFunc(f, append=append):
  2893. global exceptionLoggedNotify
  2894. if exceptionLoggedNotify is None:
  2895. from direct.directnotify.DirectNotifyGlobal import directNotify
  2896. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  2897. def _exceptionLogged(*args, **kArgs):
  2898. try:
  2899. return f(*args, **kArgs)
  2900. except Exception, e:
  2901. try:
  2902. s = '%s(' % f.func_name
  2903. for arg in args:
  2904. s += '%s, ' % arg
  2905. for key, value in kArgs.items():
  2906. s += '%s=%s, ' % (key, value)
  2907. if len(args) or len(kArgs):
  2908. s = s[:-2]
  2909. s += ')'
  2910. if append:
  2911. appendStr(e, '\n%s' % s)
  2912. else:
  2913. exceptionLoggedNotify.info(s)
  2914. except:
  2915. exceptionLoggedNotify.info(
  2916. '%s: ERROR IN PRINTING' % f.func_name)
  2917. raise
  2918. _exceptionLogged.__doc__ = f.__doc__
  2919. return _exceptionLogged
  2920. return _decoratorFunc
  2921. # class 'decorator' that records the stack at the time of creation
  2922. # be careful with this, it creates a StackTrace, and that can take a
  2923. # lot of CPU
  2924. def recordCreationStack(cls):
  2925. if not hasattr(cls, '__init__'):
  2926. raise 'recordCreationStack: class \'%s\' must define __init__' % cls.__name__
  2927. cls.__moved_init__ = cls.__init__
  2928. def __recordCreationStack_init__(self, *args, **kArgs):
  2929. self._creationStackTrace = StackTrace(start=1)
  2930. return self.__moved_init__(*args, **kArgs)
  2931. def getCreationStackTrace(self):
  2932. return self._creationStackTrace
  2933. def getCreationStackTraceCompactStr(self):
  2934. return self._creationStackTrace.compact()
  2935. def printCreationStackTrace(self):
  2936. print self._creationStackTrace
  2937. cls.__init__ = __recordCreationStack_init__
  2938. cls.getCreationStackTrace = getCreationStackTrace
  2939. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2940. cls.printCreationStackTrace = printCreationStackTrace
  2941. return cls
  2942. # like recordCreationStack but stores the stack as a compact stack list-of-strings
  2943. # scales well for memory usage
  2944. def recordCreationStackStr(cls):
  2945. if not hasattr(cls, '__init__'):
  2946. raise 'recordCreationStackStr: class \'%s\' must define __init__' % cls.__name__
  2947. cls.__moved_init__ = cls.__init__
  2948. def __recordCreationStackStr_init__(self, *args, **kArgs):
  2949. # store as list of strings to conserve memory
  2950. self._creationStackTraceStrLst = StackTrace(start=1).compact().split(',')
  2951. return self.__moved_init__(*args, **kArgs)
  2952. def getCreationStackTraceCompactStr(self):
  2953. return string.join(self._creationStackTraceStrLst, ',')
  2954. def printCreationStackTrace(self):
  2955. print string.join(self._creationStackTraceStrLst, ',')
  2956. cls.__init__ = __recordCreationStackStr_init__
  2957. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2958. cls.printCreationStackTrace = printCreationStackTrace
  2959. return cls
  2960. # class 'decorator' that logs all method calls for a particular class
  2961. def logMethodCalls(cls):
  2962. if not hasattr(cls, 'notify'):
  2963. raise 'logMethodCalls: class \'%s\' must have a notify' % cls.__name__
  2964. for name in dir(cls):
  2965. method = getattr(cls, name)
  2966. if callable(method):
  2967. def getLoggedMethodCall(method):
  2968. def __logMethodCall__(obj, *args, **kArgs):
  2969. s = '%s(' % method.__name__
  2970. for arg in args:
  2971. try:
  2972. argStr = repr(arg)
  2973. except:
  2974. argStr = 'bad repr: %s' % arg.__class__
  2975. s += '%s, ' % argStr
  2976. for karg, value in kArgs.items():
  2977. s += '%s=%s, ' % (karg, repr(value))
  2978. if len(args) or len(kArgs):
  2979. s = s[:-2]
  2980. s += ')'
  2981. obj.notify.info(s)
  2982. return method(obj, *args, **kArgs)
  2983. return __logMethodCall__
  2984. setattr(cls, name, getLoggedMethodCall(method))
  2985. __logMethodCall__ = None
  2986. return cls
  2987. # http://en.wikipedia.org/wiki/Golden_ratio
  2988. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  2989. class GoldenRectangle:
  2990. @staticmethod
  2991. def getLongerEdge(shorter):
  2992. return shorter * GoldenRatio
  2993. @staticmethod
  2994. def getShorterEdge(longer):
  2995. return longer / GoldenRatio
  2996. class HotkeyBreaker:
  2997. def __init__(self,breakKeys = []):
  2998. from direct.showbase.DirectObject import DirectObject
  2999. self.do = DirectObject()
  3000. self.breakKeys = {}
  3001. if not isinstance(breakKeys, (list,tuple)):
  3002. breakKeys = (breakKeys,)
  3003. for key in breakKeys:
  3004. self.addBreakKey(key)
  3005. def addBreakKey(self,breakKey):
  3006. if __dev__:
  3007. self.do.accept(breakKey,self.breakFunc,extraArgs = [breakKey])
  3008. def removeBreakKey(self,breakKey):
  3009. if __dev__:
  3010. self.do.ignore(breakKey)
  3011. def breakFunc(self,breakKey):
  3012. if __dev__:
  3013. self.breakKeys[breakKey] = True
  3014. def setBreakPt(self, breakKey = None, persistent = False):
  3015. if __dev__:
  3016. if not breakKey:
  3017. import pdb;pdb.set_trace()
  3018. return True
  3019. else:
  3020. if self.breakKeys.get(breakKey,False):
  3021. if not persistent:
  3022. self.breakKeys.pop(breakKey)
  3023. import pdb;pdb.set_trace()
  3024. return True
  3025. return True
  3026. def clearBreakPt(self, breakKey):
  3027. if __dev__:
  3028. return bool(self.breakKeys.pop(breakKey,None))
  3029. def nullGen():
  3030. # generator that ends immediately
  3031. if False:
  3032. # yield that never runs but still exists, making this func a generator
  3033. yield None
  3034. def loopGen(l):
  3035. # generator that yields the items of an iterable object forever
  3036. def _gen(l):
  3037. while True:
  3038. for item in l:
  3039. yield item
  3040. gen = _gen(l)
  3041. # don't leak
  3042. _gen = None
  3043. return gen
  3044. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  3045. # iterates and finally yields a flywheel generator object
  3046. # the number of appearances for each object is controlled by passing in
  3047. # a list of counts, or a functor that returns a count when called with
  3048. # an object from the 'objects' list.
  3049. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  3050. def flywheel(index2objectAndCount):
  3051. # generator to produce a sequence whose elements appear a specific number of times
  3052. while len(index2objectAndCount):
  3053. keyList = index2objectAndCount.keys()
  3054. for key in keyList:
  3055. if index2objectAndCount[key][1] > 0:
  3056. yield index2objectAndCount[key][0]
  3057. index2objectAndCount[key][1] -= 1
  3058. if index2objectAndCount[key][1] <= 0:
  3059. del index2objectAndCount[key]
  3060. # if we were not given a list of counts, create it by calling countFunc
  3061. if countList is None:
  3062. countList = []
  3063. for object in objects:
  3064. yield None
  3065. countList.append(countFunc(object))
  3066. if scale is not None:
  3067. # scale the counts if we've got a scale factor
  3068. for i in xrange(len(countList)):
  3069. yield None
  3070. if countList[i] > 0:
  3071. countList[i] = max(1, int(countList[i] * scale))
  3072. # create a dict for the flywheel to use during its iteration to efficiently select
  3073. # the objects for the sequence
  3074. index2objectAndCount = {}
  3075. for i in xrange(len(countList)):
  3076. yield None
  3077. index2objectAndCount[i] = [objects[i], countList[i]]
  3078. # create the flywheel generator
  3079. yield flywheel(index2objectAndCount)
  3080. def flywheel(*args, **kArgs):
  3081. # create a flywheel generator
  3082. # see arguments and comments in flywheelGen above
  3083. # example usage:
  3084. """
  3085. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  3086. ... print i,
  3087. ...
  3088. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  3089. """
  3090. for flywheel in makeFlywheelGen(*args, **kArgs):
  3091. pass
  3092. return flywheel
  3093. if __debug__:
  3094. f = flywheel(['a','b','c','d'], countList=[11,20,3,4])
  3095. obj2count = {}
  3096. for obj in f:
  3097. obj2count.setdefault(obj, 0)
  3098. obj2count[obj] += 1
  3099. assert obj2count['a'] == 11
  3100. assert obj2count['b'] == 20
  3101. assert obj2count['c'] == 3
  3102. assert obj2count['d'] == 4
  3103. f = flywheel([1,2,3,4], countFunc=lambda x: x*2)
  3104. obj2count = {}
  3105. for obj in f:
  3106. obj2count.setdefault(obj, 0)
  3107. obj2count[obj] += 1
  3108. assert obj2count[1] == 2
  3109. assert obj2count[2] == 4
  3110. assert obj2count[3] == 6
  3111. assert obj2count[4] == 8
  3112. f = flywheel([1,2,3,4], countFunc=lambda x: x, scale = 3)
  3113. obj2count = {}
  3114. for obj in f:
  3115. obj2count.setdefault(obj, 0)
  3116. obj2count[obj] += 1
  3117. assert obj2count[1] == 1 * 3
  3118. assert obj2count[2] == 2 * 3
  3119. assert obj2count[3] == 3 * 3
  3120. assert obj2count[4] == 4 * 3
  3121. def quickProfile(name="unnamed"):
  3122. def profileDecorator(f):
  3123. if(not config.GetBool("use-profiler",0)):
  3124. return f
  3125. def _profiled(*args, **kArgs):
  3126. # must do this in here because we don't have base/simbase
  3127. # at the time that PythonUtil is loaded
  3128. if(not config.GetBool("profile-debug",0)):
  3129. #dumb timings
  3130. st=globalClock.getRealTime()
  3131. f(*args,**kArgs)
  3132. s=globalClock.getRealTime()-st
  3133. print "Function %s.%s took %s seconds"%(f.__module__, f.__name__,s)
  3134. else:
  3135. import profile as prof, pstats
  3136. #detailed profile, stored in base.stats under (
  3137. if(not hasattr(base,"stats")):
  3138. base.stats={}
  3139. if(not base.stats.get(name)):
  3140. base.stats[name]=[]
  3141. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  3142. s=pstats.Stats("t.prof")
  3143. #p=hotshot.Profile("t.prof")
  3144. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  3145. #s = hotshot.stats.load("t.prof")
  3146. s.strip_dirs()
  3147. s.sort_stats("cumulative")
  3148. base.stats[name].append(s)
  3149. _profiled.__doc__ = f.__doc__
  3150. return _profiled
  3151. return profileDecorator
  3152. def getTotalAnnounceTime():
  3153. td=0
  3154. for objs in base.stats.values():
  3155. for stat in objs:
  3156. td+=getAnnounceGenerateTime(stat)
  3157. return td
  3158. def getAnnounceGenerateTime(stat):
  3159. val=0
  3160. stats=stat.stats
  3161. for i in stats.keys():
  3162. if(i[2]=="announceGenerate"):
  3163. newVal=stats[i][3]
  3164. if(newVal>val):
  3165. val=newVal
  3166. return val
  3167. def choice(condition, ifTrue, ifFalse):
  3168. # equivalent of C++ (condition ? ifTrue : ifFalse)
  3169. if condition:
  3170. return ifTrue
  3171. else:
  3172. return ifFalse
  3173. class MiniLog:
  3174. def __init__(self, name):
  3175. self.indent = 1
  3176. self.name = name
  3177. self.lines = []
  3178. def __str__(self):
  3179. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  3180. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  3181. def enterFunction(self, funcName, *args, **kw):
  3182. rArgs = [`x`+', ' for x in args] + \
  3183. [ x + ' = ' + '%s, ' % `y` for x,y in kw.items()]
  3184. if not rArgs:
  3185. rArgs = '()'
  3186. else:
  3187. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  3188. line = '%s%s' % (funcName, rArgs)
  3189. self.appendFunctionCall(line)
  3190. self.indent += 1
  3191. return line
  3192. def exitFunction(self):
  3193. self.indent -= 1
  3194. return self.indent
  3195. def appendFunctionCall(self, line):
  3196. self.lines.append(' '*(self.indent*2) + line)
  3197. return line
  3198. def appendLine(self, line):
  3199. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  3200. return line
  3201. def flush(self):
  3202. outStr = str(self)
  3203. self.indent = 0
  3204. self.lines = []
  3205. return outStr
  3206. class MiniLogSentry:
  3207. def __init__(self, log, funcName, *args, **kw):
  3208. self.log = log
  3209. if self.log:
  3210. self.log.enterFunction(funcName, *args, **kw)
  3211. def __del__(self):
  3212. if self.log:
  3213. self.log.exitFunction()
  3214. del self.log
  3215. def logBlock(id, msg):
  3216. print '<< LOGBLOCK(%03d)' % id
  3217. print str(msg)
  3218. print '/LOGBLOCK(%03d) >>' % id
  3219. class HierarchyException(Exception):
  3220. JOSWILSO = 0
  3221. def __init__(self, owner, description):
  3222. self.owner = owner
  3223. self.desc = description
  3224. def __str__(self):
  3225. return '(%s): %s' % (self.owner, self.desc)
  3226. def __repr__(self):
  3227. return 'HierarchyException(%s)' % (self.owner, )
  3228. # __dev__ is not defined at import time, call this after it's defined
  3229. def recordFunctorCreationStacks():
  3230. global Functor
  3231. if __dev__:
  3232. if not hasattr(Functor, '_functorCreationStacksRecorded'):
  3233. Functor = recordCreationStackStr(Functor)
  3234. Functor._functorCreationStacksRecorded = True
  3235. Functor.__call__ = Functor._exceptionLoggedCreationStack__call__
  3236. def formatTimeCompact(seconds):
  3237. # returns string in format '1d3h22m43s'
  3238. result = ''
  3239. a = int(seconds)
  3240. seconds = a % 60
  3241. a /= 60
  3242. if a > 0:
  3243. minutes = a % 60
  3244. a /= 60
  3245. if a > 0:
  3246. hours = a % 24
  3247. a /= 24
  3248. if a > 0:
  3249. days = a
  3250. result += '%sd' % days
  3251. result += '%sh' % hours
  3252. result += '%sm' % minutes
  3253. result += '%ss' % seconds
  3254. return result
  3255. class AlphabetCounter:
  3256. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  3257. def __init__(self):
  3258. self._curCounter = ['A']
  3259. def next(self):
  3260. result = ''.join([c for c in self._curCounter])
  3261. index = -1
  3262. while True:
  3263. curChar = self._curCounter[index]
  3264. if curChar is 'Z':
  3265. nextChar = 'A'
  3266. carry = True
  3267. else:
  3268. nextChar = chr(ord(self._curCounter[index])+1)
  3269. carry = False
  3270. self._curCounter[index] = nextChar
  3271. if carry:
  3272. if (-index) == len(self._curCounter):
  3273. self._curCounter = ['A',] + self._curCounter
  3274. break
  3275. else:
  3276. index -= 1
  3277. carry = False
  3278. else:
  3279. break
  3280. return result
  3281. if __debug__:
  3282. def testAlphabetCounter():
  3283. tempList = []
  3284. ac = AlphabetCounter()
  3285. for i in xrange(26*3):
  3286. tempList.append(ac.next())
  3287. assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  3288. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
  3289. 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',]
  3290. ac = AlphabetCounter()
  3291. num = 26 # A-Z
  3292. num += (26*26) # AA-ZZ
  3293. num += 26 # AAZ
  3294. num += 1 # ABA
  3295. num += 2 # ABC
  3296. for i in xrange(num):
  3297. x = ac.next()
  3298. assert x == 'ABC'
  3299. testAlphabetCounter()
  3300. del testAlphabetCounter
  3301. globalPdb = None
  3302. traceCalled = False
  3303. def setupPdb():
  3304. import pdb;
  3305. class pandaPdb(pdb.Pdb):
  3306. def stop_here(self, frame):
  3307. global traceCalled
  3308. if(traceCalled):
  3309. result = pdb.Pdb.stop_here(self, frame)
  3310. if(result == True):
  3311. traceCalled = False
  3312. return result
  3313. if frame is self.stopframe:
  3314. return True
  3315. return False
  3316. global globalPdb
  3317. globalPdb = pandaPdb()
  3318. globalPdb.reset()
  3319. sys.settrace(globalPdb.trace_dispatch)
  3320. def pandaTrace():
  3321. if __dev__:
  3322. if not globalPdb:
  3323. setupPdb()
  3324. global traceCalled
  3325. globalPdb.set_trace(sys._getframe().f_back)
  3326. traceCalled = True
  3327. packageMap = {
  3328. "toontown":"$TOONTOWN",
  3329. "direct":"$DIRECT",
  3330. "otp":"$OTP",
  3331. "pirates":"$PIRATES",
  3332. }
  3333. #assuming . dereferncing for nice linking to imports
  3334. def pandaBreak(dotpath, linenum, temporary = 0, cond = None):
  3335. if __dev__:
  3336. from pandac.PandaModules import Filename
  3337. if not globalPdb:
  3338. setupPdb()
  3339. dirs = dotpath.split(".")
  3340. root = Filename.expandFrom(packageMap[dirs[0]]).toOsSpecific()
  3341. filename = root + "\\src"
  3342. for d in dirs[1:]:
  3343. filename="%s\\%s"%(filename,d)
  3344. globalPdb.set_break(filename+".py", linenum, temporary, cond)
  3345. import __builtin__
  3346. __builtin__.Functor = Functor
  3347. __builtin__.Stack = Stack
  3348. __builtin__.Queue = Queue
  3349. __builtin__.Enum = Enum
  3350. __builtin__.SerialNumGen = SerialNumGen
  3351. __builtin__.ScratchPad = ScratchPad
  3352. __builtin__.DestructiveScratchPad = DestructiveScratchPad
  3353. __builtin__.uniqueName = uniqueName
  3354. __builtin__.serialNum = serialNum
  3355. __builtin__.profiled = profiled
  3356. __builtin__.set_trace = set_trace
  3357. __builtin__.setTrace = setTrace
  3358. __builtin__.pm = pm
  3359. __builtin__.itype = itype
  3360. __builtin__.exceptionLogged = exceptionLogged
  3361. __builtin__.appendStr = appendStr
  3362. __builtin__.bound = bound
  3363. __builtin__.lerp = lerp
  3364. __builtin__.notNone = notNone
  3365. __builtin__.clampScalar = clampScalar
  3366. __builtin__.makeList = makeList
  3367. __builtin__.makeTuple = makeTuple
  3368. __builtin__.printStack = printStack
  3369. __builtin__.printReverseStack = printReverseStack
  3370. __builtin__.printVerboseStack = printVerboseStack
  3371. __builtin__.DelayedCall = DelayedCall
  3372. __builtin__.DelayedFunctor = DelayedFunctor
  3373. __builtin__.FrameDelayedCall = FrameDelayedCall
  3374. __builtin__.SubframeCall = SubframeCall
  3375. __builtin__.ArgumentEater = ArgumentEater
  3376. __builtin__.ClassTree = ClassTree
  3377. __builtin__.invertDict = invertDict
  3378. __builtin__.invertDictLossless = invertDictLossless
  3379. __builtin__.getBase = getBase
  3380. __builtin__.safeRepr = safeRepr
  3381. __builtin__.fastRepr = fastRepr
  3382. __builtin__.nullGen = nullGen
  3383. __builtin__.flywheel = flywheel
  3384. __builtin__.loopGen = loopGen
  3385. __builtin__.StackTrace = StackTrace
  3386. __builtin__.choice = choice
  3387. __builtin__.report = report
  3388. __builtin__.MiniLog = MiniLog
  3389. __builtin__.MiniLogSentry = MiniLogSentry
  3390. __builtin__.logBlock = logBlock
  3391. __builtin__.HierarchyException = HierarchyException
  3392. __builtin__.pdir = pdir
  3393. __builtin__.deeptype = deeptype