PythonUtil.py 123 KB

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