Task.py 49 KB

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