PythonUtil.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  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 sys.version_info < (3, 0) and t is types.InstanceType:
  1458. return "<type 'instance' of <class %s>>" % (obj.__class__)
  1459. else:
  1460. # C++ object instances appear to be types via type()
  1461. # check if this is a C++ object
  1462. if dtoolSuperBase is None:
  1463. _getDtoolSuperBase()
  1464. if isinstance(obj, dtoolSuperBase):
  1465. return "<type 'instance' of %s>" % (obj.__class__)
  1466. return t
  1467. def deeptype(obj, maxLen=100, _visitedIds=None):
  1468. if _visitedIds is None:
  1469. _visitedIds = set()
  1470. if id(obj) in _visitedIds:
  1471. return '<ALREADY-VISITED %s>' % itype(obj)
  1472. t = type(obj)
  1473. if t in (tuple, list):
  1474. s = ''
  1475. s += {tuple: '(',
  1476. list: '[',}[type(obj)]
  1477. if maxLen is not None and len(obj) > maxLen:
  1478. o = obj[:maxLen]
  1479. ellips = '...'
  1480. else:
  1481. o = obj
  1482. ellips = ''
  1483. _visitedIds.add(id(obj))
  1484. for item in o:
  1485. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  1486. s += ', '
  1487. _visitedIds.remove(id(obj))
  1488. s += ellips
  1489. s += {tuple: ')',
  1490. list: ']',}[type(obj)]
  1491. return s
  1492. elif type(obj) is dict:
  1493. s = '{'
  1494. if maxLen is not None and len(obj) > maxLen:
  1495. o = list(obj.keys())[:maxLen]
  1496. ellips = '...'
  1497. else:
  1498. o = list(obj.keys())
  1499. ellips = ''
  1500. _visitedIds.add(id(obj))
  1501. for key in o:
  1502. value = obj[key]
  1503. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  1504. deeptype(value, maxLen, _visitedIds=_visitedIds))
  1505. _visitedIds.remove(id(obj))
  1506. s += ellips
  1507. s += '}'
  1508. return s
  1509. else:
  1510. return str(itype(obj))
  1511. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  1512. """get a string that has each item of the list on its own line,
  1513. and each item is numbered on the left from zero"""
  1514. digits = 0
  1515. n = len(items)
  1516. while n > 0:
  1517. digits += 1
  1518. n //= 10
  1519. digits = digits
  1520. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1521. first = True
  1522. s = ''
  1523. snip = '<SNIP>'
  1524. for i in xrange(len(items)):
  1525. if not first:
  1526. s += '\n'
  1527. first = False
  1528. objStr = fastRepr(items[i])
  1529. if len(objStr) > maxLen:
  1530. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1531. s += format % (i, itype(items[i]), objStr)
  1532. return s
  1533. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  1534. """get a string that has each item of the list on its own line,
  1535. the items are stringwise-sorted, and each item is numbered on
  1536. the left from zero"""
  1537. digits = 0
  1538. n = len(items)
  1539. while n > 0:
  1540. digits += 1
  1541. n //= 10
  1542. digits = digits
  1543. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  1544. snip = '<SNIP>'
  1545. strs = []
  1546. for item in items:
  1547. objStr = fastRepr(item)
  1548. if len(objStr) > maxLen:
  1549. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1550. strs.append(objStr)
  1551. first = True
  1552. s = ''
  1553. strs.sort()
  1554. for i in xrange(len(strs)):
  1555. if not first:
  1556. s += '\n'
  1557. first = False
  1558. objStr = strs[i]
  1559. s += format % (i, itype(items[i]), strs[i])
  1560. return s
  1561. def printNumberedTyped(items, maxLen=5000):
  1562. """print out each item of the list on its own line,
  1563. with each item numbered on the left from zero"""
  1564. digits = 0
  1565. n = len(items)
  1566. while n > 0:
  1567. digits += 1
  1568. n //= 10
  1569. digits = digits
  1570. format = '%0' + '%s' % digits + 'i:%s \t%s'
  1571. for i in xrange(len(items)):
  1572. objStr = fastRepr(items[i])
  1573. if len(objStr) > maxLen:
  1574. snip = '<SNIP>'
  1575. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  1576. print(format % (i, itype(items[i]), objStr))
  1577. def printNumberedTypesGen(items, maxLen=5000):
  1578. digits = 0
  1579. n = len(items)
  1580. while n > 0:
  1581. digits += 1
  1582. n //= 10
  1583. digits = digits
  1584. format = '%0' + '%s' % digits + 'i:%s'
  1585. for i in xrange(len(items)):
  1586. print(format % (i, itype(items[i])))
  1587. yield None
  1588. def printNumberedTypes(items, maxLen=5000):
  1589. """print out the type of each item of the list on its own line,
  1590. with each item numbered on the left from zero"""
  1591. for result in printNumberedTypesGen(items, maxLen):
  1592. yield result
  1593. class DelayedCall:
  1594. """ calls a func after a specified delay """
  1595. def __init__(self, func, name=None, delay=None):
  1596. if name is None:
  1597. name = 'anonymous'
  1598. if delay is None:
  1599. delay = .01
  1600. self._func = func
  1601. self._taskName = 'DelayedCallback-%s' % name
  1602. self._delay = delay
  1603. self._finished = False
  1604. self._addDoLater()
  1605. def destroy(self):
  1606. self._finished = True
  1607. self._removeDoLater()
  1608. def finish(self):
  1609. if not self._finished:
  1610. self._doCallback()
  1611. self.destroy()
  1612. def _addDoLater(self):
  1613. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  1614. def _removeDoLater(self):
  1615. taskMgr.remove(self._taskName)
  1616. def _doCallback(self, task):
  1617. self._finished = True
  1618. func = self._func
  1619. del self._func
  1620. func()
  1621. class FrameDelayedCall:
  1622. """ calls a func after N frames """
  1623. def __init__(self, name, callback, frames=None, cancelFunc=None):
  1624. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  1625. # and callback is not called
  1626. if frames is None:
  1627. frames = 1
  1628. self._name = name
  1629. self._frames = frames
  1630. self._callback = callback
  1631. self._cancelFunc = cancelFunc
  1632. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  1633. self._finished = False
  1634. self._startTask()
  1635. def destroy(self):
  1636. self._finished = True
  1637. self._stopTask()
  1638. def finish(self):
  1639. if not self._finished:
  1640. self._finished = True
  1641. self._callback()
  1642. self.destroy()
  1643. def _startTask(self):
  1644. taskMgr.add(self._frameTask, self._taskName)
  1645. self._counter = 0
  1646. def _stopTask(self):
  1647. taskMgr.remove(self._taskName)
  1648. def _frameTask(self, task):
  1649. if self._cancelFunc and self._cancelFunc():
  1650. self.destroy()
  1651. return task.done
  1652. self._counter += 1
  1653. if self._counter >= self._frames:
  1654. self.finish()
  1655. return task.done
  1656. return task.cont
  1657. class DelayedFunctor:
  1658. """ Waits for this object to be called, then calls supplied functor after a delay.
  1659. Effectively inserts a time delay between the caller and the functor. """
  1660. def __init__(self, functor, name=None, delay=None):
  1661. self._functor = functor
  1662. self._name = name
  1663. # FunctionInterval requires __name__
  1664. self.__name__ = self._name
  1665. self._delay = delay
  1666. def _callFunctor(self):
  1667. cb = Functor(self._functor, *self._args, **self._kwArgs)
  1668. del self._functor
  1669. del self._name
  1670. del self._delay
  1671. del self._args
  1672. del self._kwArgs
  1673. del self._delayedCall
  1674. del self.__name__
  1675. cb()
  1676. def __call__(self, *args, **kwArgs):
  1677. self._args = args
  1678. self._kwArgs = kwArgs
  1679. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  1680. class SubframeCall:
  1681. """Calls a callback at a specific time during the frame using the
  1682. task system"""
  1683. def __init__(self, functor, taskPriority, name=None):
  1684. self._functor = functor
  1685. self._name = name
  1686. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  1687. taskMgr.add(self._doCallback,
  1688. self._taskName,
  1689. priority=taskPriority)
  1690. def _doCallback(self, task):
  1691. functor = self._functor
  1692. del self._functor
  1693. functor()
  1694. del self._name
  1695. self._taskName = None
  1696. return task.done
  1697. def cleanup(self):
  1698. if (self._taskName):
  1699. taskMgr.remove(self._taskName)
  1700. self._taskName = None
  1701. class PStatScope:
  1702. collectors = {}
  1703. def __init__(self, level = None):
  1704. self.levels = []
  1705. if level:
  1706. self.levels.append(level)
  1707. def copy(self, push = None):
  1708. c = PStatScope()
  1709. c.levels = self.levels[:]
  1710. if push:
  1711. c.push(push)
  1712. return c
  1713. def __repr__(self):
  1714. return 'PStatScope - \'%s\'' % (self,)
  1715. def __str__(self):
  1716. return ':'.join(self.levels)
  1717. def push(self, level):
  1718. self.levels.append(level.replace('_',''))
  1719. def pop(self):
  1720. return self.levels.pop()
  1721. def start(self, push = None):
  1722. if push:
  1723. self.push(push)
  1724. pass
  1725. self.getCollector().start()
  1726. def stop(self, pop = False):
  1727. self.getCollector().stop()
  1728. if pop:
  1729. self.pop()
  1730. def getCollector(self):
  1731. label = str(self)
  1732. if label not in self.collectors:
  1733. from panda3d.core import PStatCollector
  1734. self.collectors[label] = PStatCollector(label)
  1735. pass
  1736. # print ' ',self.collectors[label]
  1737. return self.collectors[label]
  1738. def pstatcollect(scope, level = None):
  1739. def decorator(f):
  1740. return f
  1741. try:
  1742. if not (__dev__ or ConfigVariableBool('force-pstatcollect', False)) or \
  1743. not scope:
  1744. return decorator
  1745. def decorator(f):
  1746. def wrap(*args, **kw):
  1747. scope.start(push = (level or f.__name__))
  1748. val = f(*args, **kw)
  1749. scope.stop(pop = True)
  1750. return val
  1751. return wrap
  1752. pass
  1753. except:
  1754. pass
  1755. return decorator
  1756. __report_indent = 0
  1757. def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigParam = []):
  1758. """
  1759. This is a decorator generating function. Use is similar to
  1760. a @decorator, except you must be sure to call it as a function.
  1761. It actually returns the decorator which is then used to transform
  1762. your decorated function. Confusing at first, I know.
  1763. Decoration occurs at function definition time.
  1764. If __dev__ is not defined, or resolves to False, this function
  1765. has no effect and no wrapping/transform occurs. So in production,
  1766. it's as if the report has been asserted out.
  1767. Parameters::
  1768. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  1769. This allows you to specify certain useful bits of info.
  1770. module: Prints the module that this report statement
  1771. can be found in.
  1772. args: Prints the arguments as they were passed to
  1773. this function.
  1774. timeStamp: Adds the current frame time to the output.
  1775. deltaStamp: Adds the current AI synched frame time to
  1776. the output
  1777. frameCount: Adds the current frame count to the output.
  1778. Usually cleaner than the timeStamp output.
  1779. avLocation: Adds the localAvatar's network location
  1780. to the output. Useful for interest debugging.
  1781. interests: Prints the current interest state after the
  1782. report.
  1783. stackTrace: Prints a stack trace after the report.
  1784. prefix: Optional string to prepend to output, just before the function.
  1785. Allows for easy grepping and is useful when merging AI/Client
  1786. reports into a single file.
  1787. xform: Optional callback that accepts a single parameter: argument 0 to
  1788. the decorated function. (assumed to be 'self')
  1789. It should return a value to be inserted into the report output string.
  1790. notifyFunc: A notify function such as info, debug, warning, etc.
  1791. By default the report will be printed to stdout. This
  1792. will allow you send the report to a designated 'notify'
  1793. output.
  1794. dConfigParam: A list of Config.prc string variables.
  1795. By default the report will always print. If you
  1796. specify this param, it will only print if one of the
  1797. specified config strings resolve to True.
  1798. """
  1799. def indent(str):
  1800. global __report_indent
  1801. return ' '*__report_indent+str
  1802. def decorator(f):
  1803. return f
  1804. try:
  1805. if not (__dev__ or config.GetBool('force-reports', 0)):
  1806. return decorator
  1807. # determine whether we should use the decorator
  1808. # based on the value of dConfigParam.
  1809. dConfigParamList = []
  1810. doPrint = False
  1811. if not dConfigParam:
  1812. doPrint = True
  1813. else:
  1814. if not isinstance(dConfigParam, (list,tuple)):
  1815. dConfigParams = (dConfigParam,)
  1816. else:
  1817. dConfigParams = dConfigParam
  1818. dConfigParamList = [param for param in dConfigParams \
  1819. if config.GetBool('want-%s-report' % (param,), 0)]
  1820. doPrint = bool(dConfigParamList)
  1821. pass
  1822. if not doPrint:
  1823. return decorator
  1824. # Determine any prefixes defined in our Config.prc.
  1825. if prefix:
  1826. prefixes = set([prefix])
  1827. else:
  1828. prefixes = set()
  1829. pass
  1830. for param in dConfigParamList:
  1831. prefix = config.GetString('prefix-%s-report' % (param,), '')
  1832. if prefix:
  1833. prefixes.add(prefix)
  1834. pass
  1835. pass
  1836. except NameError as e:
  1837. return decorator
  1838. globalClockDelta = importlib.import_module("direct.distributed.ClockDelta").globalClockDelta
  1839. def decorator(f):
  1840. def wrap(*args,**kwargs):
  1841. if args:
  1842. rArgs = [args[0].__class__.__name__ + ', ']
  1843. else:
  1844. rArgs = []
  1845. if 'args' in types:
  1846. rArgs += [repr(x)+', ' for x in args[1:]] + \
  1847. [ x + ' = ' + '%s, ' % repr(y) for x,y in kwargs.items()]
  1848. if not rArgs:
  1849. rArgs = '()'
  1850. else:
  1851. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  1852. outStr = '%s%s' % (f.__name__, rArgs)
  1853. # Insert prefix place holder, if needed
  1854. if prefixes:
  1855. outStr = '%%s %s' % (outStr,)
  1856. if 'module' in types:
  1857. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  1858. if 'frameCount' in types:
  1859. outStr = '%-8d : %s' % (globalClock.getFrameCount(), outStr)
  1860. if 'timeStamp' in types:
  1861. outStr = '%-8.3f : %s' % (globalClock.getFrameTime(), outStr)
  1862. if 'deltaStamp' in types:
  1863. outStr = '%-8.2f : %s' % (globalClock.getRealTime() - \
  1864. globalClockDelta.delta, outStr)
  1865. if 'avLocation' in types:
  1866. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  1867. if xform:
  1868. outStr = '%s : %s' % (outStr, xform(args[0]))
  1869. if prefixes:
  1870. # This will print the same report once for each prefix
  1871. for prefix in prefixes:
  1872. if notifyFunc:
  1873. notifyFunc(outStr % (prefix,))
  1874. else:
  1875. print(indent(outStr % (prefix,)))
  1876. else:
  1877. if notifyFunc:
  1878. notifyFunc(outStr)
  1879. else:
  1880. print(indent(outStr))
  1881. if 'interests' in types:
  1882. base.cr.printInterestSets()
  1883. if 'stackTrace' in types:
  1884. print(StackTrace())
  1885. global __report_indent
  1886. rVal = None
  1887. try:
  1888. __report_indent += 1
  1889. rVal = f(*args,**kwargs)
  1890. finally:
  1891. __report_indent -= 1
  1892. if rVal is not None:
  1893. print(indent(' -> '+repr(rVal)))
  1894. pass
  1895. pass
  1896. return rVal
  1897. wrap.__name__ = f.__name__
  1898. wrap.__dict__ = f.__dict__
  1899. wrap.__doc__ = f.__doc__
  1900. wrap.__module__ = f.__module__
  1901. return wrap
  1902. return decorator
  1903. def getBase():
  1904. try:
  1905. return base
  1906. except:
  1907. return simbase
  1908. def getRepository():
  1909. try:
  1910. return base.cr
  1911. except:
  1912. return simbase.air
  1913. exceptionLoggedNotify = None
  1914. if __debug__:
  1915. def exceptionLogged(append=True):
  1916. """decorator that outputs the function name and all arguments
  1917. if an exception passes back through the stack frame
  1918. if append is true, string is appended to the __str__ output of
  1919. the exception. if append is false, string is printed to the log
  1920. directly. If the output will take up many lines, it's recommended
  1921. to set append to False so that the exception stack is not hidden
  1922. by the output of this decorator.
  1923. """
  1924. try:
  1925. null = not __dev__
  1926. except:
  1927. null = not __debug__
  1928. if null:
  1929. # if we're not in __dev__, just return the function itself. This
  1930. # results in zero runtime overhead, since decorators are evaluated
  1931. # at module-load.
  1932. def nullDecorator(f):
  1933. return f
  1934. return nullDecorator
  1935. def _decoratorFunc(f, append=append):
  1936. global exceptionLoggedNotify
  1937. if exceptionLoggedNotify is None:
  1938. from direct.directnotify.DirectNotifyGlobal import directNotify
  1939. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  1940. def _exceptionLogged(*args, **kArgs):
  1941. try:
  1942. return f(*args, **kArgs)
  1943. except Exception as e:
  1944. try:
  1945. s = '%s(' % f.__name__
  1946. for arg in args:
  1947. s += '%s, ' % arg
  1948. for key, value in list(kArgs.items()):
  1949. s += '%s=%s, ' % (key, value)
  1950. if len(args) or len(kArgs):
  1951. s = s[:-2]
  1952. s += ')'
  1953. if append:
  1954. appendStr(e, '\n%s' % s)
  1955. else:
  1956. exceptionLoggedNotify.info(s)
  1957. except:
  1958. exceptionLoggedNotify.info(
  1959. '%s: ERROR IN PRINTING' % f.__name__)
  1960. raise
  1961. _exceptionLogged.__doc__ = f.__doc__
  1962. return _exceptionLogged
  1963. return _decoratorFunc
  1964. # http://en.wikipedia.org/wiki/Golden_ratio
  1965. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  1966. class GoldenRectangle:
  1967. @staticmethod
  1968. def getLongerEdge(shorter):
  1969. return shorter * GoldenRatio
  1970. @staticmethod
  1971. def getShorterEdge(longer):
  1972. return longer / GoldenRatio
  1973. def nullGen():
  1974. # generator that ends immediately
  1975. if False:
  1976. # yield that never runs but still exists, making this func a generator
  1977. yield None
  1978. def loopGen(l):
  1979. # generator that yields the items of an iterable object forever
  1980. def _gen(l):
  1981. while True:
  1982. for item in l:
  1983. yield item
  1984. gen = _gen(l)
  1985. # don't leak
  1986. _gen = None
  1987. return gen
  1988. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  1989. # iterates and finally yields a flywheel generator object
  1990. # the number of appearances for each object is controlled by passing in
  1991. # a list of counts, or a functor that returns a count when called with
  1992. # an object from the 'objects' list.
  1993. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  1994. def flywheel(index2objectAndCount):
  1995. # generator to produce a sequence whose elements appear a specific number of times
  1996. while len(index2objectAndCount):
  1997. keyList = list(index2objectAndCount.keys())
  1998. for key in keyList:
  1999. if index2objectAndCount[key][1] > 0:
  2000. yield index2objectAndCount[key][0]
  2001. index2objectAndCount[key][1] -= 1
  2002. if index2objectAndCount[key][1] <= 0:
  2003. del index2objectAndCount[key]
  2004. # if we were not given a list of counts, create it by calling countFunc
  2005. if countList is None:
  2006. countList = []
  2007. for object in objects:
  2008. yield None
  2009. countList.append(countFunc(object))
  2010. if scale is not None:
  2011. # scale the counts if we've got a scale factor
  2012. for i in xrange(len(countList)):
  2013. yield None
  2014. if countList[i] > 0:
  2015. countList[i] = max(1, int(countList[i] * scale))
  2016. # create a dict for the flywheel to use during its iteration to efficiently select
  2017. # the objects for the sequence
  2018. index2objectAndCount = {}
  2019. for i in xrange(len(countList)):
  2020. yield None
  2021. index2objectAndCount[i] = [objects[i], countList[i]]
  2022. # create the flywheel generator
  2023. yield flywheel(index2objectAndCount)
  2024. def flywheel(*args, **kArgs):
  2025. # create a flywheel generator
  2026. # see arguments and comments in flywheelGen above
  2027. # example usage:
  2028. """
  2029. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  2030. ... print i,
  2031. ...
  2032. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  2033. """
  2034. for flywheel in makeFlywheelGen(*args, **kArgs):
  2035. pass
  2036. return flywheel
  2037. if __debug__:
  2038. def quickProfile(name="unnamed"):
  2039. import pstats
  2040. def profileDecorator(f):
  2041. if(not config.GetBool("use-profiler",0)):
  2042. return f
  2043. def _profiled(*args, **kArgs):
  2044. # must do this in here because we don't have base/simbase
  2045. # at the time that PythonUtil is loaded
  2046. if(not config.GetBool("profile-debug",0)):
  2047. #dumb timings
  2048. st=globalClock.getRealTime()
  2049. f(*args,**kArgs)
  2050. s=globalClock.getRealTime()-st
  2051. print("Function %s.%s took %s seconds"%(f.__module__, f.__name__,s))
  2052. else:
  2053. import profile as prof, pstats
  2054. #detailed profile, stored in base.stats under (
  2055. if(not hasattr(base,"stats")):
  2056. base.stats={}
  2057. if(not base.stats.get(name)):
  2058. base.stats[name]=[]
  2059. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  2060. s=pstats.Stats("t.prof")
  2061. #p=hotshot.Profile("t.prof")
  2062. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  2063. #s = hotshot.stats.load("t.prof")
  2064. s.strip_dirs()
  2065. s.sort_stats("cumulative")
  2066. base.stats[name].append(s)
  2067. _profiled.__doc__ = f.__doc__
  2068. return _profiled
  2069. return profileDecorator
  2070. def getTotalAnnounceTime():
  2071. td=0
  2072. for objs in base.stats.values():
  2073. for stat in objs:
  2074. td+=getAnnounceGenerateTime(stat)
  2075. return td
  2076. def getAnnounceGenerateTime(stat):
  2077. val=0
  2078. stats=stat.stats
  2079. for i in list(stats.keys()):
  2080. if(i[2]=="announceGenerate"):
  2081. newVal=stats[i][3]
  2082. if(newVal>val):
  2083. val=newVal
  2084. return val
  2085. class MiniLog:
  2086. def __init__(self, name):
  2087. self.indent = 1
  2088. self.name = name
  2089. self.lines = []
  2090. def __str__(self):
  2091. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  2092. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  2093. def enterFunction(self, funcName, *args, **kw):
  2094. rArgs = [repr(x)+', ' for x in args] + \
  2095. [ x + ' = ' + '%s, ' % repr(y) for x,y in kw.items()]
  2096. if not rArgs:
  2097. rArgs = '()'
  2098. else:
  2099. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2100. line = '%s%s' % (funcName, rArgs)
  2101. self.appendFunctionCall(line)
  2102. self.indent += 1
  2103. return line
  2104. def exitFunction(self):
  2105. self.indent -= 1
  2106. return self.indent
  2107. def appendFunctionCall(self, line):
  2108. self.lines.append(' '*(self.indent*2) + line)
  2109. return line
  2110. def appendLine(self, line):
  2111. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  2112. return line
  2113. def flush(self):
  2114. outStr = str(self)
  2115. self.indent = 0
  2116. self.lines = []
  2117. return outStr
  2118. class MiniLogSentry:
  2119. def __init__(self, log, funcName, *args, **kw):
  2120. self.log = log
  2121. if self.log:
  2122. self.log.enterFunction(funcName, *args, **kw)
  2123. def __del__(self):
  2124. if self.log:
  2125. self.log.exitFunction()
  2126. del self.log
  2127. def logBlock(id, msg):
  2128. print('<< LOGBLOCK(%03d)' % id)
  2129. print(str(msg))
  2130. print('/LOGBLOCK(%03d) >>' % id)
  2131. class HierarchyException(Exception):
  2132. JOSWILSO = 0
  2133. def __init__(self, owner, description):
  2134. self.owner = owner
  2135. self.desc = description
  2136. def __str__(self):
  2137. return '(%s): %s' % (self.owner, self.desc)
  2138. def __repr__(self):
  2139. return 'HierarchyException(%s)' % (self.owner, )
  2140. def formatTimeCompact(seconds):
  2141. # returns string in format '1d3h22m43s'
  2142. result = ''
  2143. a = int(seconds)
  2144. seconds = a % 60
  2145. a //= 60
  2146. if a > 0:
  2147. minutes = a % 60
  2148. a //= 60
  2149. if a > 0:
  2150. hours = a % 24
  2151. a //= 24
  2152. if a > 0:
  2153. days = a
  2154. result += '%sd' % days
  2155. result += '%sh' % hours
  2156. result += '%sm' % minutes
  2157. result += '%ss' % seconds
  2158. return result
  2159. if __debug__ and __name__ == '__main__':
  2160. ftc = formatTimeCompact
  2161. assert ftc(0) == '0s'
  2162. assert ftc(1) == '1s'
  2163. assert ftc(60) == '1m0s'
  2164. assert ftc(64) == '1m4s'
  2165. assert ftc(60*60) == '1h0m0s'
  2166. assert ftc(24*60*60) == '1d0h0m0s'
  2167. assert ftc(24*60*60 + 2*60*60 + 34*60 + 12) == '1d2h34m12s'
  2168. del ftc
  2169. def formatTimeExact(seconds):
  2170. # like formatTimeCompact but leaves off '0 seconds', '0 minutes' etc. for
  2171. # times that are e.g. 1 hour, 3 days etc.
  2172. # returns string in format '1d3h22m43s'
  2173. result = ''
  2174. a = int(seconds)
  2175. seconds = a % 60
  2176. a //= 60
  2177. if a > 0:
  2178. minutes = a % 60
  2179. a //= 60
  2180. if a > 0:
  2181. hours = a % 24
  2182. a //= 24
  2183. if a > 0:
  2184. days = a
  2185. result += '%sd' % days
  2186. if hours or minutes or seconds:
  2187. result += '%sh' % hours
  2188. if minutes or seconds:
  2189. result += '%sm' % minutes
  2190. if seconds or result == '':
  2191. result += '%ss' % seconds
  2192. return result
  2193. if __debug__ and __name__ == '__main__':
  2194. fte = formatTimeExact
  2195. assert fte(0) == '0s'
  2196. assert fte(1) == '1s'
  2197. assert fte(2) == '2s'
  2198. assert fte(61) == '1m1s'
  2199. assert fte(60) == '1m'
  2200. assert fte(60*60) == '1h'
  2201. assert fte(24*60*60) == '1d'
  2202. assert fte((24*60*60) + (2 * 60)) == '1d0h2m'
  2203. del fte
  2204. class AlphabetCounter:
  2205. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  2206. def __init__(self):
  2207. self._curCounter = ['A']
  2208. def next(self):
  2209. result = ''.join([c for c in self._curCounter])
  2210. index = -1
  2211. while True:
  2212. curChar = self._curCounter[index]
  2213. if curChar == 'Z':
  2214. nextChar = 'A'
  2215. carry = True
  2216. else:
  2217. nextChar = chr(ord(self._curCounter[index])+1)
  2218. carry = False
  2219. self._curCounter[index] = nextChar
  2220. if carry:
  2221. if (-index) == len(self._curCounter):
  2222. self._curCounter = ['A',] + self._curCounter
  2223. break
  2224. else:
  2225. index -= 1
  2226. carry = False
  2227. else:
  2228. break
  2229. return result
  2230. if __debug__ and __name__ == '__main__':
  2231. def testAlphabetCounter():
  2232. tempList = []
  2233. ac = AlphabetCounter()
  2234. for i in xrange(26*3):
  2235. tempList.append(ac.next())
  2236. 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',
  2237. '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',
  2238. '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',]
  2239. ac = AlphabetCounter()
  2240. num = 26 # A-Z
  2241. num += (26*26) # AA-ZZ
  2242. num += 26 # AAZ
  2243. num += 1 # ABA
  2244. num += 2 # ABC
  2245. for i in xrange(num):
  2246. x = ac.next()
  2247. assert x == 'ABC'
  2248. testAlphabetCounter()
  2249. del testAlphabetCounter
  2250. class Default:
  2251. # represents 'use the default value'
  2252. # useful for keyword arguments to virtual methods
  2253. pass
  2254. superLogFile = None
  2255. def startSuperLog(customFunction = None):
  2256. global superLogFile
  2257. if(not superLogFile):
  2258. superLogFile = open("c:\\temp\\superLog.txt", "w")
  2259. def trace_dispatch(a,b,c):
  2260. if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0):
  2261. vars = dict(a.f_locals)
  2262. if 'self' in vars:
  2263. del vars['self']
  2264. if '__builtins__' in vars:
  2265. del vars['__builtins__']
  2266. for i in vars:
  2267. vars[i] = safeReprTypeOnFail(vars[i])
  2268. if customFunction:
  2269. superLogFile.write( "before = %s\n"%customFunction())
  2270. 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))
  2271. if customFunction:
  2272. superLogFile.write( "after = %s\n"%customFunction())
  2273. return trace_dispatch
  2274. sys.settrace(trace_dispatch)
  2275. def endSuperLog():
  2276. global superLogFile
  2277. if(superLogFile):
  2278. sys.settrace(None)
  2279. superLogFile.close()
  2280. superLogFile = None
  2281. def configIsToday(configName):
  2282. # TODO: replace usage of strptime with something else
  2283. # returns true if config string is a valid representation of today's date
  2284. today = time.localtime()
  2285. confStr = config.GetString(configName, '')
  2286. for format in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
  2287. try:
  2288. confDate = time.strptime(confStr, format)
  2289. except ValueError:
  2290. pass
  2291. else:
  2292. if (confDate.tm_year == today.tm_year and
  2293. confDate.tm_mon == today.tm_mon and
  2294. confDate.tm_mday == today.tm_mday):
  2295. return True
  2296. return False
  2297. def typeName(o):
  2298. if hasattr(o, '__class__'):
  2299. return o.__class__.__name__
  2300. else:
  2301. return o.__name__
  2302. def safeTypeName(o):
  2303. try:
  2304. return typeName(o)
  2305. except:
  2306. pass
  2307. try:
  2308. return type(o)
  2309. except:
  2310. pass
  2311. return '<failed safeTypeName()>'
  2312. def histogramDict(l):
  2313. d = {}
  2314. for e in l:
  2315. d.setdefault(e, 0)
  2316. d[e] += 1
  2317. return d
  2318. def unescapeHtmlString(s):
  2319. # converts %## to corresponding character
  2320. # replaces '+' with ' '
  2321. result = ''
  2322. i = 0
  2323. while i < len(s):
  2324. char = s[i]
  2325. if char == '+':
  2326. char = ' '
  2327. elif char == '%':
  2328. if i < (len(s)-2):
  2329. num = int(s[i+1:i+3], 16)
  2330. char = chr(num)
  2331. i += 2
  2332. i += 1
  2333. result += char
  2334. return result
  2335. class PriorityCallbacks:
  2336. """ manage a set of prioritized callbacks, and allow them to be invoked in order of priority """
  2337. def __init__(self):
  2338. self._callbacks = []
  2339. def clear(self):
  2340. del self._callbacks[:]
  2341. def add(self, callback, priority=None):
  2342. if priority is None:
  2343. priority = 0
  2344. callbacks = self._callbacks
  2345. lo = 0
  2346. hi = len(callbacks)
  2347. while lo < hi:
  2348. mid = (lo + hi) // 2
  2349. if priority < callbacks[mid][0]:
  2350. hi = mid
  2351. else:
  2352. lo = mid + 1
  2353. item = (priority, callback)
  2354. callbacks.insert(lo, item)
  2355. return item
  2356. def remove(self, item):
  2357. self._callbacks.remove(item)
  2358. def __call__(self):
  2359. for priority, callback in self._callbacks:
  2360. callback()
  2361. builtins.Functor = Functor
  2362. builtins.Stack = Stack
  2363. builtins.Queue = Queue
  2364. builtins.Enum = Enum
  2365. builtins.SerialNumGen = SerialNumGen
  2366. builtins.SerialMaskedGen = SerialMaskedGen
  2367. builtins.ScratchPad = ScratchPad
  2368. builtins.uniqueName = uniqueName
  2369. builtins.serialNum = serialNum
  2370. if __debug__:
  2371. builtins.profiled = profiled
  2372. builtins.exceptionLogged = exceptionLogged
  2373. builtins.itype = itype
  2374. builtins.appendStr = appendStr
  2375. builtins.bound = bound
  2376. builtins.clamp = clamp
  2377. builtins.lerp = lerp
  2378. builtins.makeList = makeList
  2379. builtins.makeTuple = makeTuple
  2380. if __debug__:
  2381. builtins.printStack = printStack
  2382. builtins.printReverseStack = printReverseStack
  2383. builtins.printVerboseStack = printVerboseStack
  2384. builtins.DelayedCall = DelayedCall
  2385. builtins.DelayedFunctor = DelayedFunctor
  2386. builtins.FrameDelayedCall = FrameDelayedCall
  2387. builtins.SubframeCall = SubframeCall
  2388. builtins.invertDict = invertDict
  2389. builtins.invertDictLossless = invertDictLossless
  2390. builtins.getBase = getBase
  2391. builtins.getRepository = getRepository
  2392. builtins.safeRepr = safeRepr
  2393. builtins.fastRepr = fastRepr
  2394. builtins.nullGen = nullGen
  2395. builtins.flywheel = flywheel
  2396. builtins.loopGen = loopGen
  2397. if __debug__:
  2398. builtins.StackTrace = StackTrace
  2399. builtins.report = report
  2400. builtins.pstatcollect = pstatcollect
  2401. builtins.MiniLog = MiniLog
  2402. builtins.MiniLogSentry = MiniLogSentry
  2403. builtins.logBlock = logBlock
  2404. builtins.HierarchyException = HierarchyException
  2405. builtins.deeptype = deeptype
  2406. builtins.Default = Default
  2407. builtins.configIsToday = configIsToday
  2408. builtins.typeName = typeName
  2409. builtins.safeTypeName = safeTypeName
  2410. builtins.histogramDict = histogramDict