Ejemplo n.º 1
0
    def setHDR(self, toggle):
        self.hdrToggle = toggle

        if toggle:
            # Don't clamp lighting calculations with hdr.
            render.setAttrib(LightRampAttrib.makeIdentity())
        else:
            render.setAttrib(LightRampAttrib.makeDefault())
Ejemplo n.º 2
0
    def enable_hdr(self, enable):
        """Turn HDR effect on or off.

        Arguments:
            enable {bool} -- flag
        """
        if enable:
            self.render.set_attrib(LightRampAttrib.makeHdr0())
        else:
            self.render.set_attrib(LightRampAttrib.makeDefault())
        self._hdr_enabled = enable
Ejemplo n.º 3
0
 def toggle_hdr(self):
     self.hdr += 1
     if self.hdr > 3: self.hdr = 0
     print("HDR:", self.hdr)
     if self.hdr == 0:
         self.world.clearAttrib(LightRampAttrib.getClassType())
     elif self.hdr == 1:
         self.world.setAttrib(LightRampAttrib.makeHdr0())
     elif self.hdr == 2:
         self.world.setAttrib(LightRampAttrib.makeHdr1())
     elif self.hdr == 3:
         self.world.setAttrib(LightRampAttrib.makeHdr2())
    def setHDR(self, toggle):
        self.hdrToggle = toggle

        #if not hasattr(self, 'hdr'):
        #    return

        if toggle:
            # Don't clamp lighting calculations with hdr.
            render.setAttrib(LightRampAttrib.makeIdentity())
            #self.hdr.enable()
        else:
            render.setAttrib(LightRampAttrib.makeDefault())
Ejemplo n.º 5
0
    def new_game(self):
        Maze.__init__(self, self.total_rooms)
        self.items = []
        self.tiles = defaultdict(Tile)
        self.root = render.attach_new_node("map_root")
        self.static = self.root.attach_new_node("map-static")
        self.unlit = render.attach_new_node("map-unlit")
        self.backsides = self.root.attach_new_node("map-backsides")
        self.dynamic = render.attach_new_node("map-dynamic")
        self.enemies = []
        self.rooms = {}
        self.rooms_visited = 0
        self.current_set = 0
        self.tile_set = self.tile_sets[self.sets[self.current_set]]
        self.dynamic.hide(0b001)
        base.player.root.hide(0b001)
        for target_np in [
                self.static,
                self.backsides,
                self.unlit,
                self.dynamic,
        ]:
            target_np.set_attrib(
                LightRampAttrib.make_single_threshold(0.0, 1.0))
            target_np.set_light(base.fov_point_np)
        base.fov_point_np.reparent_to(base.player.root)
        base.fov_point.set_scene(self.root)

        p = self.pos(8)
        self.rooms[p] = Room(*p)
        base.player.root.set_pos((p[0] + 4, -p[1] - 4, 0))
        base.player.reset()
    def __init__(self):
        base.disableMouse()
        base.cam.node().getLens().setNear(10.0)
        base.cam.node().getLens().setFar(9999999)
        camera.setPos(0, -50, 0)
        
        # Check video card capabilities.
        
        if (base.win.getGsg().getSupportsBasicShaders() == 0):
            addTitle("Toon Shader: Video driver reports that shaders are not supported.")
            return
        
        # Enable a 'light ramp' - this discretizes the lighting,
        # which is half of what makes a model look like a cartoon.
        # Light ramps only work if shader generation is enabled,
        # so we call 'setShaderAuto'.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.5, 0.4))
        tempnode.setShaderAuto()
        base.cam.node().setInitialState(tempnode.getState())
        
        # Use class 'CommonFilters' to enable a cartoon inking filter.
        # This can fail if the video card is not powerful enough, if so,
        # display an error and exit.
        
        self.separation = 1 # Pixels
        self.filters = CommonFilters(base.win, base.cam)
        filterok = self.filters.setCartoonInk(separation=self.separation)
        if (filterok == False):
            addTitle("Toon Shader: Video card not powerful enough to do image postprocessing")
            return
        
        # Create a non-attenuating point light and an ambient light.
        
        plightnode = PointLight("point light")
        plightnode.setAttenuation(Vec3(1,0,0))
        plight = render.attachNewNode(plightnode)
        plight.setPos(30,-50,0)
        alightnode = AmbientLight("ambient light")
        alightnode.setColor(Vec4(0.8,0.8,0.8,1))
        alight = render.attachNewNode(alightnode)
        render.setLight(alight)
        render.setLight(plight)
        
        # Panda contains a built-in viewer that lets you view the 
        # results of all render-to-texture operations.  This lets you
        # see what class CommonFilters is doing behind the scenes.
        
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")
        self.accept("s", self.filters.manager.resizeBuffers)
        
        # These allow you to change cartooning parameters in realtime
        
        self.accept("escape", sys.exit, [0])
 def __init__(self, aCol, dDir, dCol):
     render.setAttrib(LightRampAttrib.makeHdr1())
     ambientLight = AmbientLight("ambientLight")
     ambientLight.setColor(aCol)
     directionalLight = DirectionalLight("directionalLight")
     directionalLight.setDirection(dDir)
     directionalLight.setColor(dCol)
     directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 0))
     render.setLight(render.attachNewNode(ambientLight))
     render.setLight(render.attachNewNode(directionalLight))
