PythonUtil.py 94 KB

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