ShowBase.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554
  1. """Undocumented Module"""
  2. __all__ = ['ShowBase', 'WindowControls']
  3. # This module redefines the builtin import function with one
  4. # that prints out every import it does in a hierarchical form
  5. # Annoying and very noisy, but sometimes useful
  6. #import VerboseImport
  7. from pandac.PandaModules import *
  8. # This needs to be available early for DirectGUI imports
  9. import __builtin__
  10. __builtin__.config = getConfigShowbase()
  11. from direct.directnotify.DirectNotifyGlobal import *
  12. from MessengerGlobal import *
  13. from BulletinBoardGlobal import *
  14. from direct.task.TaskManagerGlobal import *
  15. from JobManagerGlobal import *
  16. from EventManagerGlobal import *
  17. from PythonUtil import *
  18. from direct.showbase import PythonUtil
  19. #from direct.interval.IntervalManager import ivalMgr
  20. from direct.interval import IntervalManager
  21. from InputStateGlobal import inputState
  22. from direct.showbase.BufferViewer import BufferViewer
  23. from direct.task import Task
  24. from direct.directutil import Verify
  25. from direct.showbase import GarbageReport
  26. import EventManager
  27. import math,sys,os
  28. import Loader
  29. import time
  30. import gc
  31. from direct.fsm import ClassicFSM
  32. from direct.fsm import State
  33. from direct.showbase import ExceptionVarDump
  34. import DirectObject
  35. import SfxPlayer
  36. if __debug__:
  37. from direct.directutil import DeltaProfiler
  38. import OnScreenDebug
  39. import AppRunnerGlobal
  40. __builtin__.FADE_SORT_INDEX = 1000
  41. __builtin__.NO_FADE_SORT_INDEX = 2000
  42. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  43. # hooks on messages, particularly on window-event. This doesn't
  44. # *seem* to cause anyone any problems.
  45. class ShowBase(DirectObject.DirectObject):
  46. notify = directNotify.newCategory("ShowBase")
  47. def __init__(self, fStartDirect = True, windowType = None):
  48. __builtin__.__dev__ = config.GetBool('want-dev', 0)
  49. if config.GetBool('want-variable-dump', 0):
  50. ExceptionVarDump.install()
  51. # Locate the directory containing the main program
  52. self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
  53. # The appRunner should have been created by the time ShowBase
  54. # has been.
  55. self.appRunner = AppRunnerGlobal.appRunner
  56. #debug running multiplier
  57. self.debugRunningMultiplier = 4
  58. # Get the dconfig object
  59. self.config = config
  60. # Setup wantVerifyPdb as soon as reasonable:
  61. Verify.wantVerifyPdb = self.config.GetBool('want-verify-pdb', 0)
  62. # [gjeon] to disable sticky keys
  63. if self.config.GetBool('disable-sticky-keys', 0):
  64. storeAccessibilityShortcutKeys()
  65. allowAccessibilityShortcutKeys(False)
  66. self.printEnvDebugInfo()
  67. vfs = VirtualFileSystem.getGlobalPtr()
  68. self.nextWindowIndex = 1
  69. self.__directStarted = False
  70. self.__deadInputs = 0
  71. # Store dconfig variables
  72. self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
  73. self.musicActive = self.config.GetBool('audio-music-active', 1)
  74. self.wantFog = self.config.GetBool('want-fog', 1)
  75. self.wantRender2dp = self.config.GetBool('want-render2dp', 1)
  76. self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
  77. self.musicManager = None
  78. self.musicManagerIsValid = None
  79. self.sfxManagerList = []
  80. self.sfxManagerIsValidList = []
  81. self.wantStats = self.config.GetBool('want-pstats', 0)
  82. # Fill this in with a function to invoke when the user "exits"
  83. # the program by closing the main window.
  84. self.exitFunc = None
  85. # Add final-exit callbacks to this list. These will be called
  86. # when sys.exit() is called, after Panda has unloaded, and
  87. # just before Python is about to shut down.
  88. self.finalExitCallbacks = []
  89. Task.TaskManager.taskTimerVerbose = self.config.GetBool('task-timer-verbose', 0)
  90. Task.TaskManager.extendedExceptions = self.config.GetBool('extended-exceptions', 0)
  91. Task.TaskManager.pStatsTasks = self.config.GetBool('pstats-tasks', 0)
  92. # Set up the TaskManager to reset the PStats clock back
  93. # whenever we resume from a pause. This callback function is
  94. # a little hacky, but we can't call it directly from within
  95. # the TaskManager because he doesn't know about PStats (and
  96. # has to run before libpanda is even loaded).
  97. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  98. if(self.config.GetBool("want-dev",0)):
  99. import profile, pstats
  100. profile.Profile.bias = float(self.config.GetString("profile-bias","0"))
  101. def f8(x):
  102. return ("%"+"8.%df"%base.config.GetInt("profile-decimals",3)) % x
  103. pstats.f8=f8
  104. # If the aspect ratio is 0 or None, it means to infer the
  105. # aspect ratio from the window size.
  106. # If you need to know the actual aspect ratio call base.getAspectRatio()
  107. self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).getValue()
  108. # This variable is used to see if the aspect ratio has changed when
  109. # we get a window-event.
  110. self.__oldAspectRatio = None
  111. self.windowType = windowType
  112. if self.windowType is None:
  113. self.windowType = self.config.GetString('window-type', 'onscreen')
  114. self.requireWindow = self.config.GetBool('require-window', 1)
  115. # base.win is the main, or only window; base.winList is a list of
  116. # *all* windows. Similarly with base.camList.
  117. self.win = None
  118. self.frameRateMeter = None
  119. self.winList = []
  120. self.winControls = []
  121. self.mainWinMinimized = 0
  122. self.mainWinForeground = 0
  123. self.pipe = None
  124. self.pipeList = []
  125. self.mouse2cam = None
  126. self.buttonThrowers = None
  127. self.mouseWatcher = None
  128. self.mouseWatcherNode = None
  129. self.pointerWatcherNodes = None
  130. self.mouseInterface = None
  131. self.drive = None
  132. self.trackball = None
  133. self.texmem = None
  134. self.showVertices = None
  135. self.cam = None
  136. self.cam2d = None
  137. self.cam2dp = None
  138. self.camera = None
  139. self.camera2d = None
  140. self.camera2dp = None
  141. self.camList = []
  142. self.camNode = None
  143. self.camLens = None
  144. self.camFrustumVis = None
  145. # This is used for syncing multiple PCs in a distributed cluster
  146. try:
  147. # Has the cluster sync variable been set externally?
  148. self.clusterSyncFlag = clusterSyncFlag
  149. except NameError:
  150. # Has the clusterSyncFlag been set via a config variable
  151. self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0)
  152. self.hidden = NodePath('hidden')
  153. self.graphicsEngine = GraphicsEngine.getGlobalPtr()
  154. self.setupRender()
  155. self.setupRender2d()
  156. self.setupDataGraph()
  157. if self.wantRender2dp:
  158. self.setupRender2dp()
  159. # This is a placeholder for a CollisionTraverser. If someone
  160. # stores a CollisionTraverser pointer here, we'll traverse it
  161. # in the collisionLoop task.
  162. self.shadowTrav = 0
  163. # in the collisionLoop task.
  164. self.cTrav = 0
  165. self.cTravStack = Stack()
  166. # Ditto for an AppTraverser.
  167. self.appTrav = 0
  168. # This is the DataGraph traverser, which we might as well
  169. # create now.
  170. self.dgTrav = DataGraphTraverser()
  171. # Maybe create a RecorderController to record and/or play back
  172. # the user session.
  173. self.recorder = None
  174. playbackSession = self.config.GetString('playback-session', '')
  175. recordSession = self.config.GetString('record-session', '')
  176. if playbackSession:
  177. self.recorder = RecorderController()
  178. self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession))
  179. elif recordSession:
  180. self.recorder = RecorderController()
  181. self.recorder.beginRecord(Filename.fromOsSpecific(recordSession))
  182. if self.recorder:
  183. # If we're either playing back or recording, pass the
  184. # random seed into the system so each session will have
  185. # the same random seed.
  186. import random #, whrandom
  187. seed = self.recorder.getRandomSeed()
  188. random.seed(seed)
  189. #whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
  190. # Now that we've set up the window structures, assign an exitfunc.
  191. self.oldexitfunc = getattr(sys, 'exitfunc', None)
  192. sys.exitfunc = self.exitfunc
  193. # Open the default rendering window.
  194. if self.windowType != 'none':
  195. props = WindowProperties.getDefault()
  196. if (self.config.GetBool('read-raw-mice', 0)):
  197. props.setRawMice(1)
  198. self.openDefaultWindow(startDirect = False, props=props)
  199. self.loader = Loader.Loader(self)
  200. self.graphicsEngine.setDefaultLoader(self.loader.loader)
  201. self.eventMgr = eventMgr
  202. self.messenger = messenger
  203. self.bboard = bulletinBoard
  204. self.taskMgr = taskMgr
  205. self.jobMgr = jobMgr
  206. # Particle manager
  207. self.particleMgr = None
  208. self.particleMgrEnabled = 0
  209. # Physics manager
  210. self.physicsMgr = None
  211. self.physicsMgrEnabled = 0
  212. self.physicsMgrAngular = 0
  213. self.createBaseAudioManagers()
  214. self.createStats()
  215. self.AppHasAudioFocus = 1
  216. # Get a pointer to Panda's global ClockObject, used for
  217. # synchronizing events between Python and C.
  218. globalClock = ClockObject.getGlobalClock()
  219. # Since we have already started up a TaskManager, and probably
  220. # a number of tasks; and since the TaskManager had to use the
  221. # TrueClock to tell time until this moment, make sure the
  222. # globalClock object is exactly in sync with the TrueClock.
  223. trueClock = TrueClock.getGlobalPtr()
  224. globalClock.setRealTime(trueClock.getShortTime())
  225. globalClock.tick()
  226. # Now we can make the TaskManager start using the new globalClock.
  227. taskMgr.globalClock = globalClock
  228. # client CPU affinity is determined by, in order:
  229. # - client-cpu-affinity-mask config
  230. # - pcalt-# (# is CPU number, 0-based)
  231. # - client-cpu-affinity config
  232. # - auto-single-cpu-affinity config
  233. affinityMask = self.config.GetInt('client-cpu-affinity-mask', -1)
  234. if affinityMask != -1:
  235. TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
  236. else:
  237. # this is useful on machines that perform better with each process
  238. # assigned to a single CPU
  239. autoAffinity = self.config.GetBool('auto-single-cpu-affinity', 0)
  240. affinity = None
  241. if autoAffinity and ('clientIndex' in __builtin__.__dict__):
  242. affinity = abs(int(__builtin__.clientIndex))
  243. else:
  244. affinity = self.config.GetInt('client-cpu-affinity', -1)
  245. if (affinity in (None, -1)) and autoAffinity:
  246. affinity = 0
  247. if affinity not in (None, -1):
  248. # Windows XP supports a 32-bit affinity mask
  249. TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
  250. __builtin__.base = self
  251. __builtin__.render2d = self.render2d
  252. __builtin__.aspect2d = self.aspect2d
  253. __builtin__.pixel2d = self.pixel2d
  254. __builtin__.render = self.render
  255. __builtin__.hidden = self.hidden
  256. __builtin__.camera = self.camera
  257. __builtin__.loader = self.loader
  258. __builtin__.taskMgr = self.taskMgr
  259. __builtin__.jobMgr = self.jobMgr
  260. __builtin__.eventMgr = self.eventMgr
  261. __builtin__.messenger = self.messenger
  262. __builtin__.bboard = self.bboard
  263. # Config needs to be defined before ShowBase is constructed
  264. #__builtin__.config = self.config
  265. __builtin__.run = self.run
  266. __builtin__.ostream = Notify.out()
  267. __builtin__.directNotify = directNotify
  268. __builtin__.giveNotify = giveNotify
  269. __builtin__.globalClock = globalClock
  270. __builtin__.vfs = vfs
  271. __builtin__.cpMgr = ConfigPageManager.getGlobalPtr()
  272. __builtin__.cvMgr = ConfigVariableManager.getGlobalPtr()
  273. __builtin__.pandaSystem = PandaSystem.getGlobalPtr()
  274. __builtin__.wantUberdog = base.config.GetBool('want-uberdog', 1)
  275. if __debug__:
  276. __builtin__.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
  277. __builtin__.onScreenDebug = OnScreenDebug.OnScreenDebug()
  278. if self.wantRender2dp:
  279. __builtin__.render2dp = self.render2dp
  280. __builtin__.aspect2dp = self.aspect2dp
  281. __builtin__.pixel2dp = self.pixel2dp
  282. ShowBase.notify.info('__dev__ == %s' % __dev__)
  283. # set up recording of Functor creation stacks in __dev__
  284. PythonUtil.recordFunctorCreationStacks()
  285. if __dev__ or self.config.GetBool('want-e3-hacks', False):
  286. if self.config.GetBool('track-gui-items', True):
  287. # dict of guiId to gui item, for tracking down leaks
  288. self.guiItems = {}
  289. # Now hang a hook on the window-event from Panda. This allows
  290. # us to detect when the user resizes, minimizes, or closes the
  291. # main window.
  292. self.accept('window-event', self.windowEvent)
  293. # Transition effects (fade, iris, etc)
  294. import Transitions
  295. self.transitions = Transitions.Transitions(self.loader)
  296. # Setup the window controls - handy for multiwindow applications
  297. self.setupWindowControls()
  298. # Client sleep
  299. sleepTime = self.config.GetFloat('client-sleep', 0.0)
  300. self.clientSleep = 0.0
  301. self.setSleep(sleepTime)
  302. # Extra sleep for running 4+ clients on a single machine
  303. # adds a sleep right after the main render in igloop
  304. # tends to even out the frame rate and keeps it from going
  305. # to zero in the out of focus windows
  306. if base.config.GetBool('multi-sleep', 0):
  307. self.multiClientSleep = 1
  308. else:
  309. self.multiClientSleep = 0
  310. # Offscreen buffer viewing utility.
  311. # This needs to be allocated even if the viewer is off.
  312. self.bufferViewer = BufferViewer()
  313. if self.wantRender2dp:
  314. self.bufferViewer.setRenderParent(self.render2dp)
  315. if self.windowType != 'none':
  316. if fStartDirect: # [gjeon] if this is False let them start direct manually
  317. self.__doStartDirect()
  318. if self.config.GetBool('show-tex-mem', False):
  319. if not self.texmem or self.texmem.cleanedUp:
  320. self.toggleTexMem()
  321. taskMgr.finalInit()
  322. # Start IGLOOP
  323. self.restart()
  324. # add a collision traverser via pushCTrav and remove it via popCTrav
  325. # that way the owner of the new cTrav doesn't need to hold onto the
  326. # previous one in order to put it back
  327. def pushCTrav(self, cTrav):
  328. self.cTravStack.push(self.cTrav)
  329. self.cTrav = cTrav
  330. def popCTrav(self):
  331. self.cTrav = self.cTravStack.pop()
  332. # temp; see ToonBase.py
  333. def getExitErrorCode(self):
  334. return 0
  335. def printEnvDebugInfo(self):
  336. """
  337. Print some information about the environment that we are running
  338. in. Stuff like the model paths and other paths. Feel free to
  339. add stuff to this.
  340. """
  341. if self.config.GetBool('want-env-debug-info', 0):
  342. print "\n\nEnvironment Debug Info {"
  343. print "* model path:"
  344. print getModelPath()
  345. #print "* dna path:"
  346. #print getDnaPath()
  347. print "* texture path:"
  348. print getTexturePath()
  349. print "* sound path:"
  350. print getSoundPath()
  351. print "}"
  352. def destroy(self):
  353. """ Call this function to destroy the ShowBase and stop all
  354. its tasks, freeing all of the Panda resources. Normally, you
  355. should not need to call it explicitly, as it is bound to the
  356. exitfunc and will be called at application exit time
  357. automatically.
  358. This function is designed to be safe to call multiple times."""
  359. for cb in self.finalExitCallbacks:
  360. cb()
  361. # [gjeon] restore sticky key settings
  362. if self.config.GetBool('disable-sticky-keys', 0):
  363. allowAccessibilityShortcutKeys(True)
  364. taskMgr.destroy()
  365. if getattr(self, 'musicManager', None):
  366. self.musicManager.shutdown()
  367. self.musicManager = None
  368. for sfxManager in self.sfxManagerList:
  369. sfxManager.shutdown()
  370. self.sfxManagerList = []
  371. if getattr(self, 'loader', None):
  372. self.loader.destroy()
  373. self.loader = None
  374. if getattr(self, 'graphicsEngine', None):
  375. self.graphicsEngine.removeAllWindows()
  376. try:
  377. self.direct.panel.destroy()
  378. except:
  379. pass
  380. if hasattr(self, 'win'):
  381. del self.win
  382. del self.winList
  383. del self.pipe
  384. vfs = VirtualFileSystem.getGlobalPtr()
  385. vfs.unmountAll()
  386. def exitfunc(self):
  387. """
  388. This should be assigned to sys.exitfunc to be called just
  389. before Python shutdown. It guarantees that the Panda window
  390. is closed cleanly, so that we free system resources, restore
  391. the desktop and keyboard functionality, etc.
  392. """
  393. self.destroy()
  394. if self.oldexitfunc:
  395. self.oldexitfunc()
  396. def makeDefaultPipe(self, printPipeTypes = True):
  397. """
  398. Creates the default GraphicsPipe, which will be used to make
  399. windows unless otherwise specified.
  400. """
  401. assert self.pipe == None
  402. selection = GraphicsPipeSelection.getGlobalPtr()
  403. if printPipeTypes:
  404. selection.printPipeTypes()
  405. self.pipe = selection.makeDefaultPipe()
  406. if not self.pipe:
  407. self.notify.error(
  408. "No graphics pipe is available!\n"
  409. "Your Config.prc file must name at least one valid panda display\n"
  410. "library via load-display or aux-display.")
  411. self.notify.info("Default graphics pipe is %s (%s)." % (
  412. self.pipe.getType().getName(), self.pipe.getInterfaceName()))
  413. self.pipeList.append(self.pipe)
  414. def makeModulePipe(self, moduleName):
  415. """
  416. Returns a GraphicsPipe from the indicated module,
  417. e.g. 'pandagl' or 'pandadx9'. Does not affect base.pipe or
  418. base.pipeList.
  419. """
  420. selection = GraphicsPipeSelection.getGlobalPtr()
  421. return selection.makeModulePipe(moduleName)
  422. def makeAllPipes(self):
  423. """
  424. Creates all GraphicsPipes that the system knows about and fill up
  425. self.pipeList with them.
  426. """
  427. shouldPrintPipes = 0
  428. selection = GraphicsPipeSelection.getGlobalPtr()
  429. selection.loadAuxModules()
  430. # First, we should make sure the default pipe exists.
  431. if self.pipe == None:
  432. self.makeDefaultPipe()
  433. # Now go through the list of known pipes, and make each one if
  434. # we don't have one already.
  435. numPipeTypes = selection.getNumPipeTypes()
  436. for i in range(numPipeTypes):
  437. pipeType = selection.getPipeType(i)
  438. # Do we already have a pipe of this type on the list?
  439. # This operation is n-squared, but presumably there won't
  440. # be more than a handful of pipe types, so who cares.
  441. already = 0
  442. for pipe in self.pipeList:
  443. if pipe.getType() == pipeType:
  444. already = 1
  445. if not already:
  446. pipe = selection.makePipe(pipeType)
  447. if pipe:
  448. self.notify.info("Got aux graphics pipe %s (%s)." % (
  449. pipe.getType().getName(), pipe.getInterfaceName()))
  450. self.pipeList.append(pipe)
  451. else:
  452. self.notify.info("Could not make graphics pipe %s." % (
  453. pipeType.getName()))
  454. def openWindow(self, props = None, pipe = None, gsg = None,
  455. type = None, name = None, size = None, aspectRatio = None,
  456. makeCamera = 1, keepCamera = 0,
  457. scene = None, stereo = None, rawmice = 0):
  458. """
  459. Creates a window and adds it to the list of windows that are
  460. to be updated every frame.
  461. """
  462. if pipe == None:
  463. pipe = self.pipe
  464. if pipe == None:
  465. self.makeDefaultPipe()
  466. pipe = self.pipe
  467. if pipe == None:
  468. # We couldn't get a pipe.
  469. return None
  470. if isinstance(gsg, GraphicsOutput):
  471. # If the gsg is a window or buffer, it means to use the
  472. # GSG from that buffer.
  473. gsg = gsg.getGsg()
  474. # If we are using DirectX, force a new GSG to be created,
  475. # since at the moment DirectX seems to misbehave if we do
  476. # not do this. This will cause a delay while all textures
  477. # etc. are reloaded, so we should revisit this later if we
  478. # can fix the underlying bug in our DirectX support.
  479. if pipe.getType().getName().startswith('wdx'):
  480. gsg = None
  481. if type == None:
  482. type = self.windowType
  483. if props == None:
  484. props = WindowProperties.getDefault()
  485. if size != None:
  486. # If we were given an explicit size, use it; otherwise,
  487. # the size from the properties is used.
  488. props = WindowProperties(props)
  489. props.setSize(size[0], size[1])
  490. if name == None:
  491. name = 'window%s' % (self.nextWindowIndex)
  492. self.nextWindowIndex += 1
  493. win = None
  494. fbprops = FrameBufferProperties.getDefault()
  495. flags = GraphicsPipe.BFFbPropsOptional
  496. if type == 'onscreen':
  497. flags = flags | GraphicsPipe.BFRequireWindow
  498. elif type == 'offscreen':
  499. flags = flags | GraphicsPipe.BFRefuseWindow
  500. if gsg:
  501. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  502. props, flags, gsg)
  503. else:
  504. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  505. props, flags)
  506. if win == None:
  507. # Couldn't create a window!
  508. return None
  509. if hasattr(win, "requestProperties"):
  510. win.requestProperties(props)
  511. mainWindow = False
  512. if self.win == None:
  513. mainWindow = True
  514. self.win = win
  515. self.winList.append(win)
  516. # Set up a 3-d camera for the window by default.
  517. if keepCamera:
  518. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  519. stereo = stereo, useCamera = base.cam)
  520. elif makeCamera:
  521. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  522. stereo = stereo)
  523. messenger.send('open_window', [win, mainWindow])
  524. if mainWindow:
  525. messenger.send('open_main_window')
  526. return win
  527. def closeWindow(self, win, keepCamera = 0):
  528. """
  529. Closes the indicated window and removes it from the list of
  530. windows. If it is the main window, clears the main window
  531. pointer to None.
  532. """
  533. # First, remove all of the cameras associated with display
  534. # regions on the window.
  535. numRegions = win.getNumDisplayRegions()
  536. for i in range(numRegions):
  537. dr = win.getDisplayRegion(i)
  538. # [gjeon] remove drc in base.direct.drList
  539. if base.direct is not None:
  540. for drc in base.direct.drList:
  541. if drc.cam == dr.getCamera():
  542. base.direct.drList.displayRegionList.remove(drc)
  543. break
  544. cam = NodePath(dr.getCamera())
  545. dr.setCamera(NodePath())
  546. if not cam.isEmpty() and \
  547. cam.node().getNumDisplayRegions() == 0 and \
  548. not keepCamera:
  549. # If the camera is used by no other DisplayRegions,
  550. # remove it.
  551. if self.camList.count(cam) != 0:
  552. self.camList.remove(cam)
  553. # Don't throw away self.camera; we want to
  554. # preserve it for reopening the window.
  555. if cam == self.cam:
  556. self.cam = None
  557. if cam == self.cam2d:
  558. self.cam2d = None
  559. if cam == self.cam2dp:
  560. self.cam2dp = None
  561. cam.removeNode()
  562. # [gjeon] remove winControl
  563. for winCtrl in self.winControls:
  564. if winCtrl.win == win:
  565. self.winControls.remove(winCtrl)
  566. break
  567. # Now we can actually close the window.
  568. self.graphicsEngine.removeWindow(win)
  569. self.winList.remove(win)
  570. mainWindow = False
  571. if win == self.win:
  572. mainWindow = True
  573. self.win = None
  574. if self.frameRateMeter:
  575. self.frameRateMeter.clearWindow()
  576. self.frameRateMeter = None
  577. messenger.send('close_window', [win, mainWindow])
  578. if mainWindow:
  579. messenger.send('close_main_window')
  580. if not self.winList:
  581. # Give the window(s) a chance to actually close before we
  582. # continue.
  583. base.graphicsEngine.renderFrame()
  584. def openDefaultWindow(self, *args, **kw):
  585. # Creates the main window for the first time, without being
  586. # too particular about the kind of graphics API that is
  587. # chosen. The suggested window type from the load-display
  588. # config variable is tried first; if that fails, the first
  589. # window type that can be successfully opened at all is
  590. # accepted. Returns true on success, false otherwise.
  591. #
  592. # This is intended to be called only once, at application
  593. # startup. It is normally called automatically unless
  594. # window-type is configured to 'none'.
  595. startDirect = kw.get('startDirect', True)
  596. if 'startDirect' in kw:
  597. del kw['startDirect']
  598. if self.win:
  599. # If we've already opened a window before, this does
  600. # little more work than openMainWindow() alone.
  601. self.openMainWindow(*args, **kw)
  602. self.graphicsEngine.openWindows()
  603. return
  604. self.openMainWindow(*args, **kw)
  605. # Give the window a chance to truly open.
  606. self.graphicsEngine.openWindows()
  607. if self.win != None and not self.isMainWindowOpen():
  608. self.notify.info("Window did not open, removing.")
  609. self.closeWindow(self.win)
  610. if self.win == None:
  611. # Try a little harder if the window wouldn't open.
  612. self.makeAllPipes()
  613. try:
  614. self.pipeList.remove(self.pipe)
  615. except ValueError:
  616. pass
  617. while self.win == None and self.pipeList:
  618. self.pipe = self.pipeList[0]
  619. self.notify.info("Trying pipe type %s (%s)" % (
  620. self.pipe.getType(), self.pipe.getInterfaceName()))
  621. self.openMainWindow(*args, **kw)
  622. self.graphicsEngine.openWindows()
  623. if self.win != None and not self.isMainWindowOpen():
  624. self.notify.info("Window did not open, removing.")
  625. self.closeWindow(self.win)
  626. if self.win == None:
  627. self.pipeList.remove(self.pipe)
  628. if self.win == None:
  629. self.notify.warning("Unable to open '%s' window." % (
  630. self.windowType))
  631. if self.requireWindow:
  632. # Unless require-window is set to false, it is an
  633. # error not to open a window.
  634. raise StandardError, 'Could not open window.'
  635. else:
  636. self.notify.info("Successfully opened window of type %s (%s)" % (
  637. self.win.getType(), self.win.getPipe().getInterfaceName()))
  638. # The default is trackball mode, which is more convenient for
  639. # ad-hoc development in Python using ShowBase. Applications
  640. # can explicitly call base.useDrive() if they prefer a drive
  641. # interface.
  642. self.mouseInterface = self.trackball
  643. self.useTrackball()
  644. if startDirect:
  645. self.__doStartDirect()
  646. return self.win != None
  647. def isMainWindowOpen(self):
  648. if self.win != None:
  649. return self.win.isValid()
  650. return 0
  651. def openMainWindow(self, *args, **kw):
  652. """
  653. Creates the initial, main window for the application, and sets
  654. up the mouse and render2d structures appropriately for it. If
  655. this method is called a second time, it will close the
  656. previous main window and open a new one, preserving the lens
  657. properties in base.camLens.
  658. The return value is true on success, or false on failure (in
  659. which case base.win may be either None, or the previous,
  660. closed window).
  661. """
  662. keepCamera = kw.get('keepCamera', 0)
  663. success = 1
  664. oldWin = self.win
  665. oldLens = self.camLens
  666. oldClearColorActive = None
  667. if self.win != None:
  668. # Close the previous window.
  669. oldClearColorActive = self.win.getClearColorActive()
  670. oldClearColor = VBase4(self.win.getClearColor())
  671. oldClearDepthActive = self.win.getClearDepthActive()
  672. oldClearDepth = self.win.getClearDepth()
  673. oldClearStencilActive = self.win.getClearStencilActive()
  674. oldClearStencil = self.win.getClearStencil()
  675. self.closeWindow(self.win, keepCamera = keepCamera)
  676. # Open a new window.
  677. self.openWindow(*args, **kw)
  678. if self.win == None:
  679. self.win = oldWin
  680. self.winList.append(oldWin)
  681. success = 0
  682. if self.win != None:
  683. if isinstance(self.win, GraphicsWindow):
  684. self.setupMouse(self.win)
  685. self.makeCamera2d(self.win)
  686. self.makeCamera2dp(self.win)
  687. if oldLens != None:
  688. # Restore the previous lens properties.
  689. self.camNode.setLens(oldLens)
  690. self.camLens = oldLens
  691. if oldClearColorActive != None:
  692. # Restore the previous clear properties.
  693. self.win.setClearColorActive(oldClearColorActive)
  694. self.win.setClearColor(oldClearColor)
  695. self.win.setClearDepthActive(oldClearDepthActive)
  696. self.win.setClearDepth(oldClearDepth)
  697. self.win.setClearStencilActive(oldClearStencilActive)
  698. self.win.setClearStencil(oldClearStencil)
  699. flag = self.config.GetBool('show-frame-rate-meter', False)
  700. if self.appRunner is not None and self.appRunner.allowPythonDev:
  701. # In an allow_python_dev p3d application, we always
  702. # start up with the frame rate meter enabled, to
  703. # provide a visual reminder that this flag has been
  704. # set.
  705. flag = True
  706. self.setFrameRateMeter(flag)
  707. return success
  708. def setSleep(self, amount):
  709. """
  710. Sets up a task that calls python 'sleep' every frame. This is a simple
  711. way to reduce the CPU usage (and frame rate) of a panda program.
  712. """
  713. if (self.clientSleep == amount):
  714. return
  715. self.clientSleep = amount
  716. if (amount == 0.0):
  717. self.taskMgr.remove('clientSleep')
  718. else:
  719. # Spawn it after igloop (at the end of each frame)
  720. self.taskMgr.remove('clientSleep')
  721. self.taskMgr.add(self.sleepCycleTask, 'clientSleep', priority = 55)
  722. def sleepCycleTask(self, task):
  723. Thread.sleep(self.clientSleep)
  724. #time.sleep(self.clientSleep)
  725. return Task.cont
  726. def setFrameRateMeter(self, flag):
  727. """
  728. Turns on or off (according to flag) a standard frame rate
  729. meter in the upper-right corner of the main window.
  730. """
  731. if flag:
  732. if not self.frameRateMeter:
  733. self.frameRateMeter = FrameRateMeter('frameRateMeter')
  734. self.frameRateMeter.setupWindow(self.win)
  735. else:
  736. if self.frameRateMeter:
  737. self.frameRateMeter.clearWindow()
  738. self.frameRateMeter = None
  739. # [gjeon] now you can add more winControls after creating a showbase instance
  740. def setupWindowControls(self, winCtrl=None):
  741. if winCtrl is None:
  742. winCtrl = WindowControls(
  743. self.win, mouseWatcher=self.mouseWatcher,
  744. cam=self.camera, camNode = self.camNode, cam2d=self.camera2d,
  745. mouseKeyboard = self.dataRoot.find("**/*"))
  746. self.winControls.append(winCtrl)
  747. def setupRender(self):
  748. """
  749. Creates the render scene graph, the primary scene graph for
  750. rendering 3-d geometry.
  751. """
  752. self.render = NodePath('render')
  753. self.render.setAttrib(RescaleNormalAttrib.makeDefault())
  754. self.render.setTwoSided(0)
  755. self.backfaceCullingEnabled = 1
  756. self.textureEnabled = 1
  757. self.wireframeEnabled = 0
  758. def setupRender2d(self):
  759. """
  760. Creates the render2d scene graph, the primary scene graph for
  761. 2-d objects and gui elements that are superimposed over the
  762. 3-d geometry in the window.
  763. """
  764. self.render2d = NodePath('render2d')
  765. # Set up some overrides to turn off certain properties which
  766. # we probably won't need for 2-d objects.
  767. # It's probably important to turn off the depth test, since
  768. # many 2-d objects will be drawn over each other without
  769. # regard to depth position.
  770. # We used to avoid clearing the depth buffer before drawing
  771. # render2d, but nowadays we clear it anyway, since we
  772. # occasionally want to put 3-d geometry under render2d, and
  773. # it's simplest (and seems to be easier on graphics drivers)
  774. # if the 2-d scene has been cleared first.
  775. self.render2d.setDepthTest(0)
  776. self.render2d.setDepthWrite(0)
  777. self.render2d.setMaterialOff(1)
  778. self.render2d.setTwoSided(1)
  779. # The normal 2-d DisplayRegion has an aspect ratio that
  780. # matches the window, but its coordinate system is square.
  781. # This means anything we parent to render2d gets stretched.
  782. # For things where that makes a difference, we set up
  783. # aspect2d, which scales things back to the right aspect
  784. # ratio.
  785. aspectRatio = self.getAspectRatio()
  786. self.aspect2d = self.render2d.attachNewNode(PGTop("aspect2d"))
  787. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  788. self.a2dBackground = self.aspect2d.attachNewNode("a2dBackground")
  789. # It's important to know the bounds of the aspect2d screen.
  790. self.a2dTop = 1.0
  791. self.a2dBottom = -1.0
  792. self.a2dLeft = -aspectRatio
  793. self.a2dRight = aspectRatio
  794. self.a2dTopCenter = self.aspect2d.attachNewNode("a2dTopCenter")
  795. self.a2dBottomCenter = self.aspect2d.attachNewNode("a2dBottomCenter")
  796. self.a2dLeftCenter = self.aspect2d.attachNewNode("a2dLeftCenter")
  797. self.a2dRightCenter = self.aspect2d.attachNewNode("a2dRightCenter")
  798. self.a2dTopLeft = self.aspect2d.attachNewNode("a2dTopLeft")
  799. self.a2dTopRight = self.aspect2d.attachNewNode("a2dTopRight")
  800. self.a2dBottomLeft = self.aspect2d.attachNewNode("a2dBottomLeft")
  801. self.a2dBottomRight = self.aspect2d.attachNewNode("a2dBottomRight")
  802. # Put the nodes in their places
  803. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  804. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  805. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  806. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  807. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  808. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  809. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  810. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  811. # This special root, pixel2d, uses units in pixels that are relative
  812. # to the window. The upperleft corner of the window is (0, 0),
  813. # the lowerleft corner is (xsize, -ysize), in this coordinate system.
  814. xsize, ysize = self.getSize()
  815. self.pixel2d = self.render2d.attachNewNode(PGTop("pixel2d"))
  816. self.pixel2d.setPos(-1, 0, 1)
  817. self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  818. def setupRender2dp(self):
  819. """
  820. Creates a render2d scene graph, the secondary scene graph for
  821. 2-d objects and gui elements that are superimposed over the
  822. 2-d and 3-d geometry in the window.
  823. """
  824. self.render2dp = NodePath('render2dp')
  825. # Set up some overrides to turn off certain properties which
  826. # we probably won't need for 2-d objects.
  827. # It's probably important to turn off the depth test, since
  828. # many 2-d objects will be drawn over each other without
  829. # regard to depth position.
  830. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  831. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  832. self.render2dp.setDepthTest(0)
  833. self.render2dp.setDepthWrite(0)
  834. self.render2dp.setMaterialOff(1)
  835. self.render2dp.setTwoSided(1)
  836. # The normal 2-d DisplayRegion has an aspect ratio that
  837. # matches the window, but its coordinate system is square.
  838. # This means anything we parent to render2d gets stretched.
  839. # For things where that makes a difference, we set up
  840. # aspect2d, which scales things back to the right aspect
  841. # ratio.
  842. aspectRatio = self.getAspectRatio()
  843. self.aspect2dp = self.render2dp.attachNewNode(PGTop("aspect2dp"))
  844. self.aspect2dp.node().setStartSort(16384)
  845. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  846. # It's important to know the bounds of the aspect2d screen.
  847. self.a2dpTop = 1.0
  848. self.a2dpBottom = -1.0
  849. self.a2dpLeft = -aspectRatio
  850. self.a2dpRight = aspectRatio
  851. self.a2dpTopCenter = self.aspect2dp.attachNewNode("a2dpTopCenter")
  852. self.a2dpBottomCenter = self.aspect2dp.attachNewNode("a2dpBottomCenter")
  853. self.a2dpLeftCenter = self.aspect2dp.attachNewNode("a2dpLeftCenter")
  854. self.a2dpRightCenter = self.aspect2dp.attachNewNode("a2dpRightCenter")
  855. self.a2dpTopLeft = self.aspect2dp.attachNewNode("a2dpTopLeft")
  856. self.a2dpTopRight = self.aspect2dp.attachNewNode("a2dpTopRight")
  857. self.a2dpBottomLeft = self.aspect2dp.attachNewNode("a2dpBottomLeft")
  858. self.a2dpBottomRight = self.aspect2dp.attachNewNode("a2dpBottomRight")
  859. # Put the nodes in their places
  860. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  861. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  862. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  863. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  864. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  865. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  866. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  867. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  868. # This special root, pixel2d, uses units in pixels that are relative
  869. # to the window. The upperleft corner of the window is (0, 0),
  870. # the lowerleft corner is (xsize, -ysize), in this coordinate system.
  871. xsize, ysize = self.getSize()
  872. self.pixel2dp = self.render2dp.attachNewNode(PGTop("pixel2dp"))
  873. self.pixel2dp.node().setStartSort(16384)
  874. self.pixel2dp.setPos(-1, 0, 1)
  875. self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  876. def getAspectRatio(self, win = None):
  877. # Returns the actual aspect ratio of the indicated (or main
  878. # window), or the default aspect ratio if there is not yet a
  879. # main window.
  880. # If the config it set, we return that
  881. if self.__configAspectRatio:
  882. return self.__configAspectRatio
  883. aspectRatio = 1
  884. if win == None:
  885. win = self.win
  886. if win != None and win.hasSize():
  887. if(win.getYSize() == 0 or win.getXSize() == 0):
  888. #flub the aspect since we can't actually see anything
  889. return 1
  890. aspectRatio = float(win.getXSize()) / float(win.getYSize())
  891. else:
  892. if win == None or not hasattr(win, "getRequestedProperties"):
  893. props = WindowProperties.getDefault()
  894. else:
  895. props = win.getRequestedProperties()
  896. if not props.hasSize():
  897. props = WindowProperties.getDefault()
  898. if props.hasSize():
  899. aspectRatio = float(props.getXSize()) / float(props.getYSize())
  900. return aspectRatio
  901. def getSize(self, win = None):
  902. # Returns the actual size of the indicated (or main
  903. # window), or the default size if there is not yet a
  904. # main window.
  905. if win == None:
  906. win = self.win
  907. if win != None and win.hasSize():
  908. return win.getXSize(), win.getYSize()
  909. else:
  910. if win == None or not hasattr(win, "getRequestedProperties"):
  911. props = WindowProperties.getDefault()
  912. else:
  913. props = win.getRequestedProperties()
  914. if not props.hasSize():
  915. props = WindowProperties.getDefault()
  916. if props.hasSize():
  917. return props.getXSize(), props.getYSize()
  918. def makeCamera(self, win, sort = 0, scene = None,
  919. displayRegion = (0, 1, 0, 1), stereo = None,
  920. aspectRatio = None, clearDepth = 0, clearColor = None,
  921. lens = None, camName = 'cam', mask = None,
  922. useCamera = None):
  923. """
  924. Makes a new 3-d camera associated with the indicated window,
  925. and creates a display region in the indicated subrectangle.
  926. If stereo is True, then a stereo camera is created, with a
  927. pair of DisplayRegions. If stereo is False, then a standard
  928. camera is created. If stereo is None or omitted, a stereo
  929. camera is created if the window says it can render in stereo.
  930. If useCamera is not None, it is a NodePath to be used as the
  931. camera to apply to the window, rather than creating a new
  932. camera.
  933. """
  934. # self.camera is the parent node of all cameras: a node that
  935. # we can move around to move all cameras as a group.
  936. if self.camera == None:
  937. # We make it a ModelNode with the PTLocal flag, so that
  938. # a wayward flatten operations won't attempt to mangle the
  939. # camera.
  940. self.camera = self.render.attachNewNode(ModelNode('camera'))
  941. self.camera.node().setPreserveTransform(ModelNode.PTLocal)
  942. __builtin__.camera = self.camera
  943. if useCamera:
  944. # Use the existing camera node.
  945. cam = useCamera
  946. camNode = useCamera.node()
  947. assert(isinstance(camNode, Camera))
  948. lens = camNode.getLens()
  949. cam.reparentTo(self.camera)
  950. else:
  951. # Make a new Camera node.
  952. camNode = Camera(camName)
  953. if lens == None:
  954. lens = PerspectiveLens()
  955. if aspectRatio == None:
  956. aspectRatio = self.getAspectRatio(win)
  957. lens.setAspectRatio(aspectRatio)
  958. cam = self.camera.attachNewNode(camNode)
  959. if lens != None:
  960. camNode.setLens(lens)
  961. if scene != None:
  962. camNode.setScene(scene)
  963. if mask != None:
  964. if (isinstance(mask, int)):
  965. mask = BitMask32(mask)
  966. camNode.setCameraMask(mask)
  967. if self.cam == None:
  968. self.cam = cam
  969. self.camNode = camNode
  970. self.camLens = lens
  971. self.camList.append(cam)
  972. # Now, make a DisplayRegion for the camera.
  973. if stereo is not None:
  974. if stereo:
  975. dr = win.makeStereoDisplayRegion(*displayRegion)
  976. else:
  977. dr = win.makeMonoDisplayRegion(*displayRegion)
  978. else:
  979. dr = win.makeDisplayRegion(*displayRegion)
  980. dr.setSort(sort)
  981. # By default, we do not clear 3-d display regions (the entire
  982. # window will be cleared, which is normally sufficient). But
  983. # we will if clearDepth is specified.
  984. if clearDepth:
  985. dr.setClearDepthActive(1)
  986. elif dr.isStereo():
  987. # If it's a stereo DisplayRegion, we clear the right
  988. # channel by default.
  989. dr.getRightEye().setClearDepthActive(1)
  990. if clearColor:
  991. dr.setClearColorActive(1)
  992. dr.setClearColor(clearColor)
  993. dr.setCamera(cam)
  994. return cam
  995. def makeCamera2d(self, win, sort = 10,
  996. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  997. lens = None, cameraName = None):
  998. """
  999. Makes a new camera2d associated with the indicated window, and
  1000. assigns it to render the indicated subrectangle of render2d.
  1001. """
  1002. dr = win.makeMonoDisplayRegion(*displayRegion)
  1003. dr.setSort(sort)
  1004. # Enable clearing of the depth buffer on this new display
  1005. # region (see the comment in setupRender2d, above).
  1006. dr.setClearDepthActive(1)
  1007. # Make any texture reloads on the gui come up immediately.
  1008. dr.setIncompleteRender(False)
  1009. left, right, bottom, top = coords
  1010. # Now make a new Camera node.
  1011. if (cameraName):
  1012. cam2dNode = Camera('cam2d_' + cameraName)
  1013. else:
  1014. cam2dNode = Camera('cam2d')
  1015. if lens == None:
  1016. lens = OrthographicLens()
  1017. lens.setFilmSize(right - left, top - bottom)
  1018. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1019. lens.setNearFar(-1000, 1000)
  1020. cam2dNode.setLens(lens)
  1021. # self.camera2d is the analog of self.camera, although it's
  1022. # not as clear how useful it is.
  1023. if self.camera2d == None:
  1024. self.camera2d = self.render2d.attachNewNode('camera2d')
  1025. camera2d = self.camera2d.attachNewNode(cam2dNode)
  1026. dr.setCamera(camera2d)
  1027. if self.cam2d == None:
  1028. self.cam2d = camera2d
  1029. return camera2d
  1030. def makeCamera2dp(self, win, sort = 20,
  1031. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  1032. lens = None, cameraName = None):
  1033. """
  1034. Makes a new camera2dp associated with the indicated window, and
  1035. assigns it to render the indicated subrectangle of render2dp.
  1036. """
  1037. dr = win.makeMonoDisplayRegion(*displayRegion)
  1038. dr.setSort(sort)
  1039. # Unlike render2d, we don't clear the depth buffer for
  1040. # render2dp. Caveat emptor.
  1041. if hasattr(dr, 'setIncompleteRender'):
  1042. dr.setIncompleteRender(False)
  1043. left, right, bottom, top = coords
  1044. # Now make a new Camera node.
  1045. if (cameraName):
  1046. cam2dNode = Camera('cam2dp_' + cameraName)
  1047. else:
  1048. cam2dNode = Camera('cam2dp')
  1049. if lens == None:
  1050. lens = OrthographicLens()
  1051. lens.setFilmSize(right - left, top - bottom)
  1052. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1053. lens.setNearFar(-1000, 1000)
  1054. cam2dNode.setLens(lens)
  1055. # self.camera2d is the analog of self.camera, although it's
  1056. # not as clear how useful it is.
  1057. if self.camera2dp == None:
  1058. self.camera2dp = self.render2dp.attachNewNode('camera2dp')
  1059. camera2dp = self.camera2dp.attachNewNode(cam2dNode)
  1060. dr.setCamera(camera2dp)
  1061. if self.cam2dp == None:
  1062. self.cam2dp = camera2dp
  1063. return camera2dp
  1064. def setupDataGraph(self):
  1065. """
  1066. Creates the data graph and populates it with the basic input
  1067. devices.
  1068. """
  1069. self.dataRoot = NodePath('dataRoot')
  1070. # Cache the node so we do not ask for it every frame
  1071. self.dataRootNode = self.dataRoot.node()
  1072. self.dataUnused = NodePath('dataUnused')
  1073. # [gjeon] now you can create multiple mouse watchers to support multiple windows
  1074. def setupMouse(self, win, fMultiWin=False):
  1075. """
  1076. Creates the structures necessary to monitor the mouse input,
  1077. using the indicated window. If the mouse has already been set
  1078. up for a different window, those structures are deleted first.
  1079. """
  1080. if not fMultiWin and self.buttonThrowers != None:
  1081. for bt in self.buttonThrowers:
  1082. mw = bt.getParent()
  1083. mk = mw.getParent()
  1084. bt.removeNode()
  1085. mw.removeNode()
  1086. mk.removeNode()
  1087. bts, pws = self.setupMouseCB(win)
  1088. if fMultiWin:
  1089. return bts[0]
  1090. self.buttonThrowers = bts[:]
  1091. self.pointerWatcherNodes = pws[:]
  1092. self.mouseWatcher = self.buttonThrowers[0].getParent()
  1093. self.mouseWatcherNode = self.mouseWatcher.node()
  1094. if self.recorder:
  1095. # If we have a recorder, the mouseWatcher belongs under a
  1096. # special MouseRecorder node, which may intercept the
  1097. # mouse activity.
  1098. mw = self.buttonThrowers[0].getParent()
  1099. mouseRecorder = MouseRecorder('mouse')
  1100. self.recorder.addRecorder(
  1101. 'mouse', mouseRecorder.upcastToRecorderBase())
  1102. np = mw.getParent().attachNewNode(mouseRecorder)
  1103. mw.reparentTo(np)
  1104. # Now we have the main trackball & drive interfaces.
  1105. # useTrackball() and useDrive() switch these in and out; only
  1106. # one is in use at a given time.
  1107. self.trackball = self.dataUnused.attachNewNode(Trackball('trackball'))
  1108. self.drive = self.dataUnused.attachNewNode(DriveInterface('drive'))
  1109. self.mouse2cam = self.dataUnused.attachNewNode(Transform2SG('mouse2cam'))
  1110. self.mouse2cam.node().setNode(self.camera.node())
  1111. # A special ButtonThrower to generate keyboard events and
  1112. # include the time from the OS. This is separate only to
  1113. # support legacy code that did not expect a time parameter; it
  1114. # will eventually be folded into the normal ButtonThrower,
  1115. # above.
  1116. mw = self.buttonThrowers[0].getParent()
  1117. self.timeButtonThrower = mw.attachNewNode(ButtonThrower('timeButtons'))
  1118. self.timeButtonThrower.node().setPrefix('time-')
  1119. self.timeButtonThrower.node().setTimeFlag(1)
  1120. # Tell the gui system about our new mouse watcher.
  1121. self.aspect2d.node().setMouseWatcher(mw.node())
  1122. self.aspect2dp.node().setMouseWatcher(mw.node())
  1123. self.pixel2d.node().setMouseWatcher(mw.node())
  1124. self.pixel2dp.node().setMouseWatcher(mw.node())
  1125. mw.node().addRegion(PGMouseWatcherBackground())
  1126. # [gjeon] this function is seperated from setupMouse to allow multiple mouse watchers
  1127. def setupMouseCB(self, win):
  1128. # For each mouse/keyboard device, we create
  1129. # - MouseAndKeyboard
  1130. # - MouseWatcher
  1131. # - ButtonThrower
  1132. # The ButtonThrowers are stored in a list, self.buttonThrowers.
  1133. # Given a ButtonThrower, one can access the MouseWatcher and
  1134. # MouseAndKeyboard using getParent.
  1135. #
  1136. # The MouseAndKeyboard generates mouse events and mouse
  1137. # button/keyboard events; the MouseWatcher passes them through
  1138. # unchanged when the mouse is not over a 2-d button, and passes
  1139. # nothing through when the mouse *is* over a 2-d button. Therefore,
  1140. # objects that don't want to get events when the mouse is over a
  1141. # button, like the driveInterface, should be parented to
  1142. # MouseWatcher, while objects that want events in all cases, like the
  1143. # chat interface, should be parented to the MouseAndKeyboard.
  1144. buttonThrowers = []
  1145. pointerWatcherNodes = []
  1146. for i in range(win.getNumInputDevices()):
  1147. name = win.getInputDeviceName(i)
  1148. mk = self.dataRoot.attachNewNode(MouseAndKeyboard(win, i, name))
  1149. mw = mk.attachNewNode(MouseWatcher("watcher%s" % (i)))
  1150. mb = mw.node().getModifierButtons()
  1151. mb.addButton(KeyboardButton.shift())
  1152. mb.addButton(KeyboardButton.control())
  1153. mb.addButton(KeyboardButton.alt())
  1154. mb.addButton(KeyboardButton.meta())
  1155. mw.node().setModifierButtons(mb)
  1156. bt = mw.attachNewNode(ButtonThrower("buttons%s" % (i)))
  1157. if (i != 0):
  1158. bt.node().setPrefix('mousedev%s-' % (i))
  1159. mods = ModifierButtons()
  1160. mods.addButton(KeyboardButton.shift())
  1161. mods.addButton(KeyboardButton.control())
  1162. mods.addButton(KeyboardButton.alt())
  1163. mods.addButton(KeyboardButton.meta())
  1164. bt.node().setModifierButtons(mods)
  1165. buttonThrowers.append(bt)
  1166. if (win.hasPointer(i)):
  1167. pointerWatcherNodes.append(mw.node())
  1168. return buttonThrowers, pointerWatcherNodes
  1169. def enableSoftwareMousePointer(self):
  1170. """
  1171. Creates some geometry and parents it to render2d to show
  1172. the currently-known mouse position. Useful if the mouse
  1173. pointer is invisible for some reason.
  1174. """
  1175. mouseViz = render2d.attachNewNode('mouseViz')
  1176. lilsmiley = loader.loadModel('lilsmiley')
  1177. lilsmiley.reparentTo(mouseViz)
  1178. aspectRatio = self.getAspectRatio()
  1179. # Scale the smiley face to 32x32 pixels.
  1180. height = self.win.getYSize()
  1181. lilsmiley.setScale(
  1182. 32.0 / height / aspectRatio,
  1183. 1.0, 32.0 / height)
  1184. self.mouseWatcherNode.setGeometry(mouseViz.node())
  1185. def getAlt(self):
  1186. return self.mouseWatcherNode.getModifierButtons().isDown(
  1187. KeyboardButton.alt())
  1188. def getShift(self):
  1189. return self.mouseWatcherNode.getModifierButtons().isDown(
  1190. KeyboardButton.shift())
  1191. def getControl(self):
  1192. return self.mouseWatcherNode.getModifierButtons().isDown(
  1193. KeyboardButton.control())
  1194. def getMeta(self):
  1195. return self.mouseWatcherNode.getModifierButtons().isDown(
  1196. KeyboardButton.meta())
  1197. def addAngularIntegrator(self):
  1198. if not self.physicsMgrAngular:
  1199. self.physicsMgrAngular = 1
  1200. integrator = AngularEulerIntegrator()
  1201. self.physicsMgr.attachAngularIntegrator(integrator)
  1202. def enableParticles(self):
  1203. if not self.particleMgrEnabled:
  1204. if not self.particleMgr:
  1205. from direct.particles.ParticleManagerGlobal import particleMgr
  1206. self.particleMgr = particleMgr
  1207. self.particleMgr.setFrameStepping(1)
  1208. if not self.physicsMgr:
  1209. from PhysicsManagerGlobal import physicsMgr
  1210. self.physicsMgr = physicsMgr
  1211. integrator = LinearEulerIntegrator()
  1212. self.physicsMgr.attachLinearIntegrator(integrator)
  1213. self.particleMgrEnabled = 1
  1214. self.physicsMgrEnabled = 1
  1215. self.taskMgr.remove('manager-update')
  1216. self.taskMgr.add(self.updateManagers, 'manager-update')
  1217. def disableParticles(self):
  1218. if self.particleMgrEnabled:
  1219. self.particleMgrEnabled = 0
  1220. self.physicsMgrEnabled = 0
  1221. self.taskMgr.remove('manager-update')
  1222. def toggleParticles(self):
  1223. if self.particleMgrEnabled == 0:
  1224. self.enableParticles()
  1225. else:
  1226. self.disableParticles()
  1227. def isParticleMgrEnabled(self):
  1228. return self.particleMgrEnabled
  1229. def isPhysicsMgrEnabled(self):
  1230. return self.physicsMgrEnabled
  1231. def updateManagers(self, state):
  1232. dt = globalClock.getDt()
  1233. if (self.particleMgrEnabled == 1):
  1234. self.particleMgr.doParticles(dt)
  1235. if (self.physicsMgrEnabled == 1):
  1236. self.physicsMgr.doPhysics(dt)
  1237. return Task.cont
  1238. def createStats(self, hostname=None, port=None):
  1239. # You can specify pstats-host in your Config.prc or use ~pstats/~aipstats
  1240. # The default is localhost
  1241. if not self.wantStats:
  1242. return False
  1243. if PStatClient.isConnected():
  1244. PStatClient.disconnect()
  1245. # these default values match the C++ default values
  1246. if hostname is None:
  1247. hostname = ''
  1248. if port is None:
  1249. port = -1
  1250. PStatClient.connect(hostname, port)
  1251. return PStatClient.isConnected()
  1252. def addSfxManager(self, extraSfxManager):
  1253. # keep a list of sfx manager objects to apply settings to,
  1254. # since there may be others in addition to the one we create here
  1255. self.sfxManagerList.append(extraSfxManager)
  1256. newSfxManagerIsValid = (extraSfxManager!=None) and extraSfxManager.isValid()
  1257. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  1258. if newSfxManagerIsValid:
  1259. extraSfxManager.setActive(self.sfxActive)
  1260. def createBaseAudioManagers(self):
  1261. self.sfxPlayer = SfxPlayer.SfxPlayer()
  1262. sfxManager = AudioManager.createAudioManager()
  1263. self.addSfxManager(sfxManager)
  1264. self.musicManager = AudioManager.createAudioManager()
  1265. self.musicManagerIsValid=self.musicManager!=None \
  1266. and self.musicManager.isValid()
  1267. if self.musicManagerIsValid:
  1268. # ensure only 1 midi song is playing at a time:
  1269. self.musicManager.setConcurrentSoundLimit(1)
  1270. self.musicManager.setActive(self.musicActive)
  1271. # enableMusic/enableSoundEffects are meant to be called in response
  1272. # to a user request so sfxActive/musicActive represent how things
  1273. # *should* be, regardless of App/OS/HW state
  1274. def enableMusic(self, bEnableMusic):
  1275. # dont setActive(1) if no audiofocus
  1276. if self.AppHasAudioFocus and self.musicManagerIsValid:
  1277. self.musicManager.setActive(bEnableMusic)
  1278. self.musicActive = bEnableMusic
  1279. if bEnableMusic:
  1280. # This is useful when we want to play different music
  1281. # from what the manager has queued
  1282. messenger.send("MusicEnabled")
  1283. self.notify.debug("Enabling music")
  1284. else:
  1285. self.notify.debug("Disabling music")
  1286. def SetAllSfxEnables(self, bEnabled):
  1287. for i in range(len(self.sfxManagerList)):
  1288. if (self.sfxManagerIsValidList[i]):
  1289. self.sfxManagerList[i].setActive(bEnabled)
  1290. def enableSoundEffects(self, bEnableSoundEffects):
  1291. # dont setActive(1) if no audiofocus
  1292. if self.AppHasAudioFocus or (bEnableSoundEffects==0):
  1293. self.SetAllSfxEnables(bEnableSoundEffects)
  1294. self.sfxActive=bEnableSoundEffects
  1295. if bEnableSoundEffects:
  1296. self.notify.debug("Enabling sound effects")
  1297. else:
  1298. self.notify.debug("Disabling sound effects")
  1299. # enable/disableAllAudio allow a programmable global override-off
  1300. # for current audio settings. they're meant to be called when app
  1301. # loses audio focus (switched out), so we can turn off sound without
  1302. # affecting internal sfxActive/musicActive sound settings, so things
  1303. # come back ok when the app is switched back to
  1304. def disableAllAudio(self):
  1305. self.AppHasAudioFocus = 0
  1306. self.SetAllSfxEnables(0)
  1307. if self.musicManagerIsValid:
  1308. self.musicManager.setActive(0)
  1309. self.notify.debug("Disabling audio")
  1310. def enableAllAudio(self):
  1311. self.AppHasAudioFocus = 1
  1312. self.SetAllSfxEnables(self.sfxActive)
  1313. if self.musicManagerIsValid:
  1314. self.musicManager.setActive(self.musicActive)
  1315. self.notify.debug("Enabling audio")
  1316. # This function should only be in the loader but is here for
  1317. # backwards compatibility. Please do not add code here, add
  1318. # it to the loader.
  1319. def loadSfx(self, name):
  1320. return self.loader.loadSfx(name)
  1321. # This function should only be in the loader but is here for
  1322. # backwards compatibility. Please do not add code here, add
  1323. # it to the loader.
  1324. def loadMusic(self, name):
  1325. return self.loader.loadMusic(name)
  1326. def playSfx(
  1327. self, sfx, looping = 0, interrupt = 1, volume = None,
  1328. time = 0.0, node = None, listener = None, cutoff = None):
  1329. # This goes through a special player for potential localization
  1330. return self.sfxPlayer.playSfx(sfx, looping, interrupt, volume, time, node, listener, cutoff)
  1331. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  1332. if music:
  1333. if volume != None:
  1334. music.setVolume(volume)
  1335. # if interrupt was set to 0, start over even if it's
  1336. # already playing
  1337. if interrupt or (music.status() != AudioSound.PLAYING):
  1338. music.setTime(time)
  1339. music.setLoop(looping)
  1340. music.play()
  1341. def __resetPrevTransform(self, state):
  1342. # Clear out the previous velocity deltas now, after we have
  1343. # rendered (the previous frame). We do this after the render,
  1344. # so that we have a chance to draw a representation of spheres
  1345. # along with their velocities. At the beginning of the frame
  1346. # really means after the command prompt, which allows the user
  1347. # to interactively query these deltas meaningfully.
  1348. PandaNode.resetAllPrevTransform()
  1349. return Task.cont
  1350. def __dataLoop(self, state):
  1351. # traverse the data graph. This reads all the control
  1352. # inputs (from the mouse and keyboard, for instance) and also
  1353. # directly acts upon them (for instance, to move the avatar).
  1354. self.dgTrav.traverse(self.dataRootNode)
  1355. return Task.cont
  1356. def __ivalLoop(self, state):
  1357. # Execute all intervals in the global ivalMgr.
  1358. IntervalManager.ivalMgr.step()
  1359. return Task.cont
  1360. def initShadowTrav(self):
  1361. if not self.shadowTrav:
  1362. # set up the shadow collision traverser
  1363. self.shadowTrav = CollisionTraverser("base.shadowTrav")
  1364. self.shadowTrav.setRespectPrevTransform(False)
  1365. def __shadowCollisionLoop(self, state):
  1366. # run the collision traversal if we have a
  1367. # CollisionTraverser set.
  1368. if self.shadowTrav:
  1369. self.shadowTrav.traverse(self.render)
  1370. return Task.cont
  1371. def __collisionLoop(self, state):
  1372. # run the collision traversal if we have a
  1373. # CollisionTraverser set.
  1374. if self.cTrav:
  1375. self.cTrav.traverse(self.render)
  1376. if self.appTrav:
  1377. self.appTrav.traverse(self.render)
  1378. if self.shadowTrav:
  1379. self.shadowTrav.traverse(self.render)
  1380. messenger.send("collisionLoopFinished")
  1381. return Task.cont
  1382. def __audioLoop(self, state):
  1383. if (self.musicManager != None):
  1384. self.musicManager.update()
  1385. for x in self.sfxManagerList:
  1386. x.update()
  1387. return Task.cont
  1388. def __igLoop(self, state):
  1389. # We render the watch variables for the onScreenDebug as soon
  1390. # as we reasonably can before the renderFrame().
  1391. onScreenDebug.render()
  1392. if self.recorder:
  1393. self.recorder.recordFrame()
  1394. # Finally, render the frame.
  1395. self.graphicsEngine.renderFrame()
  1396. if self.clusterSyncFlag:
  1397. self.graphicsEngine.syncFrame()
  1398. if self.multiClientSleep:
  1399. time.sleep(0)
  1400. # We clear the text buffer for the onScreenDebug as soon
  1401. # as we reasonably can after the renderFrame().
  1402. onScreenDebug.clear()
  1403. if self.recorder:
  1404. self.recorder.playFrame()
  1405. if self.mainWinMinimized:
  1406. # If the main window is minimized, slow down the app a bit
  1407. # by sleeping here in igLoop so we don't use all available
  1408. # CPU needlessly.
  1409. # Note: this isn't quite right if multiple windows are
  1410. # open. We should base this on whether *all* windows are
  1411. # minimized, not just the main window. But it will do for
  1412. # now until someone complains.
  1413. time.sleep(0.1)
  1414. # Lerp stuff needs this event, and it must be generated in
  1415. # C++, not in Python.
  1416. throwNewFrame()
  1417. return Task.cont
  1418. def restart(self):
  1419. self.shutdown()
  1420. # __resetPrevTransform goes at the very beginning of the frame.
  1421. self.taskMgr.add(
  1422. self.__resetPrevTransform, 'resetPrevTransform', priority = -51)
  1423. # give the dataLoop task a reasonably "early" priority,
  1424. # so that it will get run before most tasks
  1425. self.taskMgr.add(self.__dataLoop, 'dataLoop', priority = -50)
  1426. self.__deadInputs = 0
  1427. # spawn the ivalLoop with a later priority, so that it will
  1428. # run after most tasks, but before igLoop.
  1429. self.taskMgr.add(self.__ivalLoop, 'ivalLoop', priority = 20)
  1430. # make the collisionLoop task run before igLoop,
  1431. # but leave enough room for the app to insert tasks
  1432. # between collisionLoop and igLoop
  1433. self.taskMgr.add(self.__collisionLoop, 'collisionLoop', priority = 30)
  1434. # give the igLoop task a reasonably "late" priority,
  1435. # so that it will get run after most tasks
  1436. self.taskMgr.add(self.__igLoop, 'igLoop', priority = 50)
  1437. # the audioLoop updates the positions of 3D sounds.
  1438. # as such, it needs to run after the cull traversal in the igLoop.
  1439. self.taskMgr.add(self.__audioLoop, 'audioLoop', priority = 60)
  1440. self.eventMgr.restart()
  1441. def shutdown(self):
  1442. self.taskMgr.remove('audioLoop')
  1443. self.taskMgr.remove('igLoop')
  1444. self.taskMgr.remove('shadowCollisionLoop')
  1445. self.taskMgr.remove('collisionLoop')
  1446. self.taskMgr.remove('dataLoop')
  1447. self.taskMgr.remove('resetPrevTransform')
  1448. self.taskMgr.remove('ivalLoop')
  1449. self.eventMgr.shutdown()
  1450. def getBackgroundColor(self, win = None):
  1451. """
  1452. Returns the current window background color. This assumes
  1453. the window is set up to clear the color each frame (this is
  1454. the normal setting).
  1455. """
  1456. if win == None:
  1457. win = self.win
  1458. return VBase4(win.getClearColor())
  1459. def setBackgroundColor(self, r = None, g = None, b = None, a = 0.0, win = None):
  1460. """
  1461. Sets the window background color to the indicated value.
  1462. This assumes the window is set up to clear the color each
  1463. frame (this is the normal setting).
  1464. The color may be either a VBase3 or a VBase4, or a 3-component
  1465. tuple, or the individual r, g, b parameters.
  1466. """
  1467. if g != None:
  1468. color = VBase4(r, g, b, a)
  1469. else:
  1470. arg = r
  1471. if isinstance(arg, VBase4):
  1472. color = arg
  1473. else:
  1474. color = VBase4(arg[0], arg[1], arg[2], a)
  1475. if win == None:
  1476. win = self.win
  1477. if win:
  1478. win.setClearColor(color)
  1479. def toggleBackface(self):
  1480. if self.backfaceCullingEnabled:
  1481. self.backfaceCullingOff()
  1482. else:
  1483. self.backfaceCullingOn()
  1484. def backfaceCullingOn(self):
  1485. if not self.backfaceCullingEnabled:
  1486. self.render.setTwoSided(0)
  1487. self.backfaceCullingEnabled = 1
  1488. def backfaceCullingOff(self):
  1489. if self.backfaceCullingEnabled:
  1490. self.render.setTwoSided(1)
  1491. self.backfaceCullingEnabled = 0
  1492. def toggleTexture(self):
  1493. if self.textureEnabled:
  1494. self.textureOff()
  1495. else:
  1496. self.textureOn()
  1497. def textureOn(self):
  1498. self.render.clearTexture()
  1499. self.textureEnabled = 1
  1500. def textureOff(self):
  1501. self.render.setTextureOff(100)
  1502. self.textureEnabled = 0
  1503. def toggleWireframe(self):
  1504. if self.wireframeEnabled:
  1505. self.wireframeOff()
  1506. else:
  1507. self.wireframeOn()
  1508. def wireframeOn(self):
  1509. self.render.setRenderModeWireframe(100)
  1510. self.render.setTwoSided(1)
  1511. self.wireframeEnabled = 1
  1512. def wireframeOff(self):
  1513. self.render.clearRenderMode()
  1514. render.setTwoSided(not self.backfaceCullingEnabled)
  1515. self.wireframeEnabled = 0
  1516. def disableMouse(self):
  1517. """
  1518. Temporarily disable the mouse control of the camera, either
  1519. via the drive interface or the trackball, whichever is
  1520. currently in use.
  1521. """
  1522. # We don't reparent the drive interface or the trackball;
  1523. # whichever one was there before will remain in the data graph
  1524. # and active. This way they won't lose button events while
  1525. # the mouse is disabled. However, we do move the mouse2cam
  1526. # object out of there, so we won't be updating the camera any
  1527. # more.
  1528. if self.mouse2cam:
  1529. self.mouse2cam.reparentTo(self.dataUnused)
  1530. def enableMouse(self):
  1531. """
  1532. Reverse the effect of a previous call to disableMouse().
  1533. useDrive() also implicitly enables the mouse.
  1534. """
  1535. if self.mouse2cam:
  1536. self.mouse2cam.reparentTo(self.mouseInterface)
  1537. def silenceInput(self):
  1538. """
  1539. This is a heavy-handed way of temporarily turning off
  1540. all inputs. Bring them back with reviveInput().
  1541. """
  1542. if not self.__deadInputs:
  1543. self.__deadInputs = taskMgr.remove('dataLoop')
  1544. def reviveInput(self):
  1545. """
  1546. Restores inputs after a previous call to silenceInput.
  1547. """
  1548. if self.__deadInputs:
  1549. self.eventMgr.doEvents()
  1550. self.dgTrav.traverse(base.dataRootNode)
  1551. self.eventMgr.eventQueue.clear()
  1552. self.taskMgr.add(self.__dataLoop, 'dataLoop', priority = -50)
  1553. self.__deadInputs = 0
  1554. def setMouseOnNode(self, newNode):
  1555. if self.mouse2cam:
  1556. self.mouse2cam.node().setNode(newNode)
  1557. def changeMouseInterface(self, changeTo):
  1558. """
  1559. Switch mouse action
  1560. """
  1561. # Get rid of the prior interface:
  1562. self.mouseInterface.reparentTo(self.dataUnused)
  1563. # Update the mouseInterface to point to the drive
  1564. self.mouseInterface = changeTo
  1565. self.mouseInterfaceNode = self.mouseInterface.node()
  1566. # Hookup the drive to the camera.
  1567. self.mouseInterface.reparentTo(self.mouseWatcher)
  1568. if self.mouse2cam:
  1569. self.mouse2cam.reparentTo(self.mouseInterface)
  1570. def useDrive(self):
  1571. """
  1572. Switch mouse action to drive mode
  1573. """
  1574. if self.drive:
  1575. self.changeMouseInterface(self.drive)
  1576. # Set the height to a good eyeheight
  1577. self.mouseInterfaceNode.reset()
  1578. self.mouseInterfaceNode.setZ(4.0)
  1579. def useTrackball(self):
  1580. """
  1581. Switch mouse action to trackball mode
  1582. """
  1583. if self.trackball:
  1584. self.changeMouseInterface(self.trackball)
  1585. def toggleTexMem(self):
  1586. """ Toggles a handy texture memory watcher. See TexMemWatcher
  1587. for more information. """
  1588. if self.texmem and not self.texmem.cleanedUp:
  1589. self.texmem.cleanup()
  1590. self.texmem = None
  1591. return
  1592. from direct.showutil.TexMemWatcher import TexMemWatcher
  1593. self.texmem = TexMemWatcher()
  1594. def toggleShowVertices(self):
  1595. """ Toggles a mode that visualizes vertex density per screen
  1596. area. """
  1597. if self.showVertices:
  1598. # Clean up the old mode.
  1599. self.showVertices.node().setActive(0)
  1600. dr = self.showVertices.node().getDisplayRegion(0)
  1601. base.win.removeDisplayRegion(dr)
  1602. self.showVertices.removeNode()
  1603. self.showVertices = None
  1604. return
  1605. dr = base.win.makeDisplayRegion()
  1606. dr.setSort(1000)
  1607. cam = Camera('showVertices')
  1608. cam.setLens(base.camLens)
  1609. # Set up a funny state to render only vertices.
  1610. override = 100000
  1611. t = NodePath('t')
  1612. t.setColor(1, 0, 1, 0.02, override)
  1613. t.setColorScale(1, 1, 1, 1, override)
  1614. t.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha), override)
  1615. t.setAttrib(RenderModeAttrib.make(RenderModeAttrib.MPoint, 10), override)
  1616. t.setTwoSided(True, override)
  1617. t.setBin('fixed', 0, override)
  1618. t.setDepthTest(False, override)
  1619. t.setDepthWrite(False, override)
  1620. t.setLightOff(override)
  1621. t.setShaderOff(override)
  1622. t.setFogOff(override)
  1623. t.setAttrib(AntialiasAttrib.make(AntialiasAttrib.MNone), override)
  1624. t.setAttrib(RescaleNormalAttrib.make(RescaleNormalAttrib.MNone), override)
  1625. t.setTextureOff(override)
  1626. # Make the spots round, so there's less static in the display.
  1627. # This forces software point generation on many drivers, so
  1628. # it's not on by default.
  1629. if self.config.GetBool('round-show-vertices', False):
  1630. spot = PNMImage(256, 256, 1)
  1631. spot.renderSpot((1, 1, 1, 1), (0, 0, 0, 0), 0.8, 1)
  1632. tex = Texture('spot')
  1633. tex.load(spot)
  1634. tex.setFormat(tex.FAlpha)
  1635. t.setTexture(tex, override)
  1636. t.setAttrib(TexGenAttrib.make(TextureStage.getDefault(), TexGenAttrib.MPointSprite), override)
  1637. cam.setInitialState(t.getState())
  1638. cam.setCameraMask(~PandaNode.getOverallBit())
  1639. self.showVertices = self.cam.attachNewNode(cam)
  1640. dr.setCamera(self.showVertices)
  1641. def oobe(self):
  1642. """
  1643. Enable a special "out-of-body experience" mouse-interface
  1644. mode. This can be used when a "god" camera is needed; it
  1645. moves the camera node out from under its normal node and sets
  1646. the world up in trackball state. Button events are still sent
  1647. to the normal mouse action node (e.g. the DriveInterface), and
  1648. mouse events, if needed, may be sent to the normal node by
  1649. holding down the Control key.
  1650. This is different than useTrackball(), which simply changes
  1651. the existing mouse action to a trackball interface. In fact,
  1652. OOBE mode doesn't care whether useDrive() or useTrackball() is
  1653. in effect; it just temporarily layers a new trackball
  1654. interface on top of whatever the basic interface is. You can
  1655. even switch between useDrive() and useTrackball() while OOBE
  1656. mode is in effect.
  1657. This is a toggle; the second time this function is called, it
  1658. disables the mode.
  1659. """
  1660. # If oobeMode was never set, set it to false and create the
  1661. # structures we need to implement OOBE.
  1662. try:
  1663. self.oobeMode
  1664. except:
  1665. self.oobeMode = 0
  1666. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  1667. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  1668. self.oobeLens = PerspectiveLens()
  1669. self.oobeLens.setAspectRatio(self.getAspectRatio())
  1670. self.oobeLens.setNearFar(0.1, 10000.0)
  1671. self.oobeLens.setMinFov(40)
  1672. self.oobeTrackball = self.dataUnused.attachNewNode(Trackball('oobeTrackball'), 1)
  1673. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  1674. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  1675. self.oobeVis = loader.loadModel('models/misc/camera', okMissing = True)
  1676. if not self.oobeVis:
  1677. self.oobeVis = NodePath('oobeVis')
  1678. self.oobeVis.node().setFinal(1)
  1679. self.oobeVis.setLightOff(1)
  1680. self.oobeCullFrustum = None
  1681. self.oobeCullFrustumVis = None
  1682. self.accept('oobe-down', self.__oobeButton, extraArgs = [''])
  1683. self.accept('oobe-repeat', self.__oobeButton, extraArgs = ['-repeat'])
  1684. self.accept('oobe-up', self.__oobeButton, extraArgs = ['-up'])
  1685. if self.oobeMode:
  1686. # Disable OOBE mode.
  1687. if self.oobeCullFrustum != None:
  1688. # First, disable OOBE cull mode.
  1689. self.oobeCull()
  1690. if self.oobeVis:
  1691. self.oobeVis.reparentTo(self.hidden)
  1692. # Restore the mouse interface node, and remove the oobe
  1693. # trackball from the data path.
  1694. self.mouseInterfaceNode.clearButton(KeyboardButton.control())
  1695. self.oobeTrackball.detachNode()
  1696. bt = self.buttonThrowers[0].node()
  1697. bt.setSpecificFlag(1)
  1698. bt.setButtonDownEvent('')
  1699. bt.setButtonRepeatEvent('')
  1700. bt.setButtonUpEvent('')
  1701. self.cam.reparentTo(self.camera)
  1702. self.camNode.setLens(self.camLens)
  1703. self.oobeCamera.reparentTo(self.hidden)
  1704. self.oobeMode = 0
  1705. bboard.post('oobeEnabled', False)
  1706. else:
  1707. bboard.post('oobeEnabled', True)
  1708. try:
  1709. cameraParent = localAvatar
  1710. except:
  1711. # Make oobeCamera be a sibling of wherever camera is now.
  1712. cameraParent = self.camera.getParent()
  1713. self.oobeCamera.reparentTo(cameraParent)
  1714. self.oobeCamera.clearMat()
  1715. # Make the regular MouseInterface node respond only when
  1716. # the control button is pressed. And the oobe node will
  1717. # respond only when control is *not* pressed.
  1718. self.mouseInterfaceNode.requireButton(KeyboardButton.control(), True)
  1719. self.oobeTrackball.node().requireButton(KeyboardButton.control(), False)
  1720. self.oobeTrackball.reparentTo(self.mouseWatcher)
  1721. # Set our initial OOB position to be just behind the camera.
  1722. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  1723. mat.invertInPlace()
  1724. self.oobeTrackball.node().setMat(mat)
  1725. self.cam.reparentTo(self.oobeCameraTrackball)
  1726. # Temporarily disable button events by routing them
  1727. # through the oobe filters.
  1728. bt = self.buttonThrowers[0].node()
  1729. bt.setSpecificFlag(0)
  1730. bt.setButtonDownEvent('oobe-down')
  1731. bt.setButtonRepeatEvent('oobe-repeat')
  1732. bt.setButtonUpEvent('oobe-up')
  1733. # Don't change the camera lens--keep it with the original lens.
  1734. #self.camNode.setLens(self.oobeLens)
  1735. if self.oobeVis:
  1736. self.oobeVis.reparentTo(self.camera)
  1737. self.oobeMode = 1
  1738. def __oobeButton(self, suffix, button):
  1739. if button.startswith('mouse'):
  1740. # Eat mouse buttons.
  1741. return
  1742. # Transmit other buttons.
  1743. messenger.send(button + suffix)
  1744. def oobeCull(self):
  1745. """
  1746. While in OOBE mode (see above), cull the viewing frustum as if
  1747. it were still attached to our original camera. This allows us
  1748. to visualize the effectiveness of our bounding volumes.
  1749. """
  1750. # First, make sure OOBE mode is enabled.
  1751. try:
  1752. if not self.oobeMode:
  1753. self.oobe()
  1754. except:
  1755. self.oobe()
  1756. if self.oobeCullFrustum == None:
  1757. # Enable OOBE culling.
  1758. pnode = LensNode('oobeCull')
  1759. pnode.setLens(self.camLens)
  1760. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  1761. # Create a visible representation of the frustum.
  1762. geom = self.camLens.makeGeometry()
  1763. if geom != None:
  1764. gn = GeomNode('frustum')
  1765. gn.addGeom(geom)
  1766. self.oobeCullFrustumVis = self.oobeVis.attachNewNode(gn)
  1767. # Tell the camera to cull from here instead of its own
  1768. # origin.
  1769. for cam in base.camList:
  1770. cam.node().setCullCenter(self.oobeCullFrustum)
  1771. else:
  1772. # Disable OOBE culling.
  1773. for cam in base.camList:
  1774. cam.node().setCullCenter(NodePath())
  1775. self.oobeCullFrustum.removeNode()
  1776. self.oobeCullFrustum = None
  1777. if self.oobeCullFrustumVis != None:
  1778. self.oobeCullFrustumVis.removeNode()
  1779. self.oobeCullFrustumVis = None
  1780. def showCameraFrustum(self):
  1781. # Create a visible representation of the frustum.
  1782. self.removeCameraFrustum()
  1783. geom = self.camLens.makeGeometry()
  1784. if geom != None:
  1785. gn = GeomNode('frustum')
  1786. gn.addGeom(geom)
  1787. self.camFrustumVis = self.camera.attachNewNode(gn)
  1788. def removeCameraFrustum(self):
  1789. if self.camFrustumVis:
  1790. self.camFrustumVis.removeNode()
  1791. def screenshot(self, namePrefix = 'screenshot',
  1792. defaultFilename = 1, source = None,
  1793. imageComment=""):
  1794. """ Captures a screenshot from the main window or from the
  1795. specified window or Texture and writes it to a filename in the
  1796. current directory (or to a specified directory).
  1797. If defaultFilename is True, the filename is synthesized by
  1798. appending namePrefix to a default filename suffix (including
  1799. the filename extension) specified in the Config variable
  1800. screenshot-filename. Otherwise, if defaultFilename is False,
  1801. the entire namePrefix is taken to be the filename to write,
  1802. and this string should include a suitable filename extension
  1803. that will be used to determine the type of image file to
  1804. write.
  1805. Normally, the source is a GraphicsWindow, GraphicsBuffer or
  1806. DisplayRegion. If a Texture is supplied instead, it must have
  1807. a ram image (that is, if it was generated by
  1808. makeTextureBuffer() or makeCubeMap(), the parameter toRam
  1809. should have been set true). If it is a cube map texture as
  1810. generated by makeCubeMap(), namePrefix should contain the hash
  1811. mark ('#') character.
  1812. The return value is the filename if successful, or None if
  1813. there is a problem.
  1814. """
  1815. if source == None:
  1816. source = self.win
  1817. if defaultFilename:
  1818. filename = GraphicsOutput.makeScreenshotFilename(namePrefix)
  1819. else:
  1820. filename = Filename(namePrefix)
  1821. if isinstance(source, Texture):
  1822. if source.getZSize() > 1:
  1823. saved = source.write(filename, 0, 0, 1, 0)
  1824. else:
  1825. saved = source.write(filename)
  1826. else:
  1827. saved = source.saveScreenshot(filename, imageComment)
  1828. if saved:
  1829. # Announce to anybody that a screenshot has been taken
  1830. messenger.send('screenshot', [filename])
  1831. return filename
  1832. return None
  1833. def saveCubeMap(self, namePrefix = 'cube_map_#.png',
  1834. defaultFilename = 0, source = None,
  1835. camera = None, size = 128,
  1836. cameraMask = PandaNode.getAllCameraMask()):
  1837. """
  1838. Similar to screenshot(), this sets up a temporary cube map
  1839. Texture which it uses to take a series of six snapshots of the
  1840. current scene, one in each of the six cube map directions.
  1841. This requires rendering a new frame.
  1842. Unlike screenshot(), source may only be a GraphicsWindow,
  1843. GraphicsBuffer, or DisplayRegion; it may not be a Texture.
  1844. camera should be the node to which the cubemap cameras will be
  1845. parented. The default is the camera associated with source,
  1846. if source is a DisplayRegion, or base.camera otherwise.
  1847. The return value is the filename if successful, or None if
  1848. there is a problem.
  1849. """
  1850. if source == None:
  1851. source = base.win
  1852. if camera == None:
  1853. if hasattr(source, "getCamera"):
  1854. camera = source.getCamera()
  1855. if camera == None:
  1856. camera = base.camera
  1857. if hasattr(source, "getWindow"):
  1858. source = source.getWindow()
  1859. rig = NodePath(namePrefix)
  1860. buffer = source.makeCubeMap(namePrefix, size, rig, cameraMask, 1)
  1861. if buffer == None:
  1862. raise StandardError, "Could not make cube map."
  1863. # Set the near and far planes from the default lens.
  1864. lens = rig.find('**/+Camera').node().getLens()
  1865. lens.setNearFar(base.camLens.getNear(), base.camLens.getFar())
  1866. # Now render a frame to fill up the texture.
  1867. rig.reparentTo(camera)
  1868. base.graphicsEngine.openWindows()
  1869. base.graphicsEngine.renderFrame()
  1870. tex = buffer.getTexture()
  1871. saved = self.screenshot(namePrefix = namePrefix,
  1872. defaultFilename = defaultFilename,
  1873. source = tex)
  1874. base.graphicsEngine.removeWindow(buffer)
  1875. rig.removeNode()
  1876. return saved
  1877. def saveSphereMap(self, namePrefix = 'spheremap.png',
  1878. defaultFilename = 0, source = None,
  1879. camera = None, size = 256,
  1880. cameraMask = PandaNode.getAllCameraMask(),
  1881. numVertices = 1000):
  1882. """
  1883. This works much like saveCubeMap(), and uses the graphics
  1884. API's hardware cube-mapping ability to get a 360-degree view
  1885. of the world. But then it converts the six cube map faces
  1886. into a single fisheye texture, suitable for applying as a
  1887. static environment map (sphere map).
  1888. For eye-relative static environment maps, sphere maps are
  1889. often preferable to cube maps because they require only a
  1890. single texture and because they are supported on a broader
  1891. range of hardware.
  1892. The return value is the filename if successful, or None if
  1893. there is a problem.
  1894. """
  1895. if source == None:
  1896. source = base.win
  1897. if camera == None:
  1898. if hasattr(source, "getCamera"):
  1899. camera = source.getCamera()
  1900. if camera == None:
  1901. camera = base.camera
  1902. if hasattr(source, "getWindow"):
  1903. source = source.getWindow()
  1904. # First, make an offscreen buffer to convert the cube map to a
  1905. # sphere map. We make it first so we can guarantee the
  1906. # rendering order for the cube map.
  1907. toSphere = source.makeTextureBuffer(namePrefix, size, size,
  1908. Texture(), 1)
  1909. # Now make the cube map buffer.
  1910. rig = NodePath(namePrefix)
  1911. buffer = toSphere.makeCubeMap(namePrefix, size, rig, cameraMask, 0)
  1912. if buffer == None:
  1913. base.graphicsEngine.removeWindow(toSphere)
  1914. raise StandardError, "Could not make cube map."
  1915. # Set the near and far planes from the default lens.
  1916. lens = rig.find('**/+Camera').node().getLens()
  1917. lens.setNearFar(base.camLens.getNear(), base.camLens.getFar())
  1918. # Set up the scene to convert the cube map. It's just a
  1919. # simple scene, with only the FisheyeMaker object in it.
  1920. dr = toSphere.makeMonoDisplayRegion()
  1921. camNode = Camera('camNode')
  1922. lens = OrthographicLens()
  1923. lens.setFilmSize(2, 2)
  1924. lens.setNearFar(-1000, 1000)
  1925. camNode.setLens(lens)
  1926. root = NodePath('buffer')
  1927. cam = root.attachNewNode(camNode)
  1928. dr.setCamera(cam)
  1929. fm = FisheyeMaker('card')
  1930. fm.setNumVertices(numVertices)
  1931. fm.setSquareInscribed(1, 1.1)
  1932. fm.setReflection(1)
  1933. card = root.attachNewNode(fm.generate())
  1934. card.setTexture(buffer.getTexture())
  1935. # Now render a frame. This will render out the cube map and
  1936. # then apply it to the the card in the toSphere buffer.
  1937. rig.reparentTo(camera)
  1938. base.graphicsEngine.openWindows()
  1939. base.graphicsEngine.renderFrame()
  1940. # One more frame for luck.
  1941. base.graphicsEngine.renderFrame()
  1942. saved = self.screenshot(namePrefix = namePrefix,
  1943. defaultFilename = defaultFilename,
  1944. source = toSphere.getTexture())
  1945. base.graphicsEngine.removeWindow(buffer)
  1946. base.graphicsEngine.removeWindow(toSphere)
  1947. rig.removeNode()
  1948. return saved
  1949. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  1950. format = 'png', sd = 4, source = None):
  1951. """
  1952. Spawn a task to capture a movie using the screenshot function.
  1953. - namePrefix will be used to form output file names (can include
  1954. path information (e.g. '/i/beta/frames/myMovie')
  1955. - duration is the length of the movie in seconds
  1956. - fps is the frame rate of the resulting movie
  1957. - format specifies output file format (e.g. png, bmp)
  1958. - sd specifies number of significant digits for frame count in the
  1959. output file name (e.g. if sd = 4, movie_0001.png)
  1960. - source is the Window, Buffer, DisplayRegion, or Texture from which
  1961. to save the resulting images. The default is the main window.
  1962. """
  1963. globalClock.setMode(ClockObject.MNonRealTime)
  1964. globalClock.setDt(1.0/float(fps))
  1965. t = taskMgr.add(self._movieTask, namePrefix + '_task')
  1966. t.frameIndex = 0 # Frame 0 is not captured.
  1967. t.numFrames = int(duration * fps)
  1968. t.source = source
  1969. t.outputString = namePrefix + '_%0' + `sd` + 'd.' + format
  1970. t.setUponDeath(lambda state: globalClock.setMode(ClockObject.MNormal))
  1971. def _movieTask(self, state):
  1972. if state.frameIndex != 0:
  1973. frameName = state.outputString % state.frameIndex
  1974. self.notify.info("Capturing frame: " + frameName)
  1975. self.screenshot(namePrefix = frameName, defaultFilename = 0,
  1976. source = state.source)
  1977. state.frameIndex += 1
  1978. if state.frameIndex > state.numFrames:
  1979. return Task.done
  1980. else:
  1981. return Task.cont
  1982. def windowEvent(self, win):
  1983. if win == self.win:
  1984. properties = win.getProperties()
  1985. self.notify.info("Got window event: %s" % (repr(properties)))
  1986. if not properties.getOpen():
  1987. # If the user closes the main window, we should exit.
  1988. self.notify.info("User closed main window.")
  1989. if __dev__ and (not config.GetBool('disable-garbage-logging', 1)):
  1990. GarbageReport.b_checkForGarbageLeaks()
  1991. self.userExit()
  1992. if properties.getForeground() and not self.mainWinForeground:
  1993. self.mainWinForeground = 1
  1994. elif not properties.getForeground() and self.mainWinForeground:
  1995. self.mainWinForeground = 0
  1996. if __dev__ and (not config.GetBool('disable-garbage-logging', 1)):
  1997. GarbageReport.b_checkForGarbageLeaks()
  1998. if properties.getMinimized() and not self.mainWinMinimized:
  1999. # If the main window is minimized, throw an event to
  2000. # stop the music.
  2001. self.mainWinMinimized = 1
  2002. messenger.send('PandaPaused')
  2003. elif not properties.getMinimized() and self.mainWinMinimized:
  2004. # If the main window is restored, throw an event to
  2005. # restart the music.
  2006. self.mainWinMinimized = 0
  2007. messenger.send('PandaRestarted')
  2008. # If we have not forced the aspect ratio, let's see if it has
  2009. # changed and update the camera lenses and aspect2d parameters
  2010. if not self.__configAspectRatio:
  2011. aspectRatio = self.getAspectRatio()
  2012. if aspectRatio != self.__oldAspectRatio:
  2013. self.__oldAspectRatio = aspectRatio
  2014. # Fix up some anything that depends on the aspectRatio
  2015. self.camLens.setAspectRatio(aspectRatio)
  2016. if aspectRatio < 1:
  2017. # If the window is TALL, lets expand the top and bottom
  2018. self.aspect2d.setScale(1.0, 1.0, aspectRatio)
  2019. self.a2dTop = 1.0 / aspectRatio
  2020. self.a2dBottom = - 1.0 / aspectRatio
  2021. self.a2dLeft = -1
  2022. self.a2dRight = 1.0
  2023. # Don't forget 2dp
  2024. self.aspect2dp.setScale(1.0, 1.0, aspectRatio)
  2025. self.a2dpTop = 1.0 / aspectRatio
  2026. self.a2dpBottom = - 1.0 / aspectRatio
  2027. self.a2dpLeft = -1
  2028. self.a2dpRight = 1.0
  2029. else:
  2030. # If the window is WIDE, lets expand the left and right
  2031. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2032. self.a2dTop = 1.0
  2033. self.a2dBottom = -1.0
  2034. self.a2dLeft = -aspectRatio
  2035. self.a2dRight = aspectRatio
  2036. # Don't forget 2dp
  2037. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2038. self.a2dpTop = 1.0
  2039. self.a2dpBottom = -1.0
  2040. self.a2dpLeft = -aspectRatio
  2041. self.a2dpRight = aspectRatio
  2042. # Reposition the aspect2d marker nodes
  2043. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  2044. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  2045. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  2046. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  2047. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  2048. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  2049. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  2050. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  2051. # Reposition the aspect2dp marker nodes
  2052. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  2053. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  2054. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  2055. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  2056. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  2057. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  2058. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  2059. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  2060. # If anybody needs to update their GUI, put a callback on this event
  2061. messenger.send("aspectRatioChanged")
  2062. self.pixel2d.setScale(2.0 / win.getXSize(), 1.0, 2.0 / win.getYSize())
  2063. self.pixel2dp.setScale(2.0 / win.getXSize(), 1.0, 2.0 / win.getYSize())
  2064. def userExit(self):
  2065. # The user has requested we exit the program. Deal with this.
  2066. if self.exitFunc:
  2067. self.exitFunc()
  2068. self.notify.info("Exiting ShowBase.")
  2069. self.finalizeExit()
  2070. def finalizeExit(self):
  2071. sys.exit()
  2072. # [gjeon] start wxPyhton
  2073. def startWx(self, fWantWx = 1):
  2074. self.wantWx = fWantWx
  2075. if self.wantWx:
  2076. initAppForGui()
  2077. from direct.showbase import WxGlobal
  2078. taskMgr.remove('wxLoop')
  2079. WxGlobal.spawnWxLoop()
  2080. def startTk(self, fWantTk = 1):
  2081. self.wantTk = fWantTk
  2082. if self.wantTk:
  2083. initAppForGui()
  2084. from direct.showbase import TkGlobal
  2085. taskMgr.remove('tkLoop')
  2086. TkGlobal.spawnTkLoop()
  2087. def startDirect(self, fWantDirect = 1, fWantTk = 1, fWantWx = 0):
  2088. self.startTk(fWantTk)
  2089. self.startWx(fWantWx)
  2090. self.wantDirect = fWantDirect
  2091. if self.wantDirect:
  2092. from direct.directtools import DirectSession
  2093. base.direct.enable()
  2094. else:
  2095. __builtin__.direct = self.direct = None
  2096. def getRepository(self):
  2097. return None
  2098. def __doStartDirect(self):
  2099. if self.__directStarted:
  2100. return
  2101. self.__directStarted = False
  2102. # Start Tk, Wx and DIRECT if specified by Config.prc
  2103. fTk = self.config.GetBool('want-tk', 0)
  2104. fWx = self.config.GetBool('want-wx', 0)
  2105. # Start DIRECT if specified in Config.prc or in cluster mode
  2106. fDirect = (self.config.GetBool('want-directtools', 0) or
  2107. (self.config.GetString("cluster-mode", '') != ''))
  2108. # Set fWantTk to 0 to avoid starting Tk with this call
  2109. self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)
  2110. def run(self):
  2111. # This method runs the TaskManager when self.appRunner is
  2112. # None, which is to say, when we are not running from within a
  2113. # p3d file. When we *are* within a p3d file, the Panda
  2114. # runtime has to be responsible for running the main loop, so
  2115. # we can't allow the application to do it.
  2116. if self.appRunner is None or self.appRunner.dummy or \
  2117. (self.appRunner.interactiveConsole and not self.appRunner.initialAppImport):
  2118. self.taskMgr.run()
  2119. # A class to encapsulate information necessary for multiwindow support.
  2120. class WindowControls:
  2121. def __init__(
  2122. self, win, cam=None, camNode=None, cam2d=None, mouseWatcher=None,
  2123. mouseKeyboard=None, closeCmd=lambda: 0):
  2124. self.win = win
  2125. self.camera = cam
  2126. if camNode is None and cam is not None:
  2127. camNode = cam.node()
  2128. self.camNode = camNode
  2129. self.camera2d = cam2d
  2130. self.mouseWatcher = mouseWatcher
  2131. self.mouseKeyboard = mouseKeyboard
  2132. self.closeCommand = closeCmd
  2133. def __str__(self):
  2134. s = "window = " + str(self.win) + "\n"
  2135. s += "camera = " + str(self.camera) + "\n"
  2136. s += "camNode = " + str(self.camNode) + "\n"
  2137. s += "camera2d = " + str(self.camera2d) + "\n"
  2138. s += "mouseWatcher = " + str(self.mouseWatcher) + "\n"
  2139. s += "mouseAndKeyboard = " + str(self.mouseKeyboard) + "\n"
  2140. return s