Ejemplo n.º 8
0
	def __init__(self, aCol, dDir, dCol):
		render.setAttrib(LightRampAttrib.makeHdr1())
		ambientLight = AmbientLight("ambientLight")
		ambientLight.setColor(aCol)
		directionalLight = DirectionalLight("directionalLight")
		directionalLight.setDirection(dDir)
		directionalLight.setColor(dCol)
		directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 0))
		render.setLight(render.attachNewNode(ambientLight))
		render.setLight(render.attachNewNode(directionalLight))
Ejemplo n.º 9
0
  def stop(self):
    if self.hdrtype!=None:
      render.clearAttrib(LightRampAttrib.getClassType())

    if self.perpixel:
      render.setShaderOff()
    
    if self.bloomSize!=None:
      self.cf.delBloom()
    
    if self.showbuffers:
      base.bufferViewer.toggleEnable()
Ejemplo n.º 10
0
 def toggle_cartoon(self):
     ''' Use Cartoon ink filter '''
     self.cartoon = not self.cartoon
     if self.cartoon:
         tempnode = NodePath(PandaNode("temp node"))
         tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.4, 0.6))
         tempnode.setShaderAuto()
         base.cam.node().setInitialState(tempnode.getState())
         self.separation = 1.3 # Pixels
         self.filters = CommonFilters(base.win, base.cam)
         self.filters.setCartoonInk(separation=self.separation)
         # Currently using MAuto antialias, uncomment to use different
         #render.setAntialias(AntialiasAttrib.MBetter)
         #self.filters.finalQuad.setAntialias(AntialiasAttrib.MBetter)
     else:
         self.filters.cleanup()
         base.cam.node().setInitialState(self.alight.getState())
Ejemplo n.º 11
0
	def register(self, render, camera, keys, render2d):
		State.register(self, render, camera, keys, render2d)
		self.node.attachNewNode(self.stage.maps[self.room].getNode())


		for c in self.characters:
			self.status[c].reparentTo(self.node2d)

		for char in self.characters.values():
			char.getNode().reparentTo(self.node)
			char.stunRender = self.node

		for l in self.stage.getLights():
			render.setLight(l)

		# COWABUNGA test!!!
		self.hearts = {}
		numChar=0

		self.heartsNode = NodePath(PandaNode('hearts'))
		self.heartsNode.reparentTo(self.node2d)

		for char in self.characters:
			self.hearts[char] = []

			for i in range(Character.maxHearts):
				self.hearts[char].append(Sprite("heart.png", 0.05, 0.05))
				self.hearts[char][i].setPos(-0.8 + 1.4*numChar + (i%3)*0.055 , -0.9 - int(i/3)*0.055)
				self.hearts[char][i].getNode().reparentTo(self.heartsNode)

			numChar += 1

		#COWABUNGA comment this to stop the madness
		render.setAttrib(LightRampAttrib.makeSingleThreshold(0.1, 1))

		# THE TRUE CARTOON SHADER :P
#		self.separation = 1 # Pixels
		self.filters = CommonFilters(base.win, self.camera.camera)
		# cell shading
#		filterok = self.filters.setCartoonInk(separation=self.separation)
		# glow
		filterok = self.filters.setBloom(blend=(0.5,0.5,0.5,1), desat=-0.5, intensity=0.5, size="small")

		self.camera.setPos(0, -2.5, -2.5)
		self.camera.lookAt(0, 0, 0)
Ejemplo n.º 12
0
    def compose_filters(self, win, cam, seperation=.6):
        """
        function to handle the composing, which makes for the basic look and feel of the game
        also handles any filters which are attached to the cam
        :return:
        """
        # set up the lightramp effect
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(
            0.5, 0.4))  # warning can be ignored..
        tempnode.setShaderAuto()
        cam.node().setInitialState(tempnode.getState())

        self.separation = seperation  # Pixels
        self.filters = CommonFilters(win, cam)
        filterok = self.filters.setCartoonInk(separation=self.separation)
        if (filterok == False):
            return
Ejemplo n.º 13
0
    def setShaders(self):
        if not base.win.getGsg().getSupportsBasicShaders():
            print(
                "Toon Shader: Video driver reports that Cg shaders are not supported."
            )
            return

        tempnode = NodePath(PandaNode("temp node"))

        tempnode.setAttrib(LightRampAttrib.makeHdr0())
        self.filters = CommonFilters(base.win, base.cam)

        # GLOW
        self.filters.setBloom(blend=(0.3, 0.4, 0.3, 0.0),
                              mintrigger=0.6,
                              maxtrigger=1.0,
                              desat=0.6,
                              intensity=1.0,
                              size="medium")

        tempnode.setShaderAuto()
        base.cam.node().setInitialState(tempnode.getState())
