ShowBase.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. # This module redefines the builtin import function with one
  2. # that prints out every import it does in a hierarchical form
  3. # Annoying and very noisy, but sometimes useful
  4. # import VerboseImport
  5. from PandaModules import *
  6. from DirectNotifyGlobal import *
  7. from MessengerGlobal import *
  8. from TaskManagerGlobal import *
  9. from EventManagerGlobal import *
  10. from PythonUtil import *
  11. from ParticleManagerGlobal import *
  12. from PhysicsManagerGlobal import *
  13. from IntervalManager import ivalMgr
  14. from InputStateGlobal import inputState
  15. import Task
  16. import EventManager
  17. import math
  18. import sys
  19. import Loader
  20. import time
  21. import ClassicFSM
  22. import State
  23. import DirectObject
  24. import SfxPlayer
  25. if __debug__:
  26. import DeltaProfiler
  27. import OnScreenDebug
  28. __builtins__["FADE_SORT_INDEX"] = 1000
  29. __builtins__["NO_FADE_SORT_INDEX"] = 2000
  30. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  31. # hooks on messages, particularly on window-event. This doesn't
  32. # *seem* to cause anyone any problems.
  33. class ShowBase(DirectObject.DirectObject):
  34. notify = directNotify.newCategory("ShowBase")
  35. def __init__(self):
  36. # Get the dconfig object
  37. self.config = ConfigConfigureGetConfigConfigShowbase
  38. # Setup wantVerifyPdb as soon as reasonable:
  39. Verify.wantVerifyPdb = self.config.GetBool('want-verify-pdb', 0)
  40. self.printEnvDebugInfo()
  41. if self.config.GetBool('use-vfs', 1):
  42. vfs = VirtualFileSystem.getGlobalPtr()
  43. else:
  44. vfs = None
  45. self.nextWindowIndex = 1
  46. # Store dconfig variables
  47. self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
  48. self.musicActive = self.config.GetBool('audio-music-active', 1)
  49. self.wantFog = self.config.GetBool('want-fog', 1)
  50. self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
  51. self.musicManager = None
  52. self.musicManagerIsValid = None
  53. self.sfxManagerList = []
  54. self.sfxManagerIsValidList = []
  55. self.wantStats = self.config.GetBool('want-pstats', 0)
  56. # Fill this in with a function to invoke when the user "exits"
  57. # the program by closing the main window.
  58. self.exitFunc = None
  59. taskMgr.taskTimerVerbose = self.config.GetBool('task-timer-verbose', 0)
  60. taskMgr.extendedExceptions = self.config.GetBool('extended-exceptions', 0)
  61. taskMgr.pStatsTasks = self.config.GetBool('pstats-tasks', 0)
  62. # Set up the TaskManager to reset the PStats clock back
  63. # whenever we resume from a pause. This callback function is
  64. # a little hacky, but we can't call it directly from within
  65. # the TaskManager because he doesn't know about PStats (and
  66. # has to run before libpanda is even loaded).
  67. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  68. fsmRedefine = self.config.GetBool('fsm-redefine', 0)
  69. State.FsmRedefine = fsmRedefine
  70. # Get the default window properties.
  71. winWidth = self.config.GetInt('win-width', 640)
  72. winHeight = self.config.GetInt('win-height', 480)
  73. fullscreen = self.config.GetBool('fullscreen', 0)
  74. undecorated = self.config.GetBool('undecorated', 0)
  75. cursorHidden = self.config.GetBool('cursor-hidden', 0)
  76. windowTitle = self.config.GetString('window-title', 'Panda')
  77. self.defaultWindowProps = WindowProperties()
  78. self.defaultWindowProps.setOpen(1)
  79. self.defaultWindowProps.setSize(winWidth, winHeight)
  80. self.defaultWindowProps.setFullscreen(fullscreen)
  81. self.defaultWindowProps.setUndecorated(undecorated)
  82. self.defaultWindowProps.setCursorHidden(cursorHidden)
  83. self.defaultWindowProps.setTitle(windowTitle)
  84. # If the aspect ratio is 0 or None, it means to infer the
  85. # aspect ratio from the window size.
  86. self.aspectRatio = self.config.GetFloat('aspect-ratio', 0)
  87. # The default background color for a window.
  88. self.winBackgroundColor = VBase4(
  89. self.config.GetFloat('win-background-r', 0.41),
  90. self.config.GetFloat('win-background-g', 0.41),
  91. self.config.GetFloat('win-background-b', 0.41),
  92. 1.0)
  93. self.windowType = self.config.GetString('window-type', 'onscreen')
  94. # base.win is the main, or only window; base.winList is a list of
  95. # *all* windows. Similarly with base.camList.
  96. self.win = None
  97. self.frameRateMeter = None
  98. self.winList = []
  99. self.mainWinMinimized = 0
  100. self.pipe = None
  101. self.pipeList = []
  102. self.mak = None
  103. self.mouse2cam = None
  104. self.mouseInterface = None
  105. self.mouseWatcherNode = None
  106. self.drive = None
  107. self.trackball = None
  108. self.cam = None
  109. self.camList = []
  110. self.camNode = None
  111. self.camLens = None
  112. self.camera = None
  113. self.camera2d = None
  114. # This is used for syncing multiple PCs in a distributed cluster
  115. try:
  116. # Has the cluster sync variable been set externally?
  117. self.clusterSyncFlag = clusterSyncFlag
  118. except NameError:
  119. # Has the clusterSyncFlag been set via a config variable
  120. self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0)
  121. self.hidden = NodePath('hidden')
  122. # We need a graphics engine to manage the actual rendering.
  123. self.graphicsEngine = GraphicsEngine()
  124. self.setupRender()
  125. self.setupRender2d()
  126. self.setupDataGraph()
  127. # This is a placeholder for a CollisionTraverser. If someone
  128. # stores a CollisionTraverser pointer here, we'll traverse it
  129. # in the collisionloop task.
  130. self.shadowTrav = 0
  131. # in the collisionloop task.
  132. self.cTrav = 0
  133. # Ditto for an AppTraverser.
  134. self.appTrav = 0
  135. # This is the DataGraph traverser, which we might as well
  136. # create now.
  137. self.dgTrav = DataGraphTraverser()
  138. # Maybe create a RecorderController to record and/or play back
  139. # the user session.
  140. self.recorder = None
  141. playbackSession = self.config.GetString('playback-session', '')
  142. recordSession = self.config.GetString('record-session', '')
  143. if playbackSession:
  144. self.recorder = RecorderController()
  145. self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession))
  146. elif recordSession:
  147. self.recorder = RecorderController()
  148. self.recorder.beginRecord(Filename.fromOsSpecific(recordSession))
  149. if self.recorder:
  150. # If we're either playing back or recording, pass the
  151. # random seed into the system so each session will have
  152. # the same random seed.
  153. import random, whrandom
  154. seed = self.recorder.getRandomSeed()
  155. random.seed(seed)
  156. whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
  157. # Now that we've set up the window structures, assign an exitfunc.
  158. self.oldexitfunc = getattr(sys, 'exitfunc', None)
  159. sys.exitfunc = self.exitfunc
  160. # Open the default rendering window.
  161. if self.windowType != 'none':
  162. self.openDefaultWindow()
  163. self.loader = Loader.Loader(self)
  164. self.eventMgr = eventMgr
  165. self.messenger = messenger
  166. self.taskMgr = taskMgr
  167. # Particle manager
  168. self.particleMgr = particleMgr
  169. self.particleMgr.setFrameStepping(1)
  170. self.particleMgrEnabled = 0
  171. # Physics manager
  172. self.physicsMgr = physicsMgr
  173. integrator = LinearEulerIntegrator()
  174. self.physicsMgr.attachLinearIntegrator(integrator)
  175. self.physicsMgrEnabled = 0
  176. self.physicsMgrAngular = 0
  177. self.createBaseAudioManagers()
  178. self.createStats()
  179. self.AppHasAudioFocus = 1
  180. __builtins__["base"] = self
  181. __builtins__["render2d"] = self.render2d
  182. __builtins__["aspect2d"] = self.aspect2d
  183. __builtins__["render"] = self.render
  184. __builtins__["hidden"] = self.hidden
  185. __builtins__["camera"] = self.camera
  186. __builtins__["loader"] = self.loader
  187. __builtins__["taskMgr"] = self.taskMgr
  188. __builtins__["eventMgr"] = self.eventMgr
  189. __builtins__["messenger"] = self.messenger
  190. __builtins__["config"] = self.config
  191. __builtins__["run"] = self.run
  192. __builtins__["ostream"] = Notify.out()
  193. __builtins__["directNotify"] = directNotify
  194. __builtins__["globalClock"] = ClockObject.getGlobalClock()
  195. __builtins__["vfs"] = vfs
  196. if __debug__:
  197. __builtins__["deltaProfiler"] = DeltaProfiler.DeltaProfiler("ShowBase")
  198. __builtins__["onScreenDebug"] = OnScreenDebug.OnScreenDebug()
  199. # Now hang a hook on the window-event from Panda. This allows
  200. # us to detect when the user resizes, minimizes, or closes the
  201. # main window.
  202. self.accept('window-event', self.__windowEvent)
  203. # Transition effects (fade, iris, etc)
  204. import Transitions
  205. self.transitions = Transitions.Transitions(self.loader)
  206. # Start Tk and DIRECT if specified by Configrc
  207. fTk = self.config.GetBool('want-tk', 0)
  208. # Start DIRECT if specified in Configrc or in cluster mode
  209. fDirect = (self.config.GetBool('want-directtools', 0) or
  210. (base.config.GetString("cluster-mode", '') != ''))
  211. # Set fWantTk to 0 to avoid starting Tk with this call
  212. self.startDirect(fWantDirect = fDirect, fWantTk = fTk)
  213. # Start IGLOOP
  214. self.restart()
  215. def printEnvDebugInfo(self):
  216. """
  217. Print some information about the environment that we are running
  218. in. Stuff like the model paths and other paths. Feel free to
  219. add stuff to this.
  220. """
  221. if self.config.GetBool('want-env-debug-info', 0):
  222. print "\n\nEnvironment Debug Info {"
  223. print "* model path:", getModelPath()
  224. print "* texture path:", getTexturePath()
  225. print "* sound path:", getSoundPath()
  226. print "}"
  227. def exitfunc(self):
  228. """
  229. This should be assigned to sys.exitfunc to be called just
  230. before Python shutdown. It guarantees that the Panda window
  231. is closed cleanly, so that we free system resources, restore
  232. the desktop and keyboard functionality, etc.
  233. """
  234. self.graphicsEngine.removeAllWindows()
  235. del self.win
  236. del self.winList
  237. del self.pipe
  238. del self.musicManager
  239. del self.sfxManagerList
  240. try:
  241. direct.panel.destroy()
  242. except StandardError:
  243. pass
  244. if self.oldexitfunc:
  245. self.oldexitfunc()
  246. def makeDefaultPipe(self):
  247. """
  248. Creates the default GraphicsPipe, which will be used to make
  249. windows unless otherwise specified.
  250. """
  251. assert(self.pipe == None)
  252. selection = GraphicsPipeSelection.getGlobalPtr()
  253. selection.printPipeTypes()
  254. self.pipe = selection.makeDefaultPipe()
  255. if not self.pipe:
  256. self.notify.error("No graphics pipe is available! Check your Configrc!")
  257. self.notify.info("Default graphics pipe is %s (%s)." % (self.pipe.getInterfaceName(), self.pipe.getType().getName()))
  258. self.pipeList.append(self.pipe)
  259. def makeAllPipes(self):
  260. """
  261. Creates all GraphicsPipes that the system knows about and fill up
  262. self.pipeList with them.
  263. """
  264. shouldPrintPipes = 0
  265. selection = GraphicsPipeSelection.getGlobalPtr()
  266. selection.loadAuxModules()
  267. # First, we should make sure the default pipe exists.
  268. if self.pipe == None:
  269. self.makeDefaultPipe()
  270. # Now go through the list of known pipes, and make each one if
  271. # we don't have one already.
  272. numPipeTypes = selection.getNumPipeTypes()
  273. for i in range(numPipeTypes):
  274. pipeType = selection.getPipeType(i)
  275. # Do we already have a pipe of this type on the list?
  276. # This operation is n-squared, but presumably there won't
  277. # be more than a handful of pipe types, so who cares.
  278. already = 0
  279. for pipe in self.pipeList:
  280. if pipe.getType() == pipeType:
  281. already = 1
  282. if not already:
  283. pipe = selection.makePipe(pipeType)
  284. if pipe:
  285. self.notify.info("Got aux graphics pipe %s (%s)." % (pipe.getInterfaceName(), pipe.getType().getName()))
  286. self.pipeList.append(pipe)
  287. else:
  288. self.notify.info("Could not make graphics pipe %s." % (pipeType.getName()))
  289. def openWindow(self, props = None, pipe = None, gsg = None,
  290. type = None, name = None):
  291. """
  292. Creates a window and adds it to the list of windows that are
  293. to be updated every frame.
  294. """
  295. if pipe == None:
  296. pipe = self.pipe
  297. if pipe == None:
  298. self.makeDefaultPipe()
  299. pipe = self.pipe
  300. if pipe == None:
  301. # We couldn't get a pipe.
  302. return None
  303. if gsg == None:
  304. # If we weren't given a gsg, create a new one just for
  305. # this window.
  306. gsg = self.graphicsEngine.makeGsg(pipe)
  307. if gsg == None:
  308. # Couldn't make a gsg.
  309. return None
  310. if type == None:
  311. type = self.windowType
  312. if props == None:
  313. props = self.defaultWindowProps
  314. if name == None:
  315. name = 'window%s' % (self.nextWindowIndex)
  316. self.nextWindowIndex += 1
  317. # Temporary try .. except for old Pandas.
  318. win = None
  319. try:
  320. if type == 'onscreen':
  321. win = self.graphicsEngine.makeWindow(gsg, name, 0)
  322. elif type == 'offscreen':
  323. win = self.graphicsEngine.makeBuffer(
  324. gsg, name, 0, props.getXSize(), props.getYSize(), 0)
  325. except:
  326. if type == 'onscreen':
  327. win = self.graphicsEngine.makeWindow(pipe, gsg)
  328. elif type == 'offscreen':
  329. win = self.graphicsEngine.makeBuffer(
  330. pipe, gsg, props.getXSize(), props.getYSize(), 0)
  331. if win == None:
  332. # Couldn't create a window!
  333. return None
  334. if hasattr(win, "requestProperties"):
  335. win.requestProperties(props)
  336. # By default, the window is cleared to the background color.
  337. win.setClearColorActive(1)
  338. win.setClearDepthActive(1)
  339. win.setClearColor(self.winBackgroundColor)
  340. win.setClearDepth(1.0)
  341. if self.win == None:
  342. self.win = win
  343. self.winList.append(win)
  344. # Set up a 3-d camera for the window by default.
  345. self.makeCamera(win)
  346. return win
  347. def closeWindow(self, win):
  348. """
  349. Closes the indicated window and removes it from the list of
  350. windows. If it is the main window, clears the main window
  351. pointer to None.
  352. """
  353. # First, remove all of the cameras associated with display
  354. # regions on the window.
  355. numRegions = win.getNumDisplayRegions()
  356. for i in range(numRegions):
  357. dr = win.getDisplayRegion(i)
  358. cam = NodePath(dr.getCamera())
  359. dr.setCamera(NodePath())
  360. if not cam.isEmpty() and cam.node().getNumDisplayRegions() == 0:
  361. # If the camera is used by no other DisplayRegions,
  362. # remove it.
  363. if self.camList.count(cam) != 0:
  364. self.camList.remove(cam)
  365. # Don't throw away self.camera; we want to
  366. # preserve it for reopening the window.
  367. if cam == self.cam:
  368. self.cam = None
  369. cam.removeNode()
  370. # Now we can actually close the window.
  371. self.graphicsEngine.removeWindow(win)
  372. self.winList.remove(win)
  373. if win == self.win:
  374. self.win = None
  375. self.frameRateMeter = None
  376. def openDefaultWindow(self):
  377. # Creates the main window for the first time, without being
  378. # too particular about the kind of graphics API that is
  379. # chosen. The suggested window type from the load-display
  380. # config variable is tried first; if that fails, the first
  381. # window type that can be successfully opened at all is
  382. # accepted. Returns true on success, false otherwise.
  383. #
  384. # This is intended to be called only once, at application
  385. # startup. It is normally called automatically unless
  386. # window-type is configured to 'none'.
  387. self.openMainWindow()
  388. # Give the window a chance to truly open.
  389. self.graphicsEngine.renderFrame()
  390. self.graphicsEngine.renderFrame()
  391. if self.win != None and not self.isMainWindowOpen():
  392. self.notify.info("Window did not open, removing.")
  393. self.closeWindow(self.win)
  394. if self.win == None:
  395. # Try a little harder if the window wouldn't open.
  396. self.makeAllPipes()
  397. while self.win == None and len(self.pipeList) > 1:
  398. self.pipeList.remove(self.pipe)
  399. self.pipe = self.pipeList[0]
  400. self.openMainWindow()
  401. self.graphicsEngine.renderFrame()
  402. self.graphicsEngine.renderFrame()
  403. if self.win != None and not self.isMainWindowOpen():
  404. self.notify.info("Window did not open, removing.")
  405. self.closeWindow(self.win)
  406. if self.win == None:
  407. # This doesn't really need to be an error condition, but I
  408. # figure any app that includes ShowBase really wants to
  409. # have a window open.
  410. self.notify.error("Unable to open '%s' window." % (self.windowType))
  411. return (self.win != None)
  412. def isMainWindowOpen(self):
  413. if self.win != None:
  414. # Temporary try .. except for old Pandas.
  415. try:
  416. valid = self.win.isValid()
  417. except:
  418. valid = self.win.isOpen()
  419. return valid
  420. return 0
  421. def openMainWindow(self):
  422. """
  423. Creates the initial, main window for the application, and sets
  424. up the mouse and render2d structures appropriately for it. If
  425. this method is called a second time, it will close the
  426. previous main window and open a new one, preserving the lens
  427. properties in base.camLens.
  428. The return value is true on success, or false on failure (in
  429. which case base.win may be either None, or the previous,
  430. closed window).
  431. """
  432. success = 1
  433. oldWin = self.win
  434. oldLens = self.camLens
  435. oldClearColorActive = None
  436. if self.win != None:
  437. # Close the previous window.
  438. oldClearColorActive = self.win.getClearColorActive()
  439. oldClearColor = VBase4(self.win.getClearColor())
  440. oldClearDepthActive = self.win.getClearDepthActive()
  441. oldClearDepth = self.win.getClearDepth()
  442. self.closeWindow(self.win)
  443. # Open a new window.
  444. self.openWindow()
  445. if self.win == None:
  446. self.win = oldWin
  447. self.winList.append(oldWin)
  448. success = 0
  449. if self.win != None:
  450. if isinstance(self.win, GraphicsWindow):
  451. self.setupMouse(self.win)
  452. self.makeCamera2d(self.win)
  453. if oldLens != None:
  454. # Restore the previous lens properties.
  455. self.camNode.setLens(oldLens)
  456. self.camLens = oldLens
  457. if oldClearColorActive != None:
  458. # Restore the previous clear properties.
  459. self.win.setClearColorActive(oldClearColorActive)
  460. self.win.setClearColor(oldClearColor)
  461. self.win.setClearDepthActive(oldClearDepthActive)
  462. self.win.setClearDepth(oldClearDepth)
  463. if self.config.GetBool('show-frame-rate-meter', 0):
  464. self.frameRateMeter = FrameRateMeter('frameRateMeter')
  465. self.frameRateMeter.setupLayer(self.win)
  466. return success
  467. def setupRender(self):
  468. """
  469. Creates the render scene graph, the primary scene graph for
  470. rendering 3-d geometry.
  471. """
  472. self.render = NodePath('render')
  473. self.render.setTwoSided(0)
  474. self.backfaceCullingEnabled = 1
  475. self.textureEnabled = 1
  476. self.wireframeEnabled = 0
  477. def setupRender2d(self):
  478. """
  479. Creates the render2d scene graph, the primary scene graph for
  480. 2-d objects and gui elements that are superimposed over the
  481. 3-d geometry in the window.
  482. """
  483. self.render2d = NodePath('render2d')
  484. # Set up some overrides to turn off certain properties which
  485. # we probably won't need for 2-d objects.
  486. # It's probably important to turn off the depth test, since
  487. # many 2-d objects will be drawn over each other without
  488. # regard to depth position.
  489. # We used to avoid clearing the depth buffer before drawing
  490. # render2d, but nowadays we clear it anyway, since we
  491. # occasionally want to put 3-d geometry under render2d, and
  492. # it's simplest (and seems to be easier on graphics drivers)
  493. # if the 2-d scene has been cleared first.
  494. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  495. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  496. #lt = LightTransition.allOff()
  497. self.render2d.node().setAttrib(dt)
  498. self.render2d.node().setAttrib(dw)
  499. #self.render2d.node().setAttrib(lt, 1)
  500. self.render2d.setMaterialOff(1)
  501. self.render2d.setTwoSided(1)
  502. # The normal 2-d layer has an aspect ratio that matches the
  503. # window, but its coordinate system is square. This means
  504. # anything we parent to render2d gets stretched. For things
  505. # where that makes a difference, we set up aspect2d, which
  506. # scales things back to the right aspect ratio.
  507. aspectRatio = self.getAspectRatio()
  508. self.aspect2d = self.render2d.attachNewNode(PGTop("aspect2d"))
  509. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  510. # It's important to know the bounds of the aspect2d screen.
  511. self.a2dTop = 1.0
  512. self.a2dBottom = -1.0
  513. self.a2dLeft = -aspectRatio
  514. self.a2dRight = aspectRatio
  515. def getAspectRatio(self, win = None):
  516. # Returns the actual aspect ratio of the indicated (or main
  517. # window), or the default aspect ratio if there is not yet a
  518. # main window.
  519. if self.aspectRatio:
  520. return self.aspectRatio
  521. aspectRatio = 1
  522. if win == None:
  523. win = self.win
  524. if win != None and win.hasSize():
  525. aspectRatio = float(win.getXSize()) / float(win.getYSize())
  526. else:
  527. props = self.defaultWindowProps
  528. if not props.hasSize():
  529. props = win.getRequestedProperties()
  530. if props.hasSize():
  531. aspectRatio = float(props.getXSize()) / float(props.getYSize())
  532. return aspectRatio
  533. def makeCamera(self, win, chan = None, layer = None, layerSort = 0,
  534. scene = None,
  535. displayRegion = (0, 1, 0, 1), aspectRatio = None):
  536. """
  537. Makes a new 3-d camera associated with the indicated window,
  538. and creates a display region in the indicated subrectangle.
  539. """
  540. if chan == None:
  541. chan = win.getChannel(0)
  542. if layer == None:
  543. # Make a new layer on the window.
  544. layer = chan.makeLayer(layerSort)
  545. if scene == None:
  546. scene = self.render
  547. # And make a display region on this layer of the requested
  548. # area.
  549. dr = layer.makeDisplayRegion(*displayRegion)
  550. # By default, we do not clear 3-d display regions (the entire
  551. # window will be cleared, which is normally sufficient).
  552. if aspectRatio == None:
  553. aspectRatio = self.getAspectRatio()
  554. # Now make a new Camera node.
  555. camNode = Camera('cam')
  556. lens = PerspectiveLens()
  557. lens.setAspectRatio(aspectRatio)
  558. camNode.setLens(lens)
  559. camNode.setScene(scene)
  560. # self.camera is the parent node of all cameras: a node that
  561. # we can move around to move all cameras as a group.
  562. if self.camera == None:
  563. self.camera = self.render.attachNewNode('camera')
  564. __builtins__["camera"] = self.camera
  565. cam = self.camera.attachNewNode(camNode)
  566. dr.setCamera(cam)
  567. if self.cam == None:
  568. self.cam = cam
  569. self.camNode = camNode
  570. self.camLens = lens
  571. self.camList.append(cam)
  572. return cam
  573. def makeCamera2d(self, win, chan = None, layer = None, layerSort = 10,
  574. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1)):
  575. """
  576. Makes a new camera2d associated with the indicated window, and
  577. assigns it to render the indicated subrectangle of render2d.
  578. """
  579. if chan == None:
  580. chan = win.getChannel(0)
  581. if layer == None:
  582. # Make a new layer on the window.
  583. layer = chan.makeLayer(layerSort)
  584. # And make a display region on this layer of the requested
  585. # area.
  586. dr = layer.makeDisplayRegion(*displayRegion)
  587. # Enable clearing of the depth buffer on this new display
  588. # region (see the comment in setupRender2d, above).
  589. dr.setClearDepthActive(1)
  590. left, right, bottom, top = coords
  591. # Now make a new Camera node.
  592. cam2dNode = Camera('cam2d')
  593. lens = OrthographicLens()
  594. lens.setFilmSize(right - left, top - bottom)
  595. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  596. lens.setNearFar(-1000, 1000)
  597. cam2dNode.setLens(lens)
  598. cam2dNode.setScene(self.render2d)
  599. # self.camera2d is the analog of self.camera, although it's
  600. # not as clear how useful it is.
  601. if self.camera2d == None:
  602. self.camera2d = self.render2d.attachNewNode('camera2d')
  603. camera2d = self.camera2d.attachNewNode(cam2dNode)
  604. dr.setCamera(camera2d)
  605. return camera2d
  606. def setupDataGraph(self):
  607. """
  608. Creates the data graph and populates it with the basic input
  609. devices.
  610. """
  611. self.dataRoot = NodePath('dataRoot')
  612. # Cache the node so we do not ask for it every frame
  613. self.dataRootNode = self.dataRoot.node()
  614. self.dataUnused = NodePath('dataUnused')
  615. def setupMouse(self, win):
  616. """
  617. Creates the structures necessary to monitor the mouse input,
  618. using the indicated window. If the mouse has already been set
  619. up for a different window, this changes the mouse to reference
  620. the new window.
  621. """
  622. if self.mak != None:
  623. # The mouse has already been set up; reappropriate it.
  624. self.mak.node().setSource(win, 0)
  625. # Reset the currently-held modifier button list for good
  626. # measure.
  627. bt = self.buttonThrower.node()
  628. mb = ModifierButtons(bt.getModifierButtons())
  629. mb.allButtonsUp()
  630. bt.setModifierButtons(mb)
  631. return
  632. # The mouse has not yet been set up in this application;
  633. # create the mouse structures now.
  634. # We create both a MouseAndKeyboard object and a MouseWatcher object
  635. # for the window. The MouseAndKeyboard generates mouse events and
  636. # mouse button/keyboard events; the MouseWatcher passes them through
  637. # unchanged when the mouse is not over a 2-d button, and passes
  638. # nothing through when the mouse *is* over a 2-d button. Therefore,
  639. # objects that don't want to get events when the mouse is over a
  640. # button, like the driveInterface, should be parented to
  641. # mouseWatcher, while objects that want events in all cases, like the
  642. # chat interface, should be parented to mak.
  643. self.mak = self.dataRoot.attachNewNode(MouseAndKeyboard(win, 0, 'mak'))
  644. self.mouseWatcherNode = MouseWatcher('mouseWatcher')
  645. self.mouseWatcher = self.mak.attachNewNode(self.mouseWatcherNode)
  646. if self.recorder:
  647. # If we have a recorder, the mouseWatcher belongs under a
  648. # special MouseRecorder node, which may intercept the
  649. # mouse activity.
  650. mouseRecorder = MouseRecorder('mouse')
  651. self.recorder.addRecorder('mouse', mouseRecorder.upcastToRecorderBase())
  652. np = self.mak.attachNewNode(mouseRecorder)
  653. self.mouseWatcher.reparentTo(np)
  654. mb = self.mouseWatcherNode.getModifierButtons()
  655. mb.addButton(KeyboardButton.shift())
  656. mb.addButton(KeyboardButton.control())
  657. mb.addButton(KeyboardButton.alt())
  658. self.mouseWatcherNode.setModifierButtons(mb)
  659. # Now we have the main trackball & drive interfaces.
  660. # useTrackball() and useDrive() switch these in and out; only
  661. # one is in use at a given time.
  662. self.trackball = self.dataUnused.attachNewNode(Trackball('trackball'))
  663. self.drive = self.dataUnused.attachNewNode(DriveInterface('drive'))
  664. self.mouse2cam = self.dataUnused.attachNewNode(Transform2SG('mouse2cam'))
  665. self.mouse2cam.node().setNode(self.camera.node())
  666. # The default is trackball mode, which is more convenient for
  667. # ad-hoc development in Python using ShowBase. Applications
  668. # can explicitly call base.useDrive() if they prefer a drive
  669. # interface.
  670. self.mouseInterface = self.trackball
  671. self.useTrackball()
  672. # A ButtonThrower to generate events from the mouse and
  673. # keyboard buttons as they are pressed.
  674. self.buttonThrower = self.mouseWatcher.attachNewNode(ButtonThrower('buttons'))
  675. # Specialize the events based on whether the modifier keys are
  676. # being held down.
  677. mods = ModifierButtons()
  678. mods.addButton(KeyboardButton.shift())
  679. mods.addButton(KeyboardButton.control())
  680. mods.addButton(KeyboardButton.alt())
  681. self.buttonThrower.node().setModifierButtons(mods)
  682. # A special ButtonThrower to generate keyboard events and
  683. # include the time from the OS. This is separate only to
  684. # support legacy code that did not expect a time parameter; it
  685. # will eventually be folded into the normal ButtonThrower,
  686. # above.
  687. self.timeButtonThrower = self.mouseWatcher.attachNewNode(ButtonThrower('timeButtons'))
  688. self.timeButtonThrower.node().setPrefix('time-')
  689. self.timeButtonThrower.node().setTimeFlag(1)
  690. # Tell the gui system about our new mouse watcher.
  691. self.aspect2d.node().setMouseWatcher(self.mouseWatcherNode)
  692. self.mouseWatcherNode.addRegion(PGMouseWatcherBackground())
  693. def enableSoftwareMousePointer(self):
  694. """enableSoftwareMousePointer(self)
  695. Creates some geometry and parents it to render2d to show
  696. the currently-known mouse position. Useful if the mouse
  697. pointer is invisible for some reason.
  698. """
  699. mouseViz = render2d.attachNewNode('mouseViz')
  700. lilsmiley = loader.loadModel('lilsmiley')
  701. lilsmiley.reparentTo(mouseViz)
  702. aspectRatio = self.getAspectRatio()
  703. # Scale the smiley face to 32x32 pixels.
  704. lilsmiley.setScale(32.0 / self.win.getHeight() / aspectRatio,
  705. 1.0, 32.0 / self.win.getHeight())
  706. #self.mouseWatcherNode.setGeometry(mouseViz)
  707. def getAlt(self):
  708. return self.mouseWatcherNode.getModifierButtons().isDown(
  709. KeyboardButton.alt())
  710. def getShift(self):
  711. return self.mouseWatcherNode.getModifierButtons().isDown(
  712. KeyboardButton.shift())
  713. def getControl(self):
  714. return self.mouseWatcherNode.getModifierButtons().isDown(
  715. KeyboardButton.control())
  716. def addAngularIntegrator(self):
  717. """addAngularIntegrator(self)"""
  718. if (self.physicsMgrAngular == 0):
  719. self.physicsMgrAngular = 1
  720. integrator = AngularEulerIntegrator()
  721. self.physicsMgr.attachAngularIntegrator(integrator)
  722. def enableParticles(self):
  723. """enableParticles(self)"""
  724. self.particleMgrEnabled = 1
  725. self.physicsMgrEnabled = 1
  726. self.taskMgr.remove('manager-update')
  727. self.taskMgr.add(self.updateManagers, 'manager-update')
  728. def disableParticles(self):
  729. """enableParticles(self)"""
  730. self.particleMgrEnabled = 0
  731. self.physicsMgrEnabled = 0
  732. self.taskMgr.remove('manager-update')
  733. def toggleParticles(self):
  734. if self.particleMgrEnabled == 0:
  735. self.enableParticles()
  736. else:
  737. self.disableParticles()
  738. def isParticleMgrEnabled(self):
  739. return self.particleMgrEnabled
  740. def isPhysicsMgrEnabled(self):
  741. return self.physicsMgrEnabled
  742. def updateManagers(self, state):
  743. """updateManagers(self)"""
  744. dt = globalClock.getDt()
  745. if (self.particleMgrEnabled == 1):
  746. self.particleMgr.doParticles(dt)
  747. if (self.physicsMgrEnabled == 1):
  748. self.physicsMgr.doPhysics(dt)
  749. return Task.cont
  750. def createStats(self):
  751. # You must specify a pstats-host in your configrc
  752. # The default is localhost
  753. if self.wantStats:
  754. PStatClient.connect()
  755. def addSfxManager(self, extraSfxManager):
  756. # keep a list of sfx manager objects to apply settings to, since there may be others
  757. # in addition to the one we create here
  758. self.sfxManagerList.append(extraSfxManager)
  759. newSfxManagerIsValid = (extraSfxManager!=None) and extraSfxManager.isValid()
  760. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  761. if newSfxManagerIsValid:
  762. extraSfxManager.setActive(self.sfxActive)
  763. def createBaseAudioManagers(self):
  764. self.sfxPlayer = SfxPlayer.SfxPlayer()
  765. sfxManager = AudioManager.createAudioManager()
  766. self.addSfxManager(sfxManager)
  767. self.musicManager = AudioManager.createAudioManager()
  768. self.musicManagerIsValid=self.musicManager!=None \
  769. and self.musicManager.isValid()
  770. if self.musicManagerIsValid:
  771. # ensure only 1 midi song is playing at a time:
  772. self.musicManager.setConcurrentSoundLimit(1)
  773. self.musicManager.setActive(self.musicActive)
  774. # enableMusic/enableSoundEffects are meant to be called in response to a user request
  775. # so sfxActive/musicActive represent how things *should* be, regardless of App/OS/HW state
  776. def enableMusic(self, bEnableMusic):
  777. # dont setActive(1) if no audiofocus
  778. if self.AppHasAudioFocus and self.musicManagerIsValid:
  779. self.musicManager.setActive(bEnableMusic)
  780. self.musicActive = bEnableMusic
  781. if bEnableMusic:
  782. self.notify.debug("Enabling music")
  783. else:
  784. self.notify.debug("Disabling music")
  785. def SetAllSfxEnables(self, bEnabled):
  786. for i in range(len(self.sfxManagerList)):
  787. if (self.sfxManagerIsValidList[i]):
  788. self.sfxManagerList[i].setActive(bEnabled)
  789. def enableSoundEffects(self, bEnableSoundEffects):
  790. # dont setActive(1) if no audiofocus
  791. if self.AppHasAudioFocus or (bEnableSoundEffects==0):
  792. self.SetAllSfxEnables(bEnableSoundEffects)
  793. self.sfxActive=bEnableSoundEffects
  794. if bEnableSoundEffects:
  795. self.notify.debug("Enabling sound effects")
  796. else:
  797. self.notify.debug("Disabling sound effects")
  798. # enable/disableAllAudio allow a programmable global override-off for current audio settings.
  799. # they're meant to be called when app loses audio focus (switched out), so we can turn off sound
  800. # without affecting internal sfxActive/musicActive sound settings, so things
  801. # come back ok when the app is switched back to
  802. def disableAllAudio(self):
  803. self.AppHasAudioFocus = 0
  804. self.SetAllSfxEnables(0)
  805. if self.musicManagerIsValid:
  806. self.musicManager.setActive(0)
  807. self.notify.debug("Disabling audio")
  808. def enableAllAudio(self):
  809. self.AppHasAudioFocus = 1
  810. self.SetAllSfxEnables(self.sfxActive)
  811. if self.musicManagerIsValid:
  812. self.musicManager.setActive(self.musicActive)
  813. self.notify.debug("Enabling audio")
  814. # This function should only be in the loader but is here for
  815. # backwards compatibility. Please do not add code here, add
  816. # it to the loader.
  817. def loadSfx(self, name):
  818. return self.loader.loadSfx(name)
  819. # This function should only be in the loader but is here for
  820. # backwards compatibility. Please do not add code here, add
  821. # it to the loader.
  822. def loadMusic(self, name):
  823. return self.loader.loadMusic(name)
  824. def playSfx(self, sfx, looping = 0, interrupt = 1, volume = None, time = 0.0, node = None):
  825. # This goes through a special player for potential localization
  826. return self.sfxPlayer.playSfx(sfx, looping, interrupt, volume, time, node)
  827. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  828. if music:
  829. if volume != None:
  830. music.setVolume(volume)
  831. # if interrupt was set to 0, start over even if it's already playing
  832. if interrupt or (music.status() != AudioSound.PLAYING):
  833. music.setTime(time)
  834. music.setLoop(looping)
  835. music.play()
  836. def resetPrevTransform(self, state):
  837. # Clear out the previous velocity deltas now, after we have
  838. # rendered (the previous frame). We do this after the render,
  839. # so that we have a chance to draw a representation of spheres
  840. # along with their velocities. At the beginning of the frame
  841. # really means after the command prompt, which allows the user
  842. # to interactively query these deltas meaningfully.
  843. if self.cTrav:
  844. self.cTrav.resetPrevTransform(self.render)
  845. return Task.cont
  846. def dataloop(self, state):
  847. # traverse the data graph. This reads all the control
  848. # inputs (from the mouse and keyboard, for instance) and also
  849. # directly acts upon them (for instance, to move the avatar).
  850. self.dgTrav.traverse(self.dataRootNode)
  851. return Task.cont
  852. def ivalloop(self, state):
  853. # Execute all intervals in the global ivalMgr.
  854. ivalMgr.step()
  855. return Task.cont
  856. def shadowCollisionLoop(self, state):
  857. # run the collision traversal if we have a
  858. # CollisionTraverser set.
  859. if self.shadowTrav:
  860. self.shadowTrav.traverse(self.render)
  861. return Task.cont
  862. def collisionloop(self, state):
  863. # run the collision traversal if we have a
  864. # CollisionTraverser set.
  865. if self.cTrav:
  866. self.cTrav.traverse(self.render)
  867. if self.appTrav:
  868. self.appTrav.traverse(self.render)
  869. return Task.cont
  870. def igloop(self, state):
  871. if __debug__:
  872. # We render the watch variables for the onScreenDebug as soon
  873. # as we reasonably can before the renderFrame().
  874. onScreenDebug.render()
  875. if self.recorder:
  876. self.recorder.recordFrame()
  877. # Finally, render the frame.
  878. self.graphicsEngine.renderFrame()
  879. if self.clusterSyncFlag:
  880. self.graphicsEngine.syncFrame()
  881. if __debug__:
  882. # We clear the text buffer for the onScreenDebug as soon
  883. # as we reasonably can after the renderFrame().
  884. onScreenDebug.clear()
  885. if self.recorder:
  886. self.recorder.playFrame()
  887. if self.mainWinMinimized:
  888. # If the main window is minimized, slow down the app a bit
  889. # by sleeping here in igloop so we don't use all available
  890. # CPU needlessly.
  891. # Note: this isn't quite right if multiple windows are
  892. # open. We should base this on whether *all* windows are
  893. # minimized, not just the main window. But it will do for
  894. # now until someone complains.
  895. time.sleep(0.1)
  896. # Lerp stuff needs this event, and it must be generated in
  897. # C++, not in Python.
  898. throwNewFrame()
  899. return Task.cont
  900. def restart(self):
  901. self.shutdown()
  902. # resetPrevTransform goes at the very beginning of the frame.
  903. self.taskMgr.add(self.resetPrevTransform, 'resetPrevTransform', priority = -51)
  904. # give the dataloop task a reasonably "early" priority,
  905. # so that it will get run before most tasks
  906. self.taskMgr.add(self.dataloop, 'dataloop', priority = -50)
  907. # spawn the ivalloop with a later priority, so that it will
  908. # run after most tasks, but before igloop.
  909. self.taskMgr.add(self.ivalloop, 'ivalloop', priority = 20)
  910. # make the collisionloop task run before igloop,
  911. # but leave enough room for the app to insert tasks
  912. # between collisionloop and igloop
  913. self.taskMgr.add(self.collisionloop, 'collisionloop', priority = 30)
  914. # do the shadowCollisionLoop after the collisionloop and
  915. # befor the igloop:
  916. self.taskMgr.add(self.shadowCollisionLoop, 'shadowCollisionLoop', priority = 34)
  917. # give the igloop task a reasonably "late" priority,
  918. # so that it will get run after most tasks
  919. self.taskMgr.add(self.igloop, 'igloop', priority = 50)
  920. self.eventMgr.restart()
  921. def shutdown(self):
  922. self.taskMgr.remove('igloop')
  923. self.taskMgr.remove('shadowCollisionLoop')
  924. self.taskMgr.remove('collisionloop')
  925. self.taskMgr.remove('dataloop')
  926. self.taskMgr.remove('resetPrevTransform')
  927. self.taskMgr.remove('ivalloop')
  928. self.eventMgr.shutdown()
  929. def getBackgroundColor(self, win = None):
  930. """
  931. Returns the current window background color. This assumes
  932. the window is set up to clear the color each frame (this is
  933. the normal setting).
  934. """
  935. if win == None:
  936. win = self.win
  937. return VBase4(win.getClearColor())
  938. def setBackgroundColor(self, r = None, g = None, b = None, win = None):
  939. """
  940. Sets the window background color to the indicated value.
  941. This assumes the window is set up to clear the color each
  942. frame (this is the normal setting).
  943. The color may be either a VBase3 or a VBase4, or a 3-component
  944. tuple, or the individual r, g, b parameters.
  945. """
  946. if g != None:
  947. color = VBase4(r, g, b, 1.0)
  948. else:
  949. arg = r
  950. color = VBase4(arg[0], arg[1], arg[2], 1.0)
  951. if win == None:
  952. win = self.win
  953. if win:
  954. win.setClearColor(color)
  955. def toggleBackface(self):
  956. if self.backfaceCullingEnabled:
  957. self.backfaceCullingOff()
  958. else:
  959. self.backfaceCullingOn()
  960. def backfaceCullingOn(self):
  961. if not self.backfaceCullingEnabled:
  962. self.render.setTwoSided(0)
  963. self.backfaceCullingEnabled = 1
  964. def backfaceCullingOff(self):
  965. if self.backfaceCullingEnabled:
  966. self.render.setTwoSided(1)
  967. self.backfaceCullingEnabled = 0
  968. def toggleTexture(self):
  969. if self.textureEnabled:
  970. self.textureOff()
  971. else:
  972. self.textureOn()
  973. def textureOn(self):
  974. self.render.clearTexture()
  975. self.textureEnabled = 1
  976. def textureOff(self):
  977. self.render.setTextureOff(100)
  978. self.textureEnabled = 0
  979. def toggleWireframe(self):
  980. if self.wireframeEnabled:
  981. self.wireframeOff()
  982. else:
  983. self.wireframeOn()
  984. def wireframeOn(self):
  985. self.render.setRenderModeWireframe(100);
  986. self.render.setTwoSided(1);
  987. self.wireframeEnabled = 1
  988. def wireframeOff(self):
  989. self.render.clearRenderMode()
  990. render.setTwoSided(not self.backfaceCullingEnabled)
  991. self.wireframeEnabled = 0
  992. def disableMouse(self):
  993. """
  994. Temporarily disable the mouse control of the camera, either
  995. via the drive interface or the trackball, whichever is
  996. currently in use.
  997. """
  998. # We don't reparent the drive interface or the trackball;
  999. # whichever one was there before will remain in the data graph
  1000. # and active. This way they won't lose button events while
  1001. # the mouse is disabled. However, we do move the mouse2cam
  1002. # object out of there, so we won't be updating the camera any
  1003. # more.
  1004. if self.mouse2cam:
  1005. self.mouse2cam.reparentTo(self.dataUnused)
  1006. def enableMouse(self):
  1007. """
  1008. Reverse the effect of a previous call to disableMouse().
  1009. useDrive() also implicitly enables the mouse.
  1010. """
  1011. if self.mouse2cam:
  1012. self.mouse2cam.reparentTo(self.mouseInterface)
  1013. def setMouseOnNode(self, newNode):
  1014. if self.mouse2cam:
  1015. self.mouse2cam.node().setNode(newNode)
  1016. def changeMouseInterface(self, changeTo):
  1017. """
  1018. Switch mouse action
  1019. """
  1020. # Get rid of the prior interface:
  1021. self.mouseInterface.reparentTo(self.dataUnused)
  1022. # Update the mouseInterface to point to the drive
  1023. self.mouseInterface = changeTo
  1024. self.mouseInterfaceNode = self.mouseInterface.node()
  1025. # Hookup the drive to the camera.
  1026. self.mouseInterface.reparentTo(self.mouseWatcher)
  1027. if self.mouse2cam:
  1028. self.mouse2cam.reparentTo(self.mouseInterface)
  1029. def useDrive(self):
  1030. """
  1031. Switch mouse action to drive mode
  1032. """
  1033. if self.drive:
  1034. self.changeMouseInterface(self.drive)
  1035. # Set the height to a good eyeheight
  1036. self.mouseInterfaceNode.reset()
  1037. self.mouseInterfaceNode.setZ(4.0)
  1038. def useTrackball(self):
  1039. """
  1040. Switch mouse action to trackball mode
  1041. """
  1042. if self.trackball:
  1043. self.changeMouseInterface(self.trackball)
  1044. def oobe(self):
  1045. """
  1046. Enable a special "out-of-body experience" mouse-interface
  1047. mode. This can be used when a "god" camera is needed; it
  1048. moves the camera node out from under its normal node and sets
  1049. the world up in trackball state. Button events are still sent
  1050. to the normal mouse action node (e.g. the DriveInterface), and
  1051. mouse events, if needed, may be sent to the normal node by
  1052. holding down the Control key.
  1053. This is different than useTrackball(), which simply changes
  1054. the existing mouse action to a trackball interface. In fact,
  1055. OOBE mode doesn't care whether useDrive() or useTrackball() is
  1056. in effect; it just temporarily layers a new trackball
  1057. interface on top of whatever the basic interface is. You can
  1058. even switch between useDrive() and useTrackball() while OOBE
  1059. mode is in effect.
  1060. This is a toggle; the second time this function is called, it
  1061. disables the mode.
  1062. """
  1063. # If oobeMode was never set, set it to false and create the
  1064. # structures we need to implement OOBE.
  1065. try:
  1066. self.oobeMode
  1067. except:
  1068. self.oobeMode = 0
  1069. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  1070. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  1071. self.oobeLens = PerspectiveLens()
  1072. self.oobeLens.setAspectRatio(self.getAspectRatio())
  1073. self.oobeLens.setNearFar(0.1, 10000.0)
  1074. self.oobeLens.setFov(52.0)
  1075. self.oobeTrackball = self.dataUnused.attachNewNode(Trackball('oobeTrackball'), 1)
  1076. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  1077. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  1078. self.oobeVis = loader.loadModelOnce('models/misc/camera')
  1079. if self.oobeVis:
  1080. self.oobeVis.node().setFinal(1)
  1081. self.oobeCullFrustum = None
  1082. self.oobeCullFrustumVis = None
  1083. if self.oobeMode:
  1084. # Disable OOBE mode.
  1085. if self.oobeCullFrustum != None:
  1086. # First, disable OOBE cull mode.
  1087. self.oobeCull()
  1088. if self.oobeVis:
  1089. self.oobeVis.reparentTo(self.hidden)
  1090. # Restore the mouse interface node.
  1091. #self.mouseInterface.reparentTo(self.mouseWatcher)
  1092. self.oobeTrackball.reparentTo(self.dataUnused)
  1093. self.cam.reparentTo(self.camera)
  1094. self.camNode.setLens(self.camLens)
  1095. self.oobeCamera.reparentTo(self.hidden)
  1096. self.oobeMode = 0
  1097. else:
  1098. # Make oobeCamera be a sibling of wherever camera is now.
  1099. cameraParent = self.camera.getParent()
  1100. self.oobeCamera.reparentTo(cameraParent)
  1101. self.oobeCamera.clearMat()
  1102. # Move aside the current mouse interface node and put the
  1103. # oobeTrackball in its place.
  1104. #self.mouseInterface.reparentTo(self.dataUnused)
  1105. self.oobeTrackball.reparentTo(self.mouseWatcher)
  1106. # Set our initial OOB position to be just behind the camera.
  1107. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  1108. mat.invertInPlace()
  1109. self.oobeTrackball.node().setMat(mat)
  1110. self.cam.reparentTo(self.oobeCameraTrackball)
  1111. self.camNode.setLens(self.oobeLens)
  1112. if self.oobeVis:
  1113. self.oobeVis.reparentTo(self.camera)
  1114. self.oobeMode = 1
  1115. def oobeCull(self):
  1116. """
  1117. While in OOBE mode (see above), cull the viewing frustum as if
  1118. it were still attached to our original camera. This allows us
  1119. to visualize the effectiveness of our bounding volumes.
  1120. """
  1121. # First, make sure OOBE mode is enabled.
  1122. try:
  1123. if not self.oobeMode:
  1124. self.oobe()
  1125. except:
  1126. self.oobe()
  1127. if self.oobeCullFrustum == None:
  1128. # Enable OOBE culling.
  1129. pnode = LensNode('oobeCull')
  1130. pnode.setLens(self.camLens)
  1131. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  1132. # Create a visible representation of the frustum.
  1133. geom = self.camLens.makeGeometry()
  1134. if geom != None:
  1135. gn = GeomNode('frustum')
  1136. gn.addGeom(geom)
  1137. self.oobeCullFrustumVis = self.oobeVis.attachNewNode(gn)
  1138. # Assign each DisplayRegion shared by the camera to use
  1139. # this cull frustum.
  1140. # Support for this is currently absent from Panda.
  1141. ## numDisplayRegions = self.camNode.getNumDisplayRegions()
  1142. ## for d in range(0, numDisplayRegions):
  1143. ## dr = self.camNode.getDisplayRegion(d)
  1144. ## dr.setCullFrustum(pnode)
  1145. else:
  1146. # Disable OOBE culling.
  1147. # Assign each DisplayRegion shared by the camera to use
  1148. # the default cull frustum, the camera itself.
  1149. ## numDisplayRegions = self.camNode.getNumDisplayRegions()
  1150. ## for d in range(0, numDisplayRegions):
  1151. ## dr = self.camNode.getDisplayRegion(d)
  1152. ## dr.setCullFrustum(self.camNode)
  1153. self.oobeCullFrustum.removeNode()
  1154. self.oobeCullFrustum = None
  1155. if self.oobeCullFrustumVis != None:
  1156. self.oobeCullFrustumVis.removeNode()
  1157. self.oobeCullFrustumVis = None
  1158. def screenshot(self, namePrefix='screenshot'):
  1159. filename = self.win.saveScreenshotDefault(namePrefix)
  1160. if filename.empty():
  1161. # The screenshot attempt failed for some reason.
  1162. return 0
  1163. # Announce to anybody that a screenshot has been taken
  1164. messenger.send('screenshot', [filename])
  1165. return 1
  1166. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  1167. format = 'rgb', sd = 4):
  1168. """
  1169. movie(namePrefix = 'movie', duration=1.0, fps=30, format='rgb', sd=4)
  1170. Spawn a task to capture a movie using the takeSnapshot function.
  1171. - namePrefix will be used to form output file names (can include
  1172. path information (e.g. 'I:/beta/frames/myMovie')
  1173. - duration is the length of the movie in seconds
  1174. - fps is the frame rate of the resulting movie
  1175. - format specifies output file format (e.g. rgb, bmp)
  1176. - sd specifies number of significant digits for frame count in the
  1177. output file name (e.g. if sd = 4, movie_0001.rgb)
  1178. """
  1179. globalClock.setMode(ClockObject.MNonRealTime)
  1180. globalClock.setDt(1.0/float(fps))
  1181. t = taskMgr.add(self._movieTask, namePrefix + '_task')
  1182. t.endT = globalClock.getFrameTime() + duration
  1183. t.frameIndex = 1
  1184. t.outputString = namePrefix + '_%0' + `sd` + 'd.' + format
  1185. t.uponDeath = lambda state: globalClock.setMode(ClockObject.MNormal)
  1186. def _movieTask(self, state):
  1187. currT = globalClock.getFrameTime()
  1188. if currT >= state.endT:
  1189. return Task.done
  1190. else:
  1191. frameName = state.outputString % state.frameIndex
  1192. self.notify.info("Capturing frame: " + frameName)
  1193. takeSnapshot(self.win, frameName )
  1194. state.frameIndex += 1
  1195. return Task.cont
  1196. def __windowEvent(self, win):
  1197. if win == self.win:
  1198. properties = win.getProperties()
  1199. self.notify.info("Got window event: %s" % (repr(properties)))
  1200. if not properties.getOpen():
  1201. # If the user closes the main window, we should exit.
  1202. self.notify.info("User closed main window.")
  1203. self.userExit()
  1204. if properties.getMinimized() and not self.mainWinMinimized:
  1205. # If the main window is minimized, throw an event to
  1206. # stop the music.
  1207. self.mainWinMinimized = 1
  1208. messenger.send('PandaPaused')
  1209. elif not properties.getMinimized() and self.mainWinMinimized:
  1210. # If the main window is restored, throw an event to
  1211. # restart the music.
  1212. self.mainWinMinimized = 0
  1213. messenger.send('PandaRestarted')
  1214. def userExit(self):
  1215. # The user has requested we exit the program. Deal with this.
  1216. if self.exitFunc:
  1217. self.exitFunc()
  1218. self.notify.info("Exiting ShowBase.")
  1219. sys.exit()
  1220. def startTk(self, fWantTk = 1):
  1221. self.wantTk = fWantTk
  1222. if self.wantTk:
  1223. import TkGlobal
  1224. taskMgr.remove('tkloop')
  1225. TkGlobal.spawnTkLoop()
  1226. def startDirect(self, fWantDirect = 1, fWantTk = 1):
  1227. self.startTk(fWantTk)
  1228. self.wantDirect = fWantDirect
  1229. if self.wantDirect:
  1230. import DirectSession
  1231. direct.enable()
  1232. else:
  1233. __builtins__["direct"] = self.direct = None
  1234. def run(self):
  1235. self.taskMgr.run()