PythonUtil.py 85 KB

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