Ejemplo n.º 14
0
    def __init__(self):
        DirectObject.__init__(self)
        self.filename = None
        self.unsaved = False
        self.idGenerator = IDGenerator()
        self.world = None
        self.isOpen = False
        self.gsg = None
        self.page = None
        self.shaderGenerator = None

        self.numlights = 0

        # Each document has its own message bus, task manager, and event manager.
        self.taskMgr = TaskManager()
        self.taskMgr.mgr = AsyncTaskManager("documentTaskMgr")
        self.messenger = Messenger(self.taskMgr)
        self.eventMgr = EventManager(messenger=self.messenger,
                                     taskMgr=self.taskMgr)
        self.messenger.setEventMgr(self.eventMgr)

        self.render = NodePath("docRender")
        self.render.setAttrib(LightRampAttrib.makeIdentity())
        #self.render.setShaderAuto()

        self.viewportMgr = ViewportManager(self)
        self.toolMgr = ToolManager(self)
        self.selectionMgr = SelectionManager(self)
        self.actionMgr = ActionManager(self)

        # Create the page that the document is viewed in.
        self.page = DocumentWindow(self)
        #self.createShaderGenerator()

        self.toolMgr.addTools()

        self.eventMgr.restart()
Ejemplo n.º 15
0
    def renderSceneInto(self,
                        depthtex=None,
                        colortex=None,
                        auxtex=None,
                        auxbits=0,
                        textures=None,
                        fbprops=None,
                        clamping=None):
        """ Causes the scene to be rendered into the supplied textures
        instead of into the original window.  Puts a fullscreen quad
        into the original window to show the render-to-texture results.
        Returns the quad.  Normally, the caller would then apply a
        shader to the quad.

        To elaborate on how this all works:

        * An offscreen buffer is created.  It is set up to mimic
          the original display region - it is the same size,
          uses the same clear colors, and contains a DisplayRegion
          that uses the original camera.

        * A fullscreen quad and an orthographic camera to render
          that quad are both created.  The original camera is
          removed from the original window, and in its place, the
          orthographic quad-camera is installed.

        * The fullscreen quad is textured with the data from the
          offscreen buffer.  A shader is applied that tints the
          results pink.

        * Automatic shader generation NOT enabled.
          If you have a filter that depends on a render target from
          the auto-shader, you either need to set an auto-shader
          attrib on the main camera or scene, or, you need to provide
          these outputs in your own shader.

        * All clears are disabled on the original display region.
          If the display region fills the whole window, then clears
          are disabled on the original window as well.  It is
          assumed that rendering the full-screen quad eliminates
          the need to do clears.

        Hence, the original window which used to contain the actual
        scene, now contains a pink-tinted quad with a texture of the
        scene.  It is assumed that the user will replace the shader
        on the quad with a more interesting filter. """

        if textures:
            colortex = textures.get("color", None)
            depthtex = textures.get("depth", None)
            auxtex = textures.get("aux", None)
            auxtex0 = textures.get("aux0", auxtex)
            auxtex1 = textures.get("aux1", None)
        else:
            auxtex0 = auxtex
            auxtex1 = None

        if colortex is None:
            colortex = Texture("filter-base-color")
            colortex.setWrapU(Texture.WMClamp)
            colortex.setWrapV(Texture.WMClamp)

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        # Choose the size of the offscreen buffer.

        (winx, winy) = self.getScaledSize(1, 1, 1)
        if fbprops is not None:
            buffer = self.createBuffer("filter-base",
                                       winx,
                                       winy,
                                       texgroup,
                                       fbprops=fbprops)
        else:
            buffer = self.createBuffer("filter-base", winx, winy, texgroup)

        if buffer is None:
            return None

        cm = CardMaker("filter-base-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setTexture(colortex)
        quad.setColor(1, 0.5, 0.5, 1)

        cs = NodePath("dummy")
        cs.setState(self.camstate)
        # Do we really need to turn on the Shader Generator?
        #cs.setShaderAuto()
        if auxbits:
            cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
        if clamping is False:
            # Disables clamping in the shader generator.
            cs.setAttrib(LightRampAttrib.make_identity())
        self.camera.node().setInitialState(cs.getState())

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)

        self.region.setCamera(quadcam)

        self.setStackedClears(buffer, self.rclears, self.wclears)
        if auxtex0:
            buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
            buffer.setClearValue(GraphicsOutput.RTPAuxRgba0,
                                 (0.5, 0.5, 1.0, 0.0))
        if auxtex1:
            buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
        self.region.disableClears()
        if self.isFullscreen():
            self.win.disableClears()

        dr = buffer.makeDisplayRegion()
        dr.disableClears()
        dr.setCamera(self.camera)
        dr.setActive(1)

        self.buffers.append(buffer)
        self.sizes.append((1, 1, 1))

        return quad
