Task.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. """Undocumented Module"""
  2. __all__ = ['Task', 'TaskPriorityList', 'TaskManager']
  3. # This module may not import pandac.PandaModules, since it is imported
  4. # by the Toontown Launcher before the complete PandaModules have been
  5. # downloaded. Instead, it imports only libpandaexpressModules, the
  6. # subset of PandaModules that we know is available immediately.
  7. # Methods that require more advanced C++ methods may import the
  8. # appropriate files within their own scope.
  9. from pandac.libpandaexpressModules import *
  10. from direct.directnotify.DirectNotifyGlobal import *
  11. from direct.showbase.PythonUtil import *
  12. from direct.showbase.MessengerGlobal import *
  13. import time
  14. import fnmatch
  15. import string
  16. import signal
  17. try:
  18. Dtool_PreloadDLL("libp3heapq")
  19. from libp3heapq import heappush, heappop, heapify
  20. except:
  21. Dtool_PreloadDLL("libheapq")
  22. from libheapq import heappush, heappop, heapify
  23. import types
  24. if __debug__:
  25. # For pstats
  26. from pandac.PandaModules import PStatCollector
  27. def print_exc_plus():
  28. """
  29. Print the usual traceback information, followed by a listing of all the
  30. local variables in each frame.
  31. """
  32. import sys
  33. import traceback
  34. tb = sys.exc_info()[2]
  35. while 1:
  36. if not tb.tb_next:
  37. break
  38. tb = tb.tb_next
  39. stack = []
  40. f = tb.tb_frame
  41. while f:
  42. stack.append(f)
  43. f = f.f_back
  44. stack.reverse()
  45. traceback.print_exc()
  46. print "Locals by frame, innermost last"
  47. for frame in stack:
  48. print
  49. print "Frame %s in %s at line %s" % (frame.f_code.co_name,
  50. frame.f_code.co_filename,
  51. frame.f_lineno)
  52. for key, value in frame.f_locals.items():
  53. print "\t%20s = " % key,
  54. #We have to be careful not to cause a new error in our error
  55. #printer! Calling str() on an unknown object could cause an
  56. #error we don't want.
  57. try:
  58. print value
  59. except:
  60. print "<ERROR WHILE PRINTING VALUE>"
  61. class Task:
  62. # This enum is a copy of the one at the top-level.
  63. exit = -1
  64. done = 0
  65. cont = 1
  66. again = 2
  67. count = 0
  68. def __init__(self, callback, priority = 0):
  69. try:
  70. config
  71. except:
  72. pass
  73. else:
  74. if config.GetBool('record-task-creation-stack', 0):
  75. self.debugInitTraceback = StackTrace("Task "+str(callback), 1, 10)
  76. # Unique ID for each task
  77. self.id = Task.count
  78. Task.count += 1
  79. #set to have the task managed
  80. self.owner = None
  81. self.__call__ = callback
  82. self._priority = priority
  83. self._removed = 0
  84. self.dt = 0.0
  85. if TaskManager.taskTimerVerbose:
  86. self.avgDt = 0.0
  87. self.maxDt = 0.0
  88. self.runningTotal = 0.0
  89. self.pstats = None
  90. self.pstatCollector = None
  91. self.extraArgs = []
  92. # Used for doLaters
  93. self.wakeTime = 0.0
  94. # for repeating doLaters
  95. self.delayTime = 0.0
  96. self.time = 0.0
  97. # # Used for putting into the doLaterList
  98. # # the heapq calls __cmp__ via the rich compare function
  99. # def __cmp__(self, other):
  100. # if isinstance(other, Task):
  101. # if self.wakeTime < other.wakeTime:
  102. # return -1
  103. # elif self.wakeTime > other.wakeTime:
  104. # return 1
  105. # # If the wakeTimes happen to be the same, just
  106. # # sort them based on id
  107. # else:
  108. # return cmp(id(self), id(other))
  109. # # This is important for people doing a (task != None) and such.
  110. # else:
  111. # return cmp(id(self), id(other))
  112. # # According to the Python manual (3.3.1), if you define a cmp operator
  113. # # you should also define a hash operator or your objects will not be
  114. # # usable in dictionaries. Since no two task objects are unique, we can
  115. # # just return the unique id.
  116. # def __hash__(self):
  117. # return self.id
  118. def remove(self):
  119. if not self._removed:
  120. if(self.owner):
  121. self.owner._clearTask(self)
  122. self._removed = 1
  123. # Remove any refs to real objects
  124. # In case we hang around the doLaterList for a while
  125. del self.__call__
  126. del self.extraArgs
  127. if TaskManager.taskTimerVerbose and self.pstatCollector:
  128. self.pstatCollector.subLevelNow(1)
  129. def isRemoved(self):
  130. return self._removed
  131. def getPriority(self):
  132. return self._priority
  133. def setPriority(self, pri):
  134. self._priority = pri
  135. def setStartTimeFrame(self, startTime, startFrame):
  136. self.starttime = startTime
  137. self.startframe = startFrame
  138. def setCurrentTimeFrame(self, currentTime, currentFrame):
  139. # Calculate and store this task's time (relative to when it started)
  140. self.time = currentTime - self.starttime
  141. self.frame = currentFrame - self.startframe
  142. def setupPStats(self):
  143. if __debug__ and TaskManager.taskTimerVerbose and not self.pstats:
  144. # Get the PStats name for the task. By convention,
  145. # this is everything until the first hyphen; the part
  146. # of the task name following the hyphen is generally
  147. # used to differentiate particular tasks that do the
  148. # same thing to different objects.
  149. name = self.name
  150. hyphen = name.find('-')
  151. if hyphen >= 0:
  152. name = name[0:hyphen]
  153. self.pstats = PStatCollector("App:Show code:" + name)
  154. if self.wakeTime or self.delayTime:
  155. self.pstatCollector = PStatCollector("Tasks:doLaters:" + name)
  156. else:
  157. self.pstatCollector = PStatCollector("Tasks:" + name)
  158. self.pstatCollector.addLevelNow(1)
  159. def finishTask(self, verbose):
  160. if hasattr(self, "uponDeath"):
  161. self.uponDeath(self)
  162. if verbose:
  163. # We regret to announce...
  164. messenger.send('TaskManager-removeTask', sentArgs = [self, self.name])
  165. del self.uponDeath
  166. def __repr__(self):
  167. if hasattr(self, 'name'):
  168. return ('Task id: %s, name %s' % (self.id, self.name))
  169. else:
  170. return ('Task id: %s, no name' % (self.id))
  171. def pause(delayTime):
  172. def func(self):
  173. if (self.time < self.delayTime):
  174. return cont
  175. else:
  176. return done
  177. task = Task(func)
  178. task.name = 'pause'
  179. task.delayTime = delayTime
  180. return task
  181. Task.pause = staticmethod(pause)
  182. def sequence(*taskList):
  183. return make_sequence(taskList)
  184. Task.sequence = staticmethod(sequence)
  185. def make_sequence(taskList):
  186. def func(self):
  187. frameFinished = 0
  188. taskDoneStatus = -1
  189. while not frameFinished:
  190. task = self.taskList[self.index]
  191. # If this is a new task, set its start time and frame
  192. if self.index > self.prevIndex:
  193. task.setStartTimeFrame(self.time, self.frame)
  194. self.prevIndex = self.index
  195. # Calculate this task's time since it started
  196. task.setCurrentTimeFrame(self.time, self.frame)
  197. # Execute the current task
  198. ret = task(task)
  199. # Check the return value from the task
  200. if ret == cont:
  201. # If this current task wants to continue,
  202. # come back to it next frame
  203. taskDoneStatus = cont
  204. frameFinished = 1
  205. elif ret == done:
  206. # If this task is done, increment the index so that next frame
  207. # we will start executing the next task on the list
  208. self.index = self.index + 1
  209. taskDoneStatus = cont
  210. frameFinished = 0
  211. elif ret == exit:
  212. # If this task wants to exit, the sequence exits
  213. taskDoneStatus = exit
  214. frameFinished = 1
  215. # If we got to the end of the list, this sequence is done
  216. if self.index >= len(self.taskList):
  217. # TaskManager.notify.debug('sequence done: ' + self.name)
  218. frameFinished = 1
  219. taskDoneStatus = done
  220. return taskDoneStatus
  221. task = Task(func)
  222. task.name = 'sequence'
  223. task.taskList = taskList
  224. task.prevIndex = -1
  225. task.index = 0
  226. return task
  227. def resetSequence(task):
  228. # Should this automatically be done as part of spawnTaskNamed?
  229. # Or should one have to create a new task instance every time
  230. # one wishes to spawn a task (currently sequences and can
  231. # only be fired off once
  232. task.index = 0
  233. task.prevIndex = -1
  234. def loop(*taskList):
  235. return make_loop(taskList)
  236. Task.loop = staticmethod(loop)
  237. def make_loop(taskList):
  238. def func(self):
  239. frameFinished = 0
  240. taskDoneStatus = -1
  241. while (not frameFinished):
  242. task = self.taskList[self.index]
  243. # If this is a new task, set its start time and frame
  244. if (self.index > self.prevIndex):
  245. task.setStartTimeFrame(self.time, self.frame)
  246. self.prevIndex = self.index
  247. # Calculate this task's time since it started
  248. task.setCurrentTimeFrame(self.time, self.frame)
  249. # Execute the current task
  250. ret = task(task)
  251. # Check the return value from the task
  252. if (ret == cont):
  253. # If this current task wants to continue,
  254. # come back to it next frame
  255. taskDoneStatus = cont
  256. frameFinished = 1
  257. elif (ret == done):
  258. # If this task is done, increment the index so that next frame
  259. # we will start executing the next task on the list
  260. # TODO: we should go to the next frame now
  261. self.index = self.index + 1
  262. taskDoneStatus = cont
  263. frameFinished = 0
  264. elif (ret == exit):
  265. # If this task wants to exit, the sequence exits
  266. taskDoneStatus = exit
  267. frameFinished = 1
  268. if (self.index >= len(self.taskList)):
  269. # If we got to the end of the list, wrap back around
  270. self.prevIndex = -1
  271. self.index = 0
  272. frameFinished = 1
  273. return taskDoneStatus
  274. task = Task(func)
  275. task.name = 'loop'
  276. task.taskList = taskList
  277. task.prevIndex = -1
  278. task.index = 0
  279. return task
  280. class TaskPriorityList(list):
  281. def __init__(self, priority):
  282. self._priority = priority
  283. self.__emptyIndex = 0
  284. def getPriority(self):
  285. return self._priority
  286. def add(self, task):
  287. if (self.__emptyIndex >= len(self)):
  288. self.append(task)
  289. self.__emptyIndex += 1
  290. else:
  291. self[self.__emptyIndex] = task
  292. self.__emptyIndex += 1
  293. def remove(self, i):
  294. assert i <= len(self)
  295. if (len(self) == 1) and (i == 1):
  296. self[i] = None
  297. self.__emptyIndex = 0
  298. else:
  299. # Swap the last element for this one
  300. lastElement = self[self.__emptyIndex-1]
  301. self[i] = lastElement
  302. self[self.__emptyIndex-1] = None
  303. self.__emptyIndex -= 1
  304. class TaskManager:
  305. # These class vars are generally overwritten by Config variables which
  306. # are read in at the start of a show (ShowBase.py or AIStart.py)
  307. notify = None
  308. # TODO: there is a bit of a bug when you default this to 0. The first
  309. # task we make, the doLaterProcessor, needs to have this set to 1 or
  310. # else we get an error.
  311. taskTimerVerbose = 1
  312. extendedExceptions = 0
  313. pStatsTasks = 0
  314. doLaterCleanupCounter = 2000
  315. OsdPrefix = 'task.'
  316. DefTaskDurationWarningThreshold = 3.
  317. def __init__(self):
  318. self.running = 0
  319. self.stepping = 0
  320. self.taskList = []
  321. # Dictionary of priority to newTaskLists
  322. self.pendingTaskDict = {}
  323. # List of tasks scheduled to execute in the future
  324. self.__doLaterList = []
  325. self._profileFrames = False
  326. self.MaxEpockSpeed = 1.0/30.0;
  327. # We copy this value in from __builtins__ when it gets set.
  328. # But since the TaskManager might have to run before it gets
  329. # set--before it can even be available--we also have to have
  330. # special-case code that handles the possibility that we don't
  331. # have a globalClock yet.
  332. self.globalClock = None
  333. # To help cope with the possibly-missing globalClock, we get a
  334. # handle to Panda's low-level TrueClock object for measuring
  335. # small intervals.
  336. self.trueClock = TrueClock.getGlobalPtr()
  337. # We don't have a base yet, but we can query the config
  338. # variables directly.
  339. self.warnTaskDuration = ConfigVariableBool('task-duration-warnings', 1).getValue()
  340. self.taskDurationWarningThreshold = ConfigVariableDouble(
  341. 'task-duration-warning-threshold',
  342. TaskManager.DefTaskDurationWarningThreshold).getValue()
  343. self.currentTime, self.currentFrame = self.__getTimeFrame()
  344. if (TaskManager.notify == None):
  345. TaskManager.notify = directNotify.newCategory("TaskManager")
  346. self.fKeyboardInterrupt = 0
  347. self.interruptCount = 0
  348. self.resumeFunc = None
  349. self.fVerbose = 0
  350. # Dictionary of task name to list of tasks with that name
  351. self.nameDict = {}
  352. # A default task.
  353. self.add(self.__doLaterProcessor, "doLaterProcessor", -10)
  354. def destroy(self):
  355. del self.nameDict
  356. del self.trueClock
  357. del self.globalClock
  358. del self.__doLaterList
  359. del self.pendingTaskDict
  360. del self.taskList
  361. def setStepping(self, value):
  362. self.stepping = value
  363. def setVerbose(self, value):
  364. self.fVerbose = value
  365. messenger.send('TaskManager-setVerbose', sentArgs = [value])
  366. def invokeDefaultHandler(self, signalNumber, stackFrame):
  367. print '*** allowing mid-frame keyboard interrupt.'
  368. # Restore default interrupt handler
  369. signal.signal(signal.SIGINT, signal.default_int_handler)
  370. # and invoke it
  371. raise KeyboardInterrupt
  372. def keyboardInterruptHandler(self, signalNumber, stackFrame):
  373. self.fKeyboardInterrupt = 1
  374. self.interruptCount += 1
  375. if self.interruptCount == 1:
  376. print '* interrupt by keyboard'
  377. elif self.interruptCount == 2:
  378. print '** waiting for end of frame before interrupting...'
  379. # The user must really want to interrupt this process
  380. # Next time around invoke the default handler
  381. signal.signal(signal.SIGINT, self.invokeDefaultHandler)
  382. def hasTaskNamed(self, taskName):
  383. # TODO: check pending task list
  384. # Get the tasks with this name
  385. # If we found some, see if any of them are still active (not removed)
  386. for task in self.nameDict.get(taskName, []):
  387. if not task._removed:
  388. return 1
  389. # Didnt find any, return 0
  390. return 0
  391. def getTasksNamed(self, taskName):
  392. # TODO: check pending tasks
  393. # Get the tasks with this name
  394. return [task for task in self.nameDict.get(taskName, []) #grab all tasks with name
  395. if not task._removed] #filter removed tasks
  396. def __doLaterFilter(self):
  397. # Filter out all the tasks that have been removed like a mark and
  398. # sweep garbage collector. Returns the number of tasks that have
  399. # been removed Warning: this creates an entirely new doLaterList.
  400. oldLen = len(self.__doLaterList)
  401. self.__doLaterList = [task for task in self.__doLaterList #grab all tasks with name
  402. if not task._removed] #filter removed tasks
  403. # Re heapify to maintain ordering after filter
  404. heapify(self.__doLaterList)
  405. newLen = len(self.__doLaterList)
  406. return oldLen - newLen
  407. def __getNextDoLaterTime(self):
  408. if self.__doLaterList:
  409. dl = self.__doLaterList[0]
  410. return dl.wakeTime
  411. return -1;
  412. def __doLaterProcessor(self, task):
  413. # Removing the tasks during the for loop is a bad idea
  414. # Instead we just flag them as removed
  415. # Later, somebody else cleans them out
  416. currentTime = self.__getTime()
  417. while self.__doLaterList:
  418. # Check the first one on the list to see if it is ready
  419. dl = self.__doLaterList[0]
  420. if dl._removed:
  421. # Get rid of this task forever
  422. heappop(self.__doLaterList)
  423. continue
  424. # If the time now is less than the start of the doLater + delay
  425. # then we are not ready yet, continue to next one
  426. elif currentTime < dl.wakeTime:
  427. # Since the list is sorted, the first one we get to, that
  428. # is not ready to go, we can return
  429. break
  430. else:
  431. # Take it off the doLaterList, set its time, and make
  432. # it pending
  433. heappop(self.__doLaterList)
  434. dl.setStartTimeFrame(self.currentTime, self.currentFrame)
  435. self.__addPendingTask(dl)
  436. continue
  437. # Every nth pass, let's clean out the list of removed tasks
  438. # This is basically a mark and sweep garbage collection of doLaters
  439. if ((task.frame % self.doLaterCleanupCounter) == 0):
  440. numRemoved = self.__doLaterFilter()
  441. # TaskManager.notify.debug("filtered %s removed doLaters" % numRemoved)
  442. return cont
  443. def doMethodLater(self, delayTime, funcOrTask, name, extraArgs=None,
  444. priority=0, uponDeath=None, appendTask=False, owner = None):
  445. if delayTime < 0:
  446. assert self.notify.warning('doMethodLater: added task: %s with negative delay: %s' % (name, delayTime))
  447. if isinstance(funcOrTask, Task):
  448. task = funcOrTask
  449. elif callable(funcOrTask):
  450. task = Task(funcOrTask, priority)
  451. else:
  452. self.notify.error('doMethodLater: Tried to add a task that was not a Task or a func')
  453. assert isinstance(name, str), 'Name must be a string type'
  454. task.setPriority(priority)
  455. task.name = name
  456. task.owner = owner
  457. if extraArgs == None:
  458. extraArgs = []
  459. appendTask = True
  460. # if told to, append the task object to the extra args list so the
  461. # method called will be able to access any properties on the task
  462. if appendTask:
  463. extraArgs.append(task)
  464. task.extraArgs = extraArgs
  465. if uponDeath:
  466. task.uponDeath = uponDeath
  467. # TaskManager.notify.debug('spawning doLater: %s' % (task))
  468. # Add this task to the nameDict
  469. nameList = self.nameDict.get(name)
  470. if nameList:
  471. nameList.append(task)
  472. else:
  473. self.nameDict[name] = [task]
  474. currentTime = self.__getTime()
  475. # Cache the time we should wake up for easier sorting
  476. task.delayTime = delayTime
  477. task.wakeTime = currentTime + delayTime
  478. # Push this onto the doLaterList. The heap maintains the sorting.
  479. heappush(self.__doLaterList, task)
  480. if self.fVerbose:
  481. # Alert the world, a new task is born!
  482. messenger.send('TaskManager-spawnDoLater',
  483. sentArgs = [task, task.name, task.id])
  484. return task
  485. def add(self, funcOrTask, name, priority=0, extraArgs=None, uponDeath=None,
  486. appendTask = False, owner = None):
  487. """
  488. Add a new task to the taskMgr.
  489. You can add a Task object or a method that takes one argument.
  490. """
  491. # TaskManager.notify.debug('add: %s' % (name))
  492. if isinstance(funcOrTask, Task):
  493. task = funcOrTask
  494. elif callable(funcOrTask):
  495. task = Task(funcOrTask, priority)
  496. else:
  497. self.notify.error(
  498. 'add: Tried to add a task that was not a Task or a func')
  499. assert isinstance(name, str), 'Name must be a string type'
  500. task.setPriority(priority)
  501. task.name = name
  502. task.owner = owner
  503. if extraArgs == None:
  504. extraArgs = []
  505. appendTask = True
  506. # if told to, append the task object to the extra args list so the
  507. # method called will be able to access any properties on the task
  508. if appendTask:
  509. extraArgs.append(task)
  510. task.extraArgs = extraArgs
  511. if uponDeath:
  512. task.uponDeath = uponDeath
  513. currentTime = self.__getTime()
  514. task.setStartTimeFrame(currentTime, self.currentFrame)
  515. nameList = self.nameDict.get(name)
  516. if nameList:
  517. nameList.append(task)
  518. else:
  519. self.nameDict[name] = [task]
  520. # Put it on the list for the end of this frame
  521. self.__addPendingTask(task)
  522. return task
  523. def __addPendingTask(self, task):
  524. # TaskManager.notify.debug('__addPendingTask: %s' % (task.name))
  525. pri = task._priority
  526. taskPriList = self.pendingTaskDict.get(pri)
  527. if not taskPriList:
  528. taskPriList = TaskPriorityList(pri)
  529. self.pendingTaskDict[pri] = taskPriList
  530. taskPriList.add(task)
  531. def __addNewTask(self, task):
  532. # The taskList is really an ordered list of TaskPriorityLists
  533. # search back from the end of the list until we find a
  534. # taskList with a lower priority, or we hit the start of the list
  535. taskPriority = task._priority
  536. index = len(self.taskList) - 1
  537. while (1):
  538. if (index < 0):
  539. newList = TaskPriorityList(taskPriority)
  540. newList.add(task)
  541. # Add the new list to the beginning of the taskList
  542. self.taskList.insert(0, newList)
  543. break
  544. taskListPriority = self.taskList[index]._priority
  545. if (taskListPriority == taskPriority):
  546. self.taskList[index].add(task)
  547. break
  548. elif (taskListPriority > taskPriority):
  549. index = index - 1
  550. elif (taskListPriority < taskPriority):
  551. # Time to insert
  552. newList = TaskPriorityList(taskPriority)
  553. newList.add(task)
  554. # Insert this new priority level
  555. # If we are already at the end, just append it
  556. if (index == len(self.taskList)-1):
  557. self.taskList.append(newList)
  558. else:
  559. # Otherwise insert it
  560. self.taskList.insert(index+1, newList)
  561. break
  562. if __debug__:
  563. if self.pStatsTasks and task.name != "igLoop":
  564. task.setupPStats()
  565. if self.fVerbose:
  566. # Alert the world, a new task is born!
  567. messenger.send(
  568. 'TaskManager-spawnTask', sentArgs = [task, task.name, index])
  569. return task
  570. def remove(self, taskOrName):
  571. if type(taskOrName) == type(''):
  572. return self.__removeTasksNamed(taskOrName)
  573. elif isinstance(taskOrName, Task):
  574. return self.__removeTasksEqual(taskOrName)
  575. else:
  576. self.notify.error('remove takes a string or a Task')
  577. def removeTasksMatching(self, taskPattern):
  578. """removeTasksMatching(self, string taskPattern)
  579. Removes tasks whose names match the pattern, which can include
  580. standard shell globbing characters like *, ?, and [].
  581. """
  582. # TaskManager.notify.debug('removing tasks matching: ' + taskPattern)
  583. num = 0
  584. keyList = filter(
  585. lambda key: fnmatch.fnmatchcase(key, taskPattern),
  586. self.nameDict.keys())
  587. for key in keyList:
  588. num += self.__removeTasksNamed(key)
  589. return num
  590. def __removeTasksEqual(self, task):
  591. # Remove this task from the nameDict (should be a short list)
  592. if self.__removeTaskFromNameDict(task):
  593. # TaskManager.notify.debug(
  594. # '__removeTasksEqual: removing task: %s' % (task))
  595. # Flag the task for removal from the real list
  596. task.remove()
  597. task.finishTask(self.fVerbose)
  598. return 1
  599. else:
  600. return 0
  601. def __removeTasksNamed(self, taskName):
  602. tasks = self.nameDict.get(taskName)
  603. if not tasks:
  604. return 0
  605. # TaskManager.notify.debug(
  606. # '__removeTasksNamed: removing tasks named: %s' % (taskName))
  607. for task in tasks:
  608. # Flag for removal
  609. task.remove()
  610. task.finishTask(self.fVerbose)
  611. # Record the number of tasks removed
  612. num = len(tasks)
  613. # Blow away the nameDict entry completely
  614. del self.nameDict[taskName]
  615. return num
  616. def __removeTaskFromNameDict(self, task):
  617. taskName = task.name
  618. # If this is the only task with that name, remove the dict entry
  619. tasksWithName = self.nameDict.get(taskName)
  620. if tasksWithName:
  621. if task in tasksWithName:
  622. # If this is the last element, just remove the entry
  623. # from the dictionary
  624. if len(tasksWithName) == 1:
  625. del self.nameDict[taskName]
  626. else:
  627. tasksWithName.remove(task)
  628. return 1
  629. return 0
  630. def __executeTask(self, task):
  631. task.setCurrentTimeFrame(self.currentTime, self.currentFrame)
  632. if not self.taskTimerVerbose:
  633. startTime = self.trueClock.getShortTime()
  634. # don't record timing info
  635. ret = task(*task.extraArgs)
  636. endTime = self.trueClock.getShortTime()
  637. # Record the dt
  638. dt = endTime - startTime
  639. task.dt = dt
  640. else:
  641. # Run the task and check the return value
  642. if task.pstats:
  643. task.pstats.start()
  644. startTime = self.trueClock.getShortTime()
  645. ret = task(*task.extraArgs)
  646. endTime = self.trueClock.getShortTime()
  647. if task.pstats:
  648. task.pstats.stop()
  649. # Record the dt
  650. dt = endTime - startTime
  651. task.dt = dt
  652. # See if this is the new max
  653. if dt > task.maxDt:
  654. task.maxDt = dt
  655. # Record the running total of all dts so we can compute an average
  656. task.runningTotal = task.runningTotal + dt
  657. if (task.frame > 0):
  658. task.avgDt = (task.runningTotal / task.frame)
  659. else:
  660. task.avgDt = 0
  661. # warn if the task took too long
  662. if self.warnTaskDuration:
  663. if dt >= self.taskDurationWarningThreshold:
  664. assert TaskManager.notify.warning('task %s ran for %.2f seconds' % (
  665. task.name, dt))
  666. return ret
  667. def __repeatDoMethod(self, task):
  668. """
  669. Called when a task execute function returns Task.again because
  670. it wants the task to execute again after the same or a modified
  671. delay (set 'delayTime' on the task object to change the delay)
  672. """
  673. if (not task._removed):
  674. # be sure to ask the globalClock for the current frame time
  675. # rather than use a cached value; globalClock's frame time may
  676. # have been synced since the start of this frame
  677. currentTime = self.__getTime()
  678. # Cache the time we should wake up for easier sorting
  679. task.wakeTime = currentTime + task.delayTime
  680. # Push this onto the doLaterList. The heap maintains the sorting.
  681. heappush(self.__doLaterList, task)
  682. if self.fVerbose:
  683. # Alert the world, a new task is born!
  684. messenger.send('TaskManager-againDoLater',
  685. sentArgs = [task, task.name, task.id])
  686. def __stepThroughList(self, taskPriList):
  687. # Traverse the taskPriList with an iterator
  688. i = 0
  689. while (i < len(taskPriList)):
  690. task = taskPriList[i]
  691. # See if we are at the end of the real tasks
  692. if task is None:
  693. break
  694. # See if this task has been removed in show code
  695. if task._removed:
  696. # assert TaskManager.notify.debug(
  697. # '__stepThroughList: task is flagged for removal %s' % (task))
  698. # If it was removed in show code, it will need finishTask run
  699. # If it was removed by the taskMgr, it will not, but that is ok
  700. # because finishTask is safe to call twice
  701. task.finishTask(self.fVerbose)
  702. taskPriList.remove(i)
  703. self.__removeTaskFromNameDict(task)
  704. # Do not increment the iterator
  705. continue
  706. # Now actually execute the task
  707. ret = self.__executeTask(task)
  708. # See if the task is done
  709. if (ret == cont):
  710. # Leave it for next frame, its not done yet
  711. pass
  712. elif (ret == again):
  713. # repeat doLater again after a delay
  714. self.__repeatDoMethod(task)
  715. taskPriList.remove(i)
  716. continue
  717. elif ((ret == done) or (ret == exit) or (ret == None)):
  718. # assert TaskManager.notify.debug(
  719. # '__stepThroughList: task is finished %s' % (task))
  720. # Remove the task
  721. if not task._removed:
  722. # assert TaskManager.notify.debug(
  723. # '__stepThroughList: task not removed %s' % (task))
  724. task.remove()
  725. # Note: Should not need to remove from doLaterList here
  726. # because this task is not in the doLaterList
  727. task.finishTask(self.fVerbose)
  728. self.__removeTaskFromNameDict(task)
  729. else:
  730. # assert TaskManager.notify.debug(
  731. # '__stepThroughList: task already removed %s' % (task))
  732. self.__removeTaskFromNameDict(task)
  733. taskPriList.remove(i)
  734. # Do not increment the iterator
  735. continue
  736. else:
  737. raise StandardError, \
  738. "Task named %s did not return cont, exit, done, or None" % \
  739. (task.name,)
  740. # Move to the next element
  741. i += 1
  742. def __addPendingTasksToTaskList(self):
  743. # Now that we are all done, add any left over pendingTasks
  744. # generated in priority levels lower or higher than where
  745. # we were when we iterated
  746. for taskList in self.pendingTaskDict.values():
  747. for task in taskList:
  748. if (task and not task._removed):
  749. # assert TaskManager.notify.debug(
  750. # 'step: moving %s from pending to taskList' % (task.name))
  751. self.__addNewTask(task)
  752. self.pendingTaskDict.clear()
  753. def profileFrames(self, num=None):
  754. self._profileFrames = True
  755. if num is None:
  756. num = 1
  757. self._profileFrameCount = num
  758. # in the event we want to do frame time managment.. this is the function to
  759. # replace or overload..
  760. def doYield(self , frameStartTime, nextScheuledTaksTime):
  761. None
  762. def doYieldExample(self , frameStartTime, nextScheuledTaksTime):
  763. minFinTime = frameStartTime + self.MaxEpockSpeed
  764. if nextScheuledTaksTime > 0 and nextScheuledTaksTime < minFinTime:
  765. print ' Adjusting Time'
  766. minFinTime = nextScheuledTaksTime;
  767. delta = minFinTime - self.globalClock.getRealTime();
  768. while(delta > 0.002):
  769. print ' sleep %s'% (delta)
  770. time.sleep(delta)
  771. delta = minFinTime - self.globalClock.getRealTime();
  772. @profiled()
  773. def _doProfiledFrames(self, *args, **kArgs):
  774. print '** profiling %s frames' % self._profileFrameCount
  775. for i in xrange(self._profileFrameCount):
  776. result = self.step(*args, **kArgs)
  777. return result
  778. def step(self):
  779. # assert TaskManager.notify.debug('step: begin')
  780. self.currentTime, self.currentFrame = self.__getTimeFrame()
  781. startFrameTime = None
  782. if self.globalClock:
  783. startFrameTime = self.globalClock.getRealTime()
  784. # Replace keyboard interrupt handler during task list processing
  785. # so we catch the keyboard interrupt but don't handle it until
  786. # after task list processing is complete.
  787. self.fKeyboardInterrupt = 0
  788. self.interruptCount = 0
  789. signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
  790. # Traverse the task list in order because it is in priority order
  791. priIndex = 0
  792. while priIndex < len(self.taskList):
  793. taskPriList = self.taskList[priIndex]
  794. pri = taskPriList._priority
  795. # assert TaskManager.notify.debug(
  796. # 'step: running through taskList at pri: %s, priIndex: %s' %
  797. # (pri, priIndex))
  798. self.__stepThroughList(taskPriList)
  799. # Now see if that generated any pending tasks for this taskPriList
  800. pendingTasks = self.pendingTaskDict.get(pri)
  801. while pendingTasks:
  802. # assert TaskManager.notify.debug('step: running through pending tasks at pri: %s' % (pri))
  803. # Remove them from the pendingTaskDict
  804. del self.pendingTaskDict[pri]
  805. # Execute them
  806. self.__stepThroughList(pendingTasks)
  807. # Add these to the real taskList
  808. for task in pendingTasks:
  809. if (task and not task._removed):
  810. # assert TaskManager.notify.debug('step: moving %s from pending to taskList' % (task.name))
  811. self.__addNewTask(task)
  812. # See if we generated any more for this pri level
  813. pendingTasks = self.pendingTaskDict.get(pri)
  814. # Any new tasks that were made pending should be converted
  815. # to real tasks now in case they need to run this frame at a
  816. # later priority level
  817. self.__addPendingTasksToTaskList()
  818. # Go to the next priority level
  819. priIndex += 1
  820. # Add new pending tasks
  821. self.__addPendingTasksToTaskList()
  822. if startFrameTime:
  823. #this is the spot for a Internal Yield Function
  824. nextTaskTime = self.__getNextDoLaterTime()
  825. self.doYield(startFrameTime,nextTaskTime)
  826. # Restore default interrupt handler
  827. signal.signal(signal.SIGINT, signal.default_int_handler)
  828. if self.fKeyboardInterrupt:
  829. raise KeyboardInterrupt
  830. def run(self):
  831. # Set the clock to have last frame's time in case we were
  832. # Paused at the prompt for a long time
  833. if self.globalClock:
  834. t = self.globalClock.getFrameTime()
  835. timeDelta = t - globalClock.getRealTime()
  836. self.globalClock.setRealTime(t)
  837. messenger.send("resetClock", [timeDelta])
  838. if self.resumeFunc != None:
  839. self.resumeFunc()
  840. if self.stepping:
  841. self.step()
  842. else:
  843. self.running = 1
  844. while self.running:
  845. try:
  846. if self._profileFrames:
  847. self._profileFrames = False
  848. self._doProfiledFrames()
  849. else:
  850. self.step()
  851. except KeyboardInterrupt:
  852. self.stop()
  853. except IOError, ioError:
  854. code, message = self._unpackIOError(ioError)
  855. # Since upgrading to Python 2.4.1, pausing the execution
  856. # often gives this IOError during the sleep function:
  857. # IOError: [Errno 4] Interrupted function call
  858. # So, let's just handle that specific exception and stop.
  859. # All other IOErrors should still get raised.
  860. # Only problem: legit IOError 4s will be obfuscated.
  861. if code == 4:
  862. self.stop()
  863. else:
  864. raise
  865. except:
  866. if self.extendedExceptions:
  867. self.stop()
  868. print_exc_plus()
  869. else:
  870. raise
  871. def _unpackIOError(self, ioError):
  872. # IOError unpack from http://www.python.org/doc/essays/stdexceptions/
  873. # this needs to be in its own method, exceptions that occur inside
  874. # a nested try block are not caught by the inner try block's except
  875. try:
  876. (code, message) = ioError
  877. except:
  878. code = 0
  879. message = ioError
  880. return code, message
  881. def stop(self):
  882. # Set a flag so we will stop before beginning next frame
  883. self.running = 0
  884. def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
  885. if (task is None) or task._removed:
  886. return 0
  887. method = task.__call__
  888. if (type(method) == types.MethodType):
  889. function = method.im_func
  890. else:
  891. function = method
  892. #print ('function: ' + `function` + '\n' +
  893. # 'method: ' + `method` + '\n' +
  894. # 'oldMethod: ' + `oldMethod` + '\n' +
  895. # 'newFunction: ' + `newFunction` + '\n')
  896. if (function == oldMethod):
  897. import new
  898. newMethod = new.instancemethod(newFunction,
  899. method.im_self,
  900. method.im_class)
  901. task.__call__ = newMethod
  902. # Found a match
  903. return 1
  904. return 0
  905. def replaceMethod(self, oldMethod, newFunction):
  906. numFound = 0
  907. # Look through the regular tasks
  908. for taskPriList in self.taskList:
  909. for task in taskPriList:
  910. if task:
  911. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  912. # Look through the pending tasks
  913. for pri, taskList in self.pendingTaskDict.items():
  914. for task in taskList:
  915. if task:
  916. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  917. # Look through the doLaters
  918. for task in self.__doLaterList:
  919. if task:
  920. numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
  921. return numFound
  922. def __repr__(self):
  923. taskNameWidth = 32
  924. dtWidth = 10
  925. priorityWidth = 10
  926. totalDt = 0
  927. totalAvgDt = 0
  928. str = "The taskMgr is handling:\n"
  929. str += ('taskList'.ljust(taskNameWidth)
  930. + 'dt(ms)'.rjust(dtWidth)
  931. + 'avg'.rjust(dtWidth)
  932. + 'max'.rjust(dtWidth)
  933. + 'priority'.rjust(priorityWidth)
  934. + '\n')
  935. str += '-------------------------------------------------------------------------\n'
  936. dtfmt = '%%%d.2f' % (dtWidth)
  937. for taskPriList in self.taskList:
  938. priority = `taskPriList._priority`
  939. for task in taskPriList:
  940. if task is None:
  941. break
  942. if task._removed:
  943. taskName = '(R)' + task.name
  944. else:
  945. taskName = task.name
  946. if self.taskTimerVerbose:
  947. totalDt = totalDt + task.dt
  948. totalAvgDt = totalAvgDt + task.avgDt
  949. str += (taskName.ljust(taskNameWidth)
  950. + dtfmt % (task.dt*1000)
  951. + dtfmt % (task.avgDt*1000)
  952. + dtfmt % (task.maxDt*1000)
  953. + priority.rjust(priorityWidth)
  954. + '\n')
  955. else:
  956. str += (task.name.ljust(taskNameWidth)
  957. + '----'.rjust(dtWidth)
  958. + '----'.rjust(dtWidth)
  959. + '----'.rjust(dtWidth)
  960. + priority.rjust(priorityWidth)
  961. + '\n')
  962. str += '-------------------------------------------------------------------------\n'
  963. str += 'pendingTasks\n'
  964. str += '-------------------------------------------------------------------------\n'
  965. for pri, taskList in self.pendingTaskDict.items():
  966. for task in taskList:
  967. if task._removed:
  968. taskName = '(PR)' + task.name
  969. else:
  970. taskName = '(P)' + task.name
  971. if (self.taskTimerVerbose):
  972. str += (' ' + taskName.ljust(taskNameWidth-2)
  973. + dtfmt % (pri)
  974. + '\n')
  975. else:
  976. str += (' ' + taskName.ljust(taskNameWidth-2)
  977. + '----'.rjust(dtWidth)
  978. + '\n')
  979. str += '-------------------------------------------------------------------------\n'
  980. if (self.taskTimerVerbose):
  981. str += ('total'.ljust(taskNameWidth)
  982. + dtfmt % (totalDt*1000)
  983. + dtfmt % (totalAvgDt*1000)
  984. + '\n')
  985. else:
  986. str += ('total'.ljust(taskNameWidth)
  987. + '----'.rjust(dtWidth)
  988. + '----'.rjust(dtWidth)
  989. + '\n')
  990. str += '-------------------------------------------------------------------------\n'
  991. str += ('doLaterList'.ljust(taskNameWidth)
  992. + 'waitTime(s)'.rjust(dtWidth)
  993. + '\n')
  994. str += '-------------------------------------------------------------------------\n'
  995. # When we print, show the doLaterList in actual sorted order.
  996. # The priority heap is not actually in order - it is a tree
  997. # Make a shallow copy so we can sort it
  998. sortedDoLaterList = self.__doLaterList[:]
  999. sortedDoLaterList.sort(lambda a, b: cmp(a.wakeTime, b.wakeTime))
  1000. sortedDoLaterList.reverse()
  1001. for task in sortedDoLaterList:
  1002. remainingTime = ((task.wakeTime) - self.currentTime)
  1003. if task._removed:
  1004. taskName = '(R)' + task.name
  1005. else:
  1006. taskName = task.name
  1007. str += (' ' + taskName.ljust(taskNameWidth-2)
  1008. + dtfmt % (remainingTime)
  1009. + '\n')
  1010. str += '-------------------------------------------------------------------------\n'
  1011. str += "End of taskMgr info\n"
  1012. return str
  1013. def getTasks(self):
  1014. # returns list of all tasks in arbitrary order
  1015. tasks = []
  1016. for taskPriList in self.taskList:
  1017. for task in taskPriList:
  1018. if task is not None and not task._removed:
  1019. tasks.append(task)
  1020. for pri, taskList in self.pendingTaskDict.iteritems():
  1021. for task in taskList:
  1022. if not task._removed:
  1023. tasks.append(task)
  1024. return tasks
  1025. def getDoLaters(self):
  1026. # returns list of all doLaters in arbitrary order
  1027. return [doLater for doLater in self.__doLaterList
  1028. if not doLater._removed]
  1029. def resetStats(self):
  1030. # WARNING: this screws up your do-later timings
  1031. if self.taskTimerVerbose:
  1032. for task in self.taskList:
  1033. task.dt = 0
  1034. task.avgDt = 0
  1035. task.maxDt = 0
  1036. task.runningTotal = 0
  1037. task.setStartTimeFrame(self.currentTime, self.currentFrame)
  1038. def popupControls(self):
  1039. from direct.tkpanels import TaskManagerPanel
  1040. return TaskManagerPanel.TaskManagerPanel(self)
  1041. def __getTimeFrame(self):
  1042. # WARNING: If you are testing tasks without an igLoop,
  1043. # you must manually tick the clock
  1044. # Ask for the time last frame
  1045. if self.globalClock:
  1046. return self.globalClock.getFrameTime(), self.globalClock.getFrameCount()
  1047. # OK, we don't have a globalClock yet. This is therefore
  1048. # running before the first frame.
  1049. return self.trueClock.getShortTime(), 0
  1050. def __getTime(self):
  1051. if self.globalClock:
  1052. return self.globalClock.getFrameTime()
  1053. return self.trueClock.getShortTime()
  1054. if __debug__:
  1055. # to catch memory leaks during the tests at the bottom of the file
  1056. def _startTrackingMemLeaks(self):
  1057. self._memUsage = ScratchPad()
  1058. mu = self._memUsage
  1059. mu.lenTaskList = len(self.taskList)
  1060. mu.lenPendingTaskDict = len(self.pendingTaskDict)
  1061. mu.lenDoLaterList = len(self.__doLaterList)
  1062. mu.lenNameDict = len(self.nameDict)
  1063. def _stopTrackingMemLeaks(self):
  1064. self._memUsage.destroy()
  1065. del self._memUsage
  1066. def _checkMemLeaks(self):
  1067. # give the mgr a chance to clear out removed tasks
  1068. self.step()
  1069. mu = self._memUsage
  1070. # the task list looks like it grows and never shrinks, replacing finished
  1071. # tasks with 'None' in the TaskPriorityLists.
  1072. # TODO: look at reducing memory usage here--clear out excess at the end of every frame?
  1073. #assert mu.lenTaskList == len(self.taskList)
  1074. assert mu.lenPendingTaskDict == len(self.pendingTaskDict)
  1075. assert mu.lenDoLaterList == len(self.__doLaterList)
  1076. assert mu.lenNameDict == len(self.nameDict)
  1077. def startOsd(self):
  1078. self.add(self.doOsd, 'taskMgr.doOsd')
  1079. self._osdEnabled = None
  1080. def osdEnabled(self):
  1081. return hasattr(self, '_osdEnabled')
  1082. def stopOsd(self):
  1083. onScreenDebug.removeAllWithPrefix(TaskManager.OsdPrefix)
  1084. self.remove('taskMgr.doOsd')
  1085. del self._osdEnabled
  1086. def doOsd(self, task):
  1087. if not onScreenDebug.enabled:
  1088. return
  1089. prefix = TaskManager.OsdPrefix
  1090. onScreenDebug.removeAllWithPrefix(prefix)
  1091. taskNameWidth = 32
  1092. dtWidth = 10
  1093. priorityWidth = 10
  1094. totalDt = 0
  1095. totalAvgDt = 0
  1096. i = 0
  1097. onScreenDebug.add(
  1098. ('%s%02i.taskList' % (prefix, i)).ljust(taskNameWidth),
  1099. '%s %s %s %s' % (
  1100. 'dt(ms)'.rjust(dtWidth),
  1101. 'avg'.rjust(dtWidth),
  1102. 'max'.rjust(dtWidth),
  1103. 'priority'.rjust(priorityWidth),))
  1104. i += 1
  1105. for taskPriList in self.taskList:
  1106. priority = `taskPriList._priority`
  1107. for task in taskPriList:
  1108. if task is None:
  1109. break
  1110. if task._removed:
  1111. taskName = '(R)' + task.name
  1112. else:
  1113. taskName = task.name
  1114. totalDt = totalDt + task.dt
  1115. totalAvgDt = totalAvgDt + task.avgDt
  1116. onScreenDebug.add(
  1117. ('%s%02i.%s' % (prefix, i, task.name)).ljust(taskNameWidth),
  1118. '%s %s %s %s' % (
  1119. dtfmt % (task.dt*1000),
  1120. dtfmt % (task.avgDt*1000),
  1121. dtfmt % (task.maxDt*1000),
  1122. priority.rjust(priorityWidth)))
  1123. i += 1
  1124. onScreenDebug.add(('%s%02i.total' % (prefix, i)).ljust(taskNameWidth),
  1125. '%s %s' % (
  1126. dtfmt % (totalDt*1000),
  1127. dtfmt % (totalAvgDt*1000),))
  1128. return cont
  1129. # These constants are moved to the top level of the module,
  1130. # to make it easier for legacy code. In general though, putting
  1131. # constants at the top level of a module is deprecated.
  1132. exit = Task.exit
  1133. done = Task.done
  1134. cont = Task.cont
  1135. again = Task.again
  1136. if __debug__:
  1137. # keep everything in a function namespace so it's easier to clean up
  1138. def runTests():
  1139. tm = TaskManager()
  1140. # looks like nothing runs on the first frame...?
  1141. # step to get past the first frame
  1142. tm.step()
  1143. # check for memory leaks after every test
  1144. tm._startTrackingMemLeaks()
  1145. tm._checkMemLeaks()
  1146. # run-once task
  1147. l = []
  1148. def _testDone(task, l=l):
  1149. l.append(None)
  1150. return task.done
  1151. tm.add(_testDone, 'testDone')
  1152. tm.step()
  1153. assert len(l) == 1
  1154. tm.step()
  1155. assert len(l) == 1
  1156. _testDone = None
  1157. tm._checkMemLeaks()
  1158. # remove by name
  1159. def _testRemoveByName(task):
  1160. return task.done
  1161. tm.add(_testRemoveByName, 'testRemoveByName')
  1162. assert tm.remove('testRemoveByName') == 1
  1163. assert tm.remove('testRemoveByName') == 0
  1164. _testRemoveByName = None
  1165. tm._checkMemLeaks()
  1166. # continued task
  1167. l = []
  1168. def _testCont(task, l = l):
  1169. l.append(None)
  1170. return task.cont
  1171. tm.add(_testCont, 'testCont')
  1172. tm.step()
  1173. assert len(l) == 1
  1174. tm.step()
  1175. assert len(l) == 2
  1176. tm.remove('testCont')
  1177. _testCont = None
  1178. tm._checkMemLeaks()
  1179. # continue until done task
  1180. l = []
  1181. def _testContDone(task, l = l):
  1182. l.append(None)
  1183. if len(l) >= 2:
  1184. return task.done
  1185. else:
  1186. return task.cont
  1187. tm.add(_testContDone, 'testContDone')
  1188. tm.step()
  1189. assert len(l) == 1
  1190. tm.step()
  1191. assert len(l) == 2
  1192. tm.step()
  1193. assert len(l) == 2
  1194. assert not tm.hasTaskNamed('testContDone')
  1195. _testContDone = None
  1196. tm._checkMemLeaks()
  1197. # hasTaskNamed
  1198. def _testHasTaskNamed(task):
  1199. return task.done
  1200. tm.add(_testHasTaskNamed, 'testHasTaskNamed')
  1201. assert tm.hasTaskNamed('testHasTaskNamed')
  1202. tm.step()
  1203. assert not tm.hasTaskNamed('testHasTaskNamed')
  1204. _testHasTaskNamed = None
  1205. tm._checkMemLeaks()
  1206. # task priority
  1207. l = []
  1208. def _testPri1(task, l = l):
  1209. l.append(1)
  1210. return task.cont
  1211. def _testPri2(task, l = l):
  1212. l.append(2)
  1213. return task.cont
  1214. tm.add(_testPri1, 'testPri1', priority = 1)
  1215. tm.add(_testPri2, 'testPri2', priority = 2)
  1216. tm.step()
  1217. assert len(l) == 2
  1218. assert l == [1, 2,]
  1219. tm.step()
  1220. assert len(l) == 4
  1221. assert l == [1, 2, 1, 2,]
  1222. tm.remove('testPri1')
  1223. tm.remove('testPri2')
  1224. _testPri1 = None
  1225. _testPri2 = None
  1226. tm._checkMemLeaks()
  1227. # task extraArgs
  1228. l = []
  1229. def _testExtraArgs(arg1, arg2, l=l):
  1230. l.extend([arg1, arg2,])
  1231. return done
  1232. tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
  1233. tm.step()
  1234. assert len(l) == 2
  1235. assert l == [4, 5,]
  1236. _testExtraArgs = None
  1237. tm._checkMemLeaks()
  1238. # task appendTask
  1239. l = []
  1240. def _testAppendTask(arg1, arg2, task, l=l):
  1241. l.extend([arg1, arg2,])
  1242. return task.done
  1243. tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
  1244. tm.step()
  1245. assert len(l) == 2
  1246. assert l == [4, 5,]
  1247. _testAppendTask = None
  1248. tm._checkMemLeaks()
  1249. # task uponDeath
  1250. l = []
  1251. def _uponDeathFunc(task, l=l):
  1252. l.append(task.name)
  1253. def _testUponDeath(task):
  1254. return done
  1255. tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
  1256. tm.step()
  1257. assert len(l) == 1
  1258. assert l == ['testUponDeath']
  1259. _testUponDeath = None
  1260. _uponDeathFunc = None
  1261. tm._checkMemLeaks()
  1262. # task owner
  1263. class _TaskOwner:
  1264. def _clearTask(self, task):
  1265. self.clearedTaskName = task.name
  1266. to = _TaskOwner()
  1267. l = []
  1268. def _testOwner(task):
  1269. return done
  1270. tm.add(_testOwner, 'testOwner', owner=to)
  1271. tm.step()
  1272. assert hasattr(to, 'clearedTaskName')
  1273. assert to.clearedTaskName == 'testOwner'
  1274. _testOwner = None
  1275. del to
  1276. _TaskOwner = None
  1277. tm._checkMemLeaks()
  1278. doLaterTests = [0,]
  1279. # doLater
  1280. l = []
  1281. def _testDoLater1(task, l=l):
  1282. l.append(1)
  1283. def _testDoLater2(task, l=l):
  1284. l.append(2)
  1285. def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
  1286. if task.time > .03:
  1287. assert l == [1, 2,]
  1288. doLaterTests[0] -= 1
  1289. return task.done
  1290. return task.cont
  1291. tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
  1292. tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
  1293. doLaterTests[0] += 1
  1294. # make sure we run this task after the doLaters if they all occur on the same frame
  1295. tm.add(_monitorDoLater, 'monitorDoLater', priority=10)
  1296. _testDoLater1 = None
  1297. _testDoLater2 = None
  1298. _monitorDoLater = None
  1299. # don't check until all the doLaters are finished
  1300. #tm._checkMemLeaks()
  1301. # doLater priority
  1302. l = []
  1303. def _testDoLaterPri1(task, l=l):
  1304. l.append(1)
  1305. def _testDoLaterPri2(task, l=l):
  1306. l.append(2)
  1307. def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
  1308. if task.time > .02:
  1309. assert l == [1, 2,]
  1310. doLaterTests[0] -= 1
  1311. return task.done
  1312. return task.cont
  1313. tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', priority=1)
  1314. tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', priority=2)
  1315. doLaterTests[0] += 1
  1316. # make sure we run this task after the doLaters if they all occur on the same frame
  1317. tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', priority=10)
  1318. _testDoLaterPri1 = None
  1319. _testDoLaterPri2 = None
  1320. _monitorDoLaterPri = None
  1321. # don't check until all the doLaters are finished
  1322. #tm._checkMemLeaks()
  1323. # doLater extraArgs
  1324. l = []
  1325. def _testDoLaterExtraArgs(arg1, l=l):
  1326. l.append(arg1)
  1327. def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
  1328. if task.time > .02:
  1329. assert l == [3,]
  1330. doLaterTests[0] -= 1
  1331. return task.done
  1332. return task.cont
  1333. tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
  1334. doLaterTests[0] += 1
  1335. # make sure we run this task after the doLaters if they all occur on the same frame
  1336. tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', priority=10)
  1337. _testDoLaterExtraArgs = None
  1338. _monitorDoLaterExtraArgs = None
  1339. # don't check until all the doLaters are finished
  1340. #tm._checkMemLeaks()
  1341. # doLater appendTask
  1342. l = []
  1343. def _testDoLaterAppendTask(arg1, task, l=l):
  1344. assert task.name == 'testDoLaterAppendTask'
  1345. l.append(arg1)
  1346. def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
  1347. if task.time > .02:
  1348. assert l == [4,]
  1349. doLaterTests[0] -= 1
  1350. return task.done
  1351. return task.cont
  1352. tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
  1353. extraArgs=[4,], appendTask=True)
  1354. doLaterTests[0] += 1
  1355. # make sure we run this task after the doLaters if they all occur on the same frame
  1356. tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', priority=10)
  1357. _testDoLaterAppendTask = None
  1358. _monitorDoLaterAppendTask = None
  1359. # don't check until all the doLaters are finished
  1360. #tm._checkMemLeaks()
  1361. # doLater uponDeath
  1362. l = []
  1363. def _testUponDeathFunc(task, l=l):
  1364. assert task.name == 'testDoLaterUponDeath'
  1365. l.append(10)
  1366. def _testDoLaterUponDeath(arg1, l=l):
  1367. return done
  1368. def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
  1369. if task.time > .02:
  1370. assert l == [10,]
  1371. doLaterTests[0] -= 1
  1372. return task.done
  1373. return task.cont
  1374. tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
  1375. uponDeath=_testUponDeathFunc)
  1376. doLaterTests[0] += 1
  1377. # make sure we run this task after the doLaters if they all occur on the same frame
  1378. tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', priority=10)
  1379. _testUponDeathFunc = None
  1380. _testDoLaterUponDeath = None
  1381. _monitorDoLaterUponDeath = None
  1382. # don't check until all the doLaters are finished
  1383. #tm._checkMemLeaks()
  1384. # doLater owner
  1385. class _DoLaterOwner:
  1386. def _clearTask(self, task):
  1387. self.clearedTaskName = task.name
  1388. doLaterOwner = _DoLaterOwner()
  1389. l = []
  1390. def _testDoLaterOwner(l=l):
  1391. pass
  1392. def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
  1393. doLaterTests=doLaterTests):
  1394. if task.time > .02:
  1395. assert hasattr(doLaterOwner, 'clearedTaskName')
  1396. assert doLaterOwner.clearedTaskName == 'testDoLaterOwner'
  1397. doLaterTests[0] -= 1
  1398. return task.done
  1399. return task.cont
  1400. tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
  1401. owner=doLaterOwner)
  1402. doLaterTests[0] += 1
  1403. # make sure we run this task after the doLaters if they all occur on the same frame
  1404. tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', priority=10)
  1405. _testDoLaterOwner = None
  1406. _monitorDoLaterOwner = None
  1407. del doLaterOwner
  1408. _DoLaterOwner = None
  1409. # don't check until all the doLaters are finished
  1410. #tm._checkMemLeaks()
  1411. # run the doLater tests
  1412. while doLaterTests[0] > 0:
  1413. tm.step()
  1414. del doLaterTests
  1415. tm._checkMemLeaks()
  1416. # getTasks
  1417. def _testGetTasks(task):
  1418. return task.cont
  1419. # the doLaterProcessor is always running
  1420. assert len(tm.getTasks()) == 1
  1421. tm.add(_testGetTasks, 'testGetTasks1')
  1422. assert len(tm.getTasks()) == 2
  1423. assert (tm.getTasks()[0].name == 'testGetTasks1' or
  1424. tm.getTasks()[1].name == 'testGetTasks1')
  1425. tm.add(_testGetTasks, 'testGetTasks2')
  1426. tm.add(_testGetTasks, 'testGetTasks3')
  1427. assert len(tm.getTasks()) == 4
  1428. tm.remove('testGetTasks2')
  1429. assert len(tm.getTasks()) == 3
  1430. tm.remove('testGetTasks1')
  1431. tm.remove('testGetTasks3')
  1432. assert len(tm.getTasks()) == 1
  1433. _testGetTasks = None
  1434. tm._checkMemLeaks()
  1435. # getDoLaters
  1436. def _testGetDoLaters():
  1437. pass
  1438. # the doLaterProcessor is always running
  1439. assert len(tm.getDoLaters()) == 0
  1440. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
  1441. assert len(tm.getDoLaters()) == 1
  1442. assert tm.getDoLaters()[0].name == 'testDoLater1'
  1443. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
  1444. tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
  1445. assert len(tm.getDoLaters()) == 3
  1446. tm.remove('testDoLater2')
  1447. assert len(tm.getDoLaters()) == 2
  1448. tm.remove('testDoLater1')
  1449. tm.remove('testDoLater3')
  1450. assert len(tm.getDoLaters()) == 0
  1451. _testGetTasks = None
  1452. tm._checkMemLeaks()
  1453. # getTasksNamed
  1454. def _testGetTasksNamed(task):
  1455. return task.cont
  1456. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1457. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1458. assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
  1459. assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
  1460. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1461. tm.add(_testGetTasksNamed, 'testGetTasksNamed')
  1462. assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
  1463. tm.remove('testGetTasksNamed')
  1464. assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
  1465. _testGetTasksNamed = None
  1466. tm._checkMemLeaks()
  1467. # removeTasksMatching
  1468. def _testRemoveTasksMatching(task):
  1469. return task.cont
  1470. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
  1471. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
  1472. tm.removeTasksMatching('testRemoveTasksMatching')
  1473. assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
  1474. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
  1475. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
  1476. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
  1477. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
  1478. tm.removeTasksMatching('testRemoveTasksMatching*')
  1479. assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
  1480. assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
  1481. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
  1482. tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
  1483. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
  1484. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
  1485. tm.removeTasksMatching('testRemoveTasksMatching?a')
  1486. assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
  1487. assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
  1488. _testRemoveTasksMatching = None
  1489. tm._checkMemLeaks()
  1490. # create Task object and add to mgr
  1491. l = []
  1492. def _testTaskObj(task, l=l):
  1493. l.append(None)
  1494. return task.cont
  1495. t = Task(_testTaskObj)
  1496. tm.add(t, 'testTaskObj')
  1497. tm.step()
  1498. assert len(l) == 1
  1499. tm.step()
  1500. assert len(l) == 2
  1501. tm.remove('testTaskObj')
  1502. tm.step()
  1503. assert len(l) == 2
  1504. _testTaskObj = None
  1505. tm._checkMemLeaks()
  1506. # remove Task via task.remove()
  1507. l = []
  1508. def _testTaskObjRemove(task, l=l):
  1509. l.append(None)
  1510. return task.cont
  1511. t = Task(_testTaskObjRemove)
  1512. tm.add(t, 'testTaskObjRemove')
  1513. tm.step()
  1514. assert len(l) == 1
  1515. tm.step()
  1516. assert len(l) == 2
  1517. t.remove()
  1518. tm.step()
  1519. assert len(l) == 2
  1520. del t
  1521. _testTaskObjRemove = None
  1522. tm._checkMemLeaks()
  1523. """
  1524. # this test fails, and it's not clear what the correct behavior should be.
  1525. # priority passed to Task.__init__ is always overridden by taskMgr.add()
  1526. # even if no priority is specified, and calling Task.setPriority() has no
  1527. # effect on the taskMgr's behavior.
  1528. # set/get Task priority
  1529. l = []
  1530. def _testTaskObjPriority(arg, task, l=l):
  1531. l.append(arg)
  1532. return task.cont
  1533. t1 = Task(_testTaskObjPriority, priority=1)
  1534. t2 = Task(_testTaskObjPriority, priority=2)
  1535. tm.add(t1, 'testTaskObjPriority1', extraArgs=['a',], appendTask=True)
  1536. tm.add(t2, 'testTaskObjPriority2', extraArgs=['b',], appendTask=True)
  1537. tm.step()
  1538. assert len(l) == 2
  1539. assert l == ['a', 'b']
  1540. assert t1.getPriority() == 1
  1541. assert t2.getPriority() == 2
  1542. t1.setPriority(3)
  1543. assert t1.getPriority() == 3
  1544. tm.step()
  1545. assert len(l) == 4
  1546. assert l == ['a', 'b', 'b', 'a',]
  1547. t1.remove()
  1548. t2.remove()
  1549. tm.step()
  1550. assert len(l) == 4
  1551. del t1
  1552. del t2
  1553. _testTaskObjPriority = None
  1554. tm._checkMemLeaks()
  1555. """
  1556. del l
  1557. tm.destroy()
  1558. del tm
  1559. runTests()
  1560. del runTests
  1561. """
  1562. import Task
  1563. def goo(task):
  1564. print 'goo'
  1565. return Task.done
  1566. def bar(task):
  1567. print 'bar'
  1568. taskMgr.add(goo, 'goo')
  1569. return Task.done
  1570. def foo(task):
  1571. print 'foo'
  1572. taskMgr.add(bar, 'bar')
  1573. return Task.done
  1574. taskMgr.add(foo, 'foo')
  1575. """