ShowBase.py 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534
  1. """ This module contains `.ShowBase`, an application framework responsible
  2. for opening a graphical display, setting up input devices and creating
  3. the scene graph.
  4. The simplest way to open a ShowBase instance is to execute this code:
  5. .. code-block:: python
  6. from direct.showbase.ShowBase import ShowBase
  7. base = ShowBase()
  8. base.run()
  9. A common approach is to create your own subclass inheriting from ShowBase.
  10. Built-in global variables
  11. -------------------------
  12. Some key variables used in all Panda3D scripts are actually attributes of the
  13. ShowBase instance. When creating an instance of this class, it will write many
  14. of these variables to the built-in scope of the Python interpreter, so that
  15. they are accessible to any Python module, without the need for extra imports.
  16. For example, the ShowBase instance itself is accessible anywhere through the
  17. :data:`~builtins.base` variable.
  18. While these are handy for prototyping, we do not recommend using them in bigger
  19. projects, as it can make the code confusing to read to other Python developers,
  20. to whom it may not be obvious where these variables are originating.
  21. Refer to the :mod:`builtins` page for a listing of the variables written to the
  22. built-in scope.
  23. """
  24. __all__ = ['ShowBase', 'WindowControls']
  25. # This module redefines the builtin import function with one
  26. # that prints out every import it does in a hierarchical form
  27. # Annoying and very noisy, but sometimes useful
  28. #import VerboseImport
  29. from panda3d.core import (
  30. AntialiasAttrib,
  31. AudioManager,
  32. AudioSound,
  33. BitMask32,
  34. ButtonThrower,
  35. Camera,
  36. ClockObject,
  37. CollisionTraverser,
  38. ColorBlendAttrib,
  39. ConfigPageManager,
  40. ConfigVariableBool,
  41. ConfigVariableDouble,
  42. ConfigVariableFilename,
  43. ConfigVariableInt,
  44. ConfigVariableManager,
  45. ConfigVariableString,
  46. DataGraphTraverser,
  47. DepthTestAttrib,
  48. DepthWriteAttrib,
  49. DriveInterface,
  50. ExecutionEnvironment,
  51. Filename,
  52. FisheyeMaker,
  53. FrameBufferProperties,
  54. FrameRateMeter,
  55. GeomNode,
  56. GraphicsEngine,
  57. GraphicsOutput,
  58. GraphicsPipe,
  59. GraphicsPipeSelection,
  60. GraphicsWindow,
  61. InputDeviceManager,
  62. InputDeviceNode,
  63. KeyboardButton,
  64. LensNode,
  65. Mat4,
  66. ModelNode,
  67. ModifierButtons,
  68. MouseAndKeyboard,
  69. MouseRecorder,
  70. MouseWatcher,
  71. NodePath,
  72. Notify,
  73. OrthographicLens,
  74. PandaNode,
  75. PandaSystem,
  76. PerspectiveLens,
  77. PGMouseWatcherBackground,
  78. PGTop,
  79. PNMImage,
  80. PStatClient,
  81. PythonCallbackObject,
  82. RecorderController,
  83. RenderModeAttrib,
  84. RenderState,
  85. RescaleNormalAttrib,
  86. SceneGraphAnalyzerMeter,
  87. TexGenAttrib,
  88. Texture,
  89. TextureStage,
  90. Thread,
  91. Trackball,
  92. Transform2SG,
  93. TransformState,
  94. TrueClock,
  95. VBase4,
  96. VirtualFileSystem,
  97. WindowProperties,
  98. getModelPath,
  99. )
  100. from panda3d.direct import throw_new_frame, init_app_for_gui
  101. from panda3d.direct import storeAccessibilityShortcutKeys, allowAccessibilityShortcutKeys
  102. from . import DConfig
  103. # Register the extension methods for NodePath.
  104. from direct.extensions_native import NodePath_extensions # pylint: disable=unused-import
  105. # This needs to be available early for DirectGUI imports
  106. import sys
  107. import builtins
  108. builtins.config = DConfig # type: ignore[attr-defined]
  109. from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
  110. from direct.directnotify.Notifier import Notifier
  111. from .MessengerGlobal import messenger
  112. from .BulletinBoardGlobal import bulletinBoard
  113. from direct.task.TaskManagerGlobal import taskMgr
  114. from .JobManagerGlobal import jobMgr
  115. from .EventManagerGlobal import eventMgr
  116. from .PythonUtil import Stack
  117. #from PythonUtil import *
  118. from direct.interval import IntervalManager
  119. from direct.showbase.BufferViewer import BufferViewer
  120. from direct.task import Task
  121. from . import Loader
  122. import time
  123. import atexit
  124. import importlib
  125. from direct.showbase import ExceptionVarDump
  126. from . import DirectObject
  127. from . import SfxPlayer
  128. from typing import ClassVar, Optional
  129. if __debug__:
  130. from direct.showbase import GarbageReport
  131. from direct.directutil import DeltaProfiler
  132. from . import OnScreenDebug
  133. import warnings
  134. @atexit.register
  135. def exitfunc():
  136. if getattr(builtins, 'base', None) is not None:
  137. builtins.base.destroy()
  138. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  139. # hooks on messages, particularly on window-event. This doesn't
  140. # *seem* to cause anyone any problems.
  141. class ShowBase(DirectObject.DirectObject):
  142. #: The deprecated `.DConfig` interface for accessing config variables.
  143. config: ClassVar = DConfig
  144. notify: ClassVar[Notifier] = directNotify.newCategory("ShowBase")
  145. guiItems: ClassVar[dict]
  146. render2d: NodePath
  147. aspect2d: NodePath
  148. pixel2d: NodePath
  149. def __init__(self, fStartDirect=True, windowType=None):
  150. """Opens a window, sets up a 3-D and several 2-D scene graphs, and
  151. everything else needed to render the scene graph to the window.
  152. To prevent a window from being opened, set windowType to the string
  153. 'none' (or 'offscreen' to create an offscreen buffer). If this is not
  154. specified, the default value is taken from the 'window-type'
  155. configuration variable.
  156. This constructor will add various things to the Python builtins scope,
  157. including this instance itself (under the name ``base``).
  158. """
  159. from . import ShowBaseGlobal
  160. #: Set if the want-dev Config.prc variable is enabled. By default, it
  161. #: is set to True except when using Python with the -O flag.
  162. self.__dev__ = ShowBaseGlobal.__dev__
  163. builtins.__dev__ = self.__dev__
  164. logStackDump = (ConfigVariableBool('log-stack-dump', False).value or
  165. ConfigVariableBool('client-log-stack-dump', False).value)
  166. uploadStackDump = ConfigVariableBool('upload-stack-dump', False).value
  167. if logStackDump or uploadStackDump:
  168. ExceptionVarDump.install(logStackDump, uploadStackDump)
  169. if __debug__:
  170. self.__autoGarbageLogging = self.__dev__ and ConfigVariableBool('auto-garbage-logging', False)
  171. #: The directory containing the main Python file of this application.
  172. self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
  173. self.main_dir = self.mainDir
  174. # This contains the global appRunner instance, as imported from
  175. # `.AppRunnerGlobal`. This is deprecated and always None nowadays.
  176. self.appRunner = None
  177. self.app_runner = self.appRunner
  178. #debug running multiplier
  179. self.debugRunningMultiplier = 4
  180. # [gjeon] to disable sticky keys
  181. if ConfigVariableBool('disable-sticky-keys', False):
  182. storeAccessibilityShortcutKeys()
  183. allowAccessibilityShortcutKeys(False)
  184. self.__disabledStickyKeys = True
  185. else:
  186. self.__disabledStickyKeys = False
  187. self.printEnvDebugInfo()
  188. vfs = VirtualFileSystem.getGlobalPtr()
  189. self.nextWindowIndex = 1
  190. self.__directStarted = False
  191. self.__deadInputs = 0
  192. # Store dconfig variables
  193. self.sfxActive = ConfigVariableBool('audio-sfx-active', True).value
  194. self.musicActive = ConfigVariableBool('audio-music-active', True).value
  195. self.wantFog = ConfigVariableBool('want-fog', True).value
  196. self.wantRender2dp = ConfigVariableBool('want-render2dp', True).value
  197. self.screenshotExtension = ConfigVariableString('screenshot-extension', 'jpg').value
  198. self.musicManager = None
  199. self.musicManagerIsValid = None
  200. self.sfxManagerList = []
  201. self.sfxManagerIsValidList = []
  202. self.wantStats = ConfigVariableBool('want-pstats', False).value
  203. self.wantTk = False
  204. self.wantWx = False
  205. self.wantDirect = False
  206. #: Fill this in with a function to invoke when the user "exits"
  207. #: the program by closing the main window.
  208. self.exitFunc = None
  209. #: Add final-exit callbacks to this list. These will be called
  210. #: when sys.exit() is called, after Panda has unloaded, and
  211. #: just before Python is about to shut down.
  212. self.finalExitCallbacks = []
  213. # Set up the TaskManager to reset the PStats clock back
  214. # whenever we resume from a pause. This callback function is
  215. # a little hacky, but we can't call it directly from within
  216. # the TaskManager because he doesn't know about PStats (and
  217. # has to run before libpanda is even loaded).
  218. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  219. if self.__dev__:
  220. self.__setupProfile()
  221. # If the aspect ratio is 0 or None, it means to infer the
  222. # aspect ratio from the window size.
  223. # If you need to know the actual aspect ratio call base.getAspectRatio()
  224. self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).value
  225. # This variable is used to see if the aspect ratio has changed when
  226. # we get a window-event.
  227. self.__oldAspectRatio = None
  228. #: This is set to the value of the window-type config variable, but may
  229. #: optionally be overridden in the Showbase constructor. Should either
  230. #: be 'onscreen' (the default), 'offscreen' or 'none'.
  231. self.windowType = windowType
  232. if self.windowType is None:
  233. self.windowType = ConfigVariableString('window-type', 'onscreen').value
  234. self.requireWindow = ConfigVariableBool('require-window', True).value
  235. #: This is the main, or only window; see `winList` for a list of *all* windows.
  236. self.win = None
  237. self.frameRateMeter = None
  238. self.sceneGraphAnalyzerMeter = None
  239. #: A list of all windows opened via `openWindow()`.
  240. self.winList = []
  241. self.winControls = []
  242. self.mainWinMinimized = 0
  243. self.mainWinForeground = 0
  244. #: Contains the :class:`~panda3d.core.GraphicsPipe` object created by
  245. #: `makeDefaultPipe()`.
  246. self.pipe = None
  247. #: The full list of :class:`~panda3d.core.GraphicsPipe` objects,
  248. #: including any auxiliary pipes. Filled by `makeAllPipes()`.
  249. self.pipeList = []
  250. self.mouse2cam = None
  251. self.buttonThrowers = None
  252. self.mouseWatcher = None
  253. #: The :class:`~panda3d.core.MouseWatcher` object, created by
  254. #: `setupMouse()`.
  255. self.mouseWatcherNode = None
  256. self.pointerWatcherNodes = None
  257. self.mouseInterface = None
  258. self.drive = None
  259. self.trackball = None
  260. self.texmem = None
  261. self.showVertices = None
  262. self.deviceButtonThrowers = []
  263. #: This is a :class:`~panda3d.core.NodePath` pointing to the
  264. #: :class:`~panda3d.core.Camera` object set up for the 3D scene.
  265. #: Usually a child of `camera`.
  266. self.cam = None
  267. #: Same as `cam`, but for the 2D scene graph.
  268. self.cam2d = None
  269. #: Same as `cam2d`, but for the 2D overlay scene graph.
  270. self.cam2dp = None
  271. #: This is the :class:`~panda3d.core.NodePath` that should be used to
  272. #: manipulate the camera. It points at the node to which the default
  273. #: camera (`cam`, `camNode`) is attached.
  274. self.camera = None
  275. #: Same as `camera`, but for the 2D scene graph. Parent of `cam2d`.
  276. self.camera2d = None
  277. #: Same as `camera2d`, but for the 2D overlay scene graph. Parent of
  278. #: `cam2dp`.
  279. self.camera2dp = None
  280. #: A list of all cameras created with `makeCamera()`, including `cam`.
  281. self.camList = []
  282. #: Convenience accessor for base.cam.node(), containing a
  283. #: :class:`~panda3d.core.Camera` object.
  284. self.camNode = None
  285. #: Convenience accessor for base.camNode.get_lens(), containing a
  286. #: :class:`~panda3d.core.Lens` object.
  287. self.camLens = None
  288. self.camFrustumVis = None
  289. self.direct = None
  290. #: This is used to store the wx.Application object used when want-wx is
  291. #: set or `startWx()` is called.
  292. self.wxApp = None
  293. self.wxAppCreated = False
  294. self.tkRoot = None
  295. self.tkRootCreated = False
  296. # This is used for syncing multiple PCs in a distributed cluster
  297. if hasattr(builtins, 'clusterSyncFlag'):
  298. # Has the cluster sync variable been set externally?
  299. self.clusterSyncFlag = builtins.clusterSyncFlag
  300. else:
  301. # Has the clusterSyncFlag been set via a config variable
  302. self.clusterSyncFlag = ConfigVariableBool('cluster-sync', False)
  303. # We've already created aspect2d in ShowBaseGlobal, for the
  304. # benefit of creating DirectGui elements before ShowBase.
  305. self.hidden = ShowBaseGlobal.hidden
  306. #: The global :class:`~panda3d.core.GraphicsEngine`, as returned by
  307. #: GraphicsEngine.getGlobalPtr()
  308. self.graphicsEngine = GraphicsEngine.getGlobalPtr()
  309. self.graphics_engine = self.graphicsEngine
  310. self.setupRender()
  311. self.setupRender2d()
  312. self.setupDataGraph()
  313. if self.wantRender2dp:
  314. self.setupRender2dp()
  315. #: A placeholder for a :class:`~panda3d.core.CollisionTraverser`. If
  316. #: someone stores a CollisionTraverser pointer here, ShowBase will
  317. #: traverse it automatically in the collisionLoop task, so you won't
  318. #: need to call :meth:`~panda3d.core.CollisionTraverser.traverse()`
  319. #: yourself every frame.
  320. self.cTrav = 0
  321. self.shadowTrav = 0
  322. self.cTravStack = Stack()
  323. # Ditto for an AppTraverser.
  324. self.appTrav = 0
  325. # This is the DataGraph traverser, which we might as well
  326. # create now.
  327. self.dgTrav = DataGraphTraverser()
  328. # Maybe create a RecorderController to record and/or play back
  329. # the user session.
  330. self.recorder = None
  331. playbackSession = ConfigVariableFilename('playback-session', '')
  332. recordSession = ConfigVariableFilename('record-session', '')
  333. if not playbackSession.empty():
  334. self.recorder = RecorderController()
  335. self.recorder.beginPlayback(playbackSession.value)
  336. elif not recordSession.empty():
  337. self.recorder = RecorderController()
  338. self.recorder.beginRecord(recordSession.value)
  339. if self.recorder:
  340. # If we're either playing back or recording, pass the
  341. # random seed into the system so each session will have
  342. # the same random seed.
  343. import random #, whrandom
  344. seed = self.recorder.getRandomSeed()
  345. random.seed(seed)
  346. #whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
  347. # For some reason, wx needs to be initialized before the graphics window
  348. if sys.platform == "darwin":
  349. if ConfigVariableBool("want-wx", False):
  350. wx = importlib.import_module('wx')
  351. self.wxApp = wx.App()
  352. # Same goes for Tk, which uses a conflicting NSApplication
  353. if ConfigVariableBool("want-tk", False):
  354. Pmw = importlib.import_module('Pmw')
  355. self.tkRoot = Pmw.initialise()
  356. # Open the default rendering window.
  357. if self.windowType != 'none':
  358. props = WindowProperties.getDefault()
  359. if ConfigVariableBool('read-raw-mice', False):
  360. props.setRawMice(1)
  361. self.openDefaultWindow(startDirect = False, props=props)
  362. # The default is trackball mode, which is more convenient for
  363. # ad-hoc development in Python using ShowBase. Applications
  364. # can explicitly call base.useDrive() if they prefer a drive
  365. # interface.
  366. self.mouseInterface = self.trackball
  367. self.useTrackball()
  368. #: `.Loader.Loader` object.
  369. self.loader = Loader.Loader(self)
  370. self.graphicsEngine.setDefaultLoader(self.loader.loader)
  371. #: The global event manager, as imported from `.EventManagerGlobal`.
  372. self.eventMgr = eventMgr
  373. #: The global messenger, as imported from `.MessengerGlobal`.
  374. self.messenger = messenger
  375. #: The global bulletin board, as imported from `.BulletinBoardGlobal`.
  376. self.bboard = bulletinBoard
  377. #: The global task manager, as imported from `.TaskManagerGlobal`.
  378. self.taskMgr = taskMgr
  379. self.task_mgr = taskMgr
  380. #: The global job manager, as imported from `.JobManagerGlobal`.
  381. self.jobMgr = jobMgr
  382. #: If `enableParticles()` has been called, this is the particle manager
  383. #: as imported from :mod:`direct.particles.ParticleManagerGlobal`.
  384. self.particleMgr = None
  385. self.particleMgrEnabled = 0
  386. #: If `enableParticles()` has been called, this is the physics manager
  387. #: as imported from :mod:`direct.showbase.PhysicsManagerGlobal`.
  388. self.physicsMgr = None
  389. self.physicsMgrEnabled = 0
  390. self.physicsMgrAngular = 0
  391. #: This is the global :class:`~panda3d.core.InputDeviceManager`, which
  392. #: keeps track of connected input devices.
  393. self.devices = InputDeviceManager.getGlobalPtr()
  394. self.__inputDeviceNodes = {}
  395. self.createStats()
  396. self.AppHasAudioFocus = 1
  397. # Get a pointer to Panda's global ClockObject, used for
  398. # synchronizing events between Python and C.
  399. clock = ClockObject.getGlobalClock()
  400. #: This is the global :class:`~panda3d.core.ClockObject`.
  401. self.clock = clock
  402. # Since we have already started up a TaskManager, and probably
  403. # a number of tasks; and since the TaskManager had to use the
  404. # TrueClock to tell time until this moment, make sure the
  405. # globalClock object is exactly in sync with the TrueClock.
  406. trueClock = TrueClock.getGlobalPtr()
  407. clock.setRealTime(trueClock.getShortTime())
  408. clock.tick()
  409. # Now we can make the TaskManager start using the new clock.
  410. taskMgr.globalClock = clock
  411. # client CPU affinity is determined by, in order:
  412. # - client-cpu-affinity-mask config
  413. # - pcalt-# (# is CPU number, 0-based)
  414. # - client-cpu-affinity config
  415. # - auto-single-cpu-affinity config
  416. affinityMask = ConfigVariableInt('client-cpu-affinity-mask', -1).value
  417. if affinityMask != -1:
  418. TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
  419. else:
  420. # this is useful on machines that perform better with each process
  421. # assigned to a single CPU
  422. autoAffinity = ConfigVariableBool('auto-single-cpu-affinity', False).value
  423. affinity = None
  424. if autoAffinity and hasattr(builtins, 'clientIndex'):
  425. affinity = abs(int(builtins.clientIndex))
  426. else:
  427. affinity = ConfigVariableInt('client-cpu-affinity', -1).value
  428. if (affinity in (None, -1)) and autoAffinity:
  429. affinity = 0
  430. if affinity not in (None, -1):
  431. # Windows XP supports a 32-bit affinity mask
  432. TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
  433. # Make sure we're not making more than one ShowBase.
  434. if hasattr(builtins, 'base'):
  435. raise Exception("Attempt to spawn multiple ShowBase instances!")
  436. # DO NOT ADD TO THIS LIST. We're trying to phase out the use of
  437. # built-in variables by ShowBase. Use a Global module if necessary.
  438. builtins.base = self
  439. builtins.render2d = self.render2d
  440. builtins.aspect2d = self.aspect2d
  441. builtins.pixel2d = self.pixel2d
  442. builtins.render = self.render
  443. builtins.hidden = self.hidden
  444. builtins.camera = self.camera
  445. builtins.loader = self.loader
  446. builtins.taskMgr = self.taskMgr
  447. builtins.jobMgr = self.jobMgr
  448. builtins.eventMgr = self.eventMgr
  449. builtins.messenger = self.messenger
  450. builtins.bboard = self.bboard
  451. # Config needs to be defined before ShowBase is constructed
  452. #builtins.config = self.config
  453. builtins.ostream = Notify.out()
  454. builtins.directNotify = directNotify
  455. builtins.giveNotify = giveNotify
  456. builtins.globalClock = clock
  457. builtins.vfs = vfs
  458. builtins.cpMgr = ConfigPageManager.getGlobalPtr()
  459. builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
  460. builtins.pandaSystem = PandaSystem.getGlobalPtr()
  461. if __debug__:
  462. builtins.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
  463. self.onScreenDebug = OnScreenDebug.OnScreenDebug()
  464. builtins.onScreenDebug = self.onScreenDebug
  465. if self.wantRender2dp:
  466. builtins.render2dp = self.render2dp
  467. builtins.aspect2dp = self.aspect2dp
  468. builtins.pixel2dp = self.pixel2dp
  469. # Now add this instance to the ShowBaseGlobal module scope.
  470. builtins.run = ShowBaseGlobal.run
  471. ShowBaseGlobal.base = self
  472. ShowBaseGlobal.__dev__ = self.__dev__
  473. if self.__dev__:
  474. ShowBase.notify.debug('__dev__ == %s' % self.__dev__)
  475. else:
  476. ShowBase.notify.info('__dev__ == %s' % self.__dev__)
  477. self.createBaseAudioManagers()
  478. if self.__dev__ and ConfigVariableBool('track-gui-items', False):
  479. # dict of guiId to gui item, for tracking down leaks
  480. if not hasattr(ShowBase, 'guiItems'):
  481. ShowBase.guiItems = {}
  482. # optionally restore the default gui sounds from 1.7.2 and earlier
  483. if ConfigVariableBool('orig-gui-sounds', False).value:
  484. from direct.gui import DirectGuiGlobals as DGG
  485. DGG.setDefaultClickSound(self.loader.loadSfx("audio/sfx/GUI_click.wav"))
  486. DGG.setDefaultRolloverSound(self.loader.loadSfx("audio/sfx/GUI_rollover.wav"))
  487. # Create a private DirectObject - allowing base.accept for window-event
  488. # as well as allowing ShowBase's default handling of this.
  489. self.__directObject = DirectObject.DirectObject()
  490. # Now hang a hook on the window-event from Panda. This allows
  491. # us to detect when the user resizes, minimizes, or closes the
  492. # main window.
  493. self.__prevWindowProperties = None
  494. self.__directObject.accept('window-event', self.windowEvent)
  495. # Transition effects (fade, iris, etc)
  496. from . import Transitions
  497. #: `.Transitions.Transitions` object.
  498. self.transitions = Transitions.Transitions(self.loader)
  499. if self.win:
  500. # Setup the window controls - handy for multiwindow applications
  501. self.setupWindowControls()
  502. # Client sleep
  503. sleepTime = ConfigVariableDouble('client-sleep', 0.0)
  504. self.clientSleep = 0.0
  505. self.setSleep(sleepTime.value)
  506. # Extra sleep for running 4+ clients on a single machine
  507. # adds a sleep right after the main render in igloop
  508. # tends to even out the frame rate and keeps it from going
  509. # to zero in the out of focus windows
  510. self.multiClientSleep = ConfigVariableBool('multi-sleep', False)
  511. #: Utility for viewing offscreen buffers, see :mod:`.BufferViewer`.
  512. self.bufferViewer = BufferViewer(self.win, self.render2dp if self.wantRender2dp else self.render2d)
  513. if self.windowType != 'none':
  514. if fStartDirect: # [gjeon] if this is False let them start direct manually
  515. self.__doStartDirect()
  516. if ConfigVariableBool('show-tex-mem', False):
  517. if not self.texmem or self.texmem.cleanedUp:
  518. self.toggleTexMem()
  519. taskMgr.finalInit()
  520. # Start IGLOOP
  521. self.restart()
  522. # add a collision traverser via pushCTrav and remove it via popCTrav
  523. # that way the owner of the new cTrav doesn't need to hold onto the
  524. # previous one in order to put it back
  525. def pushCTrav(self, cTrav):
  526. self.cTravStack.push(self.cTrav)
  527. self.cTrav = cTrav
  528. def popCTrav(self):
  529. self.cTrav = self.cTravStack.pop()
  530. def __setupProfile(self):
  531. """ Sets up the Python profiler, if available, according to
  532. some Panda config settings. """
  533. try:
  534. profile = importlib.import_module('profile')
  535. pstats = importlib.import_module('pstats')
  536. except ImportError:
  537. return
  538. profile.Profile.bias = ConfigVariableDouble("profile-bias", 0.0).value
  539. def f8(x):
  540. return ("%" + "8.%df" % ConfigVariableInt("profile-decimals", 3)) % x
  541. pstats.f8 = f8
  542. # temp; see ToonBase.py
  543. def getExitErrorCode(self):
  544. return 0
  545. def printEnvDebugInfo(self):
  546. """Print some information about the environment that we are running
  547. in. Stuff like the model paths and other paths. Feel free to
  548. add stuff to this.
  549. """
  550. if ConfigVariableBool('want-env-debug-info', False):
  551. print("\n\nEnvironment Debug Info {")
  552. print("* model path:")
  553. print(getModelPath())
  554. #print "* dna path:"
  555. #print getDnaPath()
  556. print("}")
  557. def destroy(self):
  558. """ Call this function to destroy the ShowBase and stop all
  559. its tasks, freeing all of the Panda resources. Normally, you
  560. should not need to call it explicitly, as it is bound to the
  561. exitfunc and will be called at application exit time
  562. automatically.
  563. This function is designed to be safe to call multiple times.
  564. When called from a thread other than the main thread, this will create
  565. a task to schedule the destroy on the main thread, and wait for this to
  566. complete.
  567. """
  568. if Thread.getCurrentThread() != Thread.getMainThread():
  569. task = taskMgr.add(self.destroy, extraArgs=[])
  570. task.wait()
  571. return
  572. for cb in self.finalExitCallbacks[:]:
  573. cb()
  574. # Remove the built-in base reference
  575. if getattr(builtins, 'base', None) is self:
  576. del builtins.run
  577. del builtins.base
  578. del builtins.loader
  579. del builtins.taskMgr
  580. ShowBaseGlobal = sys.modules.get('direct.showbase.ShowBaseGlobal', None)
  581. if ShowBaseGlobal:
  582. del ShowBaseGlobal.base
  583. self.aspect2d.node().removeAllChildren()
  584. self.render2d.node().removeAllChildren()
  585. self.aspect2d.reparent_to(self.render2d)
  586. # [gjeon] restore sticky key settings
  587. if self.__disabledStickyKeys:
  588. allowAccessibilityShortcutKeys(True)
  589. self.__disabledStickyKeys = False
  590. self.__directObject.ignoreAll()
  591. self.ignoreAll()
  592. self.shutdown()
  593. if getattr(self, 'musicManager', None):
  594. self.musicManager.shutdown()
  595. self.musicManager = None
  596. for sfxManager in self.sfxManagerList:
  597. sfxManager.shutdown()
  598. self.sfxManagerList = []
  599. if getattr(self, 'loader', None):
  600. self.loader.destroy()
  601. self.loader = None
  602. if getattr(self, 'graphicsEngine', None):
  603. self.graphicsEngine.removeAllWindows()
  604. try:
  605. self.direct.panel.destroy()
  606. except Exception:
  607. pass
  608. self.win = None
  609. self.winList.clear()
  610. self.pipe = None
  611. def makeDefaultPipe(self, printPipeTypes = None):
  612. """
  613. Creates the default GraphicsPipe, which will be used to make
  614. windows unless otherwise specified.
  615. """
  616. assert self.pipe is None
  617. if printPipeTypes is None:
  618. # When the user didn't specify an explicit setting, take the value
  619. # from the config variable. We could just omit the parameter, however
  620. # this way we can keep backward compatibility.
  621. printPipeTypes = ConfigVariableBool("print-pipe-types", True).value
  622. selection = GraphicsPipeSelection.getGlobalPtr()
  623. if printPipeTypes:
  624. selection.printPipeTypes()
  625. self.pipe = selection.makeDefaultPipe()
  626. if not self.pipe:
  627. self.notify.error(
  628. "No graphics pipe is available!\n"
  629. "Your Config.prc file must name at least one valid panda display\n"
  630. "library via load-display or aux-display.")
  631. self.notify.info("Default graphics pipe is %s (%s)." % (
  632. self.pipe.getType().getName(), self.pipe.getInterfaceName()))
  633. self.pipeList.append(self.pipe)
  634. def makeModulePipe(self, moduleName):
  635. """
  636. Returns a GraphicsPipe from the indicated module,
  637. e.g. 'pandagl' or 'pandadx9'. Does not affect base.pipe or
  638. base.pipeList.
  639. :rtype: panda3d.core.GraphicsPipe
  640. """
  641. selection = GraphicsPipeSelection.getGlobalPtr()
  642. return selection.makeModulePipe(moduleName)
  643. def makeAllPipes(self):
  644. """
  645. Creates all GraphicsPipes that the system knows about and fill up
  646. `pipeList` with them.
  647. """
  648. selection = GraphicsPipeSelection.getGlobalPtr()
  649. selection.loadAuxModules()
  650. # First, we should make sure the default pipe exists.
  651. if self.pipe is None:
  652. self.makeDefaultPipe()
  653. # Now go through the list of known pipes, and make each one if
  654. # we don't have one already.
  655. numPipeTypes = selection.getNumPipeTypes()
  656. for i in range(numPipeTypes):
  657. pipeType = selection.getPipeType(i)
  658. # Do we already have a pipe of this type on the list?
  659. # This operation is n-squared, but presumably there won't
  660. # be more than a handful of pipe types, so who cares.
  661. already = 0
  662. for pipe in self.pipeList:
  663. if pipe.getType() == pipeType:
  664. already = 1
  665. if not already:
  666. pipe = selection.makePipe(pipeType)
  667. if pipe:
  668. self.notify.info("Got aux graphics pipe %s (%s)." % (
  669. pipe.getType().getName(), pipe.getInterfaceName()))
  670. self.pipeList.append(pipe)
  671. else:
  672. self.notify.info("Could not make graphics pipe %s." % (
  673. pipeType.getName()))
  674. def openWindow(self, props = None, fbprops = None, pipe = None, gsg = None,
  675. host = None, type = None, name = None, size = None,
  676. aspectRatio = None, makeCamera = True, keepCamera = False,
  677. scene = None, stereo = None, unexposedDraw = None,
  678. callbackWindowDict = None, requireWindow = None):
  679. """
  680. Creates a window and adds it to the list of windows that are
  681. to be updated every frame.
  682. :param props: the :class:`~panda3d.core.WindowProperties` that
  683. describes the window.
  684. :param fbprops: the :class:`~panda3d.core.FrameBufferProperties`
  685. indicating the requested framebuffer properties.
  686. :param type: Either 'onscreen', 'offscreen', or 'none'.
  687. :param keepCamera: If True, the existing base.cam is set up to
  688. render into the new window.
  689. :param makeCamera: If True (and keepCamera is False), a new camera is
  690. set up to render into the new window.
  691. :param unexposedDraw: If not None, it specifies the initial value
  692. of :meth:`~panda3d.core.GraphicsWindow.setUnexposedDraw()`.
  693. :param callbackWindowDict: If not None, a
  694. :class:`~panda3d.core.CallbackGraphicsWindow`
  695. is created instead, which allows the caller
  696. to create the actual window with its own
  697. OpenGL context, and direct Panda's rendering
  698. into that window.
  699. :param requireWindow: If True, the function should raise an exception
  700. if the window fails to open correctly.
  701. :rtype: panda3d.core.GraphicsWindow
  702. """
  703. # Save this lambda here for convenience; we'll use it to call
  704. # down to the underlying _doOpenWindow() with all of the above
  705. # parameters.
  706. func = lambda: self._doOpenWindow(
  707. props = props, fbprops = fbprops, pipe = pipe, gsg = gsg,
  708. host = host, type = type, name = name, size = size,
  709. aspectRatio = aspectRatio, makeCamera = makeCamera,
  710. keepCamera = keepCamera, scene = scene, stereo = stereo,
  711. unexposedDraw = unexposedDraw,
  712. callbackWindowDict = callbackWindowDict)
  713. if self.win:
  714. # If we've already opened a window before, this is just a
  715. # pass-through to _doOpenWindow().
  716. win = func()
  717. self.graphicsEngine.openWindows()
  718. return win
  719. if type is None:
  720. type = self.windowType
  721. if requireWindow is None:
  722. requireWindow = self.requireWindow
  723. win = func()
  724. # Give the window a chance to truly open.
  725. self.graphicsEngine.openWindows()
  726. if win is not None and not win.isValid():
  727. self.notify.info("Window did not open, removing.")
  728. self.closeWindow(win)
  729. win = None
  730. if win is None and pipe is None:
  731. # Try a little harder if the window wouldn't open.
  732. self.makeAllPipes()
  733. try:
  734. self.pipeList.remove(self.pipe)
  735. except ValueError:
  736. pass
  737. while self.win is None and self.pipeList:
  738. self.pipe = self.pipeList[0]
  739. self.notify.info("Trying pipe type %s (%s)" % (
  740. self.pipe.getType(), self.pipe.getInterfaceName()))
  741. win = func()
  742. self.graphicsEngine.openWindows()
  743. if win is not None and not win.isValid():
  744. self.notify.info("Window did not open, removing.")
  745. self.closeWindow(win)
  746. win = None
  747. if win is None:
  748. self.pipeList.remove(self.pipe)
  749. if win is None:
  750. self.notify.warning("Unable to open '%s' window." % (type))
  751. if requireWindow:
  752. # Unless require-window is set to false, it is an
  753. # error not to open a window.
  754. raise Exception('Could not open window.')
  755. else:
  756. self.notify.info("Successfully opened window of type %s (%s)" % (
  757. win.getType(), win.getPipe().getInterfaceName()))
  758. return win
  759. def _doOpenWindow(self, props = None, fbprops = None, pipe = None,
  760. gsg = None, host = None, type = None, name = None,
  761. size = None, aspectRatio = None,
  762. makeCamera = True, keepCamera = False,
  763. scene = None, stereo = None, unexposedDraw = None,
  764. callbackWindowDict = None):
  765. if pipe is None:
  766. pipe = self.pipe
  767. if pipe is None:
  768. self.makeDefaultPipe()
  769. pipe = self.pipe
  770. if pipe is None:
  771. # We couldn't get a pipe.
  772. return None
  773. if isinstance(gsg, GraphicsOutput):
  774. # If the gsg is a window or buffer, it means to use the
  775. # GSG from that buffer.
  776. host = gsg
  777. gsg = gsg.getGsg()
  778. # If we are using DirectX, force a new GSG to be created,
  779. # since at the moment DirectX seems to misbehave if we do
  780. # not do this. This will cause a delay while all textures
  781. # etc. are reloaded, so we should revisit this later if we
  782. # can fix the underlying bug in our DirectX support.
  783. if pipe.getType().getName().startswith('wdx'):
  784. gsg = None
  785. if type is None:
  786. type = self.windowType
  787. if props is None:
  788. props = WindowProperties.getDefault()
  789. if fbprops is None:
  790. fbprops = FrameBufferProperties.getDefault()
  791. if size is not None:
  792. # If we were given an explicit size, use it; otherwise,
  793. # the size from the properties is used.
  794. props = WindowProperties(props)
  795. props.setSize(size[0], size[1])
  796. if name is None:
  797. name = 'window%s' % (self.nextWindowIndex)
  798. self.nextWindowIndex += 1
  799. win = None
  800. flags = GraphicsPipe.BFFbPropsOptional
  801. if type == 'onscreen':
  802. flags = flags | GraphicsPipe.BFRequireWindow
  803. elif type == 'offscreen':
  804. flags = flags | GraphicsPipe.BFRefuseWindow
  805. if callbackWindowDict:
  806. flags = flags | GraphicsPipe.BFRequireCallbackWindow
  807. if host:
  808. assert host.isValid()
  809. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  810. props, flags, host.getGsg(), host)
  811. elif gsg:
  812. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  813. props, flags, gsg)
  814. else:
  815. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  816. props, flags)
  817. if win is None:
  818. # Couldn't create a window!
  819. return None
  820. if unexposedDraw is not None and hasattr(win, 'setUnexposedDraw'):
  821. win.setUnexposedDraw(unexposedDraw)
  822. if callbackWindowDict:
  823. # If we asked for (and received) a CallbackGraphicsWindow,
  824. # we now have to assign the callbacks, before we start
  825. # trying to do anything with the window.
  826. for callbackName in ['Events', 'Properties', 'Render']:
  827. func = callbackWindowDict.get(callbackName, None)
  828. if not func:
  829. continue
  830. setCallbackName = 'set%sCallback' % (callbackName)
  831. setCallback = getattr(win, setCallbackName)
  832. setCallback(PythonCallbackObject(func))
  833. # We also need to set up the mouse/keyboard objects.
  834. for inputName in callbackWindowDict.get('inputDevices', ['mouse']):
  835. win.createInputDevice(inputName)
  836. if hasattr(win, "requestProperties"):
  837. win.requestProperties(props)
  838. mainWindow = False
  839. if self.win is None:
  840. mainWindow = True
  841. self.win = win
  842. if hasattr(self, 'bufferViewer'):
  843. self.bufferViewer.win = win
  844. self.winList.append(win)
  845. # Set up a 3-d camera for the window by default.
  846. if keepCamera:
  847. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  848. stereo = stereo, useCamera = self.cam)
  849. elif makeCamera:
  850. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  851. stereo = stereo)
  852. messenger.send('open_window', [win, mainWindow])
  853. if mainWindow:
  854. messenger.send('open_main_window')
  855. return win
  856. def closeWindow(self, win, keepCamera = False, removeWindow = True):
  857. """
  858. Closes the indicated window and removes it from the list of
  859. windows. If it is the main window, clears the main window
  860. pointer to None.
  861. """
  862. win.setActive(False)
  863. # First, remove all of the cameras associated with display
  864. # regions on the window.
  865. numRegions = win.getNumDisplayRegions()
  866. for i in range(numRegions):
  867. dr = win.getDisplayRegion(i)
  868. # [gjeon] remove drc in base.direct.drList
  869. if self.direct is not None:
  870. for drc in self.direct.drList:
  871. if drc.cam == dr.getCamera():
  872. self.direct.drList.displayRegionList.remove(drc)
  873. break
  874. cam = NodePath(dr.getCamera())
  875. dr.setCamera(NodePath())
  876. if not cam.isEmpty() and \
  877. cam.node().getNumDisplayRegions() == 0 and \
  878. not keepCamera:
  879. # If the camera is used by no other DisplayRegions,
  880. # remove it.
  881. if self.camList.count(cam) != 0:
  882. self.camList.remove(cam)
  883. # Don't throw away self.camera; we want to
  884. # preserve it for reopening the window.
  885. if cam == self.cam:
  886. self.cam = None
  887. if cam == self.cam2d:
  888. self.cam2d = None
  889. if cam == self.cam2dp:
  890. self.cam2dp = None
  891. cam.removeNode()
  892. # [gjeon] remove winControl
  893. for winCtrl in self.winControls:
  894. if winCtrl.win == win:
  895. self.winControls.remove(winCtrl)
  896. break
  897. # Now we can actually close the window.
  898. if removeWindow:
  899. self.graphicsEngine.removeWindow(win)
  900. self.winList.remove(win)
  901. mainWindow = False
  902. if win == self.win:
  903. mainWindow = True
  904. self.win = None
  905. if self.frameRateMeter:
  906. self.frameRateMeter.clearWindow()
  907. self.frameRateMeter = None
  908. if self.sceneGraphAnalyzerMeter:
  909. self.sceneGraphAnalyzerMeter.clearWindow()
  910. self.sceneGraphAnalyzerMeter = None
  911. messenger.send('close_window', [win, mainWindow])
  912. if mainWindow:
  913. messenger.send('close_main_window')
  914. if not self.winList:
  915. # Give the window(s) a chance to actually close before we
  916. # continue.
  917. self.graphicsEngine.renderFrame()
  918. def openDefaultWindow(self, *args, **kw):
  919. """
  920. Creates the main window for the first time, without being too
  921. particular about the kind of graphics API that is chosen.
  922. The suggested window type from the load-display config variable is
  923. tried first; if that fails, the first window type that can be
  924. successfully opened at all is accepted.
  925. This is intended to be called only once, at application startup.
  926. It is normally called automatically unless window-type is configured
  927. to 'none'.
  928. :returns: True on success, False on failure.
  929. """
  930. startDirect = kw.get('startDirect', True)
  931. if 'startDirect' in kw:
  932. del kw['startDirect']
  933. self.openMainWindow(*args, **kw)
  934. if startDirect:
  935. self.__doStartDirect()
  936. return self.win is not None
  937. def openMainWindow(self, *args, **kw):
  938. """
  939. Creates the initial, main window for the application, and sets
  940. up the mouse and render2d structures appropriately for it. If
  941. this method is called a second time, it will close the
  942. previous main window and open a new one, preserving the lens
  943. properties in base.camLens.
  944. :returns: True on success, or False on failure (in which case base.win
  945. may be either None, or the previous, closed window).
  946. """
  947. keepCamera = kw.get('keepCamera', False)
  948. success = 1
  949. oldWin = self.win
  950. oldLens = self.camLens
  951. oldClearColorActive = None
  952. if self.win is not None:
  953. # Close the previous window.
  954. oldClearColorActive = self.win.getClearColorActive()
  955. oldClearColor = VBase4(self.win.getClearColor())
  956. oldClearDepthActive = self.win.getClearDepthActive()
  957. oldClearDepth = self.win.getClearDepth()
  958. oldClearStencilActive = self.win.getClearStencilActive()
  959. oldClearStencil = self.win.getClearStencil()
  960. self.closeWindow(self.win, keepCamera = keepCamera)
  961. # Open a new window.
  962. self.openWindow(*args, **kw)
  963. if self.win is None:
  964. self.win = oldWin
  965. self.winList.append(oldWin)
  966. success = 0
  967. if self.win is not None:
  968. if isinstance(self.win, GraphicsWindow):
  969. self.setupMouse(self.win)
  970. self.makeCamera2d(self.win)
  971. if self.wantRender2dp:
  972. self.makeCamera2dp(self.win)
  973. if oldLens is not None:
  974. # Restore the previous lens properties.
  975. self.camNode.setLens(oldLens)
  976. self.camLens = oldLens
  977. if oldClearColorActive is not None:
  978. # Restore the previous clear properties.
  979. self.win.setClearColorActive(oldClearColorActive)
  980. self.win.setClearColor(oldClearColor)
  981. self.win.setClearDepthActive(oldClearDepthActive)
  982. self.win.setClearDepth(oldClearDepth)
  983. self.win.setClearStencilActive(oldClearStencilActive)
  984. self.win.setClearStencil(oldClearStencil)
  985. flag = ConfigVariableBool('show-frame-rate-meter', False)
  986. self.setFrameRateMeter(flag.value)
  987. flag = ConfigVariableBool('show-scene-graph-analyzer-meter', False)
  988. self.setSceneGraphAnalyzerMeter(flag.value)
  989. return success
  990. def setSleep(self, amount):
  991. """
  992. Sets up a task that calls python 'sleep' every frame. This is a simple
  993. way to reduce the CPU usage (and frame rate) of a panda program.
  994. """
  995. if self.clientSleep == amount:
  996. return
  997. self.clientSleep = amount
  998. if amount == 0.0:
  999. self.taskMgr.remove('clientSleep')
  1000. else:
  1001. # Spawn it after igloop (at the end of each frame)
  1002. self.taskMgr.remove('clientSleep')
  1003. self.taskMgr.add(self.__sleepCycleTask, 'clientSleep', sort = 55)
  1004. def __sleepCycleTask(self, task):
  1005. Thread.sleep(self.clientSleep)
  1006. #time.sleep(self.clientSleep)
  1007. return Task.cont
  1008. def setFrameRateMeter(self, flag):
  1009. """
  1010. Turns on or off (according to flag) a standard frame rate
  1011. meter in the upper-right corner of the main window.
  1012. """
  1013. if flag:
  1014. if not self.frameRateMeter:
  1015. self.frameRateMeter = FrameRateMeter('frameRateMeter')
  1016. self.frameRateMeter.setupWindow(self.win)
  1017. else:
  1018. if self.frameRateMeter:
  1019. self.frameRateMeter.clearWindow()
  1020. self.frameRateMeter = None
  1021. def setSceneGraphAnalyzerMeter(self, flag):
  1022. """
  1023. Turns on or off (according to flag) a standard frame rate
  1024. meter in the upper-right corner of the main window.
  1025. """
  1026. if flag:
  1027. if not self.sceneGraphAnalyzerMeter:
  1028. self.sceneGraphAnalyzerMeter = SceneGraphAnalyzerMeter('sceneGraphAnalyzerMeter', self.render.node())
  1029. self.sceneGraphAnalyzerMeter.setupWindow(self.win)
  1030. else:
  1031. if self.sceneGraphAnalyzerMeter:
  1032. self.sceneGraphAnalyzerMeter.clearWindow()
  1033. self.sceneGraphAnalyzerMeter = None
  1034. # [gjeon] now you can add more winControls after creating a showbase instance
  1035. def setupWindowControls(self, winCtrl=None):
  1036. if winCtrl is None:
  1037. winCtrl = WindowControls(
  1038. self.win, mouseWatcher=self.mouseWatcher,
  1039. cam=self.camera, camNode = self.camNode, cam2d=self.camera2d,
  1040. mouseKeyboard = self.dataRoot.find("**/*"))
  1041. self.winControls.append(winCtrl)
  1042. def setupRender(self):
  1043. """
  1044. Creates the render scene graph, the primary scene graph for
  1045. rendering 3-d geometry.
  1046. """
  1047. #: This is the root of the 3-D scene graph.
  1048. self.render = NodePath('render')
  1049. self.render.setAttrib(RescaleNormalAttrib.makeDefault())
  1050. self.render.setTwoSided(0)
  1051. self.backfaceCullingEnabled = 1
  1052. self.textureEnabled = 1
  1053. self.wireframeEnabled = 0
  1054. def setupRender2d(self):
  1055. """
  1056. Creates the render2d scene graph, the primary scene graph for
  1057. 2-d objects and gui elements that are superimposed over the
  1058. 3-d geometry in the window.
  1059. """
  1060. # We've already created render2d and aspect2d in ShowBaseGlobal,
  1061. # for the benefit of creating DirectGui elements before ShowBase.
  1062. from . import ShowBaseGlobal
  1063. #: This is the root of the 2-D scene graph.
  1064. self.render2d = ShowBaseGlobal.render2d
  1065. # Set up some overrides to turn off certain properties which
  1066. # we probably won't need for 2-d objects.
  1067. # It's probably important to turn off the depth test, since
  1068. # many 2-d objects will be drawn over each other without
  1069. # regard to depth position.
  1070. # We used to avoid clearing the depth buffer before drawing
  1071. # render2d, but nowadays we clear it anyway, since we
  1072. # occasionally want to put 3-d geometry under render2d, and
  1073. # it's simplest (and seems to be easier on graphics drivers)
  1074. # if the 2-d scene has been cleared first.
  1075. self.render2d.setDepthTest(0)
  1076. self.render2d.setDepthWrite(0)
  1077. self.render2d.setMaterialOff(1)
  1078. self.render2d.setTwoSided(1)
  1079. #: The normal 2-d DisplayRegion has an aspect ratio that
  1080. #: matches the window, but its coordinate system is square.
  1081. #: This means anything we parent to render2d gets stretched.
  1082. #: For things where that makes a difference, we set up
  1083. #: aspect2d, which scales things back to the right aspect
  1084. #: ratio along the X axis (Z is still from -1 to 1)
  1085. self.aspect2d = ShowBaseGlobal.aspect2d
  1086. aspectRatio = self.getAspectRatio()
  1087. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1088. self.a2dBackground = self.aspect2d.attachNewNode("a2dBackground")
  1089. #: The Z position of the top border of the aspect2d screen.
  1090. self.a2dTop = 1.0
  1091. #: The Z position of the bottom border of the aspect2d screen.
  1092. self.a2dBottom = -1.0
  1093. #: The X position of the left border of the aspect2d screen.
  1094. self.a2dLeft = -aspectRatio
  1095. #: The X position of the right border of the aspect2d screen.
  1096. self.a2dRight = aspectRatio
  1097. self.a2dTopCenter = self.aspect2d.attachNewNode("a2dTopCenter")
  1098. self.a2dTopCenterNs = self.aspect2d.attachNewNode("a2dTopCenterNS")
  1099. self.a2dBottomCenter = self.aspect2d.attachNewNode("a2dBottomCenter")
  1100. self.a2dBottomCenterNs = self.aspect2d.attachNewNode("a2dBottomCenterNS")
  1101. self.a2dLeftCenter = self.aspect2d.attachNewNode("a2dLeftCenter")
  1102. self.a2dLeftCenterNs = self.aspect2d.attachNewNode("a2dLeftCenterNS")
  1103. self.a2dRightCenter = self.aspect2d.attachNewNode("a2dRightCenter")
  1104. self.a2dRightCenterNs = self.aspect2d.attachNewNode("a2dRightCenterNS")
  1105. self.a2dTopLeft = self.aspect2d.attachNewNode("a2dTopLeft")
  1106. self.a2dTopLeftNs = self.aspect2d.attachNewNode("a2dTopLeftNS")
  1107. self.a2dTopRight = self.aspect2d.attachNewNode("a2dTopRight")
  1108. self.a2dTopRightNs = self.aspect2d.attachNewNode("a2dTopRightNS")
  1109. self.a2dBottomLeft = self.aspect2d.attachNewNode("a2dBottomLeft")
  1110. self.a2dBottomLeftNs = self.aspect2d.attachNewNode("a2dBottomLeftNS")
  1111. self.a2dBottomRight = self.aspect2d.attachNewNode("a2dBottomRight")
  1112. self.a2dBottomRightNs = self.aspect2d.attachNewNode("a2dBottomRightNS")
  1113. # Put the nodes in their places
  1114. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  1115. self.a2dTopCenterNs.setPos(0, 0, self.a2dTop)
  1116. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  1117. self.a2dBottomCenterNs.setPos(0, 0, self.a2dBottom)
  1118. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  1119. self.a2dLeftCenterNs.setPos(self.a2dLeft, 0, 0)
  1120. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  1121. self.a2dRightCenterNs.setPos(self.a2dRight, 0, 0)
  1122. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  1123. self.a2dTopLeftNs.setPos(self.a2dLeft, 0, self.a2dTop)
  1124. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  1125. self.a2dTopRightNs.setPos(self.a2dRight, 0, self.a2dTop)
  1126. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  1127. self.a2dBottomLeftNs.setPos(self.a2dLeft, 0, self.a2dBottom)
  1128. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  1129. self.a2dBottomRightNs.setPos(self.a2dRight, 0, self.a2dBottom)
  1130. #: This special root, pixel2d, uses units in pixels that are relative
  1131. #: to the window. The upperleft corner of the window is (0, 0),
  1132. #: the lowerleft corner is (xsize, -ysize), in this coordinate system.
  1133. self.pixel2d = self.render2d.attachNewNode(PGTop("pixel2d"))
  1134. self.pixel2d.setPos(-1, 0, 1)
  1135. xsize, ysize = self.getSize()
  1136. if xsize > 0 and ysize > 0:
  1137. self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  1138. def setupRender2dp(self):
  1139. """
  1140. Creates a render2d scene graph, the secondary scene graph for
  1141. 2-d objects and gui elements that are superimposed over the
  1142. 2-d and 3-d geometry in the window.
  1143. """
  1144. self.render2dp = NodePath('render2dp')
  1145. # Set up some overrides to turn off certain properties which
  1146. # we probably won't need for 2-d objects.
  1147. # It's probably important to turn off the depth test, since
  1148. # many 2-d objects will be drawn over each other without
  1149. # regard to depth position.
  1150. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  1151. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  1152. self.render2dp.setDepthTest(0)
  1153. self.render2dp.setDepthWrite(0)
  1154. self.render2dp.setMaterialOff(1)
  1155. self.render2dp.setTwoSided(1)
  1156. #: The normal 2-d DisplayRegion has an aspect ratio that
  1157. #: matches the window, but its coordinate system is square.
  1158. #: This means anything we parent to render2dp gets stretched.
  1159. #: For things where that makes a difference, we set up
  1160. #: aspect2dp, which scales things back to the right aspect
  1161. #: ratio along the X axis (Z is still from -1 to 1)
  1162. self.aspect2dp = self.render2dp.attachNewNode(PGTop("aspect2dp"))
  1163. self.aspect2dp.node().setStartSort(16384)
  1164. aspectRatio = self.getAspectRatio()
  1165. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1166. #: The Z position of the top border of the aspect2dp screen.
  1167. self.a2dpTop = 1.0
  1168. #: The Z position of the bottom border of the aspect2dp screen.
  1169. self.a2dpBottom = -1.0
  1170. #: The X position of the left border of the aspect2dp screen.
  1171. self.a2dpLeft = -aspectRatio
  1172. #: The X position of the right border of the aspect2dp screen.
  1173. self.a2dpRight = aspectRatio
  1174. self.a2dpTopCenter = self.aspect2dp.attachNewNode("a2dpTopCenter")
  1175. self.a2dpBottomCenter = self.aspect2dp.attachNewNode("a2dpBottomCenter")
  1176. self.a2dpLeftCenter = self.aspect2dp.attachNewNode("a2dpLeftCenter")
  1177. self.a2dpRightCenter = self.aspect2dp.attachNewNode("a2dpRightCenter")
  1178. self.a2dpTopLeft = self.aspect2dp.attachNewNode("a2dpTopLeft")
  1179. self.a2dpTopRight = self.aspect2dp.attachNewNode("a2dpTopRight")
  1180. self.a2dpBottomLeft = self.aspect2dp.attachNewNode("a2dpBottomLeft")
  1181. self.a2dpBottomRight = self.aspect2dp.attachNewNode("a2dpBottomRight")
  1182. # Put the nodes in their places
  1183. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  1184. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  1185. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  1186. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  1187. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  1188. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  1189. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  1190. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  1191. #: This special root, pixel2dp, uses units in pixels that are relative
  1192. #: to the window. The upperleft corner of the window is (0, 0),
  1193. #: the lowerleft corner is (xsize, -ysize), in this coordinate system.
  1194. self.pixel2dp = self.render2dp.attachNewNode(PGTop("pixel2dp"))
  1195. self.pixel2dp.node().setStartSort(16384)
  1196. self.pixel2dp.setPos(-1, 0, 1)
  1197. xsize, ysize = self.getSize()
  1198. if xsize > 0 and ysize > 0:
  1199. self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  1200. def setAspectRatio(self, aspectRatio):
  1201. """ Sets the global aspect ratio of the main window. Set it
  1202. to None to restore automatic scaling. """
  1203. self.__configAspectRatio = aspectRatio
  1204. self.adjustWindowAspectRatio(self.getAspectRatio())
  1205. def getAspectRatio(self, win = None):
  1206. # Returns the actual aspect ratio of the indicated (or main
  1207. # window), or the default aspect ratio if there is not yet a
  1208. # main window.
  1209. # If the config it set, we return that
  1210. if self.__configAspectRatio:
  1211. return self.__configAspectRatio
  1212. aspectRatio = 1
  1213. if win is None:
  1214. win = self.win
  1215. if win is not None and win.hasSize() and win.getSbsLeftYSize() != 0:
  1216. aspectRatio = float(win.getSbsLeftXSize()) / float(win.getSbsLeftYSize())
  1217. else:
  1218. if win is None or not hasattr(win, "getRequestedProperties"):
  1219. props = WindowProperties.getDefault()
  1220. else:
  1221. props = win.getRequestedProperties()
  1222. if not props.hasSize():
  1223. props = WindowProperties.getDefault()
  1224. if props.hasSize() and props.getYSize() != 0:
  1225. aspectRatio = float(props.getXSize()) / float(props.getYSize())
  1226. if aspectRatio == 0:
  1227. return 1
  1228. return aspectRatio
  1229. def getSize(self, win = None):
  1230. """
  1231. Returns the actual size of the indicated (or main window), or the
  1232. default size if there is not yet a main window.
  1233. """
  1234. if win is None:
  1235. win = self.win
  1236. if win is not None and win.hasSize():
  1237. return win.getXSize(), win.getYSize()
  1238. else:
  1239. if win is None or not hasattr(win, "getRequestedProperties"):
  1240. props = WindowProperties.getDefault()
  1241. else:
  1242. props = win.getRequestedProperties()
  1243. if not props.hasSize():
  1244. props = WindowProperties.getDefault()
  1245. return props.getXSize(), props.getYSize()
  1246. def makeCamera(self, win, sort = 0, scene = None,
  1247. displayRegion = (0, 1, 0, 1), stereo = None,
  1248. aspectRatio = None, clearDepth = 0, clearColor = None,
  1249. lens = None, camName = 'cam', mask = None,
  1250. useCamera = None):
  1251. """
  1252. Makes a new 3-d camera associated with the indicated window,
  1253. and creates a display region in the indicated subrectangle.
  1254. If stereo is True, then a stereo camera is created, with a
  1255. pair of DisplayRegions. If stereo is False, then a standard
  1256. camera is created. If stereo is None or omitted, a stereo
  1257. camera is created if the window says it can render in stereo.
  1258. If useCamera is not None, it is a NodePath to be used as the
  1259. camera to apply to the window, rather than creating a new
  1260. camera.
  1261. :rtype: panda3d.core.NodePath
  1262. """
  1263. # self.camera is the parent node of all cameras: a node that
  1264. # we can move around to move all cameras as a group.
  1265. if self.camera is None:
  1266. # We make it a ModelNode with the PTLocal flag, so that
  1267. # a wayward flatten operations won't attempt to mangle the
  1268. # camera.
  1269. self.camera = self.render.attachNewNode(ModelNode('camera'))
  1270. self.camera.node().setPreserveTransform(ModelNode.PTLocal)
  1271. builtins.camera = self.camera
  1272. self.mouse2cam.node().setNode(self.camera.node())
  1273. if useCamera:
  1274. # Use the existing camera node.
  1275. cam = useCamera
  1276. camNode = useCamera.node()
  1277. assert isinstance(camNode, Camera)
  1278. lens = camNode.getLens()
  1279. cam.reparentTo(self.camera)
  1280. else:
  1281. # Make a new Camera node.
  1282. camNode = Camera(camName)
  1283. if lens is None:
  1284. lens = PerspectiveLens()
  1285. if aspectRatio is None:
  1286. aspectRatio = self.getAspectRatio(win)
  1287. lens.setAspectRatio(aspectRatio)
  1288. cam = self.camera.attachNewNode(camNode)
  1289. if lens is not None:
  1290. camNode.setLens(lens)
  1291. if scene is not None:
  1292. camNode.setScene(scene)
  1293. if mask is not None:
  1294. if isinstance(mask, int):
  1295. mask = BitMask32(mask)
  1296. camNode.setCameraMask(mask)
  1297. if self.cam is None:
  1298. self.cam = cam
  1299. self.camNode = camNode
  1300. self.camLens = lens
  1301. self.camList.append(cam)
  1302. # Now, make a DisplayRegion for the camera.
  1303. if stereo is not None:
  1304. if stereo:
  1305. dr = win.makeStereoDisplayRegion(*displayRegion)
  1306. else:
  1307. dr = win.makeMonoDisplayRegion(*displayRegion)
  1308. else:
  1309. dr = win.makeDisplayRegion(*displayRegion)
  1310. dr.setSort(sort)
  1311. # By default, we do not clear 3-d display regions (the entire
  1312. # window will be cleared, which is normally sufficient). But
  1313. # we will if clearDepth is specified.
  1314. if clearDepth:
  1315. dr.setClearDepthActive(1)
  1316. if clearColor:
  1317. dr.setClearColorActive(1)
  1318. dr.setClearColor(clearColor)
  1319. dr.setCamera(cam)
  1320. return cam
  1321. def makeCamera2d(self, win, sort = 10,
  1322. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  1323. lens = None, cameraName = None):
  1324. """
  1325. Makes a new camera2d associated with the indicated window, and
  1326. assigns it to render the indicated subrectangle of render2d.
  1327. :rtype: panda3d.core.NodePath
  1328. """
  1329. dr = win.makeMonoDisplayRegion(*displayRegion)
  1330. dr.setSort(sort)
  1331. # Enable clearing of the depth buffer on this new display
  1332. # region (see the comment in setupRender2d, above).
  1333. dr.setClearDepthActive(1)
  1334. # Make any texture reloads on the gui come up immediately.
  1335. dr.setIncompleteRender(False)
  1336. left, right, bottom, top = coords
  1337. # Now make a new Camera node.
  1338. if cameraName:
  1339. cam2dNode = Camera('cam2d_' + cameraName)
  1340. else:
  1341. cam2dNode = Camera('cam2d')
  1342. if lens is None:
  1343. lens = OrthographicLens()
  1344. lens.setFilmSize(right - left, top - bottom)
  1345. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1346. lens.setNearFar(-1000, 1000)
  1347. cam2dNode.setLens(lens)
  1348. # self.camera2d is the analog of self.camera, although it's
  1349. # not as clear how useful it is.
  1350. if self.camera2d is None:
  1351. self.camera2d = self.render2d.attachNewNode('camera2d')
  1352. camera2d = self.camera2d.attachNewNode(cam2dNode)
  1353. dr.setCamera(camera2d)
  1354. if self.cam2d is None:
  1355. self.cam2d = camera2d
  1356. return camera2d
  1357. def makeCamera2dp(self, win, sort = 20,
  1358. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  1359. lens = None, cameraName = None):
  1360. """
  1361. Makes a new camera2dp associated with the indicated window, and
  1362. assigns it to render the indicated subrectangle of render2dp.
  1363. :rtype: panda3d.core.NodePath
  1364. """
  1365. dr = win.makeMonoDisplayRegion(*displayRegion)
  1366. dr.setSort(sort)
  1367. # Unlike render2d, we don't clear the depth buffer for
  1368. # render2dp. Caveat emptor.
  1369. if hasattr(dr, 'setIncompleteRender'):
  1370. dr.setIncompleteRender(False)
  1371. left, right, bottom, top = coords
  1372. # Now make a new Camera node.
  1373. if cameraName:
  1374. cam2dNode = Camera('cam2dp_' + cameraName)
  1375. else:
  1376. cam2dNode = Camera('cam2dp')
  1377. if lens is None:
  1378. lens = OrthographicLens()
  1379. lens.setFilmSize(right - left, top - bottom)
  1380. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1381. lens.setNearFar(-1000, 1000)
  1382. cam2dNode.setLens(lens)
  1383. # self.camera2d is the analog of self.camera, although it's
  1384. # not as clear how useful it is.
  1385. if self.camera2dp is None:
  1386. self.camera2dp = self.render2dp.attachNewNode('camera2dp')
  1387. camera2dp = self.camera2dp.attachNewNode(cam2dNode)
  1388. dr.setCamera(camera2dp)
  1389. if self.cam2dp is None:
  1390. self.cam2dp = camera2dp
  1391. return camera2dp
  1392. def setupDataGraph(self):
  1393. """
  1394. Creates the data graph and populates it with the basic input
  1395. devices.
  1396. """
  1397. self.dataRoot = NodePath('dataRoot')
  1398. # Cache the node so we do not ask for it every frame
  1399. self.dataRootNode = self.dataRoot.node()
  1400. # Now we have the main trackball & drive interfaces.
  1401. # useTrackball() and useDrive() switch these in and out; only
  1402. # one is in use at a given time.
  1403. self.trackball = NodePath(Trackball('trackball'))
  1404. self.drive = NodePath(DriveInterface('drive'))
  1405. self.mouse2cam = NodePath(Transform2SG('mouse2cam'))
  1406. # [gjeon] now you can create multiple mouse watchers to support multiple windows
  1407. def setupMouse(self, win, fMultiWin=False):
  1408. """
  1409. Creates the structures necessary to monitor the mouse input,
  1410. using the indicated window. If the mouse has already been set
  1411. up for a different window, those structures are deleted first.
  1412. :param fMultiWin: If True, then the previous mouse structures are not
  1413. deleted; instead, multiple windows are allowed to
  1414. monitor the mouse input. However, in this case, the
  1415. trackball controls are not set up, and must be set up
  1416. by hand if desired.
  1417. :returns: The ButtonThrower NodePath created for this window.
  1418. """
  1419. if not fMultiWin and self.buttonThrowers is not None:
  1420. for bt in self.buttonThrowers:
  1421. mw = bt.getParent()
  1422. mk = mw.getParent()
  1423. bt.removeNode()
  1424. mw.removeNode()
  1425. mk.removeNode()
  1426. bts, pws = self.setupMouseCB(win)
  1427. if fMultiWin:
  1428. return bts[0]
  1429. self.buttonThrowers = bts[:]
  1430. self.pointerWatcherNodes = pws[:]
  1431. self.mouseWatcher = self.buttonThrowers[0].getParent()
  1432. self.mouseWatcherNode = self.mouseWatcher.node()
  1433. if self.mouseInterface:
  1434. self.mouseInterface.reparentTo(self.mouseWatcher)
  1435. if self.recorder:
  1436. # If we have a recorder, the mouseWatcher belongs under a
  1437. # special MouseRecorder node, which may intercept the
  1438. # mouse activity.
  1439. mw = self.buttonThrowers[0].getParent()
  1440. mouseRecorder = MouseRecorder('mouse')
  1441. self.recorder.addRecorder('mouse', mouseRecorder)
  1442. np = mw.getParent().attachNewNode(mouseRecorder)
  1443. mw.reparentTo(np)
  1444. mw = self.buttonThrowers[0].getParent()
  1445. #: A special ButtonThrower to generate keyboard events and
  1446. #: include the time from the OS. This is separate only to
  1447. #: support legacy code that did not expect a time parameter; it
  1448. #: will eventually be folded into the normal ButtonThrower,
  1449. #: above.
  1450. self.timeButtonThrower = mw.attachNewNode(ButtonThrower('timeButtons'))
  1451. self.timeButtonThrower.node().setPrefix('time-')
  1452. self.timeButtonThrower.node().setTimeFlag(1)
  1453. # Tell the gui system about our new mouse watcher.
  1454. self.aspect2d.node().setMouseWatcher(mw.node())
  1455. self.pixel2d.node().setMouseWatcher(mw.node())
  1456. if self.wantRender2dp:
  1457. self.aspect2dp.node().setMouseWatcher(mw.node())
  1458. self.pixel2dp.node().setMouseWatcher(mw.node())
  1459. mw.node().addRegion(PGMouseWatcherBackground())
  1460. return self.buttonThrowers[0]
  1461. # [gjeon] this function is seperated from setupMouse to allow multiple mouse watchers
  1462. def setupMouseCB(self, win):
  1463. # For each mouse/keyboard device, we create
  1464. # - MouseAndKeyboard
  1465. # - MouseWatcher
  1466. # - ButtonThrower
  1467. # The ButtonThrowers are stored in a list, self.buttonThrowers.
  1468. # Given a ButtonThrower, one can access the MouseWatcher and
  1469. # MouseAndKeyboard using getParent.
  1470. #
  1471. # The MouseAndKeyboard generates mouse events and mouse
  1472. # button/keyboard events; the MouseWatcher passes them through
  1473. # unchanged when the mouse is not over a 2-d button, and passes
  1474. # nothing through when the mouse *is* over a 2-d button. Therefore,
  1475. # objects that don't want to get events when the mouse is over a
  1476. # button, like the driveInterface, should be parented to
  1477. # MouseWatcher, while objects that want events in all cases, like the
  1478. # chat interface, should be parented to the MouseAndKeyboard.
  1479. buttonThrowers = []
  1480. pointerWatcherNodes = []
  1481. for i in range(win.getNumInputDevices()):
  1482. name = win.getInputDeviceName(i)
  1483. mk = self.dataRoot.attachNewNode(MouseAndKeyboard(win, i, name))
  1484. mw = mk.attachNewNode(MouseWatcher("watcher%s" % (i)))
  1485. if win.getSideBySideStereo():
  1486. # If the window has side-by-side stereo enabled, then
  1487. # we should constrain the MouseWatcher to the window's
  1488. # DisplayRegion. This will enable the MouseWatcher to
  1489. # track the left and right halves of the screen
  1490. # individually.
  1491. mw.node().setDisplayRegion(win.getOverlayDisplayRegion())
  1492. mb = mw.node().getModifierButtons()
  1493. mb.addButton(KeyboardButton.shift())
  1494. mb.addButton(KeyboardButton.control())
  1495. mb.addButton(KeyboardButton.alt())
  1496. mb.addButton(KeyboardButton.meta())
  1497. mw.node().setModifierButtons(mb)
  1498. bt = mw.attachNewNode(ButtonThrower("buttons%s" % (i)))
  1499. if i != 0:
  1500. bt.node().setPrefix('mousedev%s-' % (i))
  1501. mods = ModifierButtons()
  1502. mods.addButton(KeyboardButton.shift())
  1503. mods.addButton(KeyboardButton.control())
  1504. mods.addButton(KeyboardButton.alt())
  1505. mods.addButton(KeyboardButton.meta())
  1506. bt.node().setModifierButtons(mods)
  1507. buttonThrowers.append(bt)
  1508. if win.hasPointer(i):
  1509. pointerWatcherNodes.append(mw.node())
  1510. return buttonThrowers, pointerWatcherNodes
  1511. def enableSoftwareMousePointer(self):
  1512. """
  1513. Creates some geometry and parents it to render2d to show
  1514. the currently-known mouse position. Useful if the mouse
  1515. pointer is invisible for some reason.
  1516. """
  1517. mouseViz = self.render2d.attachNewNode('mouseViz')
  1518. lilsmiley = self.loader.loadModel('lilsmiley')
  1519. lilsmiley.reparentTo(mouseViz)
  1520. aspectRatio = self.getAspectRatio()
  1521. # Scale the smiley face to 32x32 pixels.
  1522. height = self.win.getSbsLeftYSize()
  1523. lilsmiley.setScale(
  1524. 32.0 / height / aspectRatio,
  1525. 1.0, 32.0 / height)
  1526. self.mouseWatcherNode.setGeometry(mouseViz.node())
  1527. def getAlt(self):
  1528. """
  1529. Returns True if the alt key is currently held down.
  1530. """
  1531. return self.mouseWatcherNode.getModifierButtons().isDown(
  1532. KeyboardButton.alt())
  1533. def getShift(self):
  1534. """
  1535. Returns True if the shift key is currently held down.
  1536. """
  1537. return self.mouseWatcherNode.getModifierButtons().isDown(
  1538. KeyboardButton.shift())
  1539. def getControl(self):
  1540. """
  1541. Returns True if the control key is currently held down.
  1542. """
  1543. return self.mouseWatcherNode.getModifierButtons().isDown(
  1544. KeyboardButton.control())
  1545. def getMeta(self):
  1546. """
  1547. Returns True if the meta key is currently held down.
  1548. """
  1549. return self.mouseWatcherNode.getModifierButtons().isDown(
  1550. KeyboardButton.meta())
  1551. def attachInputDevice(self, device, prefix=None, watch=False):
  1552. """
  1553. This function attaches an input device to the data graph, which will
  1554. cause the device to be polled and generate events. If a prefix is
  1555. given and not None, it is used to prefix events generated by this
  1556. device, separated by a hyphen.
  1557. The watch argument can be set to True (as of Panda3D 1.10.3) to set up
  1558. the default MouseWatcher to receive inputs from this device, allowing
  1559. it to be polled via mouseWatcherNode and control user interfaces.
  1560. Setting this to True will also make it generate unprefixed events,
  1561. regardless of the specified prefix.
  1562. If you call this, you should consider calling detachInputDevice when
  1563. you are done with the device or when it is disconnected.
  1564. """
  1565. # Protect against the same device being attached multiple times.
  1566. assert device not in self.__inputDeviceNodes
  1567. idn = self.dataRoot.attachNewNode(InputDeviceNode(device, device.name))
  1568. # Setup the button thrower to generate events for the device.
  1569. if prefix is not None or not watch:
  1570. bt = idn.attachNewNode(ButtonThrower(device.name))
  1571. if prefix is not None:
  1572. bt.node().setPrefix(prefix + '-')
  1573. self.deviceButtonThrowers.append(bt)
  1574. assert self.notify.debug("Attached input device {0} with prefix {1}".format(device, prefix))
  1575. self.__inputDeviceNodes[device] = idn
  1576. if watch:
  1577. idn.node().addChild(self.mouseWatcherNode)
  1578. def detachInputDevice(self, device):
  1579. """
  1580. This should be called after attaching an input device using
  1581. attachInputDevice and the device is disconnected or you no longer wish
  1582. to keep polling this device for events.
  1583. You do not strictly need to call this if you expect the device to be
  1584. reconnected (but be careful that you don't reattach it).
  1585. """
  1586. if device not in self.__inputDeviceNodes:
  1587. assert device in self.__inputDeviceNodes
  1588. return
  1589. assert self.notify.debug("Detached device {0}".format(device.name))
  1590. # Remove the ButtonThrower from the deviceButtonThrowers list.
  1591. idn = self.__inputDeviceNodes[device]
  1592. for bt in self.deviceButtonThrowers:
  1593. if idn.isAncestorOf(bt):
  1594. self.deviceButtonThrowers.remove(bt)
  1595. break
  1596. idn.removeNode()
  1597. del self.__inputDeviceNodes[device]
  1598. def addAngularIntegrator(self):
  1599. """
  1600. Adds a :class:`~panda3d.physics.AngularEulerIntegrator` to the default
  1601. physics manager. By default, only a
  1602. :class:`~panda3d.physics.LinearEulerIntegrator` is attached.
  1603. """
  1604. if not self.physicsMgrAngular:
  1605. physics = importlib.import_module('panda3d.physics')
  1606. self.physicsMgrAngular = 1
  1607. integrator = physics.AngularEulerIntegrator()
  1608. self.physicsMgr.attachAngularIntegrator(integrator)
  1609. def enableParticles(self):
  1610. """
  1611. Enables the particle and physics managers, which are stored in
  1612. `particleMgr` and `physicsMgr` members, respectively. Also starts a
  1613. task to periodically update these managers.
  1614. By default, only a :class:`~panda3d.physics.LinearEulerIntegrator` is
  1615. attached to the physics manager. To attach an angular integrator,
  1616. follow this up with a call to `addAngularIntegrator()`.
  1617. """
  1618. if not self.particleMgrEnabled:
  1619. # Use importlib to prevent this import from being picked up
  1620. # by modulefinder when packaging an application.
  1621. if not self.particleMgr:
  1622. PMG = importlib.import_module('direct.particles.ParticleManagerGlobal')
  1623. self.particleMgr = PMG.particleMgr
  1624. self.particleMgr.setFrameStepping(1)
  1625. if not self.physicsMgr:
  1626. PMG = importlib.import_module('direct.showbase.PhysicsManagerGlobal')
  1627. physics = importlib.import_module('panda3d.physics')
  1628. self.physicsMgr = PMG.physicsMgr
  1629. integrator = physics.LinearEulerIntegrator()
  1630. self.physicsMgr.attachLinearIntegrator(integrator)
  1631. self.particleMgrEnabled = 1
  1632. self.physicsMgrEnabled = 1
  1633. self.taskMgr.remove('manager-update')
  1634. self.taskMgr.add(self.updateManagers, 'manager-update')
  1635. def disableParticles(self):
  1636. """
  1637. The opposite of `enableParticles()`.
  1638. """
  1639. if self.particleMgrEnabled:
  1640. self.particleMgrEnabled = 0
  1641. self.physicsMgrEnabled = 0
  1642. self.taskMgr.remove('manager-update')
  1643. def toggleParticles(self):
  1644. """
  1645. Calls `enableParticles()` or `disableParticles()` depending on the
  1646. current state.
  1647. """
  1648. if self.particleMgrEnabled == 0:
  1649. self.enableParticles()
  1650. else:
  1651. self.disableParticles()
  1652. def isParticleMgrEnabled(self):
  1653. """
  1654. Returns True if `enableParticles()` has been called.
  1655. """
  1656. return self.particleMgrEnabled
  1657. def isPhysicsMgrEnabled(self):
  1658. """
  1659. Returns True if `enableParticles()` has been called.
  1660. """
  1661. return self.physicsMgrEnabled
  1662. def updateManagers(self, state):
  1663. dt = self.clock.dt
  1664. if self.particleMgrEnabled:
  1665. self.particleMgr.doParticles(dt)
  1666. if self.physicsMgrEnabled:
  1667. self.physicsMgr.doPhysics(dt)
  1668. return Task.cont
  1669. def createStats(self, hostname=None, port=None):
  1670. """
  1671. If want-pstats is set in Config.prc, or the `wantStats` member is
  1672. otherwise set to True, connects to the PStats server.
  1673. This is normally called automatically from the ShowBase constructor.
  1674. """
  1675. # You can specify pstats-host in your Config.prc or use ~pstats/~aipstats
  1676. # The default is localhost
  1677. if not self.wantStats:
  1678. return False
  1679. if PStatClient.isConnected():
  1680. PStatClient.disconnect()
  1681. # these default values match the C++ default values
  1682. if hostname is None:
  1683. hostname = ''
  1684. if port is None:
  1685. port = -1
  1686. PStatClient.connect(hostname, port)
  1687. if PStatClient.isConnected():
  1688. PStatClient.mainTick()
  1689. return True
  1690. else:
  1691. return False
  1692. def addSfxManager(self, extraSfxManager):
  1693. """
  1694. Adds an additional SFX audio manager to `sfxManagerList`, the list of
  1695. managers managed by ShowBase.
  1696. """
  1697. # keep a list of sfx manager objects to apply settings to,
  1698. # since there may be others in addition to the one we create here
  1699. self.sfxManagerList.append(extraSfxManager)
  1700. newSfxManagerIsValid = extraSfxManager is not None and extraSfxManager.isValid()
  1701. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  1702. if newSfxManagerIsValid:
  1703. extraSfxManager.setActive(self.sfxActive)
  1704. def createBaseAudioManagers(self):
  1705. """
  1706. Creates the default SFX and music manager. Called automatically from
  1707. the ShowBase constructor.
  1708. """
  1709. self.sfxPlayer = SfxPlayer.SfxPlayer()
  1710. sfxManager = AudioManager.createAudioManager()
  1711. self.addSfxManager(sfxManager)
  1712. self.musicManager = AudioManager.createAudioManager()
  1713. self.musicManagerIsValid = self.musicManager is not None \
  1714. and self.musicManager.isValid()
  1715. if self.musicManagerIsValid:
  1716. # ensure only 1 midi song is playing at a time:
  1717. self.musicManager.setConcurrentSoundLimit(1)
  1718. self.musicManager.setActive(self.musicActive)
  1719. # enableMusic/enableSoundEffects are meant to be called in response
  1720. # to a user request so sfxActive/musicActive represent how things
  1721. # *should* be, regardless of App/OS/HW state
  1722. def enableMusic(self, bEnableMusic):
  1723. """
  1724. Enables or disables the music manager.
  1725. """
  1726. # don't setActive(1) if no audiofocus
  1727. if self.AppHasAudioFocus and self.musicManagerIsValid:
  1728. self.musicManager.setActive(bEnableMusic)
  1729. self.musicActive = bEnableMusic
  1730. if bEnableMusic:
  1731. # This is useful when we want to play different music
  1732. # from what the manager has queued
  1733. messenger.send("MusicEnabled")
  1734. self.notify.debug("Enabling music")
  1735. else:
  1736. self.notify.debug("Disabling music")
  1737. def SetAllSfxEnables(self, bEnabled):
  1738. """Calls ``setActive(bEnabled)`` on all valid SFX managers."""
  1739. for i in range(len(self.sfxManagerList)):
  1740. if self.sfxManagerIsValidList[i]:
  1741. self.sfxManagerList[i].setActive(bEnabled)
  1742. def enableSoundEffects(self, bEnableSoundEffects):
  1743. """
  1744. Enables or disables SFX managers.
  1745. """
  1746. # don't setActive(1) if no audiofocus
  1747. if self.AppHasAudioFocus or not bEnableSoundEffects:
  1748. self.SetAllSfxEnables(bEnableSoundEffects)
  1749. self.sfxActive = bEnableSoundEffects
  1750. if bEnableSoundEffects:
  1751. self.notify.debug("Enabling sound effects")
  1752. else:
  1753. self.notify.debug("Disabling sound effects")
  1754. # enable/disableAllAudio allow a programmable global override-off
  1755. # for current audio settings. they're meant to be called when app
  1756. # loses audio focus (switched out), so we can turn off sound without
  1757. # affecting internal sfxActive/musicActive sound settings, so things
  1758. # come back ok when the app is switched back to
  1759. def disableAllAudio(self):
  1760. """
  1761. Disables all SFX and music managers, meant to be called when the app
  1762. loses audio focus.
  1763. """
  1764. self.AppHasAudioFocus = 0
  1765. self.SetAllSfxEnables(0)
  1766. if self.musicManagerIsValid:
  1767. self.musicManager.setActive(0)
  1768. self.notify.debug("Disabling audio")
  1769. def enableAllAudio(self):
  1770. """
  1771. Reenables the SFX and music managers that were active at the time
  1772. `disableAllAudio()` was called. Meant to be called when the app regains
  1773. audio focus.
  1774. """
  1775. self.AppHasAudioFocus = 1
  1776. self.SetAllSfxEnables(self.sfxActive)
  1777. if self.musicManagerIsValid:
  1778. self.musicManager.setActive(self.musicActive)
  1779. self.notify.debug("Enabling audio")
  1780. # This function should only be in the loader but is here for
  1781. # backwards compatibility. Please do not add code here, add
  1782. # it to the loader.
  1783. def loadSfx(self, name):
  1784. """
  1785. :deprecated: Use `.Loader.Loader.loadSfx()` instead.
  1786. """
  1787. if __debug__:
  1788. warnings.warn("base.loadSfx is deprecated, use base.loader.loadSfx instead.", DeprecationWarning, stacklevel=2)
  1789. return self.loader.loadSfx(name)
  1790. # This function should only be in the loader but is here for
  1791. # backwards compatibility. Please do not add code here, add
  1792. # it to the loader.
  1793. def loadMusic(self, name):
  1794. """
  1795. :deprecated: Use `.Loader.Loader.loadMusic()` instead.
  1796. """
  1797. if __debug__:
  1798. warnings.warn("base.loadMusic is deprecated, use base.loader.loadMusic instead.", DeprecationWarning, stacklevel=2)
  1799. return self.loader.loadMusic(name)
  1800. def playSfx(
  1801. self, sfx, looping = 0, interrupt = 1, volume = None,
  1802. time = 0.0, node = None, listener = None, cutoff = None):
  1803. # This goes through a special player for potential localization
  1804. return self.sfxPlayer.playSfx(sfx, looping, interrupt, volume, time, node, listener, cutoff)
  1805. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  1806. if music:
  1807. if volume is not None:
  1808. music.setVolume(volume)
  1809. # if interrupt was set to 0, start over even if it's
  1810. # already playing
  1811. if interrupt or (music.status() != AudioSound.PLAYING):
  1812. music.setTime(time)
  1813. music.setLoop(looping)
  1814. music.play()
  1815. def __resetPrevTransform(self, state):
  1816. # Clear out the previous velocity deltas now, after we have
  1817. # rendered (the previous frame). We do this after the render,
  1818. # so that we have a chance to draw a representation of spheres
  1819. # along with their velocities. At the beginning of the frame
  1820. # really means after the command prompt, which allows the user
  1821. # to interactively query these deltas meaningfully.
  1822. PandaNode.resetAllPrevTransform()
  1823. return Task.cont
  1824. def __dataLoop(self, state):
  1825. # Check if there were newly connected devices.
  1826. self.devices.update()
  1827. # traverse the data graph. This reads all the control
  1828. # inputs (from the mouse and keyboard, for instance) and also
  1829. # directly acts upon them (for instance, to move the avatar).
  1830. self.dgTrav.traverse(self.dataRootNode)
  1831. return Task.cont
  1832. def __ivalLoop(self, state):
  1833. # Execute all intervals in the global ivalMgr.
  1834. IntervalManager.ivalMgr.step()
  1835. return Task.cont
  1836. def initShadowTrav(self):
  1837. if not self.shadowTrav:
  1838. # set up the shadow collision traverser
  1839. self.shadowTrav = CollisionTraverser("base.shadowTrav")
  1840. self.shadowTrav.setRespectPrevTransform(False)
  1841. def __shadowCollisionLoop(self, state):
  1842. # run the collision traversal if we have a
  1843. # CollisionTraverser set.
  1844. if self.shadowTrav:
  1845. self.shadowTrav.traverse(self.render)
  1846. return Task.cont
  1847. def __collisionLoop(self, state):
  1848. # run the collision traversal if we have a
  1849. # CollisionTraverser set.
  1850. if self.cTrav:
  1851. self.cTrav.traverse(self.render)
  1852. if self.appTrav:
  1853. self.appTrav.traverse(self.render)
  1854. if self.shadowTrav:
  1855. self.shadowTrav.traverse(self.render)
  1856. messenger.send("collisionLoopFinished")
  1857. return Task.cont
  1858. def __audioLoop(self, state):
  1859. if self.musicManager is not None:
  1860. self.musicManager.update()
  1861. for x in self.sfxManagerList:
  1862. x.update()
  1863. return Task.cont
  1864. def __garbageCollectStates(self, state):
  1865. """ This task is started only when we have
  1866. garbage-collect-states set in the Config.prc file, in which
  1867. case we're responsible for taking out Panda's garbage from
  1868. time to time. This is not to be confused with Python's
  1869. garbage collection. """
  1870. TransformState.garbageCollect()
  1871. RenderState.garbageCollect()
  1872. return Task.cont
  1873. def __igLoop(self, state):
  1874. if __debug__:
  1875. # We render the watch variables for the onScreenDebug as soon
  1876. # as we reasonably can before the renderFrame().
  1877. self.onScreenDebug.render()
  1878. if self.recorder:
  1879. self.recorder.recordFrame()
  1880. # Finally, render the frame.
  1881. self.graphicsEngine.renderFrame()
  1882. if self.clusterSyncFlag:
  1883. self.graphicsEngine.syncFrame()
  1884. if self.multiClientSleep:
  1885. time.sleep(0)
  1886. if __debug__:
  1887. # We clear the text buffer for the onScreenDebug as soon
  1888. # as we reasonably can after the renderFrame().
  1889. self.onScreenDebug.clear()
  1890. if self.recorder:
  1891. self.recorder.playFrame()
  1892. if self.mainWinMinimized:
  1893. # If the main window is minimized, slow down the app a bit
  1894. # by sleeping here in igLoop so we don't use all available
  1895. # CPU needlessly.
  1896. # Note: this isn't quite right if multiple windows are
  1897. # open. We should base this on whether *all* windows are
  1898. # minimized, not just the main window. But it will do for
  1899. # now until someone complains.
  1900. time.sleep(0.1)
  1901. # Lerp stuff needs this event, and it must be generated in
  1902. # C++, not in Python.
  1903. throw_new_frame()
  1904. return Task.cont
  1905. def __igLoopSync(self, state):
  1906. if __debug__:
  1907. # We render the watch variables for the onScreenDebug as soon
  1908. # as we reasonably can before the renderFrame().
  1909. self.onScreenDebug.render()
  1910. if self.recorder:
  1911. self.recorder.recordFrame()
  1912. self.cluster.collectData()
  1913. # Finally, render the frame.
  1914. self.graphicsEngine.renderFrame()
  1915. if self.clusterSyncFlag:
  1916. self.graphicsEngine.syncFrame()
  1917. if self.multiClientSleep:
  1918. time.sleep(0)
  1919. if __debug__:
  1920. # We clear the text buffer for the onScreenDebug as soon
  1921. # as we reasonably can after the renderFrame().
  1922. self.onScreenDebug.clear()
  1923. if self.recorder:
  1924. self.recorder.playFrame()
  1925. if self.mainWinMinimized:
  1926. # If the main window is minimized, slow down the app a bit
  1927. # by sleeping here in igLoop so we don't use all available
  1928. # CPU needlessly.
  1929. # Note: this isn't quite right if multiple windows are
  1930. # open. We should base this on whether *all* windows are
  1931. # minimized, not just the main window. But it will do for
  1932. # now until someone complains.
  1933. time.sleep(0.1)
  1934. self.graphicsEngine.readyFlip()
  1935. self.cluster.waitForFlipCommand()
  1936. self.graphicsEngine.flipFrame()
  1937. # Lerp stuff needs this event, and it must be generated in
  1938. # C++, not in Python.
  1939. throw_new_frame()
  1940. return Task.cont
  1941. def restart(self, clusterSync=False, cluster=None):
  1942. self.shutdown()
  1943. # __resetPrevTransform goes at the very beginning of the frame.
  1944. self.taskMgr.add(
  1945. self.__resetPrevTransform, 'resetPrevTransform', sort = -51)
  1946. # give the dataLoop task a reasonably "early" sort,
  1947. # so that it will get run before most tasks
  1948. self.taskMgr.add(self.__dataLoop, 'dataLoop', sort = -50)
  1949. self.__deadInputs = 0
  1950. # spawn the ivalLoop with a later sort, so that it will
  1951. # run after most tasks, but before igLoop.
  1952. self.taskMgr.add(self.__ivalLoop, 'ivalLoop', sort = 20)
  1953. # make the collisionLoop task run before igLoop,
  1954. # but leave enough room for the app to insert tasks
  1955. # between collisionLoop and igLoop
  1956. self.taskMgr.add(self.__collisionLoop, 'collisionLoop', sort = 30)
  1957. if ConfigVariableBool('garbage-collect-states').value:
  1958. self.taskMgr.add(self.__garbageCollectStates, 'garbageCollectStates', sort = 46)
  1959. # give the igLoop task a reasonably "late" sort,
  1960. # so that it will get run after most tasks
  1961. self.cluster = cluster
  1962. if not clusterSync or cluster is None:
  1963. self.taskMgr.add(self.__igLoop, 'igLoop', sort = 50)
  1964. else:
  1965. self.taskMgr.add(self.__igLoopSync, 'igLoop', sort = 50)
  1966. # the audioLoop updates the positions of 3D sounds.
  1967. # as such, it needs to run after the cull traversal in the igLoop.
  1968. self.taskMgr.add(self.__audioLoop, 'audioLoop', sort = 60)
  1969. self.eventMgr.restart()
  1970. def shutdown(self):
  1971. self.taskMgr.remove('audioLoop')
  1972. self.taskMgr.remove('igLoop')
  1973. self.taskMgr.remove('shadowCollisionLoop')
  1974. self.taskMgr.remove('collisionLoop')
  1975. self.taskMgr.remove('dataLoop')
  1976. self.taskMgr.remove('resetPrevTransform')
  1977. self.taskMgr.remove('ivalLoop')
  1978. self.taskMgr.remove('garbageCollectStates')
  1979. self.eventMgr.shutdown()
  1980. def getBackgroundColor(self, win = None):
  1981. """
  1982. Returns the current window background color. This assumes
  1983. the window is set up to clear the color each frame (this is
  1984. the normal setting).
  1985. :rtype: panda3d.core.VBase4
  1986. """
  1987. if win is None:
  1988. win = self.win
  1989. return VBase4(win.getClearColor())
  1990. def setBackgroundColor(self, r = None, g = None, b = None, a = 0.0, win = None):
  1991. """
  1992. Sets the window background color to the indicated value.
  1993. This assumes the window is set up to clear the color each
  1994. frame (this is the normal setting).
  1995. The color may be either a VBase3 or a VBase4, or a 3-component
  1996. tuple, or the individual r, g, b parameters.
  1997. """
  1998. if g is not None:
  1999. color = VBase4(r, g, b, a)
  2000. else:
  2001. arg = r
  2002. if isinstance(arg, VBase4):
  2003. color = arg
  2004. else:
  2005. color = VBase4(arg[0], arg[1], arg[2], a)
  2006. if win is None:
  2007. win = self.win
  2008. if win:
  2009. win.setClearColor(color)
  2010. def toggleBackface(self):
  2011. """
  2012. Toggles between `backfaceCullingOn()` and `backfaceCullingOff()`.
  2013. """
  2014. if self.backfaceCullingEnabled:
  2015. self.backfaceCullingOff()
  2016. else:
  2017. self.backfaceCullingOn()
  2018. def backfaceCullingOn(self):
  2019. """
  2020. Disables two-sided rendering on the entire 3D scene graph.
  2021. """
  2022. if not self.backfaceCullingEnabled:
  2023. self.render.setTwoSided(0)
  2024. self.backfaceCullingEnabled = 1
  2025. def backfaceCullingOff(self):
  2026. """
  2027. Enables two-sided rendering on the entire 3D scene graph.
  2028. """
  2029. if self.backfaceCullingEnabled:
  2030. self.render.setTwoSided(1)
  2031. self.backfaceCullingEnabled = 0
  2032. def toggleTexture(self):
  2033. """
  2034. Toggles between `textureOn()` and `textureOff()`.
  2035. """
  2036. if self.textureEnabled:
  2037. self.textureOff()
  2038. else:
  2039. self.textureOn()
  2040. def textureOn(self):
  2041. """
  2042. Undoes the effects of a previous call to `textureOff()`.
  2043. """
  2044. self.render.clearTexture()
  2045. self.textureEnabled = 1
  2046. def textureOff(self):
  2047. """
  2048. Disables texturing on the entire 3D scene graph.
  2049. """
  2050. self.render.setTextureOff(100)
  2051. self.textureEnabled = 0
  2052. def toggleWireframe(self):
  2053. """
  2054. Toggles between `wireframeOn()` and `wireframeOff()`.
  2055. """
  2056. if self.wireframeEnabled:
  2057. self.wireframeOff()
  2058. else:
  2059. self.wireframeOn()
  2060. def wireframeOn(self):
  2061. """
  2062. Enables wireframe rendering on the entire 3D scene graph.
  2063. """
  2064. self.render.setRenderModeWireframe(100)
  2065. self.render.setTwoSided(1)
  2066. self.wireframeEnabled = 1
  2067. def wireframeOff(self):
  2068. """
  2069. Undoes the effects of a previous call to `wireframeOn()`.
  2070. """
  2071. self.render.clearRenderMode()
  2072. render.setTwoSided(not self.backfaceCullingEnabled)
  2073. self.wireframeEnabled = 0
  2074. def disableMouse(self):
  2075. """
  2076. Temporarily disable the mouse control of the camera, either
  2077. via the drive interface or the trackball, whichever is
  2078. currently in use.
  2079. """
  2080. # We don't reparent the drive interface or the trackball;
  2081. # whichever one was there before will remain in the data graph
  2082. # and active. This way they won't lose button events while
  2083. # the mouse is disabled. However, we do move the mouse2cam
  2084. # object out of there, so we won't be updating the camera any
  2085. # more.
  2086. if self.mouse2cam:
  2087. self.mouse2cam.detachNode()
  2088. def enableMouse(self):
  2089. """
  2090. Reverse the effect of a previous call to `disableMouse()`.
  2091. `useDrive()` also implicitly enables the mouse.
  2092. """
  2093. if self.mouse2cam:
  2094. self.mouse2cam.reparentTo(self.mouseInterface)
  2095. def silenceInput(self):
  2096. """
  2097. This is a heavy-handed way of temporarily turning off
  2098. all inputs. Bring them back with `reviveInput()`.
  2099. """
  2100. if not self.__deadInputs:
  2101. self.__deadInputs = taskMgr.remove('dataLoop')
  2102. def reviveInput(self):
  2103. """
  2104. Restores inputs after a previous call to `silenceInput()`.
  2105. """
  2106. if self.__deadInputs:
  2107. self.eventMgr.doEvents()
  2108. self.dgTrav.traverse(self.dataRootNode)
  2109. self.eventMgr.eventQueue.clear()
  2110. self.taskMgr.add(self.__dataLoop, 'dataLoop', sort = -50)
  2111. self.__deadInputs = 0
  2112. def setMouseOnNode(self, newNode):
  2113. if self.mouse2cam:
  2114. self.mouse2cam.node().setNode(newNode)
  2115. def changeMouseInterface(self, changeTo):
  2116. """
  2117. Change the mouse interface used to control the camera.
  2118. """
  2119. # Get rid of the prior interface:
  2120. self.mouseInterface.detachNode()
  2121. # Update the mouseInterface to point to the drive
  2122. self.mouseInterface = changeTo
  2123. self.mouseInterfaceNode = self.mouseInterface.node()
  2124. # Hookup the drive to the camera.
  2125. if self.mouseWatcher:
  2126. self.mouseInterface.reparentTo(self.mouseWatcher)
  2127. if self.mouse2cam:
  2128. self.mouse2cam.reparentTo(self.mouseInterface)
  2129. def useDrive(self):
  2130. """
  2131. Changes the mouse interface used for camera control to drive mode.
  2132. """
  2133. if self.drive:
  2134. self.changeMouseInterface(self.drive)
  2135. # Set the height to a good eyeheight
  2136. self.mouseInterfaceNode.reset()
  2137. self.mouseInterfaceNode.setZ(4.0)
  2138. def useTrackball(self):
  2139. """
  2140. Changes the mouse interface used for camera control to trackball mode.
  2141. """
  2142. if self.trackball:
  2143. self.changeMouseInterface(self.trackball)
  2144. def toggleTexMem(self):
  2145. """
  2146. Toggles a handy texture memory watcher utility.
  2147. See :mod:`direct.showutil.TexMemWatcher` for more information.
  2148. """
  2149. if self.texmem and not self.texmem.cleanedUp:
  2150. self.texmem.cleanup()
  2151. self.texmem = None
  2152. return
  2153. # Use importlib to prevent this import from being picked up
  2154. # by modulefinder when packaging an application.
  2155. TMW = importlib.import_module('direct.showutil.TexMemWatcher')
  2156. self.texmem = TMW.TexMemWatcher()
  2157. def toggleShowVertices(self):
  2158. """ Toggles a mode that visualizes vertex density per screen
  2159. area. """
  2160. if self.showVertices:
  2161. # Clean up the old mode.
  2162. self.showVertices.node().setActive(0)
  2163. dr = self.showVertices.node().getDisplayRegion(0)
  2164. self.win.removeDisplayRegion(dr)
  2165. self.showVertices.removeNode()
  2166. self.showVertices = None
  2167. return
  2168. dr = self.win.makeDisplayRegion()
  2169. dr.setSort(1000)
  2170. cam = Camera('showVertices')
  2171. cam.setLens(self.camLens)
  2172. # Set up a funny state to render only vertices.
  2173. override = 100000
  2174. t = NodePath('t')
  2175. t.setColor(1, 0, 1, 0.02, override)
  2176. t.setColorScale(1, 1, 1, 1, override)
  2177. t.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha), override)
  2178. t.setAttrib(RenderModeAttrib.make(RenderModeAttrib.MPoint, 10), override)
  2179. t.setTwoSided(True, override)
  2180. t.setBin('fixed', 0, override)
  2181. t.setDepthTest(False, override)
  2182. t.setDepthWrite(False, override)
  2183. t.setLightOff(override)
  2184. t.setShaderOff(override)
  2185. t.setFogOff(override)
  2186. t.setAttrib(AntialiasAttrib.make(AntialiasAttrib.MNone), override)
  2187. t.setAttrib(RescaleNormalAttrib.make(RescaleNormalAttrib.MNone), override)
  2188. t.setTextureOff(override)
  2189. # Make the spots round, so there's less static in the display.
  2190. # This forces software point generation on many drivers, so
  2191. # it's not on by default.
  2192. if ConfigVariableBool('round-show-vertices', False):
  2193. spot = PNMImage(256, 256, 1)
  2194. spot.renderSpot((1, 1, 1, 1), (0, 0, 0, 0), 0.8, 1)
  2195. tex = Texture('spot')
  2196. tex.load(spot)
  2197. tex.setFormat(tex.FAlpha)
  2198. t.setTexture(tex, override)
  2199. t.setAttrib(TexGenAttrib.make(TextureStage.getDefault(), TexGenAttrib.MPointSprite), override)
  2200. cam.setInitialState(t.getState())
  2201. cam.setCameraMask(~PandaNode.getOverallBit())
  2202. self.showVertices = self.cam.attachNewNode(cam)
  2203. dr.setCamera(self.showVertices)
  2204. def oobe(self, cam = None):
  2205. """
  2206. Enable a special "out-of-body experience" mouse-interface
  2207. mode. This can be used when a "god" camera is needed; it
  2208. moves the camera node out from under its normal node and sets
  2209. the world up in trackball state. Button events are still sent
  2210. to the normal mouse action node (e.g. the DriveInterface), and
  2211. mouse events, if needed, may be sent to the normal node by
  2212. holding down the Control key.
  2213. This is different than `useTrackball()`, which simply changes
  2214. the existing mouse action to a trackball interface. In fact,
  2215. OOBE mode doesn't care whether `useDrive()` or `useTrackball()` is
  2216. in effect; it just temporarily layers a new trackball
  2217. interface on top of whatever the basic interface is. You can
  2218. even switch between `useDrive()` and `useTrackball()` while OOBE
  2219. mode is in effect.
  2220. This is a toggle; the second time this function is called, it
  2221. disables the mode.
  2222. """
  2223. if cam is None:
  2224. cam = self.cam
  2225. # If oobeMode was never set, set it to false and create the
  2226. # structures we need to implement OOBE.
  2227. if not hasattr(self, 'oobeMode'):
  2228. self.oobeMode = 0
  2229. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  2230. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  2231. self.oobeLens = PerspectiveLens()
  2232. self.oobeLens.setAspectRatio(self.getAspectRatio())
  2233. self.oobeLens.setNearFar(0.1, 10000.0)
  2234. self.oobeLens.setMinFov(40)
  2235. self.oobeTrackball = NodePath(Trackball('oobeTrackball'))
  2236. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  2237. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  2238. self.oobeVis = base.loader.loadModel('models/misc/camera', okMissing = True)
  2239. if not self.oobeVis:
  2240. # Sometimes we have default-model-extension set to
  2241. # egg, but the file might be a bam file.
  2242. self.oobeVis = base.loader.loadModel('models/misc/camera.bam', okMissing = True)
  2243. if not self.oobeVis:
  2244. self.oobeVis = NodePath('oobeVis')
  2245. self.oobeVis.node().setFinal(1)
  2246. self.oobeVis.setLightOff(1)
  2247. self.oobeCullFrustum = None
  2248. self.__directObject.accept('oobe-down', self.__oobeButton, extraArgs = [''])
  2249. self.__directObject.accept('oobe-repeat', self.__oobeButton, extraArgs = ['-repeat'])
  2250. self.__directObject.accept('oobe-up', self.__oobeButton, extraArgs = ['-up'])
  2251. if self.oobeMode:
  2252. # Disable OOBE mode.
  2253. if self.oobeCullFrustum is not None:
  2254. # First, disable OOBE cull mode.
  2255. self.oobeCull(cam = cam)
  2256. if self.oobeVis:
  2257. self.oobeVis.reparentTo(self.hidden)
  2258. # Restore the mouse interface node, and remove the oobe
  2259. # trackball from the data path.
  2260. self.mouseInterfaceNode.clearButton(KeyboardButton.shift())
  2261. self.oobeTrackball.detachNode()
  2262. bt = self.buttonThrowers[0].node()
  2263. bt.setSpecificFlag(1)
  2264. bt.setButtonDownEvent('')
  2265. bt.setButtonRepeatEvent('')
  2266. bt.setButtonUpEvent('')
  2267. cam.reparentTo(self.camera)
  2268. #if cam == self.cam:
  2269. # self.camNode.setLens(self.camLens)
  2270. self.oobeCamera.reparentTo(self.hidden)
  2271. self.oobeMode = 0
  2272. self.bboard.post('oobeEnabled', False)
  2273. else:
  2274. self.bboard.post('oobeEnabled', True)
  2275. try:
  2276. cameraParent = localAvatar
  2277. except NameError:
  2278. # Make oobeCamera be a sibling of wherever camera is now.
  2279. cameraParent = self.camera.getParent()
  2280. self.oobeCamera.reparentTo(cameraParent)
  2281. self.oobeCamera.clearMat()
  2282. # Make the regular MouseInterface node respond only when
  2283. # the shift button is pressed. And the oobe node will
  2284. # respond only when shift is *not* pressed.
  2285. self.mouseInterfaceNode.requireButton(KeyboardButton.shift(), True)
  2286. self.oobeTrackball.node().requireButton(KeyboardButton.shift(), False)
  2287. self.oobeTrackball.reparentTo(self.mouseWatcher)
  2288. # Set our initial OOB position to be just behind the camera.
  2289. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  2290. mat.invertInPlace()
  2291. self.oobeTrackball.node().setMat(mat)
  2292. cam.reparentTo(self.oobeCameraTrackball)
  2293. # Temporarily disable button events by routing them
  2294. # through the oobe filters.
  2295. bt = self.buttonThrowers[0].node()
  2296. bt.setSpecificFlag(0)
  2297. bt.setButtonDownEvent('oobe-down')
  2298. bt.setButtonRepeatEvent('oobe-repeat')
  2299. bt.setButtonUpEvent('oobe-up')
  2300. # Don't change the camera lens--keep it with the original lens.
  2301. #if cam == self.cam:
  2302. # self.camNode.setLens(self.oobeLens)
  2303. if self.oobeVis:
  2304. self.oobeVis.reparentTo(self.camera)
  2305. self.oobeMode = 1
  2306. def __oobeButton(self, suffix, button):
  2307. if button.startswith('mouse'):
  2308. # Eat mouse buttons.
  2309. return
  2310. # Transmit other buttons.
  2311. messenger.send(button + suffix)
  2312. def oobeCull(self, cam = None):
  2313. """
  2314. While in OOBE mode (see above), cull the viewing frustum as if
  2315. it were still attached to our original camera. This allows us
  2316. to visualize the effectiveness of our bounding volumes.
  2317. """
  2318. if cam is None:
  2319. cam = self.cam
  2320. # First, make sure OOBE mode is enabled.
  2321. if not getattr(self, 'oobeMode', False):
  2322. self.oobe(cam = cam)
  2323. if self.oobeCullFrustum is None:
  2324. # Enable OOBE culling.
  2325. pnode = LensNode('oobeCull')
  2326. pnode.setLens(self.camLens)
  2327. pnode.showFrustum()
  2328. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  2329. # Tell the camera to cull from here instead of its own
  2330. # origin.
  2331. for c in self.camList:
  2332. c.node().setCullCenter(self.oobeCullFrustum)
  2333. if cam.node().isOfType(Camera):
  2334. cam.node().setCullCenter(self.oobeCullFrustum)
  2335. for c in cam.findAllMatches('**/+Camera'):
  2336. c.node().setCullCenter(self.oobeCullFrustum)
  2337. else:
  2338. # Disable OOBE culling.
  2339. for c in self.camList:
  2340. c.node().setCullCenter(NodePath())
  2341. if cam.node().isOfType(Camera):
  2342. cam.node().setCullCenter(self.oobeCullFrustum)
  2343. for c in cam.findAllMatches('**/+Camera'):
  2344. c.node().setCullCenter(NodePath())
  2345. self.oobeCullFrustum.removeNode()
  2346. self.oobeCullFrustum = None
  2347. def showCameraFrustum(self):
  2348. # Create a visible representation of the frustum.
  2349. self.removeCameraFrustum()
  2350. geom = self.camLens.makeGeometry()
  2351. if geom is not None:
  2352. gn = GeomNode('frustum')
  2353. gn.addGeom(geom)
  2354. self.camFrustumVis = self.camera.attachNewNode(gn)
  2355. def removeCameraFrustum(self):
  2356. if self.camFrustumVis:
  2357. self.camFrustumVis.removeNode()
  2358. def screenshot(self, namePrefix = 'screenshot',
  2359. defaultFilename = 1, source = None,
  2360. imageComment="", blocking=True):
  2361. """ Captures a screenshot from the main window or from the
  2362. specified window or Texture and writes it to a filename in the
  2363. current directory (or to a specified directory).
  2364. If defaultFilename is True, the filename is synthesized by
  2365. appending namePrefix to a default filename suffix (including
  2366. the filename extension) specified in the Config variable
  2367. screenshot-filename. Otherwise, if defaultFilename is False,
  2368. the entire namePrefix is taken to be the filename to write,
  2369. and this string should include a suitable filename extension
  2370. that will be used to determine the type of image file to
  2371. write.
  2372. Normally, the source is a GraphicsWindow, GraphicsBuffer or
  2373. DisplayRegion. If a Texture is supplied instead, it must have
  2374. a ram image (that is, if it was generated by
  2375. makeTextureBuffer() or makeCubeMap(), the parameter toRam
  2376. should have been set true). If it is a cube map texture as
  2377. generated by makeCubeMap(), namePrefix should contain the hash
  2378. mark ('#') character.
  2379. Normally, this call will block until the screenshot is fully
  2380. written. To write the screenshot in a background thread
  2381. instead, pass blocking = False. In this case, the return value
  2382. is a future that can be awaited.
  2383. A "screenshot" event will be sent once the screenshot is saved.
  2384. :returns: The filename if successful, or None if there is a problem.
  2385. """
  2386. if source is None:
  2387. source = self.win
  2388. if defaultFilename:
  2389. filename = GraphicsOutput.makeScreenshotFilename(namePrefix)
  2390. else:
  2391. filename = Filename(namePrefix)
  2392. if isinstance(source, Texture):
  2393. if source.getZSize() > 1:
  2394. saved = source.write(filename, 0, 0, 1, 0)
  2395. else:
  2396. saved = source.write(filename)
  2397. elif blocking:
  2398. saved = source.saveScreenshot(filename, imageComment)
  2399. else:
  2400. request = source.saveAsyncScreenshot(filename, imageComment)
  2401. request.addDoneCallback(lambda fut, filename=filename: messenger.send('screenshot', [filename]))
  2402. return request
  2403. if saved:
  2404. # Announce to anybody that a screenshot has been taken
  2405. messenger.send('screenshot', [filename])
  2406. return filename
  2407. return None
  2408. def saveCubeMap(self, namePrefix = 'cube_map_#.png',
  2409. defaultFilename = 0, source = None,
  2410. camera = None, size = 128,
  2411. cameraMask = PandaNode.getAllCameraMask(),
  2412. sourceLens = None):
  2413. """
  2414. Similar to :meth:`screenshot()`, this sets up a temporary cube
  2415. map Texture which it uses to take a series of six snapshots of
  2416. the current scene, one in each of the six cube map directions.
  2417. This requires rendering a new frame.
  2418. Unlike `screenshot()`, source may only be a GraphicsWindow,
  2419. GraphicsBuffer, or DisplayRegion; it may not be a Texture.
  2420. camera should be the node to which the cubemap cameras will be
  2421. parented. The default is the camera associated with source,
  2422. if source is a DisplayRegion, or base.camera otherwise.
  2423. :returns: The filename if successful, or None if there is a problem.
  2424. """
  2425. if source is None:
  2426. source = self.win
  2427. if camera is None:
  2428. if hasattr(source, "getCamera"):
  2429. camera = source.getCamera()
  2430. if camera is None:
  2431. camera = self.camera
  2432. if sourceLens is None:
  2433. sourceLens = self.camLens
  2434. if hasattr(source, "getWindow"):
  2435. source = source.getWindow()
  2436. rig = NodePath(namePrefix)
  2437. buffer = source.makeCubeMap(namePrefix, size, rig, cameraMask, 1)
  2438. if buffer is None:
  2439. raise Exception("Could not make cube map.")
  2440. # Set the near and far planes from the default lens.
  2441. lens = rig.find('**/+Camera').node().getLens()
  2442. lens.setNearFar(sourceLens.getNear(), sourceLens.getFar())
  2443. # Now render a frame to fill up the texture.
  2444. rig.reparentTo(camera)
  2445. self.graphicsEngine.openWindows()
  2446. self.graphicsEngine.renderFrame()
  2447. self.graphicsEngine.renderFrame()
  2448. self.graphicsEngine.syncFrame()
  2449. tex = buffer.getTexture()
  2450. saved = self.screenshot(namePrefix = namePrefix,
  2451. defaultFilename = defaultFilename,
  2452. source = tex)
  2453. self.graphicsEngine.removeWindow(buffer)
  2454. rig.removeNode()
  2455. return saved
  2456. def saveSphereMap(self, namePrefix = 'spheremap.png',
  2457. defaultFilename = 0, source = None,
  2458. camera = None, size = 256,
  2459. cameraMask = PandaNode.getAllCameraMask(),
  2460. numVertices = 1000, sourceLens = None):
  2461. """
  2462. This works much like :meth:`saveCubeMap()`, and uses the
  2463. graphics API's hardware cube-mapping ability to get a 360-degree
  2464. view of the world. But then it converts the six cube map faces
  2465. into a single fisheye texture, suitable for applying as a static
  2466. environment map (sphere map).
  2467. For eye-relative static environment maps, sphere maps are often
  2468. preferable to cube maps because they require only a single
  2469. texture and because they are supported on a broader range of
  2470. hardware.
  2471. :returns: The filename if successful, or None if there is a problem.
  2472. """
  2473. if source is None:
  2474. source = self.win
  2475. if camera is None:
  2476. if hasattr(source, "getCamera"):
  2477. camera = source.getCamera()
  2478. if camera is None:
  2479. camera = self.camera
  2480. if sourceLens is None:
  2481. sourceLens = self.camLens
  2482. if hasattr(source, "getWindow"):
  2483. source = source.getWindow()
  2484. # First, make an offscreen buffer to convert the cube map to a
  2485. # sphere map. We make it first so we can guarantee the
  2486. # rendering order for the cube map.
  2487. toSphere = source.makeTextureBuffer(namePrefix, size, size,
  2488. Texture(), 1)
  2489. # Now make the cube map buffer.
  2490. rig = NodePath(namePrefix)
  2491. buffer = toSphere.makeCubeMap(namePrefix, size, rig, cameraMask, 0)
  2492. if buffer is None:
  2493. self.graphicsEngine.removeWindow(toSphere)
  2494. raise Exception("Could not make cube map.")
  2495. # Set the near and far planes from the default lens.
  2496. lens = rig.find('**/+Camera').node().getLens()
  2497. lens.setNearFar(sourceLens.getNear(), sourceLens.getFar())
  2498. # Set up the scene to convert the cube map. It's just a
  2499. # simple scene, with only the FisheyeMaker object in it.
  2500. dr = toSphere.makeMonoDisplayRegion()
  2501. camNode = Camera('camNode')
  2502. lens = OrthographicLens()
  2503. lens.setFilmSize(2, 2)
  2504. lens.setNearFar(-1000, 1000)
  2505. camNode.setLens(lens)
  2506. root = NodePath('buffer')
  2507. cam = root.attachNewNode(camNode)
  2508. dr.setCamera(cam)
  2509. fm = FisheyeMaker('card')
  2510. fm.setNumVertices(numVertices)
  2511. fm.setSquareInscribed(1, 1.1)
  2512. fm.setReflection(1)
  2513. card = root.attachNewNode(fm.generate())
  2514. card.setTexture(buffer.getTexture())
  2515. # Now render a frame. This will render out the cube map and
  2516. # then apply it to the the card in the toSphere buffer.
  2517. rig.reparentTo(camera)
  2518. self.graphicsEngine.openWindows()
  2519. self.graphicsEngine.renderFrame()
  2520. # One more frame for luck.
  2521. self.graphicsEngine.renderFrame()
  2522. self.graphicsEngine.syncFrame()
  2523. saved = self.screenshot(namePrefix = namePrefix,
  2524. defaultFilename = defaultFilename,
  2525. source = toSphere.getTexture())
  2526. self.graphicsEngine.removeWindow(buffer)
  2527. self.graphicsEngine.removeWindow(toSphere)
  2528. rig.removeNode()
  2529. return saved
  2530. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  2531. format = 'png', sd = 4, source = None):
  2532. """
  2533. Spawn a task to capture a movie using the screenshot function.
  2534. Args:
  2535. namePrefix (str): used to form output file names (can
  2536. include path information (e.g. '/i/beta/frames/myMovie')
  2537. duration (float): the length of the movie in seconds
  2538. fps (float): the frame rate of the resulting movie
  2539. format (str): specifies output file format (e.g. png, bmp)
  2540. sd (int): specifies number of significant digits for frame
  2541. count in the output file name (e.g. if sd = 4, the name
  2542. will be something like movie_0001.png)
  2543. source: the Window, Buffer, DisplayRegion, or Texture from
  2544. which to save the resulting images. The default is the
  2545. main window.
  2546. Returns:
  2547. A `~direct.task.Task` that can be awaited.
  2548. """
  2549. clock = self.clock
  2550. clock.mode = ClockObject.MNonRealTime
  2551. clock.dt = 1.0 / fps
  2552. t = self.taskMgr.add(self._movieTask, namePrefix + '_task')
  2553. t.frameIndex = 0 # Frame 0 is not captured.
  2554. t.numFrames = int(duration * fps)
  2555. t.source = source
  2556. t.outputString = namePrefix + '_%0' + repr(sd) + 'd.' + format
  2557. t.setUponDeath(lambda state: clock.setMode(ClockObject.MNormal))
  2558. return t
  2559. def _movieTask(self, state):
  2560. if state.frameIndex != 0:
  2561. frameName = state.outputString % state.frameIndex
  2562. self.notify.info("Capturing frame: " + frameName)
  2563. self.screenshot(namePrefix = frameName, defaultFilename = 0,
  2564. source = state.source)
  2565. state.frameIndex += 1
  2566. if state.frameIndex > state.numFrames:
  2567. return Task.done
  2568. else:
  2569. return Task.cont
  2570. def windowEvent(self, win):
  2571. if win != self.win:
  2572. # This event isn't about our window.
  2573. return
  2574. properties = win.getProperties()
  2575. if properties != self.__prevWindowProperties:
  2576. self.__prevWindowProperties = properties
  2577. self.notify.debug("Got window event: %s" % (repr(properties)))
  2578. if not properties.getOpen():
  2579. # If the user closes the main window, we should exit.
  2580. self.notify.info("User closed main window.")
  2581. if __debug__:
  2582. if self.__autoGarbageLogging:
  2583. GarbageReport.b_checkForGarbageLeaks()
  2584. self.userExit()
  2585. if properties.getForeground() and not self.mainWinForeground:
  2586. self.mainWinForeground = 1
  2587. elif not properties.getForeground() and self.mainWinForeground:
  2588. self.mainWinForeground = 0
  2589. if __debug__:
  2590. if self.__autoGarbageLogging:
  2591. GarbageReport.b_checkForGarbageLeaks()
  2592. if properties.getMinimized() and not self.mainWinMinimized:
  2593. # If the main window is minimized, throw an event to
  2594. # stop the music.
  2595. self.mainWinMinimized = 1
  2596. messenger.send('PandaPaused')
  2597. elif not properties.getMinimized() and self.mainWinMinimized:
  2598. # If the main window is restored, throw an event to
  2599. # restart the music.
  2600. self.mainWinMinimized = 0
  2601. messenger.send('PandaRestarted')
  2602. # If we have not forced the aspect ratio, let's see if it has
  2603. # changed and update the camera lenses and aspect2d parameters
  2604. self.adjustWindowAspectRatio(self.getAspectRatio())
  2605. if win.hasSize() and win.getSbsLeftYSize() != 0:
  2606. self.pixel2d.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize())
  2607. if self.wantRender2dp:
  2608. self.pixel2dp.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize())
  2609. else:
  2610. xsize, ysize = self.getSize()
  2611. if xsize > 0 and ysize > 0:
  2612. self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  2613. if self.wantRender2dp:
  2614. self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  2615. def adjustWindowAspectRatio(self, aspectRatio):
  2616. """ This function is normally called internally by
  2617. `windowEvent()`, but it may also be called to explicitly adjust
  2618. the aspect ratio of the render/render2d DisplayRegion, by a
  2619. class that has redefined these. """
  2620. if self.__configAspectRatio:
  2621. aspectRatio = self.__configAspectRatio
  2622. if aspectRatio != self.__oldAspectRatio:
  2623. self.__oldAspectRatio = aspectRatio
  2624. # Fix up some anything that depends on the aspectRatio
  2625. if self.camLens:
  2626. self.camLens.setAspectRatio(aspectRatio)
  2627. if aspectRatio < 1:
  2628. # If the window is TALL, lets expand the top and bottom
  2629. self.aspect2d.setScale(1.0, aspectRatio, aspectRatio)
  2630. self.a2dTop = 1.0 / aspectRatio
  2631. self.a2dBottom = - 1.0 / aspectRatio
  2632. self.a2dLeft = -1
  2633. self.a2dRight = 1.0
  2634. # Don't forget 2dp
  2635. if self.wantRender2dp:
  2636. self.aspect2dp.setScale(1.0, aspectRatio, aspectRatio)
  2637. self.a2dpTop = 1.0 / aspectRatio
  2638. self.a2dpBottom = - 1.0 / aspectRatio
  2639. self.a2dpLeft = -1
  2640. self.a2dpRight = 1.0
  2641. else:
  2642. # If the window is WIDE, lets expand the left and right
  2643. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2644. self.a2dTop = 1.0
  2645. self.a2dBottom = -1.0
  2646. self.a2dLeft = -aspectRatio
  2647. self.a2dRight = aspectRatio
  2648. # Don't forget 2dp
  2649. if self.wantRender2dp:
  2650. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2651. self.a2dpTop = 1.0
  2652. self.a2dpBottom = -1.0
  2653. self.a2dpLeft = -aspectRatio
  2654. self.a2dpRight = aspectRatio
  2655. # Reposition the aspect2d marker nodes
  2656. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  2657. self.a2dTopCenterNs.setPos(0, 0, self.a2dTop)
  2658. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  2659. self.a2dBottomCenterNs.setPos(0, 0, self.a2dBottom)
  2660. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  2661. self.a2dLeftCenterNs.setPos(self.a2dLeft, 0, 0)
  2662. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  2663. self.a2dRightCenterNs.setPos(self.a2dRight, 0, 0)
  2664. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  2665. self.a2dTopLeftNs.setPos(self.a2dLeft, 0, self.a2dTop)
  2666. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  2667. self.a2dTopRightNs.setPos(self.a2dRight, 0, self.a2dTop)
  2668. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  2669. self.a2dBottomLeftNs.setPos(self.a2dLeft, 0, self.a2dBottom)
  2670. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  2671. self.a2dBottomRightNs.setPos(self.a2dRight, 0, self.a2dBottom)
  2672. # Reposition the aspect2dp marker nodes
  2673. if self.wantRender2dp:
  2674. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  2675. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  2676. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  2677. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  2678. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  2679. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  2680. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  2681. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  2682. # If anybody needs to update their GUI, put a callback on this event
  2683. messenger.send("aspectRatioChanged")
  2684. def userExit(self):
  2685. # The user has requested we exit the program. Deal with this.
  2686. if self.exitFunc:
  2687. self.exitFunc()
  2688. self.notify.info("Exiting ShowBase.")
  2689. self.finalizeExit()
  2690. def finalizeExit(self):
  2691. """
  2692. Called by `userExit()` to quit the application. The default
  2693. implementation just calls `sys.exit()`.
  2694. """
  2695. sys.exit()
  2696. # [gjeon] start wxPython
  2697. def startWx(self, fWantWx = True):
  2698. fWantWx = bool(fWantWx)
  2699. if self.wantWx != fWantWx:
  2700. self.wantWx = fWantWx
  2701. if self.wantWx:
  2702. self.spawnWxLoop()
  2703. def spawnWxLoop(self):
  2704. """ Call this method to hand the main loop over to wxPython.
  2705. This sets up a wxTimer callback so that Panda still gets
  2706. updated, but wxPython owns the main loop (which seems to make
  2707. it happier than the other way around). """
  2708. if self.wxAppCreated:
  2709. # Don't do this twice.
  2710. return
  2711. init_app_for_gui()
  2712. # Use importlib to prevent this import from being picked up
  2713. # by modulefinder when packaging an application.
  2714. wx = importlib.import_module('wx')
  2715. if not self.wxApp:
  2716. # Create a new base.wxApp.
  2717. self.wxApp = wx.App(redirect = False)
  2718. if ConfigVariableBool('wx-main-loop', True):
  2719. # Put wxPython in charge of the main loop. It really
  2720. # seems to like this better; some features of wx don't
  2721. # work properly unless this is true.
  2722. # Set a timer to run the Panda frame 60 times per second.
  2723. wxFrameRate = ConfigVariableDouble('wx-frame-rate', 60.0)
  2724. self.wxTimer = wx.Timer(self.wxApp)
  2725. self.wxTimer.Start(int(round(1000.0 / wxFrameRate.value)))
  2726. self.wxApp.Bind(wx.EVT_TIMER, self.__wxTimerCallback)
  2727. # wx is now the main loop, not us any more.
  2728. self.run = self.wxRun
  2729. self.taskMgr.run = self.wxRun
  2730. builtins.run = self.wxRun
  2731. if self.appRunner:
  2732. self.appRunner.run = self.wxRun
  2733. else:
  2734. # Leave Panda in charge of the main loop. This is
  2735. # friendlier for IDE's and interactive editing in general.
  2736. def wxLoop(task):
  2737. # First we need to ensure that the OS message queue is
  2738. # processed.
  2739. self.wxApp.Yield()
  2740. # Now do all the wxPython events waiting on this frame.
  2741. while self.wxApp.Pending():
  2742. self.wxApp.Dispatch()
  2743. return task.again
  2744. self.taskMgr.add(wxLoop, 'wxLoop')
  2745. self.wxAppCreated = True
  2746. def __wxTimerCallback(self, event):
  2747. if Thread.getCurrentThread().getCurrentTask():
  2748. # This happens when the wxTimer expires while igLoop is
  2749. # rendering. Ignore it.
  2750. return
  2751. self.taskMgr.step()
  2752. def wxRun(self):
  2753. """ This method replaces `run()` after we have called `spawnWxLoop()`.
  2754. Since at this point wxPython now owns the main loop, this method is a
  2755. call to wxApp.MainLoop(). """
  2756. if Thread.getCurrentThread().getCurrentTask():
  2757. # This happens in the p3d environment during startup.
  2758. # Ignore it.
  2759. return
  2760. self.wxApp.MainLoop()
  2761. def startTk(self, fWantTk = True):
  2762. fWantTk = bool(fWantTk)
  2763. if self.wantTk != fWantTk:
  2764. self.wantTk = fWantTk
  2765. if self.wantTk:
  2766. self.spawnTkLoop()
  2767. def spawnTkLoop(self):
  2768. """ Call this method to hand the main loop over to Tkinter.
  2769. This sets up a timer callback so that Panda still gets
  2770. updated, but Tkinter owns the main loop (which seems to make
  2771. it happier than the other way around). """
  2772. if self.tkRootCreated:
  2773. # Don't do this twice.
  2774. return
  2775. # Use importlib to prevent this import from being picked up
  2776. # by modulefinder when packaging an application.
  2777. tkinter = importlib.import_module('_tkinter')
  2778. Pmw = importlib.import_module('Pmw')
  2779. # Create a new Tk root.
  2780. if not self.tkRoot:
  2781. self.tkRoot = Pmw.initialise()
  2782. builtins.tkroot = self.tkRoot
  2783. init_app_for_gui()
  2784. # Disable the Windows message loop, since Tcl wants to handle this all
  2785. # on its own, except if the Panda window is on a separate thread.
  2786. if self.graphicsEngine.getThreadingModel().getDrawStage() == 0:
  2787. ConfigVariableBool('disable-message-loop', False).value = True
  2788. if ConfigVariableBool('tk-main-loop', True):
  2789. # Put Tkinter in charge of the main loop. It really
  2790. # seems to like this better; the GUI otherwise becomes
  2791. # largely unresponsive on Mac OS X unless this is true.
  2792. # Set a timer to run the Panda frame 60 times per second.
  2793. tkFrameRate = ConfigVariableDouble('tk-frame-rate', 60.0)
  2794. self.tkDelay = int(1000.0 / tkFrameRate.value)
  2795. self.tkRoot.after(self.tkDelay, self.__tkTimerCallback)
  2796. # wx is now the main loop, not us any more.
  2797. self.run = self.tkRun
  2798. self.taskMgr.run = self.tkRun
  2799. builtins.run = self.tkRun
  2800. if self.appRunner:
  2801. self.appRunner.run = self.tkRun
  2802. else:
  2803. # Leave Panda in charge of the main loop. This is
  2804. # friendlier for IDE's and interactive editing in general.
  2805. def tkLoop(task):
  2806. # Do all the tkinter events waiting on this frame
  2807. # dooneevent will return 0 if there are no more events
  2808. # waiting or 1 if there are still more.
  2809. # DONT_WAIT tells tkinter not to block waiting for events
  2810. while self.tkRoot.dooneevent(tkinter.ALL_EVENTS | tkinter.DONT_WAIT):
  2811. pass
  2812. return task.again
  2813. self.taskMgr.add(tkLoop, 'tkLoop')
  2814. self.tkRootCreated = True
  2815. def __tkTimerCallback(self):
  2816. if not Thread.getCurrentThread().getCurrentTask():
  2817. self.taskMgr.step()
  2818. self.tkRoot.after(self.tkDelay, self.__tkTimerCallback)
  2819. def tkRun(self):
  2820. """ This method replaces `run()` after we have called `spawnTkLoop()`.
  2821. Since at this point Tkinter now owns the main loop, this method is a
  2822. call to tkRoot.mainloop(). """
  2823. if Thread.getCurrentThread().getCurrentTask():
  2824. # This happens in the p3d environment during startup.
  2825. # Ignore it.
  2826. return
  2827. self.tkRoot.mainloop()
  2828. def startDirect(self, fWantDirect = 1, fWantTk = 1, fWantWx = 0):
  2829. self.startTk(fWantTk)
  2830. self.startWx(fWantWx)
  2831. if self.wantDirect == fWantDirect:
  2832. return
  2833. self.wantDirect = fWantDirect
  2834. if self.wantDirect:
  2835. # Use importlib to prevent this import from being picked up
  2836. # by modulefinder when packaging an application.
  2837. DirectSession = importlib.import_module('direct.directtools.DirectSession')
  2838. self.direct = DirectSession.DirectSession()
  2839. self.direct.enable()
  2840. builtins.direct = self.direct
  2841. else:
  2842. builtins.direct = self.direct = None
  2843. def getRepository(self):
  2844. return None
  2845. def getAxes(self):
  2846. """
  2847. Loads and returns the ``models/misc/xyzAxis.bam`` model.
  2848. :rtype: panda3d.core.NodePath
  2849. """
  2850. return self.loader.loadModel("models/misc/xyzAxis.bam")
  2851. def __doStartDirect(self):
  2852. if self.__directStarted:
  2853. return
  2854. self.__directStarted = False
  2855. # Start Tk, Wx and DIRECT if specified by Config.prc
  2856. fTk = ConfigVariableBool('want-tk', False).value
  2857. fWx = ConfigVariableBool('want-wx', False).value
  2858. # Start DIRECT if specified in Config.prc or in cluster mode
  2859. fDirect = (ConfigVariableBool('want-directtools', 0).value or
  2860. (not ConfigVariableString("cluster-mode", '').empty()))
  2861. # Set fWantTk to 0 to avoid starting Tk with this call
  2862. self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)
  2863. def run(self): # pylint: disable=method-hidden
  2864. """This method runs the :class:`~direct.task.Task.TaskManager`
  2865. when ``self.appRunner is None``, which is to say, when we are
  2866. not running from within a p3d file. When we *are* within a p3d
  2867. file, the Panda3D runtime has to be responsible for running the
  2868. main loop, so we can't allow the application to do it.
  2869. This method must be called from the main thread, otherwise an error is
  2870. thrown.
  2871. """
  2872. if Thread.getCurrentThread() != Thread.getMainThread():
  2873. self.notify.error("run() must be called from the main thread.")
  2874. return
  2875. if self.appRunner is None or self.appRunner.dummy or \
  2876. (self.appRunner.interactiveConsole and not self.appRunner.initialAppImport):
  2877. self.taskMgr.run()
  2878. # Snake-case aliases, for people who prefer these. We're in the process
  2879. # of migrating everyone to use the snake-case alternatives.
  2880. make_default_pipe = makeDefaultPipe
  2881. make_module_pipe = makeModulePipe
  2882. make_all_pipes = makeAllPipes
  2883. open_window = openWindow
  2884. close_window = closeWindow
  2885. open_default_window = openDefaultWindow
  2886. open_main_window = openMainWindow
  2887. set_sleep = setSleep
  2888. set_frame_rate_meter = setFrameRateMeter
  2889. set_scene_graph_analyzer_meter = setSceneGraphAnalyzerMeter
  2890. setup_window_controls = setupWindowControls
  2891. setup_render = setupRender
  2892. setup_render2d = setupRender2d
  2893. setup_render2dp = setupRender2dp
  2894. set_aspect_ratio = setAspectRatio
  2895. get_aspect_ratio = getAspectRatio
  2896. get_size = getSize
  2897. make_camera = makeCamera
  2898. make_camera2d = makeCamera2d
  2899. make_camera2dp = makeCamera2dp
  2900. setup_data_graph = setupDataGraph
  2901. setup_mouse = setupMouse
  2902. setup_mouse_cb = setupMouseCB
  2903. enable_software_mouse_pointer = enableSoftwareMousePointer
  2904. detach_input_device = detachInputDevice
  2905. attach_input_device = attachInputDevice
  2906. add_angular_integrator = addAngularIntegrator
  2907. enable_particles = enableParticles
  2908. disable_particles = disableParticles
  2909. toggle_particles = toggleParticles
  2910. create_stats = createStats
  2911. add_sfx_manager = addSfxManager
  2912. enable_music = enableMusic
  2913. enable_sound_effects = enableSoundEffects
  2914. disable_all_audio = disableAllAudio
  2915. enable_all_audio = enableAllAudio
  2916. init_shadow_trav = initShadowTrav
  2917. get_background_color = getBackgroundColor
  2918. set_background_color = setBackgroundColor
  2919. toggle_backface = toggleBackface
  2920. backface_culling_on = backfaceCullingOn
  2921. backface_culling_off = backfaceCullingOff
  2922. toggle_texture = toggleTexture
  2923. texture_on = textureOn
  2924. texture_off = textureOff
  2925. toggle_wireframe = toggleWireframe
  2926. wireframe_on = wireframeOn
  2927. wireframe_off = wireframeOff
  2928. disable_mouse = disableMouse
  2929. enable_mouse = enableMouse
  2930. silence_input = silenceInput
  2931. revive_input = reviveInput
  2932. set_mouse_on_node = setMouseOnNode
  2933. change_mouse_interface = changeMouseInterface
  2934. use_drive = useDrive
  2935. use_trackball = useTrackball
  2936. toggle_tex_mem = toggleTexMem
  2937. toggle_show_vertices = toggleShowVertices
  2938. oobe_cull = oobeCull
  2939. show_camera_frustum = showCameraFrustum
  2940. remove_camera_frustum = removeCameraFrustum
  2941. save_cube_map = saveCubeMap
  2942. save_sphere_map = saveSphereMap
  2943. start_wx = startWx
  2944. start_tk = startTk
  2945. start_direct = startDirect
  2946. # A class to encapsulate information necessary for multiwindow support.
  2947. class WindowControls:
  2948. def __init__(
  2949. self, win, cam=None, camNode=None, cam2d=None, mouseWatcher=None,
  2950. mouseKeyboard=None, closeCmd=lambda: 0, grid=None):
  2951. self.win = win
  2952. self.camera = cam
  2953. if camNode is None and cam is not None:
  2954. camNode = cam.node()
  2955. self.camNode = camNode
  2956. self.camera2d = cam2d
  2957. self.mouseWatcher = mouseWatcher
  2958. self.mouseKeyboard = mouseKeyboard
  2959. self.closeCommand = closeCmd
  2960. self.grid = grid
  2961. def __str__(self):
  2962. s = "window = " + str(self.win) + "\n"
  2963. s += "camera = " + str(self.camera) + "\n"
  2964. s += "camNode = " + str(self.camNode) + "\n"
  2965. s += "camera2d = " + str(self.camera2d) + "\n"
  2966. s += "mouseWatcher = " + str(self.mouseWatcher) + "\n"
  2967. s += "mouseAndKeyboard = " + str(self.mouseKeyboard) + "\n"
  2968. return s