Ejemplo n.º 16
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        self.disableMouse()
        self.cam.node().getLens().setNear(10.0)
        self.cam.node().getLens().setFar(200.0)
        camera.setPos(0, -50, 0)

        # Check video card capabilities.
        if not self.win.getGsg().getSupportsBasicShaders():
            addTitle("Toon Shader: Video driver reports that Cg shaders are not supported.")
            return

        # Enable a 'light ramp' - this discretizes the lighting,
        # which is half of what makes a model look like a cartoon.
        # Light ramps only work if shader generation is enabled,
        # so we call 'setShaderAuto'.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.5, 0.4))
        tempnode.setShaderAuto()
        self.cam.node().setInitialState(tempnode.getState())

        # Use class 'CommonFilters' to enable a cartoon inking filter.
        # This can fail if the video card is not powerful enough, if so,
        # display an error and exit.

        self.separation = 1  # Pixels
        self.filters = CommonFilters(self.win, self.cam)
        filterok = self.filters.setCartoonInk(separation=self.separation)
        if (filterok == False):
            addTitle(
                "Toon Shader: Video card not powerful enough to do image postprocessing")
            return

        # Show instructions in the corner of the window.
        self.title = addTitle(
            "Panda3D: Tutorial - Toon Shading with Normals-Based Inking")
        self.inst1 = addInstructions(0.06, "ESC: Quit")
        self.inst2 = addInstructions(0.12, "Up/Down: Increase/Decrease Line Thickness")
        self.inst3 = addInstructions(0.18, "V: View the render-to-texture results")

        # Load a dragon model and animate it.
        self.character = Actor()
        self.character.loadModel('models/nik-dragon')
        self.character.reparentTo(render)
        self.character.loadAnims({'win': 'models/nik-dragon'})
        self.character.loop('win')
        self.character.hprInterval(15, (360, 0, 0)).loop()

        # Create a non-attenuating point light and an ambient light.
        plightnode = PointLight("point light")
        plightnode.setAttenuation((1, 0, 0))
        plight = render.attachNewNode(plightnode)
        plight.setPos(30, -50, 0)
        alightnode = AmbientLight("ambient light")
        alightnode.setColor((0.8, 0.8, 0.8, 1))
        alight = render.attachNewNode(alightnode)
        render.setLight(alight)
        render.setLight(plight)

        # Panda contains a built-in viewer that lets you view the
        # results of all render-to-texture operations.  This lets you
        # see what class CommonFilters is doing behind the scenes.
        self.accept("v", self.bufferViewer.toggleEnable)
        self.accept("V", self.bufferViewer.toggleEnable)
        self.bufferViewer.setPosition("llcorner")
        self.accept("s", self.filters.manager.resizeBuffers)

        # These allow you to change cartooning parameters in realtime
        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up", self.increaseSeparation)
        self.accept("arrow_down", self.decreaseSeparation)
Ejemplo n.º 17
0
Archivo: bt.py Proyecto: btdevel/bt
    def __init__(self):

        ShowBase.__init__(self)
        self.disableMouse()
        self.camLens.setNear(0.01)
        self.camLens.setFar(100)
        self.camLens.setFov(config.camera_angle)
        self.setBackgroundColor(Vec4(0, 0, 0, 0))
        self.setFrameRateMeter(True)
        

        self.level = load_level(config.start_level)
        self.dir = Direction()
        self.pos = Vector([0, 0])

        level_node = render_level(self.level)
        level_node.reparentTo(self.render)

        self.accept("escape", exit)
        self.accept("arrow_up", self.forward)
        self.accept("arrow_down", self.reverse)
        self.accept("arrow_down", self.backwards)
        self.accept("arrow_left", self.turn_left)
        self.accept("arrow_right", self.turn_right)

        self.accept("1", self.set_camera_in)
        self.accept("2", self.set_camera_out)
        self.accept("3", self.spin_camera_left)
        self.accept("4", self.spin_camera_right)

        self.accept("s", self.toggle_smoke)

        title = OnscreenText(text="Bard's Tale I",
                             style=1, fg=(1,1,1,1),
                             pos=(0.7,0.92), scale = .07)


        slight = PointLight('slight')
        slight.setColor(Vec4(1, 1, 1, 1))
        slnp = render.attachNewNode(slight)
        #slight.setAttenuation((1, 0, 0.02))
        render.setLight(slnp)
        self.slight = slight
        self.light = slnp

        alight = AmbientLight('alight')
        amb = 0.05
        alight.setColor((amb, amb, amb, 1))
        alnp = render.attachNewNode(alight)
        self.alight = alight
        render.setLight(alnp)

        text = TextNode("foo")
        text.setText("")
        text.setShadow(0.2,0.2)
        text.setShadowColor(0, 0, 0, 1)
        tn = NodePath(text)
        tn.setScale(0.1)
        tn.reparentTo(aspect2d)
        tn.setPos(-1, -1, 0)
        self.text = text

        print self.eventMgr

        from panda3d.core import AntialiasAttrib
        self.render.setAntialias(AntialiasAttrib.MMultisample)

        self.follow = True
        self.set_camera()


        render.setAttrib(LightRampAttrib.makeIdentity())
        render.setShaderAuto()
Ejemplo n.º 18
0
 def __set_toon():
     tempnode = NodePath(PandaNode('temp node'))
     tempnode.setAttrib(LightRampAttrib.make_single_threshold(.5, .4))
     tempnode.set_shader_auto()
     base.cam.node().set_initial_state(tempnode.get_state())
     CommonFilters(base.win, base.cam).set_cartoon_ink(separation=1)
