PythonUtil.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961
  1. """Undocumented Module"""
  2. __all__ = ['indent',
  3. 'StackTrace', 'traceFunctionCall', 'traceParentCall', 'printThisCall',
  4. 'doc', 'adjust', 'difference', 'intersection', 'union',
  5. 'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
  6. 'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
  7. 'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src',
  8. 'closestDestAngle2', 'closestDestAngle', 'binaryRepr', 'profileFunc',
  9. 'profiled', 'startProfile', 'printProfile', 'getSetterName',
  10. 'getSetter', 'Functor', 'Stack', 'Queue',
  11. 'bound', 'clamp', 'lerp', 'average', 'addListsByValue',
  12. 'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
  13. 'stackEntryInfo', 'lineInfo', 'callerInfo', 'lineTag',
  14. 'findPythonModule', 'mostDerivedLast',
  15. 'weightedChoice', 'randFloat', 'normalDistrib',
  16. 'weightedRand', 'randUint31', 'randInt32', 'randUint32',
  17. 'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
  18. 'SingletonError', 'printListEnum', 'safeRepr',
  19. 'fastRepr', 'isDefaultValue',
  20. 'ScratchPad', 'Sync', 'itype', 'getNumberedTypedString',
  21. 'getNumberedTypedSortedString', 'getNumberedTypedSortedStringWithReferrers',
  22. 'getNumberedTypedSortedStringWithReferrersGen',
  23. 'printNumberedTyped', 'DelayedCall', 'DelayedFunctor',
  24. 'FrameDelayedCall', 'SubframeCall', 'getBase',
  25. 'HotkeyBreaker','logMethodCalls','GoldenRatio',
  26. 'GoldenRectangle', 'rad90', 'rad180', 'rad270', 'rad360',
  27. 'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel', 'choice',
  28. 'printStack', 'printReverseStack', 'listToIndex2item', 'listToItem2index',
  29. 'pandaBreak','pandaTrace','formatTimeCompact',
  30. 'deeptype','getProfileResultString','StdoutCapture','StdoutPassthrough',
  31. 'Averager', 'getRepository', 'formatTimeExact', 'startSuperLog', 'endSuperLog',
  32. 'typeName', 'safeTypeName', 'histogramDict', 'unescapeHtmlString']
  33. import types
  34. import string
  35. import math
  36. import operator
  37. import inspect
  38. import os
  39. import sys
  40. import random
  41. import time
  42. import gc
  43. #if __debug__:
  44. import traceback
  45. import __builtin__
  46. from StringIO import StringIO
  47. import marshal
  48. __report_indent = 3
  49. from panda3d.core import ConfigVariableBool
  50. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  51. """
  52. # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
  53. def Functor(function, *args, **kArgs):
  54. argsCopy = args[:]
  55. def functor(*cArgs, **ckArgs):
  56. kArgs.update(ckArgs)
  57. return function(*(argsCopy + cArgs), **kArgs)
  58. return functor
  59. """
  60. class Functor:
  61. def __init__(self, function, *args, **kargs):
  62. assert callable(function), "function should be a callable obj"
  63. self._function = function
  64. self._args = args
  65. self._kargs = kargs
  66. if hasattr(self._function, '__name__'):
  67. self.__name__ = self._function.__name__
  68. else:
  69. self.__name__ = str(itype(self._function))
  70. if hasattr(self._function, '__doc__'):
  71. self.__doc__ = self._function.__doc__
  72. else:
  73. self.__doc__ = self.__name__
  74. def destroy(self):
  75. del self._function
  76. del self._args
  77. del self._kargs
  78. del self.__name__
  79. del self.__doc__
  80. def _do__call__(self, *args, **kargs):
  81. _kargs = self._kargs.copy()
  82. _kargs.update(kargs)
  83. return self._function(*(self._args + args), **_kargs)
  84. # this method is used in place of __call__ if we are recording creation stacks
  85. def _exceptionLoggedCreationStack__call__(self, *args, **kargs):
  86. try:
  87. return self._do__call__(*args, **kargs)
  88. except Exception, e:
  89. print '-->Functor creation stack (%s): %s' % (
  90. self.__name__, self.getCreationStackTraceCompactStr())
  91. raise
  92. __call__ = _do__call__
  93. def __repr__(self):
  94. s = 'Functor(%s' % self._function.__name__
  95. for arg in self._args:
  96. try:
  97. argStr = repr(arg)
  98. except:
  99. argStr = 'bad repr: %s' % arg.__class__
  100. s += ', %s' % argStr
  101. for karg, value in self._kargs.items():
  102. s += ', %s=%s' % (karg, repr(value))
  103. s += ')'
  104. return s
  105. class Stack:
  106. def __init__(self):
  107. self.__list = []
  108. def push(self, item):
  109. self.__list.append(item)
  110. def top(self):
  111. # return the item on the top of the stack without popping it off
  112. return self.__list[-1]
  113. def pop(self):
  114. return self.__list.pop()
  115. def clear(self):
  116. self.__list = []
  117. def isEmpty(self):
  118. return len(self.__list) == 0
  119. def __len__(self):
  120. return len(self.__list)
  121. class Queue:
  122. # FIFO queue
  123. # interface is intentionally identical to Stack (LIFO)
  124. def __init__(self):
  125. self.__list = []
  126. def push(self, item):
  127. self.__list.append(item)
  128. def top(self):
  129. # return the next item at the front of the queue without popping it off
  130. return self.__list[0]
  131. def front(self):
  132. return self.__list[0]
  133. def back(self):
  134. return self.__list[-1]
  135. def pop(self):
  136. return self.__list.pop(0)
  137. def clear(self):
  138. self.__list = []
  139. def isEmpty(self):
  140. return len(self.__list) == 0
  141. def __len__(self):
  142. return len(self.__list)
  143. if __debug__ and __name__ == '__main__':
  144. q = Queue()
  145. assert q.isEmpty()
  146. q.clear()
  147. assert q.isEmpty()
  148. q.push(10)
  149. assert not q.isEmpty()
  150. q.push(20)
  151. assert not q.isEmpty()
  152. assert len(q) == 2
  153. assert q.front() == 10
  154. assert q.back() == 20
  155. assert q.top() == 10
  156. assert q.top() == 10
  157. assert q.pop() == 10
  158. assert len(q) == 1
  159. assert not q.isEmpty()
  160. assert q.pop() == 20
  161. assert len(q) == 0
  162. assert q.isEmpty()
  163. def indent(stream, numIndents, str):
  164. """
  165. Write str to stream with numIndents in front of it
  166. """
  167. # To match emacs, instead of a tab character we will use 4 spaces
  168. stream.write(' ' * numIndents + str)
  169. #if __debug__: #RAU accdg to Darren its's ok that StackTrace is not protected by __debug__
  170. # DCR: if somebody ends up using StackTrace in production, either
  171. # A) it will be OK because it hardly ever gets called, or
  172. # B) it will be easy to track it down (grep for StackTrace)
  173. class StackTrace:
  174. def __init__(self, label="", start=0, limit=None):
  175. """
  176. label is a string (or anything that be be a string)
  177. that is printed as part of the trace back.
  178. This is just to make it easier to tell what the
  179. stack trace is referring to.
  180. start is an integer number of stack frames back
  181. from the most recent. (This is automatically
  182. bumped up by one to skip the __init__ call
  183. to the StackTrace).
  184. limit is an integer number of stack frames
  185. to record (or None for unlimited).
  186. """
  187. self.label = label
  188. if limit is not None:
  189. self.trace = traceback.extract_stack(sys._getframe(1+start),
  190. limit=limit)
  191. else:
  192. self.trace = traceback.extract_stack(sys._getframe(1+start))
  193. def compact(self):
  194. r = ''
  195. comma = ','
  196. for filename, lineNum, funcName, text in self.trace:
  197. r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
  198. if len(r):
  199. r = r[:-len(comma)]
  200. return r
  201. def reverseCompact(self):
  202. r = ''
  203. comma = ','
  204. for filename, lineNum, funcName, text in self.trace:
  205. r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
  206. if len(r):
  207. r = r[:-len(comma)]
  208. return r
  209. def __str__(self):
  210. r = "Debug stack trace of %s (back %s frames):\n"%(
  211. self.label, len(self.trace),)
  212. for i in traceback.format_list(self.trace):
  213. r+=i
  214. r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
  215. return r
  216. def printStack():
  217. print StackTrace(start=1).compact()
  218. return True
  219. def printReverseStack():
  220. print StackTrace(start=1).reverseCompact()
  221. return True
  222. def printVerboseStack():
  223. print StackTrace(start=1)
  224. return True
  225. #-----------------------------------------------------------------------------
  226. def traceFunctionCall(frame):
  227. """
  228. return a string that shows the call frame with calling arguments.
  229. e.g.
  230. foo(x=234, y=135)
  231. """
  232. f = frame
  233. co = f.f_code
  234. dict = f.f_locals
  235. n = co.co_argcount
  236. if co.co_flags & 4: n = n+1
  237. if co.co_flags & 8: n = n+1
  238. r=''
  239. if 'self' in dict:
  240. r = '%s.'%(dict['self'].__class__.__name__,)
  241. r+="%s("%(f.f_code.co_name,)
  242. comma=0 # formatting, whether we should type a comma.
  243. for i in range(n):
  244. name = co.co_varnames[i]
  245. if name=='self':
  246. continue
  247. if comma:
  248. r+=', '
  249. else:
  250. # ok, we skipped the first one, the rest get commas:
  251. comma=1
  252. r+=name
  253. r+='='
  254. if name in dict:
  255. v=safeRepr(dict[name])
  256. if len(v)>2000:
  257. # r+="<too big for debug>"
  258. r += (v[:2000] + "...")
  259. else:
  260. r+=v
  261. else: r+="*** undefined ***"
  262. return r+')'
  263. def traceParentCall():
  264. return traceFunctionCall(sys._getframe(2))
  265. def printThisCall():
  266. print traceFunctionCall(sys._getframe(1))
  267. return 1 # to allow "assert printThisCall()"
  268. # Magic numbers: These are the bit masks in func_code.co_flags that
  269. # reveal whether or not the function has a *arg or **kw argument.
  270. _POS_LIST = 4
  271. _KEY_DICT = 8
  272. def doc(obj):
  273. if (isinstance(obj, types.MethodType)) or \
  274. (isinstance(obj, types.FunctionType)):
  275. print obj.__doc__
  276. def adjust(command = None, dim = 1, parent = None, **kw):
  277. """
  278. adjust(command = None, parent = None, **kw)
  279. Popup and entry scale to adjust a parameter
  280. Accepts any Slider keyword argument. Typical arguments include:
  281. command: The one argument command to execute
  282. min: The min value of the slider
  283. max: The max value of the slider
  284. resolution: The resolution of the slider
  285. text: The label on the slider
  286. These values can be accessed and/or changed after the fact
  287. >>> vg = adjust()
  288. >>> vg['min']
  289. 0.0
  290. >>> vg['min'] = 10.0
  291. >>> vg['min']
  292. 10.0
  293. """
  294. # Make sure we enable Tk
  295. # Don't use a regular import, to prevent ModuleFinder from picking
  296. # it up as a dependency when building a .p3d package.
  297. import importlib
  298. Valuator = importlib.import_module('direct.tkwidgets.Valuator')
  299. # Set command if specified
  300. if command:
  301. kw['command'] = lambda x: apply(command, x)
  302. if parent is None:
  303. kw['title'] = command.__name__
  304. kw['dim'] = dim
  305. # Create toplevel if needed
  306. if not parent:
  307. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  308. else:
  309. vg = apply(Valuator.ValuatorGroup, (parent,), kw)
  310. vg.pack(expand = 1, fill = 'x')
  311. return vg
  312. def difference(a, b):
  313. """
  314. difference(list, list):
  315. """
  316. if not a: return b
  317. if not b: return a
  318. d = []
  319. for i in a:
  320. if (i not in b) and (i not in d):
  321. d.append(i)
  322. for i in b:
  323. if (i not in a) and (i not in d):
  324. d.append(i)
  325. return d
  326. def intersection(a, b):
  327. """
  328. intersection(list, list):
  329. """
  330. if not a: return []
  331. if not b: return []
  332. d = []
  333. for i in a:
  334. if (i in b) and (i not in d):
  335. d.append(i)
  336. for i in b:
  337. if (i in a) and (i not in d):
  338. d.append(i)
  339. return d
  340. def union(a, b):
  341. """
  342. union(list, list):
  343. """
  344. # Copy a
  345. c = a[:]
  346. for i in b:
  347. if (i not in c):
  348. c.append(i)
  349. return c
  350. def sameElements(a, b):
  351. if len(a) != len(b):
  352. return 0
  353. for elem in a:
  354. if elem not in b:
  355. return 0
  356. for elem in b:
  357. if elem not in a:
  358. return 0
  359. return 1
  360. def makeList(x):
  361. """returns x, converted to a list"""
  362. if type(x) is types.ListType:
  363. return x
  364. elif type(x) is types.TupleType:
  365. return list(x)
  366. else:
  367. return [x,]
  368. def makeTuple(x):
  369. """returns x, converted to a tuple"""
  370. if type(x) is types.ListType:
  371. return tuple(x)
  372. elif type(x) is types.TupleType:
  373. return x
  374. else:
  375. return (x,)
  376. def list2dict(L, value=None):
  377. """creates dict using elements of list, all assigned to same value"""
  378. return dict([(k, value) for k in L])
  379. def listToIndex2item(L):
  380. """converts list to dict of list index->list item"""
  381. d = {}
  382. for i, item in enumerate(L):
  383. d[i] = item
  384. return d
  385. assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
  386. def listToItem2index(L):
  387. """converts list to dict of list item->list index
  388. This is lossy if there are duplicate list items"""
  389. d = {}
  390. for i, item in enumerate(L):
  391. d[item] = i
  392. return d
  393. assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
  394. def invertDict(D, lossy=False):
  395. """creates a dictionary by 'inverting' D; keys are placed in the new
  396. dictionary under their corresponding value in the old dictionary.
  397. It is an error if D contains any duplicate values.
  398. >>> old = {'key1':1, 'key2':2}
  399. >>> invertDict(old)
  400. {1: 'key1', 2: 'key2'}
  401. """
  402. n = {}
  403. for key, value in D.items():
  404. if not lossy and value in n:
  405. raise 'duplicate key in invertDict: %s' % value
  406. n[value] = key
  407. return n
  408. def invertDictLossless(D):
  409. """similar to invertDict, but values of new dict are lists of keys from
  410. old dict. No information is lost.
  411. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  412. >>> invertDictLossless(old)
  413. {1: ['key1'], 2: ['key2', 'keyA']}
  414. """
  415. n = {}
  416. for key, value in D.items():
  417. n.setdefault(value, [])
  418. n[value].append(key)
  419. return n
  420. def uniqueElements(L):
  421. """are all elements of list unique?"""
  422. return len(L) == len(list2dict(L))
  423. def disjoint(L1, L2):
  424. """returns non-zero if L1 and L2 have no common elements"""
  425. used = dict([(k, None) for k in L1])
  426. for k in L2:
  427. if k in used:
  428. return 0
  429. return 1
  430. def contains(whole, sub):
  431. """
  432. Return 1 if whole contains sub, 0 otherwise
  433. """
  434. if (whole == sub):
  435. return 1
  436. for elem in sub:
  437. # The first item you find not in whole, return 0
  438. if elem not in whole:
  439. return 0
  440. # If you got here, whole must contain sub
  441. return 1
  442. def replace(list, old, new, all=0):
  443. """
  444. replace 'old' with 'new' in 'list'
  445. if all == 0, replace first occurrence
  446. otherwise replace all occurrences
  447. returns the number of items replaced
  448. """
  449. if old not in list:
  450. return 0
  451. if not all:
  452. i = list.index(old)
  453. list[i] = new
  454. return 1
  455. else:
  456. numReplaced = 0
  457. for i in xrange(len(list)):
  458. if list[i] == old:
  459. numReplaced += 1
  460. list[i] = new
  461. return numReplaced
  462. rad90 = math.pi / 2.
  463. rad180 = math.pi
  464. rad270 = 1.5 * math.pi
  465. rad360 = 2. * math.pi
  466. def reduceAngle(deg):
  467. """
  468. Reduces an angle (in degrees) to a value in [-180..180)
  469. """
  470. return (((deg + 180.) % 360.) - 180.)
  471. def fitSrcAngle2Dest(src, dest):
  472. """
  473. given a src and destination angle, returns an equivalent src angle
  474. that is within [-180..180) of dest
  475. examples:
  476. fitSrcAngle2Dest(30, 60) == 30
  477. fitSrcAngle2Dest(60, 30) == 60
  478. fitSrcAngle2Dest(0, 180) == 0
  479. fitSrcAngle2Dest(-1, 180) == 359
  480. fitSrcAngle2Dest(-180, 180) == 180
  481. """
  482. return dest + reduceAngle(src - dest)
  483. def fitDestAngle2Src(src, dest):
  484. """
  485. given a src and destination angle, returns an equivalent dest angle
  486. that is within [-180..180) of src
  487. examples:
  488. fitDestAngle2Src(30, 60) == 60
  489. fitDestAngle2Src(60, 30) == 30
  490. fitDestAngle2Src(0, 180) == -180
  491. fitDestAngle2Src(1, 180) == 180
  492. """
  493. return src + (reduceAngle(dest - src))
  494. def closestDestAngle2(src, dest):
  495. # The function above didn't seem to do what I wanted. So I hacked
  496. # this one together. I can't really say I understand it. It's more
  497. # from impirical observation... GRW
  498. diff = src - dest
  499. if diff > 180:
  500. # if the difference is greater that 180 it's shorter to go the other way
  501. return dest - 360
  502. elif diff < -180:
  503. # or perhaps the OTHER other way...
  504. return dest + 360
  505. else:
  506. # otherwise just go to the original destination
  507. return dest
  508. def closestDestAngle(src, dest):
  509. # The function above didn't seem to do what I wanted. So I hacked
  510. # this one together. I can't really say I understand it. It's more
  511. # from impirical observation... GRW
  512. diff = src - dest
  513. if diff > 180:
  514. # if the difference is greater that 180 it's shorter to go the other way
  515. return src - (diff - 360)
  516. elif diff < -180:
  517. # or perhaps the OTHER other way...
  518. return src - (360 + diff)
  519. else:
  520. # otherwise just go to the original destination
  521. return dest
  522. def binaryRepr(number, max_length = 32):
  523. # This will only work reliably for relatively small numbers.
  524. # Increase the value of max_length if you think you're going
  525. # to use long integers
  526. assert number < 2L << max_length
  527. shifts = map (operator.rshift, max_length * [number], \
  528. range (max_length - 1, -1, -1))
  529. digits = map (operator.mod, shifts, max_length * [2])
  530. if not digits.count (1): return 0
  531. digits = digits [digits.index (1):]
  532. return ''.join([repr(digit) for digit in digits])
  533. class StdoutCapture:
  534. # redirects stdout to a string
  535. def __init__(self):
  536. self._oldStdout = sys.stdout
  537. sys.stdout = self
  538. self._string = ''
  539. def destroy(self):
  540. sys.stdout = self._oldStdout
  541. del self._oldStdout
  542. def getString(self):
  543. return self._string
  544. # internal
  545. def write(self, string):
  546. self._string = ''.join([self._string, string])
  547. class StdoutPassthrough(StdoutCapture):
  548. # like StdoutCapture but also allows output to go through to the OS as normal
  549. # internal
  550. def write(self, string):
  551. self._string = ''.join([self._string, string])
  552. self._oldStdout.write(string)
  553. # constant profile defaults
  554. PyUtilProfileDefaultFilename = 'profiledata'
  555. PyUtilProfileDefaultLines = 80
  556. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  557. _ProfileResultStr = ''
  558. def getProfileResultString():
  559. # if you called profile with 'log' not set to True,
  560. # you can call this function to get the results as
  561. # a string
  562. global _ProfileResultStr
  563. return _ProfileResultStr
  564. def profileFunc(callback, name, terse, log=True):
  565. global _ProfileResultStr
  566. if 'globalProfileFunc' in __builtin__.__dict__:
  567. # rats. Python profiler is not re-entrant...
  568. base.notify.warning(
  569. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  570. #'\nStack Trace:\n%s'
  571. % (name, __builtin__.globalProfileFunc,
  572. #StackTrace()
  573. ))
  574. return
  575. __builtin__.globalProfileFunc = callback
  576. __builtin__.globalProfileResult = [None]
  577. prefix = '***** START PROFILE: %s *****' % name
  578. if log:
  579. print prefix
  580. startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
  581. suffix = '***** END PROFILE: %s *****' % name
  582. if log:
  583. print suffix
  584. else:
  585. _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
  586. result = globalProfileResult[0]
  587. del __builtin__.__dict__['globalProfileFunc']
  588. del __builtin__.__dict__['globalProfileResult']
  589. return result
  590. def profiled(category=None, terse=False):
  591. """ decorator for profiling functions
  592. turn categories on and off via "want-profile-categoryName 1"
  593. e.g.
  594. @profiled('particles')
  595. def loadParticles():
  596. ...
  597. want-profile-particles 1
  598. """
  599. assert type(category) in (types.StringType, types.NoneType), "must provide a category name for @profiled"
  600. # allow profiling in published versions
  601. """
  602. try:
  603. null = not __dev__
  604. except:
  605. null = not __debug__
  606. if null:
  607. # if we're not in __dev__, just return the function itself. This
  608. # results in zero runtime overhead, since decorators are evaluated
  609. # at module-load.
  610. def nullDecorator(f):
  611. return f
  612. return nullDecorator
  613. """
  614. def profileDecorator(f):
  615. def _profiled(*args, **kArgs):
  616. name = '(%s) %s from %s' % (category, f.func_name, f.__module__)
  617. # showbase might not be loaded yet, so don't use
  618. # base.config. Instead, query the ConfigVariableBool.
  619. if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
  620. return profileFunc(Functor(f, *args, **kArgs), name, terse)
  621. else:
  622. return f(*args, **kArgs)
  623. _profiled.__doc__ = f.__doc__
  624. return _profiled
  625. return profileDecorator
  626. # intercept profile-related file operations to avoid disk access
  627. movedOpenFuncs = []
  628. movedDumpFuncs = []
  629. movedLoadFuncs = []
  630. profileFilenames = set()
  631. profileFilenameList = Stack()
  632. profileFilename2file = {}
  633. profileFilename2marshalData = {}
  634. def _profileOpen(filename, *args, **kArgs):
  635. # this is a replacement for the file open() builtin function
  636. # for use during profiling, to intercept the file open
  637. # operation used by the Python profiler and profile stats
  638. # systems
  639. if filename in profileFilenames:
  640. # if this is a file related to profiling, create an
  641. # in-RAM file object
  642. if filename not in profileFilename2file:
  643. file = StringIO()
  644. file._profFilename = filename
  645. profileFilename2file[filename] = file
  646. else:
  647. file = profileFilename2file[filename]
  648. else:
  649. file = movedOpenFuncs[-1](filename, *args, **kArgs)
  650. return file
  651. def _profileMarshalDump(data, file):
  652. # marshal.dump doesn't work with StringIO objects
  653. # simulate it
  654. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  655. if file._profFilename in profileFilenames:
  656. profileFilename2marshalData[file._profFilename] = data
  657. return None
  658. return movedDumpFuncs[-1](data, file)
  659. def _profileMarshalLoad(file):
  660. # marshal.load doesn't work with StringIO objects
  661. # simulate it
  662. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  663. if file._profFilename in profileFilenames:
  664. return profileFilename2marshalData[file._profFilename]
  665. return movedLoadFuncs[-1](file)
  666. def _installProfileCustomFuncs(filename):
  667. assert filename not in profileFilenames
  668. profileFilenames.add(filename)
  669. profileFilenameList.push(filename)
  670. movedOpenFuncs.append(__builtin__.open)
  671. __builtin__.open = _profileOpen
  672. movedDumpFuncs.append(marshal.dump)
  673. marshal.dump = _profileMarshalDump
  674. movedLoadFuncs.append(marshal.load)
  675. marshal.load = _profileMarshalLoad
  676. def _getProfileResultFileInfo(filename):
  677. return (profileFilename2file.get(filename, None),
  678. profileFilename2marshalData.get(filename, None))
  679. def _setProfileResultsFileInfo(filename, info):
  680. f, m = info
  681. if f:
  682. profileFilename2file[filename] = f
  683. if m:
  684. profileFilename2marshalData[filename] = m
  685. def _clearProfileResultFileInfo(filename):
  686. profileFilename2file.pop(filename, None)
  687. profileFilename2marshalData.pop(filename, None)
  688. def _removeProfileCustomFuncs(filename):
  689. assert profileFilenameList.top() == filename
  690. marshal.load = movedLoadFuncs.pop()
  691. marshal.dump = movedDumpFuncs.pop()
  692. __builtin__.open = movedOpenFuncs.pop()
  693. profileFilenames.remove(filename)
  694. profileFilenameList.pop()
  695. profileFilename2file.pop(filename, None)
  696. # don't let marshalled data pile up
  697. profileFilename2marshalData.pop(filename, None)
  698. # call this from the prompt, and break back out to the prompt
  699. # to stop profiling
  700. #
  701. # OR to do inline profiling, you must make a globally-visible
  702. # function to be profiled, i.e. to profile 'self.load()', do
  703. # something like this:
  704. #
  705. # def func(self=self):
  706. # self.load()
  707. # import __builtin__
  708. # __builtin__.func = func
  709. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  710. # del __builtin__.func
  711. #
  712. def _profileWithoutGarbageLeak(cmd, filename):
  713. # The profile module isn't necessarily installed on every Python
  714. # installation, so we import it here, instead of in the module
  715. # scope.
  716. import profile
  717. # this is necessary because the profile module creates a memory leak
  718. Profile = profile.Profile
  719. statement = cmd
  720. sort = -1
  721. retVal = None
  722. #### COPIED FROM profile.run ####
  723. prof = Profile()
  724. try:
  725. prof = prof.run(statement)
  726. except SystemExit:
  727. pass
  728. if filename is not None:
  729. prof.dump_stats(filename)
  730. else:
  731. #return prof.print_stats(sort) #DCR
  732. retVal = prof.print_stats(sort) #DCR
  733. #################################
  734. # eliminate the garbage leak
  735. del prof.dispatcher
  736. return retVal
  737. def startProfile(filename=PyUtilProfileDefaultFilename,
  738. lines=PyUtilProfileDefaultLines,
  739. sorts=PyUtilProfileDefaultSorts,
  740. silent=0,
  741. callInfo=1,
  742. useDisk=False,
  743. cmd='run()'):
  744. # uniquify the filename to allow multiple processes to profile simultaneously
  745. filename = '%s.%s%s' % (filename, randUint31(), randUint31())
  746. if not useDisk:
  747. # use a RAM file
  748. _installProfileCustomFuncs(filename)
  749. _profileWithoutGarbageLeak(cmd, filename)
  750. if silent:
  751. extractProfile(filename, lines, sorts, callInfo)
  752. else:
  753. printProfile(filename, lines, sorts, callInfo)
  754. if not useDisk:
  755. # discard the RAM file
  756. _removeProfileCustomFuncs(filename)
  757. else:
  758. os.remove(filename)
  759. # call these to see the results again, as a string or in the log
  760. def printProfile(filename=PyUtilProfileDefaultFilename,
  761. lines=PyUtilProfileDefaultLines,
  762. sorts=PyUtilProfileDefaultSorts,
  763. callInfo=1):
  764. import pstats
  765. s = pstats.Stats(filename)
  766. s.strip_dirs()
  767. for sort in sorts:
  768. s.sort_stats(sort)
  769. s.print_stats(lines)
  770. if callInfo:
  771. s.print_callees(lines)
  772. s.print_callers(lines)
  773. # same args as printProfile
  774. def extractProfile(*args, **kArgs):
  775. global _ProfileResultStr
  776. # capture print output
  777. sc = StdoutCapture()
  778. # print the profile output, redirected to the result string
  779. printProfile(*args, **kArgs)
  780. # make a copy of the print output
  781. _ProfileResultStr = sc.getString()
  782. # restore stdout to what it was before
  783. sc.destroy()
  784. def getSetterName(valueName, prefix='set'):
  785. # getSetterName('color') -> 'setColor'
  786. # getSetterName('color', 'get') -> 'getColor'
  787. return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:])
  788. def getSetter(targetObj, valueName, prefix='set'):
  789. # getSetter(smiley, 'pos') -> smiley.setPos
  790. return getattr(targetObj, getSetterName(valueName, prefix))
  791. def mostDerivedLast(classList):
  792. """pass in list of classes. sorts list in-place, with derived classes
  793. appearing after their bases"""
  794. class ClassSortKey(object):
  795. __slots__ = 'classobj',
  796. def __init__(self, classobj):
  797. self.classobj = classobj
  798. def __lt__(self, other):
  799. return issubclass(other.classobj, self.classobj)
  800. classList.sort(key=ClassSortKey)
  801. def bound(value, bound1, bound2):
  802. """
  803. returns value if value is between bound1 and bound2
  804. otherwise returns bound that is closer to value
  805. """
  806. if bound1 > bound2:
  807. return min(max(value, bound2), bound1)
  808. else:
  809. return min(max(value, bound1), bound2)
  810. clamp = bound
  811. def lerp(v0, v1, t):
  812. """
  813. returns a value lerped between v0 and v1, according to t
  814. t == 0 maps to v0, t == 1 maps to v1
  815. """
  816. return v0 + ((v1 - v0) * t)
  817. def getShortestRotation(start, end):
  818. """
  819. Given two heading values, return a tuple describing
  820. the shortest interval from 'start' to 'end'. This tuple
  821. can be used to lerp a camera between two rotations
  822. while avoiding the 'spin' problem.
  823. """
  824. start, end = start % 360, end % 360
  825. if abs(end - start) > 180:
  826. if end < start:
  827. end += 360
  828. else:
  829. start += 360
  830. return (start, end)
  831. def average(*args):
  832. """ returns simple average of list of values """
  833. val = 0.
  834. for arg in args:
  835. val += arg
  836. return val / len(args)
  837. class Averager:
  838. def __init__(self, name):
  839. self._name = name
  840. self.reset()
  841. def reset(self):
  842. self._total = 0.
  843. self._count = 0
  844. def addValue(self, value):
  845. self._total += value
  846. self._count += 1
  847. def getAverage(self):
  848. return self._total / self._count
  849. def getCount(self):
  850. return self._count
  851. def addListsByValue(a, b):
  852. """
  853. returns a new array containing the sums of the two array arguments
  854. (c[0] = a[0 + b[0], etc.)
  855. """
  856. c = []
  857. for x, y in zip(a, b):
  858. c.append(x + y)
  859. return c
  860. def boolEqual(a, b):
  861. """
  862. returns true if a and b are both true or both false.
  863. returns false otherwise
  864. (a.k.a. xnor -- eXclusive Not OR).
  865. """
  866. return (a and b) or not (a or b)
  867. def lineupPos(i, num, spacing):
  868. """
  869. use to line up a series of 'num' objects, in one dimension,
  870. centered around zero
  871. 'i' is the index of the object in the lineup
  872. 'spacing' is the amount of space between objects in the lineup
  873. """
  874. assert num >= 1
  875. assert i >= 0 and i < num
  876. pos = float(i) * spacing
  877. return pos - ((float(spacing) * (num-1))/2.)
  878. def formatElapsedSeconds(seconds):
  879. """
  880. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  881. representing the indicated elapsed time in seconds.
  882. """
  883. sign = ''
  884. if seconds < 0:
  885. seconds = -seconds
  886. sign = '-'
  887. # We use math.floor() instead of casting to an int, so we avoid
  888. # problems with numbers that are too large to represent as
  889. # type int.
  890. seconds = math.floor(seconds)
  891. hours = math.floor(seconds / (60 * 60))
  892. if hours > 36:
  893. days = math.floor((hours + 12) / 24)
  894. return "%s%d days" % (sign, days)
  895. seconds -= hours * (60 * 60)
  896. minutes = (int)(seconds / 60)
  897. seconds -= minutes * 60
  898. if hours != 0:
  899. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  900. else:
  901. return "%s%d:%02d" % (sign, minutes, seconds)
  902. def solveQuadratic(a, b, c):
  903. # quadratic equation: ax^2 + bx + c = 0
  904. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  905. # returns None, root, or [root1, root2]
  906. # a cannot be zero.
  907. if a == 0.:
  908. return None
  909. # calculate the determinant (b^2 - 4ac)
  910. D = (b * b) - (4. * a * c)
  911. if D < 0:
  912. # there are no solutions (sqrt(negative number) is undefined)
  913. return None
  914. elif D == 0:
  915. # only one root
  916. return (-b) / (2. * a)
  917. else:
  918. # OK, there are two roots
  919. sqrtD = math.sqrt(D)
  920. twoA = 2. * a
  921. root1 = ((-b) - sqrtD) / twoA
  922. root2 = ((-b) + sqrtD) / twoA
  923. return [root1, root2]
  924. def stackEntryInfo(depth=0, baseFileName=1):
  925. """
  926. returns the sourcefilename, line number, and function name of
  927. an entry in the stack.
  928. 'depth' is how far back to go in the stack; 0 is the caller of this
  929. function, 1 is the function that called the caller of this function, etc.
  930. by default, strips off the path of the filename; override with baseFileName
  931. returns (fileName, lineNum, funcName) --> (string, int, string)
  932. returns (None, None, None) on error
  933. """
  934. try:
  935. stack = None
  936. frame = None
  937. try:
  938. stack = inspect.stack()
  939. # add one to skip the frame associated with this function
  940. frame = stack[depth+1]
  941. filename = frame[1]
  942. if baseFileName:
  943. filename = os.path.basename(filename)
  944. lineNum = frame[2]
  945. funcName = frame[3]
  946. result = (filename, lineNum, funcName)
  947. finally:
  948. del stack
  949. del frame
  950. except:
  951. result = (None, None, None)
  952. return result
  953. def lineInfo(baseFileName=1):
  954. """
  955. returns the sourcefilename, line number, and function name of the
  956. code that called this function
  957. (answers the question: 'hey lineInfo, where am I in the codebase?')
  958. see stackEntryInfo, above, for info on 'baseFileName' and return types
  959. """
  960. return stackEntryInfo(1, baseFileName)
  961. def callerInfo(baseFileName=1, howFarBack=0):
  962. """
  963. returns the sourcefilename, line number, and function name of the
  964. caller of the function that called this function
  965. (answers the question: 'hey callerInfo, who called me?')
  966. see stackEntryInfo, above, for info on 'baseFileName' and return types
  967. """
  968. return stackEntryInfo(2+howFarBack, baseFileName)
  969. def lineTag(baseFileName=1, verbose=0, separator=':'):
  970. """
  971. returns a string containing the sourcefilename and line number
  972. of the code that called this function
  973. (equivalent to lineInfo, above, with different return type)
  974. see stackEntryInfo, above, for info on 'baseFileName'
  975. if 'verbose' is false, returns a compact string of the form
  976. 'fileName:lineNum:funcName'
  977. if 'verbose' is true, returns a longer string that matches the
  978. format of Python stack trace dumps
  979. returns empty string on error
  980. """
  981. fileName, lineNum, funcName = callerInfo(baseFileName)
  982. if fileName is None:
  983. return ''
  984. if verbose:
  985. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  986. else:
  987. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  988. funcName)
  989. def findPythonModule(module):
  990. # Look along the python load path for the indicated filename.
  991. # Returns the located pathname, or None if the filename is not
  992. # found.
  993. filename = module + '.py'
  994. for dir in sys.path:
  995. pathname = os.path.join(dir, filename)
  996. if os.path.exists(pathname):
  997. return pathname
  998. return None
  999. def weightedChoice(choiceList, rng=random.random, sum=None):
  1000. """given a list of (weight, item) pairs, chooses an item based on the
  1001. weights. rng must return 0..1. if you happen to have the sum of the
  1002. weights, pass it in 'sum'."""
  1003. # TODO: add support for dicts
  1004. if sum is None:
  1005. sum = 0.
  1006. for weight, item in choiceList:
  1007. sum += weight
  1008. rand = rng()
  1009. accum = rand * sum
  1010. for weight, item in choiceList:
  1011. accum -= weight
  1012. if accum <= 0.:
  1013. return item
  1014. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1015. # Or you passed in a 'sum' that was was too large.
  1016. # Return the last item.
  1017. return item
  1018. def randFloat(a, b=0., rng=random.random):
  1019. """returns a random float in [a, b]
  1020. call with single argument to generate random float between arg and zero
  1021. """
  1022. return lerp(a, b, rng())
  1023. def normalDistrib(a, b, gauss=random.gauss):
  1024. """
  1025. NOTE: assumes a < b
  1026. Returns random number between a and b, using gaussian distribution, with
  1027. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1028. between a and b.
  1029. For ease of use, outlying results are re-computed until result is in [a, b]
  1030. This should fit the remaining .3% of the curve that lies outside [a, b]
  1031. uniformly onto the curve inside [a, b]
  1032. ------------------------------------------------------------------------
  1033. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1034. The 68-95-99.7% Rule
  1035. ====================
  1036. All normal density curves satisfy the following property which is often
  1037. referred to as the Empirical Rule:
  1038. 68% of the observations fall within 1 standard deviation of the mean.
  1039. 95% of the observations fall within 2 standard deviations of the mean.
  1040. 99.7% of the observations fall within 3 standard deviations of the mean.
  1041. Thus, for a normal distribution, almost all values lie within 3 standard
  1042. deviations of the mean.
  1043. ------------------------------------------------------------------------
  1044. In calculating our standard deviation, we divide (b-a) by 6, since the
  1045. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1046. """
  1047. while True:
  1048. r = gauss((a+b)*.5, (b-a)/6.)
  1049. if (r >= a) and (r <= b):
  1050. return r
  1051. def weightedRand(valDict, rng=random.random):
  1052. """
  1053. pass in a dictionary with a selection -> weight mapping. Eg.
  1054. {"Choice 1": 10,
  1055. "Choice 2": 30,
  1056. "bear": 100}
  1057. -Weights need not add up to any particular value.
  1058. -The actual selection will be returned.
  1059. """
  1060. selections = valDict.keys()
  1061. weights = valDict.values()
  1062. totalWeight = 0
  1063. for weight in weights:
  1064. totalWeight += weight
  1065. # get a random value between 0 and the total of the weights
  1066. randomWeight = rng() * totalWeight
  1067. # find the index that corresponds with this weight
  1068. for i in range(len(weights)):
  1069. totalWeight -= weights[i]
  1070. if totalWeight <= randomWeight:
  1071. return selections[i]
  1072. assert True, "Should never get here"
  1073. return selections[-1]
  1074. def randUint31(rng=random.random):
  1075. """returns a random integer in [0..2^31).
  1076. rng must return float in [0..1]"""
  1077. return int(rng() * 0x7FFFFFFF)
  1078. def randInt32(rng=random.random):
  1079. """returns a random integer in [-2147483648..2147483647].
  1080. rng must return float in [0..1]
  1081. """
  1082. i = int(rng() * 0x7FFFFFFF)
  1083. if rng() < .5:
  1084. i *= -1
  1085. return i
  1086. def randUint32(rng=random.random):
  1087. """returns a random integer in [0..2^32).
  1088. rng must return float in [0..1]"""
  1089. return long(rng() * 0xFFFFFFFFL)
  1090. class SerialNumGen:
  1091. """generates serial numbers"""
  1092. def __init__(self, start=None):
  1093. if start is None:
  1094. start = 0
  1095. self.__counter = start-1
  1096. def next(self):
  1097. self.__counter += 1
  1098. return self.__counter
  1099. class SerialMaskedGen(SerialNumGen):
  1100. def __init__(self, mask, start=None):
  1101. self._mask = mask
  1102. SerialNumGen.__init__(self, start)
  1103. def next(self):
  1104. v = SerialNumGen.next(self)
  1105. return v & self._mask
  1106. _serialGen = SerialNumGen()
  1107. def serialNum():
  1108. global _serialGen
  1109. return _serialGen.next()
  1110. def uniqueName(name):
  1111. global _serialGen
  1112. return '%s-%s' % (name, _serialGen.next())
  1113. class EnumIter:
  1114. def __init__(self, enum):
  1115. self._values = enum._stringTable.keys()
  1116. self._index = 0
  1117. def __iter__(self):
  1118. return self
  1119. def next(self):
  1120. if self._index >= len(self._values):
  1121. raise StopIteration
  1122. self._index += 1
  1123. return self._values[self._index-1]
  1124. class Enum:
  1125. """Pass in list of strings or string of comma-separated strings.
  1126. Items are accessible as instance.item, and are assigned unique,
  1127. increasing integer values. Pass in integer for 'start' to override
  1128. starting value.
  1129. Example:
  1130. >>> colors = Enum('red, green, blue')
  1131. >>> colors.red
  1132. 0
  1133. >>> colors.green
  1134. 1
  1135. >>> colors.blue
  1136. 2
  1137. >>> colors.getString(colors.red)
  1138. 'red'
  1139. """
  1140. if __debug__:
  1141. # chars that cannot appear within an item string.
  1142. InvalidChars = string.whitespace
  1143. def _checkValidIdentifier(item):
  1144. invalidChars = string.whitespace+string.punctuation
  1145. invalidChars = invalidChars.replace('_','')
  1146. invalidFirstChars = invalidChars+string.digits
  1147. if item[0] in invalidFirstChars:
  1148. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  1149. item)
  1150. if not disjoint(item, invalidChars):
  1151. for char in item:
  1152. if char in invalidChars:
  1153. raise SyntaxError, (
  1154. "Enum\n'%s'\ncontains illegal char '%s'" %
  1155. (item, char))
  1156. return 1
  1157. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1158. def __init__(self, items, start=0):
  1159. if isinstance(items, str):
  1160. items = items.split(',')
  1161. self._stringTable = {}
  1162. # make sure we don't overwrite an existing element of the class
  1163. assert self._checkExistingMembers(items)
  1164. assert uniqueElements(items)
  1165. i = start
  1166. for item in items:
  1167. # remove leading/trailing whitespace
  1168. item = item.strip()
  1169. # is there anything left?
  1170. if len(item) == 0:
  1171. continue
  1172. # make sure there are no invalid characters
  1173. assert Enum._checkValidIdentifier(item)
  1174. self.__dict__[item] = i
  1175. self._stringTable[i] = item
  1176. i += 1
  1177. def __iter__(self):
  1178. return EnumIter(self)
  1179. def hasString(self, string):
  1180. return string in set(self._stringTable.values())
  1181. def fromString(self, string):
  1182. if self.hasString(string):
  1183. return self.__dict__[string]
  1184. # throw an error
  1185. {}[string]
  1186. def getString(self, value):
  1187. return self._stringTable[value]
  1188. def __contains__(self, value):
  1189. return value in self._stringTable
  1190. def __len__(self):
  1191. return len(self._stringTable)
  1192. def copyTo(self, obj):
  1193. # copies all members onto obj
  1194. for name, value in self._stringTable:
  1195. setattr(obj, name, value)
  1196. if __debug__:
  1197. def _checkExistingMembers(self, items):
  1198. for item in items:
  1199. if hasattr(self, item):
  1200. return 0
  1201. return 1
  1202. ############################################################
  1203. # class: Singleton
  1204. # Purpose: This provides a base metaclass for all classes
  1205. # that require one and only one instance.
  1206. #
  1207. # Example: class mySingleton:
  1208. # __metaclass__ = PythonUtil.Singleton
  1209. # def __init__(self, ...):
  1210. # ...
  1211. #
  1212. # Note: This class is based on Python's New-Style Class
  1213. # design. An error will occur if a defined class
  1214. # attemps to inherit from a Classic-Style Class only,
  1215. # ie: class myClassX:
  1216. # def __init__(self, ...):
  1217. # ...
  1218. #
  1219. # class myNewClassX(myClassX):
  1220. # __metaclass__ = PythonUtil.Singleton
  1221. # def __init__(self, ...):
  1222. # myClassX.__init__(self, ...)
  1223. # ...
  1224. #
  1225. # This causes problems because myNewClassX is a
  1226. # New-Style class that inherits from only a
  1227. # Classic-Style base class. There are two ways
  1228. # simple ways to resolve this issue.
  1229. #
  1230. # First, if possible, make myClassX a
  1231. # New-Style class by inheriting from object
  1232. # object. IE: class myClassX(object):
  1233. #
  1234. # If for some reason that is not an option, make
  1235. # myNewClassX inherit from object and myClassX.
  1236. # IE: class myNewClassX(object, myClassX):
  1237. ############################################################
  1238. class Singleton(type):
  1239. def __init__(cls, name, bases, dic):
  1240. super(Singleton, cls).__init__(name, bases, dic)
  1241. cls.instance=None
  1242. def __call__(cls, *args, **kw):
  1243. if cls.instance is None:
  1244. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  1245. return cls.instance
  1246. class SingletonError(ValueError):
  1247. """ Used to indicate an inappropriate value for a Singleton."""
  1248. def printListEnumGen(l):
  1249. # log each individual item with a number in front of it
  1250. digits = 0
  1251. n = len(l)
  1252. while n > 0:
  1253. digits += 1
  1254. n //= 10
  1255. format = '%0' + '%s' % digits + 'i:%s'
  1256. for i in range(len(l)):
  1257. print format % (i, l[i])
  1258. yield None
  1259. def printListEnum(l):
  1260. for result in printListEnumGen(l):
  1261. pass
  1262. # base class for all Panda C++ objects
  1263. # libdtoolconfig doesn't seem to have this, grab it off of TypedObject
  1264. dtoolSuperBase = None
  1265. def _getDtoolSuperBase():
  1266. global dtoolSuperBase
  1267. from panda3d.core import TypedObject
  1268. dtoolSuperBase = TypedObject.__bases__[0]
  1269. assert dtoolSuperBase.__name__ == 'DTOOL_SUPER_BASE'
  1270. safeReprNotify = None
  1271. def _getSafeReprNotify():
  1272. global safeReprNotify
  1273. from direct.directnotify.DirectNotifyGlobal import directNotify
  1274. safeReprNotify = directNotify.newCategory("safeRepr")
  1275. return safeReprNotify
  1276. def safeRepr(obj):
  1277. global dtoolSuperBase
  1278. if dtoolSuperBase is None:
  1279. _getDtoolSuperBase()
  1280. global safeReprNotify
  1281. if safeReprNotify is None:
  1282. _getSafeReprNotify()
  1283. if isinstance(obj, dtoolSuperBase):
  1284. # repr of C++ object could crash, particularly if the object has been deleted
  1285. # log that we're calling repr
  1286. safeReprNotify.info('calling repr on instance of %s.%s' % (obj.__class__.__module__, obj.__class__.__name__))
  1287. sys.stdout.flush()
  1288. try:
  1289. return repr(obj)
  1290. except:
  1291. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1292. def safeReprTypeOnFail(obj):
  1293. global dtoolSuperBase
  1294. if dtoolSuperBase is None:
  1295. _getDtoolSuperBase()
  1296. global safeReprNotify
  1297. if safeReprNotify is None:
  1298. _getSafeReprNotify()
  1299. if isinstance(obj, dtoolSuperBase):
  1300. return type(obj)
  1301. try:
  1302. return repr(obj)
  1303. except:
  1304. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  1305. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  1306. """ caps the length of iterable types, so very large objects will print faster.
  1307. also prevents infinite recursion """
  1308. try:
  1309. if _visitedIds is None:
  1310. _visitedIds = set()
  1311. if id(obj) in _visitedIds:
  1312. return '<ALREADY-VISITED %s>' % itype(obj)
  1313. if type(obj) in (types.TupleType, types.ListType):
  1314. s = ''
  1315. s += {types.TupleType: '(',
  1316. types.ListType: '[',}[type(obj)]
  1317. if maxLen is not None and len(obj) > maxLen:
  1318. o = obj[:maxLen]
  1319. ellips = '...'
  1320. else:
  1321. o = obj
  1322. ellips = ''
  1323. _visitedIds.add(id(obj))
  1324. for item in o:
  1325. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  1326. s += ', '
  1327. _visitedIds.remove(id(obj))
  1328. s += ellips
  1329. s += {types.TupleType: ')',
  1330. types.ListType: ']',}[type(obj)]
  1331. return s
  1332. elif type(obj) is types.DictType:
  1333. s = '{'
  1334. if maxLen is not None and len(obj) > maxLen:
  1335. o = obj.keys()[:maxLen]
  1336. ellips = '...'
  1337. else:
  1338. o = obj.keys()
  1339. ellips = ''
  1340. _visitedIds.add(id(obj))
  1341. for key in o:
  1342. value = obj[key]
  1343. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  1344. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  1345. _visitedIds.remove(id(obj))
  1346. s += ellips
  1347. s += '}'
  1348. return s
  1349. elif type(obj) is types.StringType:
  1350. if maxLen is not None:
  1351. maxLen *= strFactor
  1352. if maxLen is not None and len(obj) > maxLen:
  1353. return safeRepr(obj[:maxLen])
  1354. else:
  1355. return safeRepr(obj)
  1356. else:
  1357. r = safeRepr(obj)
  1358. maxLen *= strFactor
  1359. if len(r) > maxLen:
  1360. r = r[:maxLen]
  1361. return r
  1362. except:
  1363. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  1364. def convertTree(objTree, idList):
  1365. newTree = {}
  1366. for key in objTree.keys():
  1367. obj = (idList[key],)
  1368. newTree[obj] = {}
  1369. r_convertTree(objTree[key], newTree[obj], idList)
  1370. return newTree
  1371. def r_convertTree(oldTree, newTree, idList):
  1372. for key in oldTree.keys():
  1373. obj = idList.get(key)
  1374. if(not obj):
  1375. continue
  1376. obj = str(obj)[:100]
  1377. newTree[obj] = {}
  1378. r_convertTree(oldTree[key], newTree[obj], idList)
  1379. def pretty_print(tree):
  1380. for name in tree.keys():
  1381. print name
  1382. r_pretty_print(tree[name], 0)
  1383. def r_pretty_print(tree, num):
  1384. num+=1
  1385. for name in tree.keys():
  1386. print " "*num,name
  1387. r_pretty_print(tree[name],num)
  1388. def isDefaultValue(x):
  1389. return x == type(x)()
  1390. def appendStr(obj, st):
  1391. """adds a string onto the __str__ output of an instance"""
  1392. def appendedStr(oldStr, st, self):
  1393. return oldStr() + st
  1394. oldStr = getattr(obj, '__str__', None)
  1395. if oldStr is None:
  1396. def stringer(s):
  1397. return s
  1398. oldStr = Functor(stringer, str(obj))
  1399. stringer = None
  1400. obj.__str__ = types.MethodType(Functor(appendedStr, oldStr, st), obj, obj.__class__)
  1401. appendedStr = None
  1402. return obj
  1403. class ScratchPad:
  1404. """empty class to stick values onto"""
  1405. def __init__(self, **kArgs):
  1406. for key, value in kArgs.iteritems():
  1407. setattr(self, key, value)
  1408. self._keys = set(kArgs.keys())
  1409. def add(self, **kArgs):
  1410. for key, value in kArgs.iteritems():
  1411. setattr(self, key, value)
  1412. self._keys.update(kArgs.keys())
  1413. def destroy(self):
  1414. for key in self._keys:
  1415. delattr(self, key)
  1416. # allow dict [] syntax
  1417. def __getitem__(self, itemName):
  1418. return getattr(self, itemName)
  1419. def get(self, itemName, default=None):
  1420. return getattr(self, itemName, default)
  1421. # allow 'in'
  1422. def __contains__(self, itemName):
  1423. return itemName in self._keys
  1424. class Sync:
  1425. _SeriesGen = SerialNumGen()
  1426. def __init__(self, name, other=None):
  1427. self._name = name
  1428. if other is None:
  1429. self._series = self._SeriesGen.next()
  1430. self._value = 0
  1431. else:
  1432. self._series = other._series
  1433. self._value = other._value
  1434. def invalidate(self):
  1435. self._value = None
  1436. def change(self):
  1437. self._value += 1
  1438. def sync(self, other):
  1439. if (self._series != other._series) or (self._value != other._value):
  1440. self._series = other._series
  1441. self._value = other._value
  1442. return True
  1443. else:
  1444. return False
  1445. def isSynced(self, other):
  1446. return ((self._series == other._series) and
  1447. (self._value == other._value))
  1448. def __repr__(self):
  1449. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  1450. self._name, self._series, self._value)
  1451. def itype(obj):
  1452. # version of type that gives more complete information about instance types
  1453. global dtoolSuperBase
  1454. t = type(obj)
  1455. if t is types.InstanceType:
  1456. return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
  1457. str(obj.__class__))
  1458. else:
  1459. # C++ object instances appear to be types via type()
  1460. # check if this is a C++ object
  1461. if dtoolSuperBase is None:
  1462. _getDtoolSuperBase()
  1463. if isinstance(obj, dtoolSuperBase):
  1464. return '%s of %s>' % (repr(types.InstanceType)[:-1],
  1465. str(obj.__class__))
  1466. return t
  1467. def deeptype(obj, maxLen=100, _visitedIds=None):
  1468. if _visitedIds is None:
  1469. _visitedIds = set()
  1470. if id(obj) in _visitedIds:
  1471. return '<ALREADY-VISITED %s>' % itype(obj)
  1472. t = type(obj)
  1473. if t in (types.TupleType, types.ListType):
  1474. s = ''
  1475. s += {types.TupleType: '(',
  1476. types.ListType: '[',}[type(obj)]
  1477. if maxLen is not None and len(obj) > maxLen:
  1478. o = obj[:maxLen]
  1479. ellips = '...'
  1480. else:
  1481. o = obj
  1482. ellips = ''
  1483. _visitedIds.add(id(obj))
  1484. for item in o:
  1485. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  1486. s += ', '
  1487. _visitedIds.remove(id(obj))
  1488. s += ellips
  1489. s += {types.TupleType: ')',
  1490. types.ListType: ']',}[type(obj)]
  1491. return s
  1492. elif type(obj) is types.DictType:
  1493. s = '{'
  1494. if maxLen is not None and len(obj) > maxLen:
  1495. o = obj.keys()[:maxLen]
  1496. ellips = '...'
  1497. else:
  1498. o = obj.keys()
  1499. ellips = ''
  1500. _visitedIds.add(id(obj))
  1501. for key in o:
  1502. value = obj[key]
  1503. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  1504. deeptype(value, maxLen, _visitedIds=_visitedIds))
  1505. _visitedIds.remove(id(obj))
  1506. s += ellips
  1507. s += '}'
  1508. return s
  1509. else:
  1510. return str(itype(obj))
  1511. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  1512. """get a string that has each item of the list on its own line,
  1513. and each item is numbered on the left from zero"""
  1514. digits = 0
  1515. n = len(items)
  1516. while n > 0:
  1517. digits += 1
  1518. n //= 10
  1519. digits = digits
  1520. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1521. first = True
  1522. s = ''
  1523. snip = '<SNIP>'
  1524. for i in xrange(len(items)):
  1525. if not first:
  1526. s += '\n'
  1527. first = False
  1528. objStr = fastRepr(items[i])
  1529. if len(objStr) > maxLen:
  1530. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1531. s += format % (i, itype(items[i]), objStr)
  1532. return s
  1533. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  1534. """get a string that has each item of the list on its own line,
  1535. the items are stringwise-sorted, and each item is numbered on
  1536. the left from zero"""
  1537. digits = 0
  1538. n = len(items)
  1539. while n > 0:
  1540. digits += 1
  1541. n //= 10
  1542. digits = digits
  1543. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1544. snip = '<SNIP>'
  1545. strs = []
  1546. for item in items:
  1547. objStr = fastRepr(item)
  1548. if len(objStr) > maxLen:
  1549. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1550. strs.append(objStr)
  1551. first = True
  1552. s = ''
  1553. strs.sort()
  1554. for i in xrange(len(strs)):
  1555. if not first:
  1556. s += '\n'
  1557. first = False
  1558. objStr = strs[i]
  1559. s += format % (i, itype(items[i]), strs[i])
  1560. return s
  1561. def getNumberedTypedSortedStringWithReferrersGen(items, maxLen=10000, numPrefix=''):
  1562. """get a string that has each item of the list on its own line,
  1563. the items are stringwise-sorted, the object's referrers are shown,
  1564. and each item is numbered on the left from zero"""
  1565. digits = 0
  1566. n = len(items)
  1567. while n > 0:
  1568. digits += 1
  1569. n //= 10
  1570. digits = digits
  1571. format = numPrefix + '%0' + '%s' % digits + 'i:%s @ %s \t%s'
  1572. snip = '<SNIP>'
  1573. strs = []
  1574. for item in items:
  1575. strs.append(fastRepr(item))
  1576. strs.sort()
  1577. for i in xrange(len(strs)):
  1578. item = items[i]
  1579. objStr = strs[i]
  1580. objStr += ', \tREFERRERS=['
  1581. referrers = gc.get_referrers(item)
  1582. for ref in referrers:
  1583. objStr += '%s@%s, ' % (itype(ref), id(ref))
  1584. objStr += ']'
  1585. if len(objStr) > maxLen:
  1586. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1587. yield format % (i, itype(items[i]), id(items[i]), objStr)
  1588. def getNumberedTypedSortedStringWithReferrers(items, maxLen=10000, numPrefix=''):
  1589. """get a string that has each item of the list on its own line,
  1590. the items are stringwise-sorted, the object's referrers are shown,
  1591. and each item is numbered on the left from zero"""
  1592. s = ''
  1593. for line in getNumberedTypedSortedStringWithReferrersGen(items, maxLen, numPrefix):
  1594. s += '%s\n' % line
  1595. return s
  1596. def printNumberedTyped(items, maxLen=5000):
  1597. """print out each item of the list on its own line,
  1598. with each item numbered on the left from zero"""
  1599. digits = 0
  1600. n = len(items)
  1601. while n > 0:
  1602. digits += 1
  1603. n //= 10
  1604. digits = digits
  1605. format = '%0' + '%s' % digits + 'i:%s \t%s'
  1606. for i in xrange(len(items)):
  1607. objStr = fastRepr(items[i])
  1608. if len(objStr) > maxLen:
  1609. snip = '<SNIP>'
  1610. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1611. print format % (i, itype(items[i]), objStr)
  1612. def printNumberedTypesGen(items, maxLen=5000):
  1613. digits = 0
  1614. n = len(items)
  1615. while n > 0:
  1616. digits += 1
  1617. n //= 10
  1618. digits = digits
  1619. format = '%0' + '%s' % digits + 'i:%s'
  1620. for i in xrange(len(items)):
  1621. print format % (i, itype(items[i]))
  1622. yield None
  1623. def printNumberedTypes(items, maxLen=5000):
  1624. """print out the type of each item of the list on its own line,
  1625. with each item numbered on the left from zero"""
  1626. for result in printNumberedTypesGen(items, maxLen):
  1627. yield result
  1628. class DelayedCall:
  1629. """ calls a func after a specified delay """
  1630. def __init__(self, func, name=None, delay=None):
  1631. if name is None:
  1632. name = 'anonymous'
  1633. if delay is None:
  1634. delay = .01
  1635. self._func = func
  1636. self._taskName = 'DelayedCallback-%s' % name
  1637. self._delay = delay
  1638. self._finished = False
  1639. self._addDoLater()
  1640. def destroy(self):
  1641. self._finished = True
  1642. self._removeDoLater()
  1643. def finish(self):
  1644. if not self._finished:
  1645. self._doCallback()
  1646. self.destroy()
  1647. def _addDoLater(self):
  1648. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  1649. def _removeDoLater(self):
  1650. taskMgr.remove(self._taskName)
  1651. def _doCallback(self, task):
  1652. self._finished = True
  1653. func = self._func
  1654. del self._func
  1655. func()
  1656. class FrameDelayedCall:
  1657. """ calls a func after N frames """
  1658. def __init__(self, name, callback, frames=None, cancelFunc=None):
  1659. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  1660. # and callback is not called
  1661. if frames is None:
  1662. frames = 1
  1663. self._name = name
  1664. self._frames = frames
  1665. self._callback = callback
  1666. self._cancelFunc = cancelFunc
  1667. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  1668. self._finished = False
  1669. self._startTask()
  1670. def destroy(self):
  1671. self._finished = True
  1672. self._stopTask()
  1673. def finish(self):
  1674. if not self._finished:
  1675. self._finished = True
  1676. self._callback()
  1677. self.destroy()
  1678. def _startTask(self):
  1679. taskMgr.add(self._frameTask, self._taskName)
  1680. self._counter = 0
  1681. def _stopTask(self):
  1682. taskMgr.remove(self._taskName)
  1683. def _frameTask(self, task):
  1684. if self._cancelFunc and self._cancelFunc():
  1685. self.destroy()
  1686. return task.done
  1687. self._counter += 1
  1688. if self._counter >= self._frames:
  1689. self.finish()
  1690. return task.done
  1691. return task.cont
  1692. class DelayedFunctor:
  1693. """ Waits for this object to be called, then calls supplied functor after a delay.
  1694. Effectively inserts a time delay between the caller and the functor. """
  1695. def __init__(self, functor, name=None, delay=None):
  1696. self._functor = functor
  1697. self._name = name
  1698. # FunctionInterval requires __name__
  1699. self.__name__ = self._name
  1700. self._delay = delay
  1701. def _callFunctor(self):
  1702. cb = Functor(self._functor, *self._args, **self._kwArgs)
  1703. del self._functor
  1704. del self._name
  1705. del self._delay
  1706. del self._args
  1707. del self._kwArgs
  1708. del self._delayedCall
  1709. del self.__name__
  1710. cb()
  1711. def __call__(self, *args, **kwArgs):
  1712. self._args = args
  1713. self._kwArgs = kwArgs
  1714. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  1715. class SubframeCall:
  1716. """Calls a callback at a specific time during the frame using the
  1717. task system"""
  1718. def __init__(self, functor, taskPriority, name=None):
  1719. self._functor = functor
  1720. self._name = name
  1721. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  1722. taskMgr.add(self._doCallback,
  1723. self._taskName,
  1724. priority=taskPriority)
  1725. def _doCallback(self, task):
  1726. functor = self._functor
  1727. del self._functor
  1728. functor()
  1729. del self._name
  1730. self._taskName = None
  1731. return task.done
  1732. def cleanup(self):
  1733. if (self._taskName):
  1734. taskMgr.remove(self._taskName)
  1735. self._taskName = None
  1736. class PStatScope:
  1737. collectors = {}
  1738. def __init__(self, level = None):
  1739. self.levels = []
  1740. if level:
  1741. self.levels.append(level)
  1742. def copy(self, push = None):
  1743. c = PStatScope()
  1744. c.levels = self.levels[:]
  1745. if push:
  1746. c.push(push)
  1747. return c
  1748. def __repr__(self):
  1749. return 'PStatScope - \'%s\'' % (self,)
  1750. def __str__(self):
  1751. return ':'.join(self.levels)
  1752. def push(self, level):
  1753. self.levels.append(level.replace('_',''))
  1754. def pop(self):
  1755. return self.levels.pop()
  1756. def start(self, push = None):
  1757. if push:
  1758. self.push(push)
  1759. pass
  1760. self.getCollector().start()
  1761. def stop(self, pop = False):
  1762. self.getCollector().stop()
  1763. if pop:
  1764. self.pop()
  1765. def getCollector(self):
  1766. label = str(self)
  1767. if label not in self.collectors:
  1768. from panda3d.core import PStatCollector
  1769. self.collectors[label] = PStatCollector(label)
  1770. pass
  1771. # print ' ',self.collectors[label]
  1772. return self.collectors[label]
  1773. def pstatcollect(scope, level = None):
  1774. def decorator(f):
  1775. return f
  1776. try:
  1777. if not (__dev__ or ConfigVariableBool('force-pstatcollect', False)) or \
  1778. not scope:
  1779. return decorator
  1780. def decorator(f):
  1781. def wrap(*args, **kw):
  1782. scope.start(push = (level or f.__name__))
  1783. val = f(*args, **kw)
  1784. scope.stop(pop = True)
  1785. return val
  1786. return wrap
  1787. pass
  1788. except:
  1789. pass
  1790. return decorator
  1791. __report_indent = 0
  1792. def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigParam = []):
  1793. """
  1794. This is a decorator generating function. Use is similar to
  1795. a @decorator, except you must be sure to call it as a function.
  1796. It actually returns the decorator which is then used to transform
  1797. your decorated function. Confusing at first, I know.
  1798. Decoration occurs at function definition time.
  1799. If __dev__ is not defined, or resolves to False, this function
  1800. has no effect and no wrapping/transform occurs. So in production,
  1801. it's as if the report has been asserted out.
  1802. Parameters::
  1803. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  1804. This allows you to specify certain useful bits of info.
  1805. module: Prints the module that this report statement
  1806. can be found in.
  1807. args: Prints the arguments as they were passed to
  1808. this function.
  1809. timeStamp: Adds the current frame time to the output.
  1810. deltaStamp: Adds the current AI synched frame time to
  1811. the output
  1812. frameCount: Adds the current frame count to the output.
  1813. Usually cleaner than the timeStamp output.
  1814. avLocation: Adds the localAvatar's network location
  1815. to the output. Useful for interest debugging.
  1816. interests: Prints the current interest state after the
  1817. report.
  1818. stackTrace: Prints a stack trace after the report.
  1819. prefix: Optional string to prepend to output, just before the function.
  1820. Allows for easy grepping and is useful when merging AI/Client
  1821. reports into a single file.
  1822. xform: Optional callback that accepts a single parameter: argument 0 to
  1823. the decorated function. (assumed to be 'self')
  1824. It should return a value to be inserted into the report output string.
  1825. notifyFunc: A notify function such as info, debug, warning, etc.
  1826. By default the report will be printed to stdout. This
  1827. will allow you send the report to a designated 'notify'
  1828. output.
  1829. dConfigParam: A list of Config.prc string variables.
  1830. By default the report will always print. If you
  1831. specify this param, it will only print if one of the
  1832. specified config strings resolve to True.
  1833. """
  1834. def indent(str):
  1835. global __report_indent
  1836. return ' '*__report_indent+str
  1837. def decorator(f):
  1838. return f
  1839. try:
  1840. if not (__dev__ or config.GetBool('force-reports', 0)):
  1841. return decorator
  1842. # determine whether we should use the decorator
  1843. # based on the value of dConfigParam.
  1844. dConfigParamList = []
  1845. doPrint = False
  1846. if not dConfigParam:
  1847. doPrint = True
  1848. else:
  1849. if not isinstance(dConfigParam, (list,tuple)):
  1850. dConfigParams = (dConfigParam,)
  1851. else:
  1852. dConfigParams = dConfigParam
  1853. dConfigParamList = [param for param in dConfigParams \
  1854. if config.GetBool('want-%s-report' % (param,), 0)]
  1855. doPrint = bool(dConfigParamList)
  1856. pass
  1857. if not doPrint:
  1858. return decorator
  1859. # Determine any prefixes defined in our Config.prc.
  1860. if prefix:
  1861. prefixes = set([prefix])
  1862. else:
  1863. prefixes = set()
  1864. pass
  1865. for param in dConfigParamList:
  1866. prefix = config.GetString('prefix-%s-report' % (param,), '')
  1867. if prefix:
  1868. prefixes.add(prefix)
  1869. pass
  1870. pass
  1871. except NameError,e:
  1872. return decorator
  1873. from direct.distributed.ClockDelta import globalClockDelta
  1874. def decorator(f):
  1875. def wrap(*args,**kwargs):
  1876. if args:
  1877. rArgs = [args[0].__class__.__name__ + ', ']
  1878. else:
  1879. rArgs = []
  1880. if 'args' in types:
  1881. rArgs += [repr(x)+', ' for x in args[1:]] + \
  1882. [ x + ' = ' + '%s, ' % repr(y) for x,y in kwargs.items()]
  1883. if not rArgs:
  1884. rArgs = '()'
  1885. else:
  1886. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  1887. outStr = '%s%s' % (f.func_name, rArgs)
  1888. # Insert prefix place holder, if needed
  1889. if prefixes:
  1890. outStr = '%%s %s' % (outStr,)
  1891. if 'module' in types:
  1892. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  1893. if 'frameCount' in types:
  1894. outStr = '%-8d : %s' % (globalClock.getFrameCount(), outStr)
  1895. if 'timeStamp' in types:
  1896. outStr = '%-8.3f : %s' % (globalClock.getFrameTime(), outStr)
  1897. if 'deltaStamp' in types:
  1898. outStr = '%-8.2f : %s' % (globalClock.getRealTime() - \
  1899. globalClockDelta.delta, outStr)
  1900. if 'avLocation' in types:
  1901. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  1902. if xform:
  1903. outStr = '%s : %s' % (outStr, xform(args[0]))
  1904. if prefixes:
  1905. # This will print the same report once for each prefix
  1906. for prefix in prefixes:
  1907. if notifyFunc:
  1908. notifyFunc(outStr % (prefix,))
  1909. else:
  1910. print indent(outStr % (prefix,))
  1911. else:
  1912. if notifyFunc:
  1913. notifyFunc(outStr)
  1914. else:
  1915. print indent(outStr)
  1916. if 'interests' in types:
  1917. base.cr.printInterestSets()
  1918. if 'stackTrace' in types:
  1919. print StackTrace()
  1920. global __report_indent
  1921. rVal = None
  1922. try:
  1923. __report_indent += 1
  1924. rVal = f(*args,**kwargs)
  1925. finally:
  1926. __report_indent -= 1
  1927. if rVal is not None:
  1928. print indent(' -> '+repr(rVal))
  1929. pass
  1930. pass
  1931. return rVal
  1932. wrap.func_name = f.func_name
  1933. wrap.func_dict = f.func_dict
  1934. wrap.func_doc = f.func_doc
  1935. wrap.__module__ = f.__module__
  1936. return wrap
  1937. return decorator
  1938. def getBase():
  1939. try:
  1940. return base
  1941. except:
  1942. return simbase
  1943. def getRepository():
  1944. try:
  1945. return base.cr
  1946. except:
  1947. return simbase.air
  1948. exceptionLoggedNotify = None
  1949. def exceptionLogged(append=True):
  1950. """decorator that outputs the function name and all arguments
  1951. if an exception passes back through the stack frame
  1952. if append is true, string is appended to the __str__ output of
  1953. the exception. if append is false, string is printed to the log
  1954. directly. If the output will take up many lines, it's recommended
  1955. to set append to False so that the exception stack is not hidden
  1956. by the output of this decorator.
  1957. """
  1958. try:
  1959. null = not __dev__
  1960. except:
  1961. null = not __debug__
  1962. if null:
  1963. # if we're not in __dev__, just return the function itself. This
  1964. # results in zero runtime overhead, since decorators are evaluated
  1965. # at module-load.
  1966. def nullDecorator(f):
  1967. return f
  1968. return nullDecorator
  1969. def _decoratorFunc(f, append=append):
  1970. global exceptionLoggedNotify
  1971. if exceptionLoggedNotify is None:
  1972. from direct.directnotify.DirectNotifyGlobal import directNotify
  1973. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  1974. def _exceptionLogged(*args, **kArgs):
  1975. try:
  1976. return f(*args, **kArgs)
  1977. except Exception, e:
  1978. try:
  1979. s = '%s(' % f.func_name
  1980. for arg in args:
  1981. s += '%s, ' % arg
  1982. for key, value in kArgs.items():
  1983. s += '%s=%s, ' % (key, value)
  1984. if len(args) or len(kArgs):
  1985. s = s[:-2]
  1986. s += ')'
  1987. if append:
  1988. appendStr(e, '\n%s' % s)
  1989. else:
  1990. exceptionLoggedNotify.info(s)
  1991. except:
  1992. exceptionLoggedNotify.info(
  1993. '%s: ERROR IN PRINTING' % f.func_name)
  1994. raise
  1995. _exceptionLogged.__doc__ = f.__doc__
  1996. return _exceptionLogged
  1997. return _decoratorFunc
  1998. # class 'decorator' that records the stack at the time of creation
  1999. # be careful with this, it creates a StackTrace, and that can take a
  2000. # lot of CPU
  2001. def recordCreationStack(cls):
  2002. if not hasattr(cls, '__init__'):
  2003. raise 'recordCreationStack: class \'%s\' must define __init__' % cls.__name__
  2004. cls.__moved_init__ = cls.__init__
  2005. def __recordCreationStack_init__(self, *args, **kArgs):
  2006. self._creationStackTrace = StackTrace(start=1)
  2007. return self.__moved_init__(*args, **kArgs)
  2008. def getCreationStackTrace(self):
  2009. return self._creationStackTrace
  2010. def getCreationStackTraceCompactStr(self):
  2011. return self._creationStackTrace.compact()
  2012. def printCreationStackTrace(self):
  2013. print self._creationStackTrace
  2014. cls.__init__ = __recordCreationStack_init__
  2015. cls.getCreationStackTrace = getCreationStackTrace
  2016. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2017. cls.printCreationStackTrace = printCreationStackTrace
  2018. return cls
  2019. # like recordCreationStack but stores the stack as a compact stack list-of-strings
  2020. # scales well for memory usage
  2021. def recordCreationStackStr(cls):
  2022. if not hasattr(cls, '__init__'):
  2023. raise 'recordCreationStackStr: class \'%s\' must define __init__' % cls.__name__
  2024. cls.__moved_init__ = cls.__init__
  2025. def __recordCreationStackStr_init__(self, *args, **kArgs):
  2026. # store as list of strings to conserve memory
  2027. self._creationStackTraceStrLst = StackTrace(start=1).compact().split(',')
  2028. return self.__moved_init__(*args, **kArgs)
  2029. def getCreationStackTraceCompactStr(self):
  2030. return ','.join(self._creationStackTraceStrLst)
  2031. def printCreationStackTrace(self):
  2032. print ','.join(self._creationStackTraceStrLst)
  2033. cls.__init__ = __recordCreationStackStr_init__
  2034. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2035. cls.printCreationStackTrace = printCreationStackTrace
  2036. return cls
  2037. # class 'decorator' that logs all method calls for a particular class
  2038. def logMethodCalls(cls):
  2039. if not hasattr(cls, 'notify'):
  2040. raise 'logMethodCalls: class \'%s\' must have a notify' % cls.__name__
  2041. for name in dir(cls):
  2042. method = getattr(cls, name)
  2043. if hasattr(method, '__call__'):
  2044. def getLoggedMethodCall(method):
  2045. def __logMethodCall__(obj, *args, **kArgs):
  2046. s = '%s(' % method.__name__
  2047. for arg in args:
  2048. try:
  2049. argStr = repr(arg)
  2050. except:
  2051. argStr = 'bad repr: %s' % arg.__class__
  2052. s += '%s, ' % argStr
  2053. for karg, value in kArgs.items():
  2054. s += '%s=%s, ' % (karg, repr(value))
  2055. if len(args) or len(kArgs):
  2056. s = s[:-2]
  2057. s += ')'
  2058. obj.notify.info(s)
  2059. return method(obj, *args, **kArgs)
  2060. return __logMethodCall__
  2061. setattr(cls, name, getLoggedMethodCall(method))
  2062. __logMethodCall__ = None
  2063. return cls
  2064. # http://en.wikipedia.org/wiki/Golden_ratio
  2065. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  2066. class GoldenRectangle:
  2067. @staticmethod
  2068. def getLongerEdge(shorter):
  2069. return shorter * GoldenRatio
  2070. @staticmethod
  2071. def getShorterEdge(longer):
  2072. return longer / GoldenRatio
  2073. class HotkeyBreaker:
  2074. def __init__(self,breakKeys = []):
  2075. from direct.showbase.DirectObject import DirectObject
  2076. self.do = DirectObject()
  2077. self.breakKeys = {}
  2078. if not isinstance(breakKeys, (list,tuple)):
  2079. breakKeys = (breakKeys,)
  2080. for key in breakKeys:
  2081. self.addBreakKey(key)
  2082. def addBreakKey(self,breakKey):
  2083. if __dev__:
  2084. self.do.accept(breakKey,self.breakFunc,extraArgs = [breakKey])
  2085. def removeBreakKey(self,breakKey):
  2086. if __dev__:
  2087. self.do.ignore(breakKey)
  2088. def breakFunc(self,breakKey):
  2089. if __dev__:
  2090. self.breakKeys[breakKey] = True
  2091. def setBreakPt(self, breakKey = None, persistent = False):
  2092. if __dev__:
  2093. if not breakKey:
  2094. import pdb;pdb.set_trace()
  2095. return True
  2096. else:
  2097. if self.breakKeys.get(breakKey,False):
  2098. if not persistent:
  2099. self.breakKeys.pop(breakKey)
  2100. import pdb;pdb.set_trace()
  2101. return True
  2102. return True
  2103. def clearBreakPt(self, breakKey):
  2104. if __dev__:
  2105. return bool(self.breakKeys.pop(breakKey,None))
  2106. def nullGen():
  2107. # generator that ends immediately
  2108. if False:
  2109. # yield that never runs but still exists, making this func a generator
  2110. yield None
  2111. def loopGen(l):
  2112. # generator that yields the items of an iterable object forever
  2113. def _gen(l):
  2114. while True:
  2115. for item in l:
  2116. yield item
  2117. gen = _gen(l)
  2118. # don't leak
  2119. _gen = None
  2120. return gen
  2121. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  2122. # iterates and finally yields a flywheel generator object
  2123. # the number of appearances for each object is controlled by passing in
  2124. # a list of counts, or a functor that returns a count when called with
  2125. # an object from the 'objects' list.
  2126. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  2127. def flywheel(index2objectAndCount):
  2128. # generator to produce a sequence whose elements appear a specific number of times
  2129. while len(index2objectAndCount):
  2130. keyList = index2objectAndCount.keys()
  2131. for key in keyList:
  2132. if index2objectAndCount[key][1] > 0:
  2133. yield index2objectAndCount[key][0]
  2134. index2objectAndCount[key][1] -= 1
  2135. if index2objectAndCount[key][1] <= 0:
  2136. del index2objectAndCount[key]
  2137. # if we were not given a list of counts, create it by calling countFunc
  2138. if countList is None:
  2139. countList = []
  2140. for object in objects:
  2141. yield None
  2142. countList.append(countFunc(object))
  2143. if scale is not None:
  2144. # scale the counts if we've got a scale factor
  2145. for i in xrange(len(countList)):
  2146. yield None
  2147. if countList[i] > 0:
  2148. countList[i] = max(1, int(countList[i] * scale))
  2149. # create a dict for the flywheel to use during its iteration to efficiently select
  2150. # the objects for the sequence
  2151. index2objectAndCount = {}
  2152. for i in xrange(len(countList)):
  2153. yield None
  2154. index2objectAndCount[i] = [objects[i], countList[i]]
  2155. # create the flywheel generator
  2156. yield flywheel(index2objectAndCount)
  2157. def flywheel(*args, **kArgs):
  2158. # create a flywheel generator
  2159. # see arguments and comments in flywheelGen above
  2160. # example usage:
  2161. """
  2162. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  2163. ... print i,
  2164. ...
  2165. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  2166. """
  2167. for flywheel in makeFlywheelGen(*args, **kArgs):
  2168. pass
  2169. return flywheel
  2170. if __debug__ and __name__ == '__main__':
  2171. f = flywheel(['a','b','c','d'], countList=[11,20,3,4])
  2172. obj2count = {}
  2173. for obj in f:
  2174. obj2count.setdefault(obj, 0)
  2175. obj2count[obj] += 1
  2176. assert obj2count['a'] == 11
  2177. assert obj2count['b'] == 20
  2178. assert obj2count['c'] == 3
  2179. assert obj2count['d'] == 4
  2180. f = flywheel([1,2,3,4], countFunc=lambda x: x*2)
  2181. obj2count = {}
  2182. for obj in f:
  2183. obj2count.setdefault(obj, 0)
  2184. obj2count[obj] += 1
  2185. assert obj2count[1] == 2
  2186. assert obj2count[2] == 4
  2187. assert obj2count[3] == 6
  2188. assert obj2count[4] == 8
  2189. f = flywheel([1,2,3,4], countFunc=lambda x: x, scale = 3)
  2190. obj2count = {}
  2191. for obj in f:
  2192. obj2count.setdefault(obj, 0)
  2193. obj2count[obj] += 1
  2194. assert obj2count[1] == 1 * 3
  2195. assert obj2count[2] == 2 * 3
  2196. assert obj2count[3] == 3 * 3
  2197. assert obj2count[4] == 4 * 3
  2198. def quickProfile(name="unnamed"):
  2199. import pstats
  2200. def profileDecorator(f):
  2201. if(not config.GetBool("use-profiler",0)):
  2202. return f
  2203. def _profiled(*args, **kArgs):
  2204. # must do this in here because we don't have base/simbase
  2205. # at the time that PythonUtil is loaded
  2206. if(not config.GetBool("profile-debug",0)):
  2207. #dumb timings
  2208. st=globalClock.getRealTime()
  2209. f(*args,**kArgs)
  2210. s=globalClock.getRealTime()-st
  2211. print "Function %s.%s took %s seconds"%(f.__module__, f.__name__,s)
  2212. else:
  2213. import profile as prof, pstats
  2214. #detailed profile, stored in base.stats under (
  2215. if(not hasattr(base,"stats")):
  2216. base.stats={}
  2217. if(not base.stats.get(name)):
  2218. base.stats[name]=[]
  2219. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  2220. s=pstats.Stats("t.prof")
  2221. #p=hotshot.Profile("t.prof")
  2222. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  2223. #s = hotshot.stats.load("t.prof")
  2224. s.strip_dirs()
  2225. s.sort_stats("cumulative")
  2226. base.stats[name].append(s)
  2227. _profiled.__doc__ = f.__doc__
  2228. return _profiled
  2229. return profileDecorator
  2230. def getTotalAnnounceTime():
  2231. td=0
  2232. for objs in base.stats.values():
  2233. for stat in objs:
  2234. td+=getAnnounceGenerateTime(stat)
  2235. return td
  2236. def getAnnounceGenerateTime(stat):
  2237. val=0
  2238. stats=stat.stats
  2239. for i in stats.keys():
  2240. if(i[2]=="announceGenerate"):
  2241. newVal=stats[i][3]
  2242. if(newVal>val):
  2243. val=newVal
  2244. return val
  2245. def choice(condition, ifTrue, ifFalse):
  2246. # equivalent of C++ (condition ? ifTrue : ifFalse)
  2247. if condition:
  2248. return ifTrue
  2249. else:
  2250. return ifFalse
  2251. class MiniLog:
  2252. def __init__(self, name):
  2253. self.indent = 1
  2254. self.name = name
  2255. self.lines = []
  2256. def __str__(self):
  2257. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  2258. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  2259. def enterFunction(self, funcName, *args, **kw):
  2260. rArgs = [repr(x)+', ' for x in args] + \
  2261. [ x + ' = ' + '%s, ' % repr(y) for x,y in kw.items()]
  2262. if not rArgs:
  2263. rArgs = '()'
  2264. else:
  2265. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2266. line = '%s%s' % (funcName, rArgs)
  2267. self.appendFunctionCall(line)
  2268. self.indent += 1
  2269. return line
  2270. def exitFunction(self):
  2271. self.indent -= 1
  2272. return self.indent
  2273. def appendFunctionCall(self, line):
  2274. self.lines.append(' '*(self.indent*2) + line)
  2275. return line
  2276. def appendLine(self, line):
  2277. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  2278. return line
  2279. def flush(self):
  2280. outStr = str(self)
  2281. self.indent = 0
  2282. self.lines = []
  2283. return outStr
  2284. class MiniLogSentry:
  2285. def __init__(self, log, funcName, *args, **kw):
  2286. self.log = log
  2287. if self.log:
  2288. self.log.enterFunction(funcName, *args, **kw)
  2289. def __del__(self):
  2290. if self.log:
  2291. self.log.exitFunction()
  2292. del self.log
  2293. def logBlock(id, msg):
  2294. print '<< LOGBLOCK(%03d)' % id
  2295. print str(msg)
  2296. print '/LOGBLOCK(%03d) >>' % id
  2297. class HierarchyException(Exception):
  2298. JOSWILSO = 0
  2299. def __init__(self, owner, description):
  2300. self.owner = owner
  2301. self.desc = description
  2302. def __str__(self):
  2303. return '(%s): %s' % (self.owner, self.desc)
  2304. def __repr__(self):
  2305. return 'HierarchyException(%s)' % (self.owner, )
  2306. # __dev__ is not defined at import time, call this after it's defined
  2307. def recordFunctorCreationStacks():
  2308. global Functor
  2309. if not hasattr(Functor, '_functorCreationStacksRecorded'):
  2310. Functor = recordCreationStackStr(Functor)
  2311. Functor._functorCreationStacksRecorded = True
  2312. Functor.__call__ = Functor._exceptionLoggedCreationStack__call__
  2313. def formatTimeCompact(seconds):
  2314. # returns string in format '1d3h22m43s'
  2315. result = ''
  2316. a = int(seconds)
  2317. seconds = a % 60
  2318. a //= 60
  2319. if a > 0:
  2320. minutes = a % 60
  2321. a //= 60
  2322. if a > 0:
  2323. hours = a % 24
  2324. a //= 24
  2325. if a > 0:
  2326. days = a
  2327. result += '%sd' % days
  2328. result += '%sh' % hours
  2329. result += '%sm' % minutes
  2330. result += '%ss' % seconds
  2331. return result
  2332. if __debug__ and __name__ == '__main__':
  2333. ftc = formatTimeCompact
  2334. assert ftc(0) == '0s'
  2335. assert ftc(1) == '1s'
  2336. assert ftc(60) == '1m0s'
  2337. assert ftc(64) == '1m4s'
  2338. assert ftc(60*60) == '1h0m0s'
  2339. assert ftc(24*60*60) == '1d0h0m0s'
  2340. assert ftc(24*60*60 + 2*60*60 + 34*60 + 12) == '1d2h34m12s'
  2341. del ftc
  2342. def formatTimeExact(seconds):
  2343. # like formatTimeCompact but leaves off '0 seconds', '0 minutes' etc. for
  2344. # times that are e.g. 1 hour, 3 days etc.
  2345. # returns string in format '1d3h22m43s'
  2346. result = ''
  2347. a = int(seconds)
  2348. seconds = a % 60
  2349. a //= 60
  2350. if a > 0:
  2351. minutes = a % 60
  2352. a //= 60
  2353. if a > 0:
  2354. hours = a % 24
  2355. a //= 24
  2356. if a > 0:
  2357. days = a
  2358. result += '%sd' % days
  2359. if hours or minutes or seconds:
  2360. result += '%sh' % hours
  2361. if minutes or seconds:
  2362. result += '%sm' % minutes
  2363. if seconds or result == '':
  2364. result += '%ss' % seconds
  2365. return result
  2366. if __debug__ and __name__ == '__main__':
  2367. fte = formatTimeExact
  2368. assert fte(0) == '0s'
  2369. assert fte(1) == '1s'
  2370. assert fte(2) == '2s'
  2371. assert fte(61) == '1m1s'
  2372. assert fte(60) == '1m'
  2373. assert fte(60*60) == '1h'
  2374. assert fte(24*60*60) == '1d'
  2375. assert fte((24*60*60) + (2 * 60)) == '1d0h2m'
  2376. del fte
  2377. class AlphabetCounter:
  2378. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  2379. def __init__(self):
  2380. self._curCounter = ['A']
  2381. def next(self):
  2382. result = ''.join([c for c in self._curCounter])
  2383. index = -1
  2384. while True:
  2385. curChar = self._curCounter[index]
  2386. if curChar is 'Z':
  2387. nextChar = 'A'
  2388. carry = True
  2389. else:
  2390. nextChar = chr(ord(self._curCounter[index])+1)
  2391. carry = False
  2392. self._curCounter[index] = nextChar
  2393. if carry:
  2394. if (-index) == len(self._curCounter):
  2395. self._curCounter = ['A',] + self._curCounter
  2396. break
  2397. else:
  2398. index -= 1
  2399. carry = False
  2400. else:
  2401. break
  2402. return result
  2403. if __debug__ and __name__ == '__main__':
  2404. def testAlphabetCounter():
  2405. tempList = []
  2406. ac = AlphabetCounter()
  2407. for i in xrange(26*3):
  2408. tempList.append(ac.next())
  2409. assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  2410. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
  2411. 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',]
  2412. ac = AlphabetCounter()
  2413. num = 26 # A-Z
  2414. num += (26*26) # AA-ZZ
  2415. num += 26 # AAZ
  2416. num += 1 # ABA
  2417. num += 2 # ABC
  2418. for i in xrange(num):
  2419. x = ac.next()
  2420. assert x == 'ABC'
  2421. testAlphabetCounter()
  2422. del testAlphabetCounter
  2423. globalPdb = None
  2424. traceCalled = False
  2425. def setupPdb():
  2426. import pdb;
  2427. class pandaPdb(pdb.Pdb):
  2428. def stop_here(self, frame):
  2429. global traceCalled
  2430. if(traceCalled):
  2431. result = pdb.Pdb.stop_here(self, frame)
  2432. if(result == True):
  2433. traceCalled = False
  2434. return result
  2435. if frame is self.stopframe:
  2436. return True
  2437. return False
  2438. global globalPdb
  2439. globalPdb = pandaPdb()
  2440. globalPdb.reset()
  2441. sys.settrace(globalPdb.trace_dispatch)
  2442. def pandaTrace():
  2443. if __dev__:
  2444. if not globalPdb:
  2445. setupPdb()
  2446. global traceCalled
  2447. globalPdb.set_trace(sys._getframe().f_back)
  2448. traceCalled = True
  2449. packageMap = {
  2450. "toontown":"$TOONTOWN",
  2451. "direct":"$DIRECT",
  2452. "otp":"$OTP",
  2453. "pirates":"$PIRATES",
  2454. }
  2455. #assuming . dereferncing for nice linking to imports
  2456. def pandaBreak(dotpath, linenum, temporary = 0, cond = None):
  2457. if __dev__:
  2458. from panda3d.core import Filename
  2459. if not globalPdb:
  2460. setupPdb()
  2461. dirs = dotpath.split(".")
  2462. root = Filename.expandFrom(packageMap[dirs[0]]).toOsSpecific()
  2463. filename = root + "\\src"
  2464. for d in dirs[1:]:
  2465. filename="%s\\%s"%(filename,d)
  2466. print filename
  2467. globalPdb.set_break(filename+".py", linenum, temporary, cond)
  2468. class Default:
  2469. # represents 'use the default value'
  2470. # useful for keyword arguments to virtual methods
  2471. pass
  2472. superLogFile = None
  2473. def startSuperLog(customFunction = None):
  2474. global superLogFile
  2475. if(not superLogFile):
  2476. superLogFile = open("c:\\temp\\superLog.txt", "w")
  2477. def trace_dispatch(a,b,c):
  2478. if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0):
  2479. vars = dict(a.f_locals)
  2480. if 'self' in vars:
  2481. del vars['self']
  2482. if '__builtins__' in vars:
  2483. del vars['__builtins__']
  2484. for i in vars:
  2485. vars[i] = safeReprTypeOnFail(vars[i])
  2486. if customFunction:
  2487. superLogFile.write( "before = %s\n"%customFunction())
  2488. superLogFile.write( "%s(%s):%s:%s\n"%(a.f_code.co_filename.split("\\")[-1],a.f_code.co_firstlineno, a.f_code.co_name, vars))
  2489. if customFunction:
  2490. superLogFile.write( "after = %s\n"%customFunction())
  2491. return trace_dispatch
  2492. sys.settrace(trace_dispatch)
  2493. def endSuperLog():
  2494. global superLogFile
  2495. if(superLogFile):
  2496. sys.settrace(None)
  2497. superLogFile.close()
  2498. superLogFile = None
  2499. def isInteger(n):
  2500. return type(n) in (types.IntType, types.LongType)
  2501. def configIsToday(configName):
  2502. # TODO: replace usage of strptime with something else
  2503. # returns true if config string is a valid representation of today's date
  2504. today = time.localtime()
  2505. confStr = config.GetString(configName, '')
  2506. for format in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
  2507. try:
  2508. confDate = time.strptime(confStr, format)
  2509. except ValueError:
  2510. pass
  2511. else:
  2512. if (confDate.tm_year == today.tm_year and
  2513. confDate.tm_mon == today.tm_mon and
  2514. confDate.tm_mday == today.tm_mday):
  2515. return True
  2516. return False
  2517. def typeName(o):
  2518. if hasattr(o, '__class__'):
  2519. return o.__class__.__name__
  2520. else:
  2521. return o.__name__
  2522. def safeTypeName(o):
  2523. try:
  2524. return typeName(o)
  2525. except:
  2526. pass
  2527. try:
  2528. return type(o)
  2529. except:
  2530. pass
  2531. return '<failed safeTypeName()>'
  2532. def histogramDict(l):
  2533. d = {}
  2534. for e in l:
  2535. d.setdefault(e, 0)
  2536. d[e] += 1
  2537. return d
  2538. def unescapeHtmlString(s):
  2539. # converts %## to corresponding character
  2540. # replaces '+' with ' '
  2541. result = ''
  2542. i = 0
  2543. while i < len(s):
  2544. char = s[i]
  2545. if char == '+':
  2546. char = ' '
  2547. elif char == '%':
  2548. if i < (len(s)-2):
  2549. num = int(s[i+1:i+3], 16)
  2550. char = chr(num)
  2551. i += 2
  2552. i += 1
  2553. result += char
  2554. return result
  2555. if __debug__ and __name__ == '__main__':
  2556. assert unescapeHtmlString('asdf') == 'asdf'
  2557. assert unescapeHtmlString('as+df') == 'as df'
  2558. assert unescapeHtmlString('as%32df') == 'as2df'
  2559. assert unescapeHtmlString('asdf%32') == 'asdf2'
  2560. def unicodeUtf8(s):
  2561. # * -> Unicode UTF-8
  2562. if type(s) is types.UnicodeType:
  2563. return s
  2564. else:
  2565. return unicode(str(s), 'utf-8')
  2566. def encodedUtf8(s):
  2567. # * -> 8-bit-encoded UTF-8
  2568. return unicodeUtf8(s).encode('utf-8')
  2569. import __builtin__
  2570. __builtin__.Functor = Functor
  2571. __builtin__.Stack = Stack
  2572. __builtin__.Queue = Queue
  2573. __builtin__.Enum = Enum
  2574. __builtin__.SerialNumGen = SerialNumGen
  2575. __builtin__.SerialMaskedGen = SerialMaskedGen
  2576. __builtin__.ScratchPad = ScratchPad
  2577. __builtin__.uniqueName = uniqueName
  2578. __builtin__.serialNum = serialNum
  2579. __builtin__.profiled = profiled
  2580. __builtin__.itype = itype
  2581. __builtin__.exceptionLogged = exceptionLogged
  2582. __builtin__.appendStr = appendStr
  2583. __builtin__.bound = bound
  2584. __builtin__.clamp = clamp
  2585. __builtin__.lerp = lerp
  2586. __builtin__.makeList = makeList
  2587. __builtin__.makeTuple = makeTuple
  2588. __builtin__.printStack = printStack
  2589. __builtin__.printReverseStack = printReverseStack
  2590. __builtin__.printVerboseStack = printVerboseStack
  2591. __builtin__.DelayedCall = DelayedCall
  2592. __builtin__.DelayedFunctor = DelayedFunctor
  2593. __builtin__.FrameDelayedCall = FrameDelayedCall
  2594. __builtin__.SubframeCall = SubframeCall
  2595. __builtin__.invertDict = invertDict
  2596. __builtin__.invertDictLossless = invertDictLossless
  2597. __builtin__.getBase = getBase
  2598. __builtin__.getRepository = getRepository
  2599. __builtin__.safeRepr = safeRepr
  2600. __builtin__.fastRepr = fastRepr
  2601. __builtin__.nullGen = nullGen
  2602. __builtin__.flywheel = flywheel
  2603. __builtin__.loopGen = loopGen
  2604. __builtin__.StackTrace = StackTrace
  2605. __builtin__.choice = choice
  2606. __builtin__.report = report
  2607. __builtin__.pstatcollect = pstatcollect
  2608. __builtin__.MiniLog = MiniLog
  2609. __builtin__.MiniLogSentry = MiniLogSentry
  2610. __builtin__.logBlock = logBlock
  2611. __builtin__.HierarchyException = HierarchyException
  2612. __builtin__.deeptype = deeptype
  2613. __builtin__.Default = Default
  2614. __builtin__.isInteger = isInteger
  2615. __builtin__.configIsToday = configIsToday
  2616. __builtin__.typeName = typeName
  2617. __builtin__.safeTypeName = safeTypeName
  2618. __builtin__.histogramDict = histogramDict
  2619. __builtin__.unicodeUtf8 = unicodeUtf8
  2620. __builtin__.encodedUtf8 = encodedUtf8