Task.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. """ This module defines a Python-level wrapper around the C++
  2. AsyncTaskManager interface. It replaces the old full-Python
  3. implementation of the Task system. """
  4. __all__ = ['Task', 'TaskManager',
  5. 'cont', 'done', 'again', 'pickup', 'exit',
  6. 'sequence', 'loop', 'pause']
  7. from direct.directnotify.DirectNotifyGlobal import *
  8. from direct.showbase import ExceptionVarDump
  9. from direct.showbase.PythonUtil import *
  10. from direct.showbase.MessengerGlobal import messenger
  11. import signal
  12. import types
  13. import time
  14. import random
  15. import string
  16. from pandac.PandaModules import *
  17. def print_exc_plus():
  18. """
  19. Print the usual traceback information, followed by a listing of all the
  20. local variables in each frame.
  21. """
  22. import sys
  23. import traceback
  24. tb = sys.exc_info()[2]
  25. while 1:
  26. if not tb.tb_next:
  27. break
  28. tb = tb.tb_next
  29. stack = []
  30. f = tb.tb_frame
  31. while f:
  32. stack.append(f)
  33. f = f.f_back
  34. stack.reverse()
  35. traceback.print_exc()
  36. print "Locals by frame, innermost last"
  37. for frame in stack:
  38. print
  39. print "Frame %s in %s at line %s" % (frame.f_code.co_name,
  40. frame.f_code.co_filename,
  41. frame.f_lineno)
  42. for key, value in frame.f_locals.items():
  43. print "\t%20s = " % key,
  44. #We have to be careful not to cause a new error in our error
  45. #printer! Calling str() on an unknown object could cause an
  46. #error we don't want.
  47. try:
  48. print value
  49. except:
  50. print "<ERROR WHILE PRINTING VALUE>"
  51. # For historical purposes, we remap the C++-defined enumeration to
  52. # these Python names, and define them both at the module level, here,
  53. # and at the class level (below). The preferred access is via the
  54. # class level.
  55. done = AsyncTask.DSDone
  56. cont = AsyncTask.DSCont
  57. again = AsyncTask.DSAgain
  58. pickup = AsyncTask.DSPickup
  59. exit = AsyncTask.DSExit
  60. # Alias PythonTask to Task for historical purposes.
  61. Task = PythonTask
  62. # Copy the module-level enums above into the class level. This funny
  63. # syntax is necessary because it's a C++-wrapped extension type, not a
  64. # true Python class.
  65. Task.DtoolClassDict['done'] = done
  66. Task.DtoolClassDict['cont'] = cont
  67. Task.DtoolClassDict['again'] = again
  68. Task.DtoolClassDict['pickup'] = pickup
  69. Task.DtoolClassDict['exit'] = exit
  70. # Alias the AsyncTaskPause constructor as Task.pause().
  71. pause = AsyncTaskPause
  72. Task.DtoolClassDict['pause'] = staticmethod(pause)
  73. def sequence(*taskList):
  74. seq = AsyncTaskSequence('sequence')
  75. for task in taskList:
  76. seq.addTask(task)
  77. return seq
  78. Task.DtoolClassDict['sequence'] = staticmethod(sequence)
  79. def loop(*taskList):
  80. seq = AsyncTaskSequence('loop')
  81. for task in taskList:
  82. seq.addTask(task)
  83. seq.setRepeatCount(-1)
  84. return seq
  85. Task.DtoolClassDict['loop'] = staticmethod(loop)
  86. class TaskManager:
  87. notify = directNotify.newCategory("TaskManager")
  88. extendedExceptions = False
  89. MaxEpochSpeed = 1.0/30.0
  90. def __init__(self):
  91. self.mgr = AsyncTaskManager.getGlobalPtr()
  92. self.resumeFunc = None
  93. self.globalClock = self.mgr.getClock()
  94. self.stepping = False
  95. self.running = False
  96. self.destroyed = False
  97. self.fKeyboardInterrupt = False
  98. self.interruptCount = 0
  99. self._frameProfileQueue = Queue()
  100. # this will be set when it's safe to import StateVar
  101. self._profileFrames = None
  102. self._frameProfiler = None
  103. self._profileTasks = None
  104. self._taskProfiler = None
  105. self._taskProfileInfo = ScratchPad(
  106. taskId = None,
  107. profiled = False,
  108. session = None,
  109. )
  110. def finalInit(self):
  111. # This function should be called once during startup, after
  112. # most things are imported.
  113. from direct.fsm.StatePush import StateVar
  114. self._profileTasks = StateVar(False)
  115. self.setProfileTasks(ConfigVariableBool('profile-task-spikes', 0).getValue())
  116. self._profileFrames = StateVar(False)
  117. self.setProfileFrames(ConfigVariableBool('profile-frames', 0).getValue())
  118. def destroy(self):
  119. # This should be safe to call multiple times.
  120. self.notify.info("TaskManager.destroy()")
  121. self.destroyed = True
  122. self._frameProfileQueue.clear()
  123. self.mgr.cleanup()
  124. def setClock(self, clockObject):
  125. self.mgr.setClock(clockObject)
  126. self.globalClock = clockObject
  127. def invokeDefaultHandler(self, signalNumber, stackFrame):
  128. print '*** allowing mid-frame keyboard interrupt.'
  129. # Restore default interrupt handler
  130. signal.signal(signal.SIGINT, signal.default_int_handler)
  131. # and invoke it
  132. raise KeyboardInterrupt
  133. def keyboardInterruptHandler(self, signalNumber, stackFrame):
  134. self.fKeyboardInterrupt = 1
  135. self.interruptCount += 1
  136. if self.interruptCount == 1:
  137. print '* interrupt by keyboard'
  138. elif self.interruptCount == 2:
  139. print '** waiting for end of frame before interrupting...'
  140. # The user must really want to interrupt this process
  141. # Next time around invoke the default handler
  142. signal.signal(signal.SIGINT, self.invokeDefaultHandler)
  143. def hasTaskChain(self, chainName):
  144. """ Returns true if a task chain with the indicated name has
  145. already been defined, or false otherwise. Note that
  146. setupTaskChain() will implicitly define a task chain if it has
  147. not already been defined, or modify an existing one if it has,
  148. so in most cases there is no need to check this method
  149. first. """
  150. return (self.mgr.findTaskChain(chainName) != None)
  151. def setupTaskChain(self, chainName, numThreads = None, tickClock = None,
  152. threadPriority = None, frameBudget = None,
  153. frameSync = None, timeslicePriority = None):
  154. """Defines a new task chain. Each task chain executes tasks
  155. potentially in parallel with all of the other task chains (if
  156. numThreads is more than zero). When a new task is created, it
  157. may be associated with any of the task chains, by name (or you
  158. can move a task to another task chain with
  159. task.setTaskChain()). You can have any number of task chains,
  160. but each must have a unique name.
  161. numThreads is the number of threads to allocate for this task
  162. chain. If it is 1 or more, then the tasks on this task chain
  163. will execute in parallel with the tasks on other task chains.
  164. If it is greater than 1, then the tasks on this task chain may
  165. execute in parallel with themselves (within tasks of the same
  166. sort value).
  167. If tickClock is True, then this task chain will be responsible
  168. for ticking the global clock each frame (and thereby
  169. incrementing the frame counter). There should be just one
  170. task chain responsible for ticking the clock, and usually it
  171. is the default, unnamed task chain.
  172. threadPriority specifies the priority level to assign to
  173. threads on this task chain. It may be one of TPLow, TPNormal,
  174. TPHigh, or TPUrgent. This is passed to the underlying
  175. threading system to control the way the threads are scheduled.
  176. frameBudget is the maximum amount of time (in seconds) to
  177. allow this task chain to run per frame. Set it to -1 to mean
  178. no limit (the default). It's not directly related to
  179. threadPriority.
  180. frameSync is true to force the task chain to sync to the
  181. clock. When this flag is false, the default, the task chain
  182. will finish all of its tasks and then immediately start from
  183. the first task again, regardless of the clock frame. When it
  184. is true, the task chain will finish all of its tasks and then
  185. wait for the clock to tick to the next frame before resuming
  186. the first task. This only makes sense for threaded tasks
  187. chains; non-threaded task chains are automatically
  188. synchronous.
  189. timeslicePriority is False in the default mode, in which each
  190. task runs exactly once each frame, round-robin style,
  191. regardless of the task's priority value; or True to change the
  192. meaning of priority so that certain tasks are run less often,
  193. in proportion to their time used and to their priority value.
  194. See AsyncTaskManager.setTimeslicePriority() for more.
  195. """
  196. chain = self.mgr.makeTaskChain(chainName)
  197. if numThreads is not None:
  198. chain.setNumThreads(numThreads)
  199. if tickClock is not None:
  200. chain.setTickClock(tickClock)
  201. if threadPriority is not None:
  202. chain.setThreadPriority(threadPriority)
  203. if frameBudget is not None:
  204. chain.setFrameBudget(frameBudget)
  205. if frameSync is not None:
  206. chain.setFrameSync(frameSync)
  207. if timeslicePriority is not None:
  208. chain.setTimeslicePriority(timeslicePriority)
  209. def hasTaskNamed(self, taskName):
  210. """Returns true if there is at least one task, active or
  211. sleeping, with the indicated name. """
  212. return bool(self.mgr.findTask(taskName))
  213. def getTasksNamed(self, taskName):
  214. """Returns a list of all tasks, active or sleeping, with the
  215. indicated name. """
  216. return self.__makeTaskList(self.mgr.findTasks(taskName))
  217. def getTasksMatching(self, taskPattern):
  218. """Returns a list of all tasks, active or sleeping, with a
  219. name that matches the pattern, which can include standard
  220. shell globbing characters like *, ?, and []. """
  221. return self.__makeTaskList(self.mgr.findTasksMatching(GlobPattern(taskPattern)))
  222. def getAllTasks(self):
  223. """Returns list of all tasks, active and sleeping, in
  224. arbitrary order. """
  225. return self.__makeTaskList(self.mgr.getTasks())
  226. def getTasks(self):
  227. """Returns list of all active tasks in arbitrary order. """
  228. return self.__makeTaskList(self.mgr.getActiveTasks())
  229. def getDoLaters(self):
  230. """Returns list of all sleeping tasks in arbitrary order. """
  231. return self.__makeTaskList(self.mgr.getSleepingTasks())
  232. def __makeTaskList(self, taskCollection):
  233. l = []
  234. for i in range(taskCollection.getNumTasks()):
  235. l.append(taskCollection.getTask(i))
  236. return l
  237. def doMethodLater(self, delayTime, funcOrTask, name, extraArgs = None,
  238. sort = None, priority = None, taskChain = None,
  239. uponDeath = None, appendTask = False, owner = None):
  240. """Adds a task to be performed at some time in the future.
  241. This is identical to add(), except that the specified
  242. delayTime is applied to the Task object first, which means
  243. that the task will not begin executing until at least the
  244. indicated delayTime (in seconds) has elapsed.
  245. After delayTime has elapsed, the task will become active, and
  246. will run in the soonest possible frame thereafter. If you
  247. wish to specify a task that will run in the next frame, use a
  248. delayTime of 0.
  249. """
  250. if delayTime < 0:
  251. assert self.notify.warning('doMethodLater: added task: %s with negative delay: %s' % (name, delayTime))
  252. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  253. task.setDelay(delayTime)
  254. self.mgr.add(task)
  255. return task
  256. def add(self, funcOrTask, name = None, sort = None, extraArgs = None,
  257. priority = None, uponDeath = None, appendTask = False,
  258. taskChain = None, owner = None):
  259. """
  260. Add a new task to the taskMgr. The task will begin executing
  261. immediately, or next frame if its sort value has already
  262. passed this frame.
  263. The parameters are:
  264. funcOrTask - either an existing Task object (not already added
  265. to the task manager), or a callable function object. If this
  266. is a function, a new Task object will be created and returned.
  267. name - the name to assign to the Task. Required, unless you
  268. are passing in a Task object that already has a name.
  269. extraArgs - the list of arguments to pass to the task
  270. function. If this is omitted, the list is just the task
  271. object itself.
  272. appendTask - a boolean flag. If this is true, then the task
  273. object itself will be appended to the end of the extraArgs
  274. list before calling the function.
  275. sort - the sort value to assign the task. The default sort is
  276. 0. Within a particular task chain, it is guaranteed that the
  277. tasks with a lower sort value will all run before tasks with a
  278. higher sort value run.
  279. priority - the priority at which to run the task. The default
  280. priority is 0. Higher priority tasks are run sooner, and/or
  281. more often. For historical purposes, if you specify a
  282. priority without also specifying a sort, the priority value is
  283. understood to actually be a sort value. (Previously, there
  284. was no priority value, only a sort value, and it was called
  285. "priority".)
  286. uponDeath - a function to call when the task terminates,
  287. either because it has run to completion, or because it has
  288. been explicitly removed.
  289. taskChain - the name of the task chain to assign the task to.
  290. owner - an optional Python object that is declared as the
  291. "owner" of this task for maintenance purposes. The owner must
  292. have two methods: owner._addTask(self, task), which is called
  293. when the task begins, and owner._clearTask(self, task), which
  294. is called when the task terminates. This is all the owner
  295. means.
  296. The return value of add() is the new Task object that has been
  297. added, or the original Task object that was passed in.
  298. """
  299. task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
  300. self.mgr.add(task)
  301. return task
  302. def __setupTask(self, funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath):
  303. if isinstance(funcOrTask, AsyncTask):
  304. task = funcOrTask
  305. elif callable(funcOrTask):
  306. task = PythonTask(funcOrTask)
  307. else:
  308. self.notify.error(
  309. 'add: Tried to add a task that was not a Task or a func')
  310. if hasattr(task, 'setArgs'):
  311. # It will only accept arguments if it's a PythonTask.
  312. if extraArgs is None:
  313. extraArgs = []
  314. appendTask = True
  315. task.setArgs(extraArgs, appendTask)
  316. elif extraArgs is not None:
  317. self.notify.error(
  318. 'Task %s does not accept arguments.' % (repr(task)))
  319. if name is not None:
  320. assert isinstance(name, types.StringTypes), 'Name must be a string type'
  321. task.setName(name)
  322. assert task.hasName()
  323. # For historical reasons, if priority is specified but not
  324. # sort, it really means sort.
  325. if priority is not None and sort is None:
  326. task.setSort(priority)
  327. else:
  328. if priority is not None:
  329. task.setPriority(priority)
  330. if sort is not None:
  331. task.setSort(sort)
  332. if taskChain is not None:
  333. task.setTaskChain(taskChain)
  334. if owner is not None:
  335. task.setOwner(owner)
  336. if uponDeath is not None:
  337. task.setUponDeath(uponDeath)
  338. return task
  339. def remove(self, taskOrName):
  340. """Removes a task from the task manager. The task is stopped,
  341. almost as if it had returned task.done. (But if the task is
  342. currently executing, it will finish out its current frame
  343. before being removed.) You may specify either an explicit
  344. Task object, or the name of a task. If you specify a name,
  345. all tasks with the indicated name are removed. Returns the
  346. number of tasks removed. """
  347. if isinstance(taskOrName, types.StringTypes):
  348. tasks = self.mgr.findTasks(taskOrName)
  349. return self.mgr.remove(tasks)
  350. elif isinstance(taskOrName, AsyncTask):
  351. return self.mgr.remove(taskOrName)
  352. elif isinstance(taskOrName, types.ListType):
  353. for task in taskOrName:
  354. self.remove(task)
  355. else:
  356. self.notify.error('remove takes a string or a Task')
  357. def removeTasksMatching(self, taskPattern):
  358. """Removes all tasks whose names match the pattern, which can
  359. include standard shell globbing characters like *, ?, and [].
  360. See also remove().
  361. Returns the number of tasks removed.
  362. """
  363. tasks = self.mgr.findTasksMatching(GlobPattern(taskPattern))
  364. return self.mgr.remove(tasks)
  365. def step(self):
  366. """Invokes the task manager for one frame, and then returns.
  367. Normally, this executes each task exactly once, though task
  368. chains that are in sub-threads or that have frame budgets
  369. might execute their tasks differently. """
  370. # Replace keyboard interrupt handler during task list processing
  371. # so we catch the keyboard interrupt but don't handle it until
  372. # after task list processing is complete.
  373. self.fKeyboardInterrupt = 0
  374. self.interruptCount = 0
  375. signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
  376. startFrameTime = self.globalClock.getRealTime()
  377. self.mgr.poll()
  378. # This is the spot for an internal yield function
  379. nextTaskTime = self.mgr.getNextWakeTime()
  380. self.doYield(startFrameTime, nextTaskTime)
  381. # Restore default interrupt handler
  382. signal.signal(signal.SIGINT, signal.default_int_handler)
  383. if self.fKeyboardInterrupt:
  384. raise KeyboardInterrupt
  385. def run(self):
  386. """Starts the task manager running. Does not return until an
  387. exception is encountered (including KeyboardInterrupt). """
  388. # Set the clock to have last frame's time in case we were
  389. # Paused at the prompt for a long time
  390. t = self.globalClock.getFrameTime()
  391. timeDelta = t - self.globalClock.getRealTime()
  392. self.globalClock.setRealTime(t)
  393. messenger.send("resetClock", [timeDelta])
  394. if self.resumeFunc != None:
  395. self.resumeFunc()
  396. if self.stepping:
  397. self.step()
  398. else:
  399. self.running = True
  400. while self.running:
  401. try:
  402. if len(self._frameProfileQueue):
  403. numFrames, session, callback = self._frameProfileQueue.pop()
  404. def _profileFunc(numFrames=numFrames):
  405. self._doProfiledFrames(numFrames)
  406. session.setFunc(_profileFunc)
  407. session.run()
  408. _profileFunc = None
  409. if callback:
  410. callback()
  411. session.release()
  412. else:
  413. self.step()
  414. except KeyboardInterrupt:
  415. self.stop()
  416. except IOError, ioError:
  417. code, message = self._unpackIOError(ioError)
  418. # Since upgrading to Python 2.4.1, pausing the execution
  419. # often gives this IOError during the sleep function:
  420. # IOError: [Errno 4] Interrupted function call
  421. # So, let's just handle that specific exception and stop.
  422. # All other IOErrors should still get raised.
  423. # Only problem: legit IOError 4s will be obfuscated.
  424. if code == 4:
  425. self.stop()
  426. else:
  427. raise
  428. except Exception, e:
  429. if self.extendedExceptions:
  430. self.stop()
  431. print_exc_plus()
  432. else:
  433. if (ExceptionVarDump.wantVariableDump and
  434. ExceptionVarDump.dumpOnExceptionInit):
  435. ExceptionVarDump._varDump__print(e)
  436. raise
  437. except:
  438. if self.extendedExceptions:
  439. self.stop()
  440. print_exc_plus()
  441. else:
  442. raise
  443. self.mgr.stopThreads()
  444. def _unpackIOError(self, ioError):
  445. # IOError unpack from http://www.python.org/doc/essays/stdexceptions/
  446. # this needs to be in its own method, exceptions that occur inside
  447. # a nested try block are not caught by the inner try block's except
  448. try:
  449. (code, message) = ioError
  450. except:
  451. code = 0
  452. message = ioError
  453. return code, message
  454. def stop(self):
  455. # Set a flag so we will stop before beginning next frame
  456. self.running = False
  457. def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
  458. if not isinstance(task, PythonTask):
  459. return 0
  460. method = task.getFunction()
  461. if (type(method) == types.MethodType):
  462. function = method.im_func
  463. else:
  464. function = method
  465. if (function == oldMethod):
  466. import new
  467. newMethod = new.instancemethod(newFunction,
  468. method.im_self,
  469. method.im_class)
  470. task.setFunction(newMethod)
  471. # Found a match
  472. return 1
  473. return 0
  474. def replaceMethod(self, oldMethod, newFunction):
  475. numFound = 0
  476. for task in self.getAllTasks():
  477. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  478. return numFound
  479. def popupControls(self):
  480. from direct.tkpanels import TaskManagerPanel
  481. return TaskManagerPanel.TaskManagerPanel(self)
  482. def getProfileSession(self, name=None):
  483. # call to get a profile session that you can modify before passing to profileFrames()
  484. if name is None:
  485. name = 'taskMgrFrameProfile'
  486. # Defer this import until we need it: some Python
  487. # distributions don't provide the profile and pstats modules.
  488. from direct.showbase.ProfileSession import ProfileSession
  489. return ProfileSession(name)
  490. def profileFrames(self, num=None, session=None, callback=None):
  491. if num is None:
  492. num = 1
  493. if session is None:
  494. session = self.getProfileSession()
  495. # make sure the profile session doesn't get destroyed before we're done with it
  496. session.acquire()
  497. self._frameProfileQueue.push((num, session, callback))
  498. def _doProfiledFrames(self, numFrames):
  499. for i in xrange(numFrames):
  500. result = self.step()
  501. return result
  502. def getProfileFrames(self):
  503. return self._profileFrames.get()
  504. def getProfileFramesSV(self):
  505. return self._profileFrames
  506. def setProfileFrames(self, profileFrames):
  507. self._profileFrames.set(profileFrames)
  508. if (not self._frameProfiler) and profileFrames:
  509. # import here due to import dependencies
  510. from direct.task.FrameProfiler import FrameProfiler
  511. self._frameProfiler = FrameProfiler()
  512. def getProfileTasks(self):
  513. return self._profileTasks.get()
  514. def getProfileTasksSV(self):
  515. return self._profileTasks
  516. def setProfileTasks(self, profileTasks):
  517. self._profileTasks.set(profileTasks)
  518. if (not self._taskProfiler) and profileTasks:
  519. # import here due to import dependencies
  520. from direct.task.TaskProfiler import TaskProfiler
  521. self._taskProfiler = TaskProfiler()
  522. def logTaskProfiles(self, name=None):
  523. if self._taskProfiler:
  524. self._taskProfiler.logProfiles(name)
  525. def flushTaskProfiles(self, name=None):
  526. if self._taskProfiler:
  527. self._taskProfiler.flush(name)
  528. def _setProfileTask(self, task):
  529. if self._taskProfileInfo.session:
  530. self._taskProfileInfo.session.release()
  531. self._taskProfileInfo.session = None
  532. self._taskProfileInfo = ScratchPad(
  533. taskFunc = task.getFunction(),
  534. taskArgs = task.getArgs(),
  535. task = task,
  536. profiled = False,
  537. session = None,
  538. )
  539. # Temporarily replace the task's own function with our
  540. # _profileTask method.
  541. task.setFunction(self._profileTask)
  542. task.setArgs([self._taskProfileInfo], True)
  543. def _profileTask(self, profileInfo, task):
  544. # This is called instead of the task function when we have
  545. # decided to profile a task.
  546. assert profileInfo.task == task
  547. # don't profile the same task twice in a row
  548. assert not profileInfo.profiled
  549. # Restore the task's proper function for next time.
  550. appendTask = False
  551. taskArgs = profileInfo.taskArgs
  552. if taskArgs and taskArgs[-1] == task:
  553. appendTask = True
  554. taskArgs = taskArgs[:-1]
  555. task.setArgs(taskArgs, appendTask)
  556. task.setFunction(profileInfo.taskFunc)
  557. # Defer this import until we need it: some Python
  558. # distributions don't provide the profile and pstats modules.
  559. from direct.showbase.ProfileSession import ProfileSession
  560. profileSession = ProfileSession('profiled-task-%s' % task.getName(),
  561. Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
  562. ret = profileSession.run()
  563. # set these values *after* profiling in case we're profiling the TaskProfiler
  564. profileInfo.session = profileSession
  565. profileInfo.profiled = True
  566. return ret
  567. def _hasProfiledDesignatedTask(self):
  568. # have we run a profile of the designated task yet?
  569. return self._taskProfileInfo.profiled
  570. def _getLastTaskProfileSession(self):
  571. return self._taskProfileInfo.session
  572. def _getRandomTask(self):
  573. # Figure out when the next frame is likely to expire, so we
  574. # won't grab any tasks that are sleeping for a long time.
  575. now = globalClock.getFrameTime()
  576. avgFrameRate = globalClock.getAverageFrameRate()
  577. if avgFrameRate < .00001:
  578. avgFrameDur = 0.
  579. else:
  580. avgFrameDur = (1. / globalClock.getAverageFrameRate())
  581. next = now + avgFrameDur
  582. # Now grab a task at random, until we find one that we like.
  583. tasks = self.mgr.getTasks()
  584. i = random.randrange(tasks.getNumTasks())
  585. task = tasks.getTask(i)
  586. while not isinstance(task, PythonTask) or \
  587. task.getWakeTime() > next:
  588. tasks.removeTask(i)
  589. i = random.randrange(tasks.getNumTasks())
  590. task = tasks.getTask(i)
  591. return task
  592. def __repr__(self):
  593. return str(self.mgr)
  594. # In the event we want to do frame time managment, this is the
  595. # function to replace or overload.
  596. def doYield(self, frameStartTime, nextScheduledTaskTime):
  597. pass
  598. """
  599. def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
  600. minFinTime = frameStartTime + self.MaxEpochSpeed
  601. if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
  602. print ' Adjusting Time'
  603. minFinTime = nextScheduledTaskTime
  604. delta = minFinTime - self.globalClock.getRealTime()
  605. while(delta > 0.002):
  606. print ' sleep %s'% (delta)
  607. time.sleep(delta)
  608. delta = minFinTime - self.globalClock.getRealTime()
  609. """
  610. if __debug__:
  611. # to catch memory leaks during the tests at the bottom of the file
  612. def _startTrackingMemLeaks(self):
  613. pass
  614. def _stopTrackingMemLeaks(self):
  615. pass
  616. def _checkMemLeaks(self):
  617. pass
  618. def _runTests(self):
  619. if __debug__:
  620. tm = TaskManager()
  621. tm.setClock(ClockObject())
  622. tm.setupTaskChain("default", tickClock = True)
  623. # check for memory leaks after every test
  624. tm._startTrackingMemLeaks()
  625. tm._checkMemLeaks()
  626. # run-once task
  627. l = []
  628. def _testDone(task, l=l):
  629. l.append(None)
  630. return task.done
  631. tm.add(_testDone, 'testDone')
  632. tm.step()
  633. assert len(l) == 1
  634. tm.step()
  635. assert len(l) == 1
  636. _testDone = None
  637. tm._checkMemLeaks()
  638. # remove by name
  639. def _testRemoveByName(task):
  640. return task.done
  641. tm.add(_testRemoveByName, 'testRemoveByName')
  642. assert tm.remove('testRemoveByName') == 1
  643. assert tm.remove('testRemoveByName') == 0
  644. _testRemoveByName = None
  645. tm._checkMemLeaks()
  646. # duplicate named tasks
  647. def _testDupNamedTasks(task):
  648. return task.done
  649. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  650. tm.add(_testDupNamedTasks, 'testDupNamedTasks')
  651. assert tm.remove('testRemoveByName') == 0
  652. _testDupNamedTasks = None
  653. tm._checkMemLeaks()
  654. # continued task
  655. l = []
  656. def _testCont(task, l = l):
  657. l.append(None)
  658. return task.cont
  659. tm.add(_testCont, 'testCont')
  660. tm.step()
  661. assert len(l) == 1
  662. tm.step()
  663. assert len(l) == 2
  664. tm.remove('testCont')
  665. _testCont = None
  666. tm._checkMemLeaks()
  667. # continue until done task
  668. l = []
  669. def _testContDone(task, l = l):
  670. l.append(None)
  671. if len(l) >= 2:
  672. return task.done
  673. else:
  674. return task.cont
  675. tm.add(_testContDone, 'testContDone')
  676. tm.step()
  677. assert len(l) == 1
  678. tm.step()
  679. assert len(l) == 2
  680. tm.step()
  681. assert len(l) == 2
  682. assert not tm.hasTaskNamed('testContDone')
  683. _testContDone = None
  684. tm._checkMemLeaks()
  685. # hasTaskNamed
  686. def _testHasTaskNamed(task):
  687. return task.done
  688. tm.add(_testHasTaskNamed, 'testHasTaskNamed')
  689. assert tm.hasTaskNamed('testHasTaskNamed')
  690. tm.step()
  691. assert not tm.hasTaskNamed('testHasTaskNamed')
  692. _testHasTaskNamed = None
  693. tm._checkMemLeaks()
  694. # task sort
  695. l = []
  696. def _testPri1(task, l = l):
  697. l.append(1)
  698. return task.cont
  699. def _testPri2(task, l = l):
  700. l.append(2)
  701. return task.cont
  702. tm.add(_testPri1, 'testPri1', sort = 1)
  703. tm.add(_testPri2, 'testPri2', sort = 2)
  704. tm.step()
  705. assert len(l) == 2
  706. assert l == [1, 2,]
  707. tm.step()
  708. assert len(l) == 4
  709. assert l == [1, 2, 1, 2,]
  710. tm.remove('testPri1')
  711. tm.remove('testPri2')
  712. _testPri1 = None
  713. _testPri2 = None
  714. tm._checkMemLeaks()
  715. # task extraArgs
  716. l = []
  717. def _testExtraArgs(arg1, arg2, l=l):
  718. l.extend([arg1, arg2,])
  719. return done
  720. tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
  721. tm.step()
  722. assert len(l) == 2
  723. assert l == [4, 5,]
  724. _testExtraArgs = None
  725. tm._checkMemLeaks()
  726. # task appendTask
  727. l = []
  728. def _testAppendTask(arg1, arg2, task, l=l):
  729. l.extend([arg1, arg2,])
  730. return task.done
  731. tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
  732. tm.step()
  733. assert len(l) == 2
  734. assert l == [4, 5,]
  735. _testAppendTask = None
  736. tm._checkMemLeaks()
  737. # task uponDeath
  738. l = []
  739. def _uponDeathFunc(task, l=l):
  740. l.append(task.name)
  741. def _testUponDeath(task):
  742. return done
  743. tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
  744. tm.step()
  745. assert len(l) == 1
  746. assert l == ['testUponDeath']
  747. _testUponDeath = None
  748. _uponDeathFunc = None
  749. tm._checkMemLeaks()
  750. # task owner
  751. class _TaskOwner:
  752. def _addTask(self, task):
  753. self.addedTaskName = task.name
  754. def _clearTask(self, task):
  755. self.clearedTaskName = task.name
  756. to = _TaskOwner()
  757. l = []
  758. def _testOwner(task):
  759. return done
  760. tm.add(_testOwner, 'testOwner', owner=to)
  761. tm.step()
  762. assert getattr(to, 'addedTaskName', None) == 'testOwner'
  763. assert getattr(to, 'clearedTaskName', None) == 'testOwner'
  764. _testOwner = None
  765. del to
  766. _TaskOwner = None
  767. tm._checkMemLeaks()
  768. doLaterTests = [0,]
  769. # doLater
  770. l = []
  771. def _testDoLater1(task, l=l):
  772. l.append(1)
  773. def _testDoLater2(task, l=l):
  774. l.append(2)
  775. def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
  776. if task.time > .03:
  777. assert l == [1, 2,]
  778. doLaterTests[0] -= 1
  779. return task.done
  780. return task.cont
  781. tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
  782. tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
  783. doLaterTests[0] += 1
  784. # make sure we run this task after the doLaters if they all occur on the same frame
  785. tm.add(_monitorDoLater, 'monitorDoLater', sort=10)
  786. _testDoLater1 = None
  787. _testDoLater2 = None
  788. _monitorDoLater = None
  789. # don't check until all the doLaters are finished
  790. #tm._checkMemLeaks()
  791. # doLater sort
  792. l = []
  793. def _testDoLaterPri1(task, l=l):
  794. l.append(1)
  795. def _testDoLaterPri2(task, l=l):
  796. l.append(2)
  797. def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
  798. if task.time > .02:
  799. assert l == [1, 2,]
  800. doLaterTests[0] -= 1
  801. return task.done
  802. return task.cont
  803. tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', sort=1)
  804. tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', sort=2)
  805. doLaterTests[0] += 1
  806. # make sure we run this task after the doLaters if they all occur on the same frame
  807. tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', sort=10)
  808. _testDoLaterPri1 = None
  809. _testDoLaterPri2 = None
  810. _monitorDoLaterPri = None
  811. # don't check until all the doLaters are finished
  812. #tm._checkMemLeaks()
  813. # doLater extraArgs
  814. l = []
  815. def _testDoLaterExtraArgs(arg1, l=l):
  816. l.append(arg1)
  817. def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
  818. if task.time > .02:
  819. assert l == [3,]
  820. doLaterTests[0] -= 1
  821. return task.done
  822. return task.cont
  823. tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
  824. doLaterTests[0] += 1
  825. # make sure we run this task after the doLaters if they all occur on the same frame
  826. tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', sort=10)
  827. _testDoLaterExtraArgs = None
  828. _monitorDoLaterExtraArgs = None
  829. # don't check until all the doLaters are finished
  830. #tm._checkMemLeaks()
  831. # doLater appendTask
  832. l = []
  833. def _testDoLaterAppendTask(arg1, task, l=l):
  834. assert task.name == 'testDoLaterAppendTask'
  835. l.append(arg1)
  836. def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
  837. if task.time > .02:
  838. assert l == [4,]
  839. doLaterTests[0] -= 1
  840. return task.done
  841. return task.cont
  842. tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
  843. extraArgs=[4,], appendTask=True)
  844. doLaterTests[0] += 1
  845. # make sure we run this task after the doLaters if they all occur on the same frame
  846. tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', sort=10)
  847. _testDoLaterAppendTask = None
  848. _monitorDoLaterAppendTask = None
  849. # don't check until all the doLaters are finished
  850. #tm._checkMemLeaks()
  851. # doLater uponDeath
  852. l = []
  853. def _testUponDeathFunc(task, l=l):
  854. assert task.name == 'testDoLaterUponDeath'
  855. l.append(10)
  856. def _testDoLaterUponDeath(arg1, l=l):
  857. return done
  858. def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
  859. if task.time > .02:
  860. assert l == [10,]
  861. doLaterTests[0] -= 1
  862. return task.done
  863. return task.cont
  864. tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
  865. uponDeath=_testUponDeathFunc)
  866. doLaterTests[0] += 1
  867. # make sure we run this task after the doLaters if they all occur on the same frame
  868. tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', sort=10)
  869. _testUponDeathFunc = None
  870. _testDoLaterUponDeath = None
  871. _monitorDoLaterUponDeath = None
  872. # don't check until all the doLaters are finished
  873. #tm._checkMemLeaks()
  874. # doLater owner
  875. class _DoLaterOwner:
  876. def _addTask(self, task):
  877. self.addedTaskName = task.name
  878. def _clearTask(self, task):
  879. self.clearedTaskName = task.name
  880. doLaterOwner = _DoLaterOwner()
  881. l = []
  882. def _testDoLaterOwner(l=l):
  883. pass
  884. def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
  885. doLaterTests=doLaterTests):
  886. if task.time > .02:
  887. assert getattr(doLaterOwner, 'addedTaskName', None) == 'testDoLaterOwner'
  888. assert getattr(doLaterOwner, 'clearedTaskName', None) == 'testDoLaterOwner'
  889. doLaterTests[0] -= 1
  890. return task.done
  891. return task.cont
  892. tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
  893. owner=doLaterOwner)
  894. doLaterTests[0] += 1
  895. # make sure we run this task after the doLaters if they all occur on the same frame
  896. tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', sort=10)
  897. _testDoLaterOwner = None
  898. _monitorDoLaterOwner = None
  899. del doLaterOwner
  900. _DoLaterOwner = None
  901. # don't check until all the doLaters are finished
  902. #tm._checkMemLeaks()
  903. # run the doLater tests
  904. while doLaterTests[0] > 0:
  905. tm.step()
  906. del doLaterTests
  907. tm._checkMemLeaks()
  908. # getTasks
  909. def _testGetTasks(task):
  910. return task.cont
  911. # No doLaterProcessor in the new world.
  912. assert len(tm.getTasks()) == 0
  913. tm.add(_testGetTasks, 'testGetTasks1')
  914. assert len(tm.getTasks()) == 1
  915. assert (tm.getTasks()[0].name == 'testGetTasks1' or
  916. tm.getTasks()[1].name == 'testGetTasks1')
  917. tm.add(_testGetTasks, 'testGetTasks2')
  918. tm.add(_testGetTasks, 'testGetTasks3')
  919. assert len(tm.getTasks()) == 3
  920. tm.remove('testGetTasks2')
  921. assert len(tm.getTasks()) == 2
  922. tm.remove('testGetTasks1')
  923. tm.remove('testGetTasks3')
  924. assert len(tm.getTasks()) == 0
  925. _testGetTasks = None
  926. tm._checkMemLeaks()
  927. # getDoLaters
  928. def _testGetDoLaters():
  929. pass
  930. assert len(tm.getDoLaters()) == 0
  931. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
  932. assert len(tm.getDoLaters()) == 1
  933. assert tm.getDoLaters()[0].name == 'testDoLater1'
  934. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
  935. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
  936. assert len(tm.getDoLaters()) == 3
  937. tm.remove('testDoLater2')
  938. assert len(tm.getDoLaters()) == 2
  939. tm.remove('testDoLater1')
  940. tm.remove('testDoLater3')
  941. assert len(tm.getDoLaters()) == 0
  942. _testGetDoLaters = None
  943. tm._checkMemLeaks()
  944. # duplicate named doLaters removed via taskMgr.remove
  945. def _testDupNameDoLaters():
  946. pass
  947. # the doLaterProcessor is always running
  948. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  949. tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
  950. assert len(tm.getDoLaters()) == 2
  951. tm.remove('testDupNameDoLater')
  952. assert len(tm.getDoLaters()) == 0
  953. _testDupNameDoLaters = None
  954. tm._checkMemLeaks()
  955. # duplicate named doLaters removed via remove()
  956. def _testDupNameDoLatersRemove():
  957. pass
  958. # the doLaterProcessor is always running
  959. dl1 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  960. dl2 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
  961. assert len(tm.getDoLaters()) == 2
  962. dl2.remove()
  963. assert len(tm.getDoLaters()) == 1
  964. dl1.remove()
  965. assert len(tm.getDoLaters()) == 0
  966. _testDupNameDoLatersRemove = None
  967. # nameDict etc. isn't cleared out right away with task.remove()
  968. tm._checkMemLeaks()
  969. # getTasksNamed
  970. def _testGetTasksNamed(task):
  971. return task.cont
  972. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  973. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  974. assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
  975. assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
  976. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  977. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  978. assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
  979. tm.remove('testGetTasksNamed')
  980. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  981. _testGetTasksNamed = None
  982. tm._checkMemLeaks()
  983. # removeTasksMatching
  984. def _testRemoveTasksMatching(task):
  985. return task.cont
  986. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
  987. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
  988. tm.removeTasksMatching('testRemoveTasksMatching')
  989. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
  990. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
  991. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
  992. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
  993. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
  994. tm.removeTasksMatching('testRemoveTasksMatching*')
  995. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
  996. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
  997. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
  998. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
  999. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
  1000. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
  1001. tm.removeTasksMatching('testRemoveTasksMatching?a')
  1002. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
  1003. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
  1004. _testRemoveTasksMatching = None
  1005. tm._checkMemLeaks()
  1006. # create Task object and add to mgr
  1007. l = []
  1008. def _testTaskObj(task, l=l):
  1009. l.append(None)
  1010. return task.cont
  1011. t = Task(_testTaskObj)
  1012. tm.add(t, 'testTaskObj')
  1013. tm.step()
  1014. assert len(l) == 1
  1015. tm.step()
  1016. assert len(l) == 2
  1017. tm.remove('testTaskObj')
  1018. tm.step()
  1019. assert len(l) == 2
  1020. _testTaskObj = None
  1021. tm._checkMemLeaks()
  1022. # remove Task via task.remove()
  1023. l = []
  1024. def _testTaskObjRemove(task, l=l):
  1025. l.append(None)
  1026. return task.cont
  1027. t = Task(_testTaskObjRemove)
  1028. tm.add(t, 'testTaskObjRemove')
  1029. tm.step()
  1030. assert len(l) == 1
  1031. tm.step()
  1032. assert len(l) == 2
  1033. t.remove()
  1034. tm.step()
  1035. assert len(l) == 2
  1036. del t
  1037. _testTaskObjRemove = None
  1038. tm._checkMemLeaks()
  1039. """
  1040. # this test fails, and it's not clear what the correct behavior should be.
  1041. # sort passed to Task.__init__ is always overridden by taskMgr.add()
  1042. # even if no sort is specified, and calling Task.setSort() has no
  1043. # effect on the taskMgr's behavior.
  1044. # set/get Task sort
  1045. l = []
  1046. def _testTaskObjSort(arg, task, l=l):
  1047. l.append(arg)
  1048. return task.cont
  1049. t1 = Task(_testTaskObjSort, sort=1)
  1050. t2 = Task(_testTaskObjSort, sort=2)
  1051. tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True)
  1052. tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True)
  1053. tm.step()
  1054. assert len(l) == 2
  1055. assert l == ['a', 'b']
  1056. assert t1.getSort() == 1
  1057. assert t2.getSort() == 2
  1058. t1.setSort(3)
  1059. assert t1.getSort() == 3
  1060. tm.step()
  1061. assert len(l) == 4
  1062. assert l == ['a', 'b', 'b', 'a',]
  1063. t1.remove()
  1064. t2.remove()
  1065. tm.step()
  1066. assert len(l) == 4
  1067. del t1
  1068. del t2
  1069. _testTaskObjSort = None
  1070. tm._checkMemLeaks()
  1071. """
  1072. del l
  1073. tm.destroy()
  1074. del tm
  1075. if __debug__:
  1076. def checkLeak():
  1077. import sys
  1078. import gc
  1079. gc.enable()
  1080. from direct.showbase.DirectObject import DirectObject
  1081. class TestClass(DirectObject):
  1082. def doTask(self, task):
  1083. return task.done
  1084. obj = TestClass()
  1085. startRefCount = sys.getrefcount(obj)
  1086. print 'sys.getrefcount(obj): %s' % sys.getrefcount(obj)
  1087. print '** addTask'
  1088. t = obj.addTask(obj.doTask, 'test')
  1089. print 'sys.getrefcount(obj): %s' % sys.getrefcount(obj)
  1090. print 'task.getRefCount(): %s' % t.getRefCount()
  1091. print '** removeTask'
  1092. obj.removeTask('test')
  1093. print 'sys.getrefcount(obj): %s' % sys.getrefcount(obj)
  1094. print 'task.getRefCount(): %s' % t.getRefCount()
  1095. print '** step'
  1096. taskMgr.step()
  1097. taskMgr.step()
  1098. taskMgr.step()
  1099. print 'sys.getrefcount(obj): %s' % sys.getrefcount(obj)
  1100. print 'task.getRefCount(): %s' % t.getRefCount()
  1101. print '** task release'
  1102. t = None
  1103. print 'sys.getrefcount(obj): %s' % sys.getrefcount(obj)
  1104. assert sys.getrefcount(obj) == startRefCount