PythonUtil.py 141 KB

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