Ejemplo n.º 19
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        base.render.setAttrib(LightRampAttrib.makeHdr0())

        # Configure depth pre-pass
        prepass_pass = lionrender.DepthScenePass()

        # Configure scene pass
        scene_fb_props = FrameBufferProperties()
        scene_fb_props.set_rgb_color(True)
        scene_fb_props.set_rgba_bits(8, 8, 8, 0)
        scene_fb_props.set_depth_bits(32)
        scene_pass = lionrender.ScenePass(
            frame_buffer_properties=scene_fb_props,
            clear_color=LColor(0.53, 0.80, 0.92, 1),
            share_depth_with=prepass_pass)
        scene_pass.node_path.set_depth_write(False)

        # Configure post processing
        filter_pass = lionrender.FilterPass(fragment_path='shaders/fsq.frag')
        filter_pass.node_path.set_shader_input('inputTexture',
                                               scene_pass.output)

        # Enable FXAA
        fxaa_pass = lionrender.FxaaFilterPass()
        fxaa_pass.node_path.set_shader_input('inputTexture',
                                             filter_pass.output)

        # Output result
        fxaa_pass.output_to(render2d)

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0,
        }

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward")
        self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        # We do not have a skybox, so we will just use a sky blue background color
        self.setBackgroundColor(0.53, 0.80, 0.92, 1)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 1.5))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("v", self.toggleCards)

        taskMgr.add(self.move, "moveTask")

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        self.cTrav = CollisionTraverser()

        # Use a CollisionHandlerPusher to handle collisions between Ralph and
        # the environment. Ralph is added as a "from" object which will be
        # "pushed" out of the environment if he walks into obstacles.
        #
        # Ralph is composed of two spheres, one around the torso and one
        # around the head.  They are slightly oversized since we want Ralph to
        # keep some distance from obstacles.
        self.ralphCol = CollisionNode('ralph')
        self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5))
        self.ralphCol.addSolid(
            CollisionSphere(center=(0, -0.25, 4), radius=1.5))
        self.ralphCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphColNp = self.ralph.attachNewNode(self.ralphCol)
        self.ralphPusher = CollisionHandlerPusher()
        self.ralphPusher.horizontal = True

        # Note that we need to add ralph both to the pusher and to the
        # traverser; the pusher needs to know which node to push back when a
        # collision occurs!
        self.ralphPusher.addCollider(self.ralphColNp, self.ralph)
        self.cTrav.addCollider(self.ralphColNp, self.ralphPusher)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.
        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        # Clean up texture attributes
        for texture in self.render.find_all_textures():
            texture.set_format(Texture.F_srgb)
Ejemplo n.º 20
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        self.disableMouse()
        self.cam.node().getLens().setNear(10.0)
        self.cam.node().getLens().setFar(200.0)
        camera.setPos(0, -50, 0)

        # Check video card capabilities.
        if not self.win.getGsg().getSupportsBasicShaders():
            addTitle(
                "Toon Shader: Video driver reports that Cg shaders are not supported."
            )
            return

        # Enable a 'light ramp' - this discretizes the lighting,
        # which is half of what makes a model look like a cartoon.
        # Light ramps only work if shader generation is enabled,
        # so we call 'setShaderAuto'.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.5, 0.4))
        tempnode.setShaderAuto()
        self.cam.node().setInitialState(tempnode.getState())

        # Use class 'CommonFilters' to enable a cartoon inking filter.
        # This can fail if the video card is not powerful enough, if so,
        # display an error and exit.

        self.separation = 1  # Pixels
        self.filters = CommonFilters(self.win, self.cam)
        filterok = self.filters.setCartoonInk(separation=self.separation)
        if (filterok == False):
            addTitle(
                "Toon Shader: Video card not powerful enough to do image postprocessing"
            )
            return

        # Show instructions in the corner of the window.
        self.title = addTitle(
            "Panda3D: Tutorial - Toon Shading with Normals-Based Inking")
        self.inst1 = addInstructions(0.06, "ESC: Quit")
        self.inst2 = addInstructions(
            0.12, "Up/Down: Increase/Decrease Line Thickness")
        self.inst3 = addInstructions(0.18,
                                     "V: View the render-to-texture results")

        # Load a dragon model and animate it.
        self.character = Actor()
        self.character.loadModel('models/nik-dragon')
        self.character.reparentTo(render)
        self.character.loadAnims({'win': 'models/nik-dragon'})
        self.character.loop('win')
        self.character.hprInterval(15, (360, 0, 0)).loop()

        # Create a non-attenuating point light and an ambient light.
        plightnode = PointLight("point light")
        plightnode.setAttenuation((1, 0, 0))
        plight = render.attachNewNode(plightnode)
        plight.setPos(30, -50, 0)
        alightnode = AmbientLight("ambient light")
        alightnode.setColor((0.8, 0.8, 0.8, 1))
        alight = render.attachNewNode(alightnode)
        render.setLight(alight)
        render.setLight(plight)

        # Panda contains a built-in viewer that lets you view the
        # results of all render-to-texture operations.  This lets you
        # see what class CommonFilters is doing behind the scenes.
        self.accept("v", self.bufferViewer.toggleEnable)
        self.accept("V", self.bufferViewer.toggleEnable)
        self.bufferViewer.setPosition("llcorner")
        self.accept("s", self.filters.manager.resizeBuffers)

        # These allow you to change cartooning parameters in realtime
        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up", self.increaseSeparation)
        self.accept("arrow_down", self.decreaseSeparation)
