PythonUtil.py 109 KB

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