PythonUtil.py 78 KB

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