Ejemplo n.º 21
0
    def __init__(self, *args, **kwargs):
        ShowBase.__init__(self, *args, **kwargs)

        from panda3d.core import RenderAttribRegistry
        from panda3d.core import ShaderAttrib, TransparencyAttrib
        from panda3d.bsp import BSPMaterialAttrib
        attribRegistry = RenderAttribRegistry.getGlobalPtr()
        attribRegistry.setSlotSort(BSPMaterialAttrib.getClassSlot(), 0)
        attribRegistry.setSlotSort(ShaderAttrib.getClassSlot(), 1)
        attribRegistry.setSlotSort(TransparencyAttrib.getClassSlot(), 2)

        gsg = self.win.getGsg()

        # Let's print out the Graphics information.
        self.notify.info(
            'Graphics Information:\n\tVendor: {0}\n\tRenderer: {1}\n'
            '\tVersion: {2}\n\tSupports Cube Maps: {3}\n'
            '\tSupports 3D Textures: {4}\n\tSupports Compute Shaders: {5}'.
            format(gsg.getDriverVendor(), gsg.getDriverRenderer(),
                   gsg.getDriverVersion(), str(gsg.getSupportsCubeMap()),
                   str(gsg.getSupports3dTexture()),
                   str(gsg.getSupportsComputeShaders())))

        # Enable shader generation on all of the main scenes
        if gsg.getSupportsBasicShaders() and gsg.getSupportsGlsl():
            self.render.setShaderAuto()
            self.render2d.setShaderAuto()
            self.render2dp.setShaderAuto()
            self.aspect2d.setShaderAuto()
            self.pixel2d.setShaderAuto()
        else:
            # I don't know how this could be possible
            self.notify.error("GLSL shaders unsupported by graphics driver.")
            return

        self.camNode.setCameraMask(CAMERA_MAIN)

        # Any ComputeNodes should be parented to this node, not render.
        # We isolate ComputeNodes to avoid traversing the same ComputeNodes
        # when doing multi-pass rendering.
        self.computeRoot = NodePath('computeRoot')
        self.computeCam = self.makeCamera(self.win)
        self.computeCam.node().setCameraMask(CAMERA_COMPUTE)
        self.computeCam.node().setCullBounds(OmniBoundingVolume())
        self.computeCam.node().setFinal(True)
        self.computeCam.reparentTo(self.computeRoot)

        self.bspLoader = None
        self.bspLevel = None
        self.brushCollisionMaterialData = {}
        self.createBSPLoader()

        self.audio3d = None
        self.create3DAudio()

        # Initialized in createShaderGenerator()
        self.shaderGenerator = None

        # Initialized in createPostProcess()
        self.filters = None

        self.render.show(CAMERA_SHADOW)
        self.render.setAttrib(LightRampAttrib.makeIdentity())
Ejemplo n.º 22
0
 def __init__(self):  #basic init start
     base.disableMouse()
     self.wp = WindowProperties()
     self.wp.setCursorHidden(True)
     base.win.requestProperties(self.wp)
     cm = CardMaker("cursor")
     cm.setFrame(0, 0.1, -0.13, 0)
     self.cust_mouse = render.attachNewNode(cm.generate())
     self.cust_mouse_tex = []
     self.cust_mouse_tex.append(
         loader.loadTexture("models/cursors/blank_cursor.png"))
     self.cust_mouse_tex.append(
         loader.loadTexture("models/cursors/main_cursor.png"))
     self.cust_mouse.setTexture(self.cust_mouse_tex[0])
     self.cust_mouse.setTransparency(TransparencyAttrib.MAlpha)
     self.cust_mouse.reparentTo(render2d)
     self.cust_mouse.setBin("gui-popup", 100)
     base.mouseWatcherNode.setGeometry(self.cust_mouse.node())
     #text and background
     textVersion = OnscreenText(text="v0.0",
                                font=arcFont,
                                pos=(1.15, -0.95),
                                fg=(0, 0, 0, 1),
                                bg=(1, 1, 1, 0.8))
     base.setBackgroundColor(1, 1, 1)
     self.curdir = (appRunner.p3dFilename.getDirname()
                    if appRunner else "..")
     self.main_config = json.loads("".join([
         line.rstrip().lstrip()
         for line in file(self.curdir + "/config.json", "rb")
     ]))
     #arrows (GENERAL)
     self.arrow = loader.loadModel("models/static/arrow")
     self.lst_arrows = []
     self.c_arr = CardMaker("arrow_hide")
     self.c_arr.setFrame(-1, 1, -0.8, 0.6)
     #light ramp
     self.rampnode = NodePath(PandaNode("temp node"))
     self.rampnode.setAttrib(LightRampAttrib.makeSingleThreshold(0.1, 0.7))
     self.rampnode.setShaderAuto()
     base.cam.node().setInitialState(self.rampnode.getState())
     #ink filter
     self.filters = CommonFilters(base.win, base.cam)
     self.filterok = self.filters.setCartoonInk(separation=1)
     #keyboard inputs
     self.accept("escape", sys.exit, [0])
     #lights
     self.lst_lghts = []
     #ambient light (permanent)
     self.alghtnode = AmbientLight("amb light")
     self.alghtnode.setColor(Vec4(0.4, 0.4, 0.4, 1))
     self.alght = render.attachNewNode(self.alghtnode)
     render.setLight(self.alght)
     #language recup
     self.langtab = self.main_config["lang"][self.main_config["lang_chx"]]
     self.lang = json.loads("".join([
         line.rstrip().lstrip()
         for line in file("misc/lang/" + self.langtab[0] + ".json", "rb")
     ]))
     #common gui elements
     self.voile = []
     self.voile.append(
         DirectFrame(frameSize=(-2, 2, -2, 2), frameColor=(0, 0, 0, 0.8)))
     self.voile[0].setBin("gui-popup", 1)
     self.voile[0].hide()
     self.voile.append(arcLabel("", (0, 0, 0.3), txtalgn=TextNode.ACenter))
     self.voile[1].setBin("gui-popup", 1)
     self.voile[1].reparentTo(self.voile[0])
     self.voile.append(arcLabel("", (0, 0, 0.17), txtalgn=TextNode.ACenter))
     self.voile[2].setBin("gui-popup", 1)
     self.voile[2].reparentTo(self.voile[0])
     self.voile.append(
         arcButton(self.lang["main_dialog"]["valid"], (-0.2, 0, 0),
                   None,
                   txtalgn=TextNode.ACenter))
     self.voile[3].setBin("gui-popup", 1)
     self.voile[3].reparentTo(self.voile[0])
     self.voile.append(
         arcButton(self.lang["main_dialog"]["cancel"], (0.2, 0, 0),
                   None,
                   txtalgn=TextNode.ACenter))
     self.voile[4].setBin("gui-popup", 1)
     self.voile[4].reparentTo(self.voile[0])
     #mouse handler
     self.mouse_trav = CollisionTraverser()
     self.mouse_hand = CollisionHandlerQueue()
     self.pickerNode = CollisionNode('mouseRay')
     self.pickerNP = camera.attachNewNode(self.pickerNode)
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))
     self.pickerRay = CollisionRay()
     self.pickerNode.addSolid(self.pickerRay)
     self.mouse_trav.addCollider(self.pickerNP, self.mouse_hand)
     self.pickly_node = render.attachNewNode("pickly_node")
     #init main scene
     self.scene = mainScene(self)
Ejemplo n.º 23
0
    def __init__(self):

        self.controlMap = {"left":0, "right":0, "forward":0, "backward":0,
            "zoom-in":0, "zoom-out":0, "wheel-in":0, "wheel-out":0}
        self.mousebtn = [0,0,0]
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Better Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "W A S D keys move Ralph forward, left, back, and right, respectively.")
        self.inst3 = addInstructions(0.85, "Use the mouse to look around and steer Ralph.")
        self.inst4 = addInstructions(0.80, "Zoom in and out using the mouse wheel, or page up and page down keys.")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("w", self.setControl, ["forward",1])
        self.accept("a", self.setControl, ["left",1])
        self.accept("s", self.setControl, ["backward",1])
        self.accept("d", self.setControl, ["right",1])
        self.accept("w-up", self.setControl, ["forward",0])
        self.accept("a-up", self.setControl, ["left",0])
        self.accept("s-up", self.setControl, ["backward",0])
        self.accept("d-up", self.setControl, ["right",0])
#        self.accept("mouse1", self.setControl, ["zoom-in", 1])
#        self.accept("mouse1-up", self.setControl, ["zoom-in", 0])
#        self.accept("mouse3", self.setControl, ["zoom-out", 1])
#        self.accept("mouse3-up", self.setControl, ["zoom-out", 0])
        self.accept("wheel_up", self.setControl, ["wheel-in", 1])
        self.accept("wheel_down", self.setControl, ["wheel-out", 1])
        self.accept("page_up", self.setControl, ["zoom-in", 1])
        self.accept("page_up-up", self.setControl, ["zoom-in", 0])
        self.accept("page_down", self.setControl, ["zoom-out", 1])
        self.accept("page_down-up", self.setControl, ["zoom-out", 0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        # Adding the camera to Ralph is a simple way to keep the camera locked
        # in behind Ralph regardless of ralph's movement.
        base.camera.reparentTo(self.ralph)
        # We don't actually want to point the camera at Ralph's feet.
        # This value will serve as a vertical offset so we can look over Ralph
        self.cameraTargetHeight = 6.0
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        # This just disables the built in camera controls; we're using our own.
        base.disableMouse()
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)

############## CollisionTube doesn't seem to be working
#        self.cameraRay = CollisionTube( (0,0,self.cameraTargetHeight),
#                                        (0,25,25),
#                                        (self.cameraTargetHeight/2))
#        self.cameraCol = CollisionNode('cameraRay')
#        self.cameraCol.addSolid(self.cameraRay)
#        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
#        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
#        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
#        self.cameraColHandler = CollisionHandlerQueue()
#        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
############

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
        #self.cameraColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        # lets add hdr lighting for fun
        render.setShaderAuto()
        render.setAttrib(LightRampAttrib.makeHdr1())
        ambientLight = AmbientLight("ambientLight")
        # existing lighting is effectively darkened so boost ambient a bit
        ambientLight.setColor(Vec4(.4, .4, .4, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        # hdr can handle any amount of lighting
        # lets make things nice and sunny
        directionalLight.setColor(Vec4(2.0, 2.0, 2.0, 1.0))
        directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Ejemplo n.º 24
0
 def __init__(self):
     
     self.keyMap = {"left":0, "right":0, "forward":0, "backward":0}
     self.angles = {"left":-90, "right":90, "forward":0, "backward":180}
     self.title = addTitle("Moving like nowaday's action game")
     
     # load the scene
     base.setBackgroundColor(0,0,0.2,1)
     floorTex = loader.loadTexture("maps/envir-ground.jpg")
     cm = CardMaker("")
     cm.setFrame(-2,2,-2,2)
     floor = render.attachNewNode(PandaNode("floor"))
     for y in range(12):
         for x in range(12):
             nn = floor.attachNewNode(cm.generate())
             nn.setP(-90)
             nn.setPos((x-6)*4, (y-6)*4, 0)
     floor.setTexture(floorTex)
     floor.flattenStrong()
     
     # create main character        
     self.eve = Actor("models/eve", 
                        {"run":"models/eve_run",
                         "walk":"models/eve_walk"})
     self.eve.reparentTo(render)
     self.eve.setScale(.4)
     self.eve.setPos(0, 0, 0)
     
     # accept the control keys for movement and rotation        
     self.accept("escape", sys.exit)
     self.accept("a", self.setKey, ["left",1])
     self.accept("d", self.setKey, ["right",1])
     self.accept("w", self.setKey, ["forward",1])
     self.accept("s", self.setKey, ["backward",1])
     self.accept("a-up", self.setKey, ["left",0])
     self.accept("d-up", self.setKey, ["right",0])
     self.accept("w-up", self.setKey, ["forward",0])
     self.accept("s-up", self.setKey, ["backward",0])
     
     self.pre_move = "forward"
     taskMgr.add(self.move, "moveTask")
     
     # game start variable
     self.isMoving = False
     
     # set up the camera        
     base.camera.reparentTo(self.eve)
     #look over eve
     self.cameraTargetHeight = 6.0
     self.cameraDistance = 30
     self.cameraPitch = 10
     # disable the default camera control by mouse
     base.disableMouse()
     # hide mouse
     props = WindowProperties()
     props.setCursorHidden(True)
     base.win.requestProperties(props)
     
     # create some lighting
     render.setShaderAuto()
     render.setAttrib(LightRampAttrib.makeHdr1())
     ambientLight = AmbientLight("ambientLight")
     ambientLight.setColor(Vec4(.4, .4, .3, 1))
     directionalLight = DirectionalLight("directionalLight")
     directionalLight.setDirection(Vec3(0, 8, -2.5))
     directionalLight.setColor(Vec4(2.0, 2.0, 2.0, 1))
     directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 1))
     render.setLight(render.attachNewNode(ambientLight))
     render.setLight(render.attachNewNode(directionalLight))
Ejemplo n.º 25
0
 def renderSceneInto(self,
                     depthtex=None,
                     colortex=None,
                     auxtex=None,
                     auxbits=0,
                     textures=None,
                     fbprops=None,
                     clamping=None):
     """
     overload direct.filters.FilterManager.renderSceneInto
     :param depthtex:
     :param colortex:
     :param auxtex:
     :param auxbits:
     :param textures:
     :param fbprops:
     :param clamping:
     :return:
     """
     if (textures):
         colortex = textures.get("color", None)
         depthtex = textures.get("depth", None)
         auxtex = textures.get("aux", None)
         auxtex0 = textures.get("aux0", auxtex)
         auxtex1 = textures.get("aux1", None)
     else:
         auxtex0 = auxtex
         auxtex1 = None
     if (colortex == None):
         colortex = Texture("filter-base-color")
         colortex.setWrapU(Texture.WMClamp)
         colortex.setWrapV(Texture.WMClamp)
     texgroup = (depthtex, colortex, auxtex0, auxtex1)
     # Choose the size of the offscreen buffer.
     (winx, winy) = self.getScaledSize(1, 1, 1)
     if fbprops is not None:
         buffer = self.createBuffer("filter-base",
                                    winx,
                                    winy,
                                    texgroup,
                                    fbprops=fbprops)
     else:
         buffer = self.createBuffer("filter-base", winx, winy, texgroup)
     if (buffer == None):
         return None
     cm = CardMaker("filter-base-quad")
     cm.setFrameFullscreenQuad()
     quad = NodePath(cm.generate())
     quad.setDepthTest(0)
     quad.setDepthWrite(0)
     quad.setTexture(colortex)
     quad.setColor(1, 0.5, 0.5, 1)
     cs = NodePath("dummy")
     cs.setState(self.camstate)
     # Do we really need to turn on the Shader Generator?
     # cs.setShaderAuto()
     if (auxbits):
         cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
     if clamping is False:
         # Disables clamping in the shader generator.
         cs.setAttrib(LightRampAttrib.make_identity())
     self.camera.node().setInitialState(cs.getState())
     quadcamnode = Camera("filter-quad-cam")
     lens = OrthographicLens()
     lens.setFilmSize(2, 2)
     lens.setFilmOffset(0, 0)
     lens.setNearFar(-1000, 1000)
     quadcamnode.setLens(lens)
     quadcam = quad.attachNewNode(quadcamnode)
     self.region.setCamera(quadcam)
     self.setStackedClears(buffer, self.rclears, self.wclears)
     if (auxtex0):
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
         buffer.setClearValue(GraphicsOutput.RTPAuxRgba0,
                              (0.5, 0.5, 1.0, 0.0))
     if (auxtex1):
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
     self.region.disableClears()
     if (self.isFullscreen()):
         self.win.disableClears()
     dr = buffer.makeDisplayRegion()
     dr.disableClears()
     dr.setCamera(self.camera)
     dr.setActive(1)
     self.buffers.append(buffer)
     self.sizes.append((1, 1, 1))
     return quad